code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module CCAR.Model.Country
(
setupCountries
, cleanupCountries
, startup
)
where
import Control.Monad.IO.Class
import Control.Monad
import Control.Monad.Logger
import Control.Monad.Trans(lift)
import Control.Monad.Trans.Maybe
import Control.Monad.Trans.Resource
import Control.Applicative as Appl
import Database.Persist
import Database.Persist.Postgresql as Postgresql
import Database.Persist.TH
import CCAR.Main.DBUtils
import CCAR.Command.ApplicationError
import Data.Text as T
import qualified CCAR.Main.EnumeratedTypes as EnumeratedTypes
import qualified CCAR.Main.GroupCommunication as GC
import Data.Aeson
import Data.Aeson.Encode as En
import Data.Aeson.Types as AeTypes(Result(..), parse)
import Data.Monoid
import Data.Text.Lazy.Encoding as E
import Data.Text.Lazy as L
import GHC.Generics
import Data.Data
import Data.Typeable
import Data.Time
import CCAR.Main.Util
import System.Log.Logger as Logger
import CCAR.Parser.CSVParser as CSVParser(parseCSV, ParseError, parseLine)
import System.IO
import System.Environment(getEnv)
import Data.Conduit ( ($$), (=$=), (=$), Conduit, await, yield)
import Data.Conduit.Binary as B (sinkFile, lines, sourceFile)
import Data.Conduit.List as CL
import Data.ByteString.Char8 as BS(ByteString, pack, unpack)
parseLine :: (Monad m, MonadIO m) => Conduit BS.ByteString m (Either ParseError [String])
parseLine = do
client <- await
case client of
Nothing -> return ()
Just aBS -> do
yield $ CSVParser.parseLine $ BS.unpack aBS
CCAR.Model.Country.parseLine
saveLine :: (MonadIO m) => Conduit (Either ParseError [String]) m ByteString
saveLine = do
client <- await
case client of
Nothing -> return ()
Just oString -> do
case oString of
Right x -> do
_ <- liftIO $ insertLine x
return x
yield $ BS.pack $ (show oString) ++ "\n"
saveLine
deleteLine ::(MonadIO m) => Conduit (Either ParseError [String]) m ByteString
deleteLine = do
client <- await
case client of
Nothing -> return ()
Just oString -> do
case oString of
Right x -> do
_ <- liftIO $ removeLine x
return x
yield $ BS.pack $ (show oString) ++ "\n"
saveLine
conduitBasedSetup aFileName = runResourceT $
B.sourceFile aFileName
$$ B.lines =$= CCAR.Model.Country.parseLine =$= saveLine =$ consume
conduitBasedDelete aFileName = runResourceT $
B.sourceFile aFileName
$$ B.lines =$= CCAR.Model.Country.parseLine =$= deleteLine =$ consume
data CRUD = Create | Read | C_Update | Delete
deriving(Show, Eq, Read, Data, Generic, Typeable)
type ISO_3 = T.Text
type ISO_2 = T.Text
type Name = T.Text
type Domain = T.Text
add :: ISO_3 -> ISO_2 -> Name -> Domain -> IO (Key Country)
add a b c d = dbOps $ do
country <- getBy $ UniqueISO3 a
case country of
Nothing -> insert $ Country c a b d
Just (Entity k v) -> do
liftIO $ Logger.debugM iModuleName
("Country " ++ (T.unpack c) ++ " already exists")
return k
remove aCountryCode = dbOps $ deleteBy $ UniqueISO3 aCountryCode
iModuleName = "CCAR.Model.Country"
removeLine aLine = remove (T.pack $ aLine !! 2)
insertLine aLine =
add (T.pack $ aLine !! 2)
(T.pack $ aLine !! 1)
(T.pack $ aLine !! 3)
(T.pack $ aLine !! 4)
--setupCountries :: FilePath -> IO [Key Country]
{-parseCountries aHandle dbFunction = do
inputLine <- hGetContents aHandle
parsedOutput <- return $ CSVParser.parseCSV inputLine
x <- case parsedOutput of
Left e -> do
putStrLn "Error processing file"
print e
Right (h:r) -> Control.Monad.mapM_ (\line -> do
print line
dbFunction line) r
return x
-}
deleteCountries = conduitBasedDelete
{-setupCountriesOld aFileName = do
handle <- openFile aFileName ReadMode
parseCountries handle insertLine
-}
setupCountries = conduitBasedSetup
cleanupCountries aFileName = conduitBasedDelete
startup = do
dataDirectory <- getEnv("DATA_DIRECTORY");
setupCountries (dataDirectory ++ "/" ++ "Country.csv") | asm-products/ccar-websockets | CCAR/Model/Country.hs | agpl-3.0 | 4,015 | 38 | 20 | 789 | 1,204 | 662 | 542 | 106 | 2 |
{-# LANGUAGE ApplicativeDo #-}
module TypeTranspilerSpec where
import TypeTranspiler
import Test.Hspec
import System.Random
import Control.Monad
a =>> b = transpile a `shouldBe` Right b
keep a = a =>> a
infix 2 =>>
gg a = transpile a `shouldBe` Left "Hugh?"
main :: IO ()
main = hspec $ do
describe "simple and easy tests" $ do
it "should work when nothing should be changed" $ do
keep "A"
keep "A.A"
keep "A.A.A"
keep "A.B.C"
keep "A.A.A.abc.Abc"
keep "_"
gg "A."
gg ">_<"
gg ".A"
gg ".."
gg "123"
gg "A.123"
it "should work when there are generic parameters" $ do
keep "A<A>"
keep "B<B>"
gg "A<>"
gg "A<"
"List<Int>" =>> "List<Integer>"
gg "A>"
"Int.Companion" =>> "Integer.Companion"
gg "<A>"
it "should work for star projections" $ do
"A<*>" =>> "A<?>"
"A<*, *, A>" =>> "A<?,?,A>"
gg "?"
gg "*<A>"
gg "?<A>"
gg "*"
gg "A<*"
gg "A*>"
it "should work for variance" $ do
"A<in A>" =>> "A<? super A>"
"List<out T>" =>> "List<? extends T>"
"Array<out CSharp, out Java>" =>> "Array<? extends CSharp,? extends Java>"
"ArrayList<in out>" =>> "ArrayList<? super out>"
"ArrayList<out in>" =>> "ArrayList<? extends in>"
keep "A<in>"
keep "Array<out>"
it "should rename" $ do
"Int" =>> "Integer"
"List<Int>" =>> "List<Integer>"
it "should remove spaces" $ do
"A<A, B>" =>> "A<A,B>"
" A " =>> "A"
" A < A > " =>> "A<A>"
"A . A . B < C >" =>> "A.A.B<C>"
gg " < > "
it "should work when there are multiple generic parameters" $ do
keep "A<A<A>>"
keep "A<A<A<A<A>>>>"
keep "A<A,B,C,D>"
keep "A<A<A<A>,A<A<A>>>,A>"
gg "A<A<A<A>,A<A<A>>,A>"
gg "A<A<AA,A<A<A>>,A>"
it "should work for 30 random tests" $ do
let test x = keep $ "Tuple<A" ++ join (replicate x ",A") ++ ">" in
replicateM_ 30 $ join $ test <$> randomRIO (10, 100)
describe "complex tests" $ do
it "should work for function types" $ do
"(A) -> B" =>> "Function1<A,B>"
"(A, B) -> C" =>> "Function2<A,B,C>"
"(A<A>, B) -> C<D>" =>> "Function2<A<A>,B,C<D>>"
"(A<A>.A<*>) -> QwQ<out T>" =>> "Function1<A<A>.A<?>,QwQ<? extends T>>"
"(A,B,C,D,E,F,G,H) -> I" =>> "Function8<A,B,C,D,E,F,G,H,I>"
"() -> A" =>> "Function0<A>"
"( ) -> Abc" =>> "Function0<Abc>"
gg "() -> ()"
gg "(A) - > B"
gg "() ->"
gg "-> A"
it "should work for complex function types" $ do
"((A) -> B) -> C" =>> "Function1<Function1<A,B>,C>"
"(A) -> (B) -> C" =>> "Function1<A,Function1<B,C>>"
"(((A) -> B) -> C) -> D" =>> "Function1<Function1<Function1<A,B>,C>,D>"
"(A, B) -> C" =>> "Function2<A,B,C>"
"((A) -> B, (B) -> C) -> (A) -> C" =>> "Function2<Function1<A,B>,Function1<B,C>,Function1<A,C>>"
it "should work for 30 random tests" $ do
let test x = join (replicate x "(Int) -> ") ++ "Long" =>>
join (replicate x "Function1<Integer,") ++ "Long" ++ replicate x '>' in
replicateM_ 30 $ join $ test <$> randomRIO (10, 100)
it "should work for other 30 random tests" $ do
let test x = "(A" ++ join (replicate x ",A") ++ ")->Unit" =>>
"Function" ++ show (x + 1) ++ "<A" ++ join (replicate x ",A") ++ ",Void>" in
replicateM_ 30 $ join $ test <$> randomRIO (10, 100)
--
| ice1000/OI-codes | codewars/authoring/haskell/TypeTranspilerSpec.hs | agpl-3.0 | 3,484 | 0 | 27 | 1,021 | 903 | 384 | 519 | 98 | 1 |
{-# OPTIONS_GHC -F -pgmF ./scripts/local-htfpp #-}
module Foo.B (htf_thisModulesTests) where
import qualified Test.Framework as HTF
test_b_OK = HTF.assertEqual 1 1
| skogsbaer/HTF | tests/Foo/B.hs | lgpl-2.1 | 167 | 0 | 6 | 23 | 32 | 20 | 12 | 4 | 1 |
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : [email protected]
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
{-# LANGUAGE TypeFamilies #-}
module Compiler.Types2.DepTypeAssignment (assignDepTypes, assignDepTypes2, assignDepTypes3, assignFunDepTypes, showExprWithDepTypes, applyVarSubstsToVarMap, unify,
solveDepConstrs2, solveDepConstrs3) where
{-import Common (delimList, maybeError)
import Indices (Idx, IdxSet)
import ModelSolver (Model(..))
import RuleSets (RuleSet)
import ExprTree (Expr(Let, Lit, Tup, Rel, If, App, Fun), renewIdAndExprIds, StructEq(..))
import qualified ExprTree (Expr(Var))
import Variables (VarSubsts, VarsIn(..), emptyVarSubsts, composeVarSubsts)
import qualified Variables (fromList)
import TypeAssignment (TyToken, TyTerm, TyConstr, TyScheme, TySchemeEx, TyEnv,
typeOfVal, rel, relNonOrd, showExprWithTypes)
import TermLanguage (Term(..), Constr(..), Subst(..), MonadicUnifierExtension,
Scheme(..), SchemeEx(..), getIdsInIdTree,
FunctionToken, Subst, monadicUnifyTrans, emptyTermEnv, applyVarSubstsToConstr,
bindTermInState, instantiateScheme, generalizeTerm, bindNewTermVarInState,
instantiateSchemeEx, instantiateSchemeEx2, schemeEnvToSchemeExEnv)
import TermBuilder (buildForIdxTree, fun, tup)
import TidyCode (tidyCode)
import Data.Map (Map, toList, (!), (\\), keysSet, keys, elems)
import qualified Data.Map (map, union, insert, empty, fromList, lookup, member, delete)
import Data.Set (Set, unions, intersection)
import qualified Data.Set (map, null)
import Control.Monad.Identity
import Control.Monad.State ( runStateT, evalStateT, StateT, modify, get, lift )
-}
import Compiler.Front.Common (delimList, maybeError, eids, dtvids, ShowP(..), hasCycle, isLeft)
import Compiler.Front.Indices (Idx, IdxSet, IdxMonad, newidST)
import Compiler.Front.ExprTree (Expr(Let, Lit, Tup, Rel, If, App, Fun), renewIdAndExprIds, StructEq(..), showExprTree)
import qualified Compiler.Front.ExprTree as E
import qualified Compiler.Front.ExprTree as ExprTree (Expr(Var))
import Compiler.Types2.TermLanguage (Term(..), Constr(..), Subst(..), MonadicUnifierExtension,
Scheme(..), SchemeEx(..), getIdsInIdTree, IdTree(..), forAllSubs, subInTerm,
FunctionToken(..), Subst, monadicUnifyTrans, defaultMonadicUnifierExtension, emptyTermEnv, applyVarSubstsToConstr,
bindTermInState, instantiateScheme, generalizeTerm, bindNewTermVarInState,
instantiateSchemeEx, instantiateSchemeEx2, schemeEnvToSchemeExEnv, lookupTermMaybe,
unifyConstraints, newTermVarFromState,
labelTerm, labelTermRec, labelArgTermRec, labelRanTermRec,
addLabelsToTermRec, addLabelsToArgTermRec, addLabelsToRanTermRec, getLabels,
stripTermLabels, stripTermLabelsRec,
getVarIdsInTerm)
import Compiler.Types2.TermBuilder (ExpLbl(..), buildForIdxTree, fun, tup)
import Compiler.Types2.TypeAssignment (TyToken(..), TyTerm, TyConstr, TyScheme, TySchemeEx, TyEnv,
typeOfVal, rel, relNonOrd, showExprWithTypes)
import Compiler.Types2.Variables (VarSubsts, VarsIn(..), emptyVarSubsts, composeVarSubsts)
import qualified Compiler.Types2.Variables as Variables
import Compiler.Types2.EmbeddedFunctions
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.State.Strict (StateT, runStateT, evalStateT, lift, get, modify)
import Control.Monad.Catch (MonadCatch(..))
import qualified Data.IntMap.Strict as IM
import qualified Data.Map.Strict as M
import qualified Data.Set as DS
import Data.Set (Set, unions, intersection, null)
import Data.IntMap.Strict ((\\))
import Debug.Trace (trace)
import Data.Maybe (fromMaybe, isJust)
import Data.List (intercalate, find)
-- |trace is used to display or hide debugging
-- |info depending on its implementation
trace' :: String -> a -> a
--trace' s = trace s
trace' s a = a
type ExpMap a = IM.IntMap a
type VarMap v = IM.IntMap v
-- |expMapFromList takes an associative array and returns
-- |the ExpMap equivalent.
expMapFromList :: [(Idx,v)] -> VarMap v
expMapFromList l = IM.fromList l
-- |varMapLookup returns the value stored under the key given
-- |in the VarMap provided.
varMapLookup :: VarMap a -> Idx -> Maybe a
varMapLookup mp idx = IM.lookup idx mp
-- |varMapFromList takes an associative array and returns
-- |the VarMap equivalent.
varMapFromList :: [(Idx,v)] -> VarMap v
varMapFromList l = IM.fromList l
-- |composeVarMaps creates the left biased union of
-- |VarMaps a and b.
composeVarMaps :: VarMap a -> VarMap a -> VarMap a
composeVarMaps a b = a `IM.union` b
-- |applyVarSubstsToVarMap subs varMap applies all the substitutions in
-- |subs to the map varMap.
applyVarSubstsToVarMap :: VarsIn a => VarSubsts a -> VarMap a -> VarMap a
applyVarSubstsToVarMap subs m = IM.map (applyVarSubsts subs) m
-- |applyVarSubstsToScheme takes a map of substitutions and a type scheme
-- |and returns the scheme with the substitutions applied to free variables.
applyVarSubstsToScheme :: VarSubsts TyTerm -> TyScheme -> TyScheme
applyVarSubstsToScheme subs (Scheme l t) = Scheme l $ applyVarSubsts (subs \\ (IM.fromList $ zip l [0..])) t
-- |applyVarSubstsToScheme map applies all substitutions to free variables in the
-- |scheme map.
applyVarSubstsToSchemeMap :: VarSubsts TyTerm -> VarMap TyScheme -> VarMap TyScheme
applyVarSubstsToSchemeMap subs env = IM.map (applyVarSubstsToScheme subs) env
-- |applyVarSubstsToSchemeExMap map applies all substitutions to free variables in the
-- |scheme map.
applyVarSubstsToSchemeExMap :: VarSubsts TyTerm -> VarMap TySchemeEx -> VarMap TySchemeEx
applyVarSubstsToSchemeExMap subs env = IM.map (\(SchemeEx it scheme) ->
SchemeEx it (applyVarSubstsToScheme (subs \\ (IM.fromList $ zip (getIdsInIdTree it) [0..])) scheme))
env
-- |applySubstsToScheme takes a list of substitutions and a type scheme
-- |and returns the scheme with the substitutions applied to free variables.
applyTermSubsts :: [(TyTerm, TyTerm)] -> TyTerm -> TyTerm
applyTermSubsts ((a,b):r) term = applyTermSubsts r (applyTermSubst a b term)
applyTermSubsts [] term = term
applyTermSubst :: TyTerm -> TyTerm -> TyTerm -> TyTerm
applyTermSubst a b c = case c of
_ | a == c -> b
Term t l -> Term t $ map (applyTermSubst a b) l
LTerm lbls t l -> LTerm lbls t $ map (applyTermSubst a b) l
other -> other
-- |Pretty print type scheme
showDepTyScheme :: TyScheme -> String
showDepTyScheme (Scheme [] term) = showEmbeddedFuns term
showDepTyScheme (Scheme vars term) = "forall " ++
(delimList "," $ map (\i -> ("v" ++ show i)) vars) ++
" => " ++ (showEmbeddedFuns term)
showDepExprTy :: TyEnv -> Idx -> String
showDepExprTy env idx = case lookupTermMaybe env idx of
Just v -> " :: " ++ (showDepTyScheme v)
Nothing -> " :: ERROR: no type term exists in env with idx " ++ (show idx)
showExprWithDepTypes :: TyEnv -> Expr -> String
showExprWithDepTypes env exp = showExprTree env showDepExprTy 2 exp
-- |lookupVar takes two var maps and an id and tries to
-- |lookup the value in the first map, or failing that in
-- |the second map.
lookupVar :: VarMap a -> VarMap a -> Idx -> Maybe a
lookupVar globals locals id = case varMapLookup locals id of
Just v -> Just v
Nothing -> case varMapLookup globals id of
Just v -> Just v
Nothing -> Nothing
-- |getIdExprPairs zips together an IdTree and a tuple expression tree
-- |returning a lift of pairs of id tree ids to expressions.
getIdExprPairs :: (IdTree, Expr) -> [(Idx, Expr)]
getIdExprPairs ab = case ab of
((IdTup al),(Tup _ bl)) | length al == length bl -> concat $ map getIdExprPairs $ zip al bl
((IdLeaf ai),expr) -> [(ai, expr)]
((IdBlank),_) -> []
other -> error $ "DepTyAss:getIdExprPairs: IdTree and Expr tuple tree are not isomorphic: " ++ (showP ab)
-- TODO may need to update to work with term labels?
-- |Instantiates a term SchemeEx by replacing every qualified term variable
-- |with a new variable, and every function application qualified variable
-- |with a ref to that var id (or expression id).
instantiateSchemeEx3 :: Monad m => VarMap TySchemeEx -> TySchemeEx -> Expr -> IdxMonad m TyTerm
instantiateSchemeEx3 varTys ts@(SchemeEx it inner) expr = do
term <- instantiateScheme inner
let varPairs = getIdExprPairs (it, expr)
--if (sum $ map ((E.countExprs (\e -> E.isVarExpr e && E.getVarExprName e == "loop")) . snd) varPairs) > 0 then error $ "instSchemeEx3: found x0: " ++ (showP expr) ++ " binding to " ++ (showP ts) else return ()
varSubs <- mapM (\(from,to) -> evalEmFunM (embedFun [] to) (error "DepTyAss:instSchemeEx3: call to embedFun should not use efsExpEnv!") varTys
>>= (\t -> return $ trace' ("Embed: " ++ (show to) ++ " => \n" ++ (show t) ++ "\n") $ (Var from) :|-> t)) varPairs
let subMap = IM.fromList $ map (\(Var vid :|-> e) -> (vid, e)) varSubs
let term' = applyVarSubsts subMap term
--let term' = forAllSubs subInTerm varSubs {-$ (if length varPairs > 0 then trace $ "VARPAIRS: " ++ (intercalate "\n" $ map (\(k,e) -> "(" ++ (show k) ++ ", " ++ (show $ E.getExprId e) ++ " " ++ (showP e) ++ ")") varPairs) ++ "\n\nVARSUBS: " ++ (showP varSubs) ++ "\n\n" ++ (showP $ E.getExprById 933 expr) ++ "\n\n" else id) $-} term
return term'
-- |For a given expression sets up the type environment, constraints,
-- |and expandable expression map.
buildConstrs :: Monad m =>
VarMap TySchemeEx -> -- global var types
VarMap TySchemeEx -> -- local var types
Expr ->
StateT TyEnv (IdxMonad m) ([TyConstr], TyTerm)
buildConstrs globalEnv localEnv exp = case exp of
-- standard constraint building
(Lit i vl) -> do
let ty = labelTermRec (ProdLbl i) $ typeOfVal vl
bindTermInState (Scheme [] ty) i
return ([], ty)
-- look for var binding in local var env
(ExprTree.Var i vi s) -> case lookupVar globalEnv localEnv vi of
(Just scheme) -> do
term <- lift $ instantiateSchemeEx2 scheme
let term' = labelTermRec (ProdLbl i) {-stripTermLabelsRec-} term
bindTermInState (Scheme [] term') i
return ([], term')
(Nothing) -> error $ "Unbound var " ++ (show vi) ++ " " ++ s
++ " when building dep type constraints."
(Tup i l) -> do -- new tup term
l' <- mapM (buildConstrs globalEnv localEnv) l
if length l == 1 || length l' == 1 then error $ "tup with one child! " ++ (show exp) else return ()
let (cl,tl) = unzip l'
let term = tup tl
bindTermInState (Scheme [] term) i
return (concat cl, term)
(Rel i l) -> case l of
-- empty list: just a term var
[] -> do
v <- lift $ newTermVarFromState
let v' = labelTerm (ProdLbl i) v
bindTermInState (Scheme [] v') i
return ([], v)
-- non empty list: all children same type
_ -> do
l' <- mapM (\e -> buildConstrs globalEnv localEnv e) l
let (cl,tl) = unzip l'
let (headTy:tail) = tl
let cl' = map (\ty -> headTy :=: ty) tail
let ty = labelTermRec (ProdLbl i) $ rel headTy (relNonOrd)
bindTermInState (Scheme [] ty) i -- TODO: change so not just non ord
return ((concat cl) ++ cl', ty)
(If i pe te ee) -> do -- PREPROCESSING NOW ELIMINATES IF EXPRESSIONS!
v <- lift $ newTermVarFromState
let v' = labelTerm (ProdLbl i) v
bindTermInState (Scheme [] v') i
(c1,t1) <- buildConstrs globalEnv localEnv pe
(c2,t2) <- buildConstrs globalEnv localEnv te
(c3,t3) <- buildConstrs globalEnv localEnv ee
{-let t2' = labelTermRec (IfLbl i) t2
let t3' = labelTermRec (IfLbl i) t3-}
return ((c1 ++ c2 ++ c3) ++ [t2 :=: t3, v' :=: t2], v')
(Let i it be ie) -> do
(c1,t1) <- buildConstrs globalEnv localEnv be
(newVarEnv, t1') <- buildForIdxTree it
let newVarEnv' = varMapFromList $ schemeEnvToSchemeExEnv newVarEnv
(c2, t2) <- buildConstrs globalEnv (newVarEnv' `composeVarMaps` localEnv) ie
let t2' = labelTermRec (ProdLbl i) t2
bindTermInState (Scheme [] t2') i
-- don't need to carry labels through from be, since only want to know about var exp ids
-- so we strip them off
return (c1 ++ [t1 :=: t1'] ++ c2, t2')
--return ((stripTermLabelsRec t1 :=: stripTermLabelsRec t1'):(c1 ++ c2), t2')
-- check if application of function with pi type
(App i fe ae) -> do
v <- lift $ newTermVarFromState
let v' = labelTermRec (ProdLbl i) v
bindTermInState (Scheme [] v') i
(c2,t2) <- buildConstrs globalEnv localEnv ae
case fe of
-- if application of function var (check if has a dep type)
(ExprTree.Var fi vi s) -> do
-- instantiate dependent type scheme using
-- func app argument expression
case lookupVar globalEnv localEnv vi of
(Just schemeEx) -> do
t1 <- lift $ instantiateSchemeEx3 globalEnv schemeEx ae
let t1' = {-addLabelsToArgTermRec (getLabels t2) $ labelRanTermRec (ProdLbl i)-} t1
bindTermInState (Scheme [] t1') fi
let constr = (t1' :=: fun t2 v')
return {- trace' ("AppConstr: " ++ s ++ ": " ++ (show constr) ++ "\n") $-} (constr:c2, v')
(Nothing) -> error $ "Unbound function var " ++ (show vi) ++ " " ++ s
++ " when building dep type constraints."
-- otherwise treat like any other function typed valueassignDepTypes
_ -> do
(c1,t1) <- buildConstrs globalEnv localEnv fe
let t1' = {-addLabelsToArgTermRec (getLabels t2) $ labelRanTermRec (ProdLbl i)-} t1
return (c1 ++ c2 ++ [t1' :=: fun t2 v'], v')
-- dive another level down
(Fun i it e) -> do
(newVarEnv, t1) <- buildForIdxTree it
let newVarEnv' = varMapFromList $ schemeEnvToSchemeExEnv newVarEnv
(cl, t2) <- buildConstrs globalEnv (newVarEnv' `composeVarMaps` localEnv) e
let term = (fun t1 t2)
bindTermInState (Scheme [] term) i
return (cl, term)
-- |Extends the unification function to postpone constraints that contain
-- |Ref's (unexpanded functions) until later.
{-postponeRefsUniferEx ::
MonadicUnifierExtension (FunctionToken TyToken) (StateT [TyConstr] Identity)
postponeRefsUniferEx env con = case con of
--(Ref i :=: t) -> modify (\l -> con:l) >> return (Left [])
--(t :=: Ref i) -> modify (\l -> (Ref i :=: t):l) >> return (Left [])
_ -> return $ Right con-}
-- if the constraint still contains one of these, it cannot be expanded yet
-- because it lacks a concrete function/or dim tuple to deal with. so we
-- should delay this until it is chosen. this may be later in unification, or
-- when filling gaps.
{-termsToDelay = ["FPair", "FSeq", "GFst", "GSnd", "GRem", "DFst", "DSnd"]
isTermToDelay :: TyTerm -> Bool
isTermToDelay (Term (Tok (Ty n)) _) = elem n termsToDelay
isTermToDelay _ = False-}
-- TODO Problem: now that some constraints can't be expanded until
-- others have been, we must keep retrying delayed constraints, until
-- none of them can be expanded, at which point we must fill gaps, and
-- then try and unify again.
-- NEED:
-- a new unify that jumps over bad constraints, trying others until
-- it is left with a set where none of them can be unified.
simplifyFunsUniferEx :: Monad m => MonadicUnifierExtension ExpLbl (FunctionToken TyToken) (StateT [(TyTerm, TyTerm)] (IdxMonad m))
simplifyFunsUniferEx env con@(a :=: b) = return $ Right con
-- |Unify all constraints ignoring those with a Ref on one side
-- |and returning them at the end if the unification succeeds
{-unifyAllButRefs :: Monad m => [TyConstr] ->
IdxMonad m (Either (VarSubsts TyTerm, [TyConstr]) TyConstr)
unifyAllButRefs cl = do
either <- evalStateT (evalStateT (monadicUnifyTrans cl) simplifyFunsUniferEx) emptyTermEnv
case either of
(Left sl) -> do
let subs = Variables.fromList $ map (\(Var i :|-> e) -> (i,e)) sl
return $ Left (subs, map (applyVarSubstsToConstr subs) refCl)
(Right con) -> return $ Right con-}
-- |Unify all constraints ignoring those with a Ref on one side
-- |and returning them at the end if the unification succeeds
unify :: Monad m => [TyConstr] ->
(IdxMonad m) (Either ([(TyTerm, TyTerm)], VarSubsts TyTerm) (TyConstr, VarSubsts TyTerm))
unify cl = do
(either, subs1) <- runStateT (evalStateT (evalStateT (monadicUnifyTrans [Tok $ Ty "FBoth"] cl) simplifyFunsUniferEx) emptyTermEnv) []
if subs1 /= [] then error $ "DepTyAss:unify: no subs should be stored in the state here.\n" else return ()
case either of
(Left sl) -> do
let subs2 = Variables.fromList $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2/DepTyAss:unify:lambda only takes vars! " ++ (show v)) $ isVar v, e)) sl
return $ Left (subs1, subs2)
(Right (con,sl)) -> do
let subs2 = Variables.fromList $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2/DepTyAss:unify:lambda only takes vars! " ++ (show v)) $ isVar v, e)) sl
return $ Right (con, subs2)
-- |Check that the constraints are all disjoint (no circular variables)
checkConstraints :: [TyConstr] -> [TyConstr]
checkConstraints l = l'
where l' = map (\(a :=: b) -> if (not $ Data.Set.null $ (getVars a) `intersection` (getVars b))
then error $ "Types:DepTypeAssignment:circlular constraint: " ++ (show (a :=: b)) ++ "\n of \n" ++ (show l)
else (a :=: b) ) l
-- |DANGER! If applyDimGensInEnv can keep on producing new constraints
-- |then this will never terminate!
solveDepConstrs :: Monad m => TyEnv -> [TyConstr] -> IdxMonad m TyEnv
solveDepConstrs tyEnv cl = do
-- check constaints are disjoint (no circular vars)
let cl1 = checkConstraints cl
-- try and unify them (ignoring refs)
res <- unify cl1
case res of
Left (subs1, subs2) -> do
-- apply extra subs made due to simplification to type env
let tyEnv1 = map (\(i, Scheme l t) -> (i, Scheme l $ applyTermSubsts subs1 t)) tyEnv
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs2 s)) tyEnv
--return tyEnv2
-- simplify any remaining unsimplified embedded func and dim generators in tyEnv
--(tyEnv3, cl2, simpSubs) <- applyDimGensInEnv tyEnv2
--let tyEnv4 = map (\(i, Scheme l t) -> (i, Scheme l $ applyTermSubsts simpSubs t)) tyEnv3
let tyEnv4 = tyEnv2
iw <- newidST dtvids
case {-cl2-} [] of
-- if no more constraints produced, return env
[] -> return $ trace' ("\nno extra constrs\n" ++ (show iw)) $ tyEnv4
-- if more constraints, solve them too
cl3 -> trace' ("\nrecur solveDepConstrs:\n" ++ (show cl3) ++ "\n" ++ (show iw)) $ solveDepConstrs tyEnv4 cl3
Right (c@(a :=: b), subs) -> do
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs s)) tyEnv
error $ "Dependent type assignment failed on constraint:\n" ++ (show c) ++ "\n of \n" ++ (show cl) ++ "\n with \n" ++ (show tyEnv)
assignDepTypes :: Monad m => VarMap TySchemeEx -> Expr -> IdxMonad m TyEnv
assignDepTypes varEnv expr = do
-- create constraints
((cl,_),tyEnv) <- runStateT (buildConstrs varEnv IM.empty expr) emptyTermEnv
-- solve constrs
tyEnv' <- solveDepConstrs tyEnv $ trace' ("Constraints:\n" ++ (intercalate "\n" $ map show cl)) $ cl
--error $ intercalate "\n" $ map show cl
return tyEnv'
-- |DANGER! If applyDimGensInEnv can keep on producing new constraints
-- |then this will never terminate!
solveDepConstrs2 :: Monad m => TyEnv -> [TyConstr] -> IdxMonad m (Either TyEnv (TyConstr,TyEnv))
solveDepConstrs2 tyEnv cl = do
-- check constaints are disjoint (no circular vars)
let cl1 = checkConstraints cl
-- try and unify them (ignoring refs)
res <- unify cl1
case res of
Left (subs1, subs2) -> do
-- apply extra subs made due to simplification to type env
let tyEnv1 = map (\(i, Scheme l t) -> (i, Scheme l $ applyTermSubsts subs1 t)) tyEnv
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs2 s)) tyEnv1
--return tyEnv2
-- simplify any remaining unsimplified embedded func and dim generators in tyEnv
{-(tyEnv3, cl2, simpSubs) <- applyDimGensInEnv tyEnv2
let tyEnv4 = map (\(i, Scheme l t) -> (i, Scheme l $ applyTermSubsts simpSubs t)) tyEnv3
iw <- newidST dtvids
case cl2 of
-- if no more constraints produced, return env
[] -> return $ trace' ("\nno extra constrs\n" ++ (show iw)) $ Left tyEnv4
-- if more constraints, solve them too
cl3 -> trace' ("\nrecur solveDepConstrs:\n" ++ (show cl3) ++ "\n" ++ (show iw)) $ solveDepConstrs2 tyEnv4 cl3-}
return $ Left tyEnv2
Right (c@(a :=: b), subs) -> do
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs s)) tyEnv
return $ Right (c, tyEnv2)
assignDepTypes2 :: Monad m => VarMap TySchemeEx -> Expr -> IdxMonad m (Either TyEnv (TyConstr, TyEnv))
assignDepTypes2 varEnv expr = do
-- create constraints
((cl,_),tyEnv) <- runStateT (buildConstrs varEnv IM.empty expr) emptyTermEnv
-- solve constrs
res <- solveDepConstrs2 tyEnv $ trace' (
"Constraints:\n" ++ (intercalate "\n" $ map show cl) ++ "\n" ++
"TyEnv:\n" ++ (intercalate "\n" $ map show tyEnv) ++ "\n") $ cl
--error $ intercalate "\n" $ map show cl
return res
-- |assignFunDepTypes varEnv domTy expr. Returns the types of the expressions in expr
-- |where expr is a function type, and domTy is the type of the function's domain.
assignFunDepTypes :: Monad m => VarMap TySchemeEx -> TyTerm -> Expr -> IdxMonad m TyEnv
assignFunDepTypes varEnv domTy expr = case expr of
(Fun eid idxTree bodyExp) -> do
-- create constraints
((cl,funTy1),tyEnv) <- runStateT (buildConstrs varEnv IM.empty expr) emptyTermEnv
-- create constraint between funType and domainType
ranTyVid <- newidST dtvids
let cl' = (funTy1 :=: fun domTy (Var ranTyVid)):cl
-- solve consts
tyEnv' <- solveDepConstrs tyEnv $ trace' ("assignFunDepTypes: " ++ (show $ head cl') ++ "\n") $cl'
return tyEnv'
other -> error $ "DepTypeAssignment:assignFunDepTypes: Requires a fun expr: " ++ (show expr)
-- -------- New 26/06/2014 -------------------
trySimplifiedPair :: (Monad m, MonadCatch m) =>
MonadicUnifierExtension ExpLbl (FunctionToken TyToken) (StateT ([TyConstr], Int) (IdxMonad m))
trySimplifiedPair env con@(a :=: b) = do
-- call unify without this extension (so it can't get into an infinite loop of simplification)
(res, subs1) <- runStateT (evalStateT (evalStateT (monadicUnifyTrans [Tok $ Ty "FBoth"] {-trace ("trySimpPair: " ++ (show con) ++ "\n") $-} [a :=: b]) defaultMonadicUnifierExtension) emptyTermEnv) []
if (subs1 :: [Subst TyTerm]) /= [] then error $ "DepTypeAssignment:simplifyFunsUnifierEx:monadicUnifyTrans returned non empty subs: " ++ (show subs1) else return ()
case res of
-- if pass, then return the subs as constraints
-- and mark that one simplifyable constraint has been solved
Left subs2 -> do
-- check if subs has a cycle
if hasCycle DS.empty $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2:DepTyAss:trySimpPair:lambad only takes vars! " ++ (show v)) $ isVar v, getVarIdsInTerm e)) subs2
-- then fail
then return $ Right (a :=: b)
-- otherwise
else do
-- transform subs
let subs3 = Variables.fromList $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2/DepTyAss:simplifyFunsUnifierEx3:lambda only takes vars! " ++ (show v)) $ isVar v, e)) subs2
-- check that subs2 leads to valid functions (i.e. doesn't expand params to be non tuples of vars)
let a' = applyVarSubsts subs3 a
let b' = applyVarSubsts subs3 b
if areValidFuns [] a' && areValidFuns [] b'
then do
-- if valid funs
-- increment pass count
return $ trace ("simplifyFunsUnifierEx3: passed: " ++ (show $ fmap showEmbeddedFuns $ fmap stripTermLabelsRec $ a :=: b) ++ "\n with: " ++ (show subs2) ++ "\n" ++ " giving: " ++ (show $ fmap showEmbeddedFuns $ fmap stripTermLabelsRec $ a' :=: b') ++ "\n\n") $ Left $ map (\(v :|-> t) -> v :=: t) subs2
else do
-- if not valid funs, then no simplification will make them valid, so fail here
return $ Right (a :=: b)
-- if fail, then add to constraints in state
-- to be unified later
Right (con,subs3) -> do
return $ trace ("simplifyFunsUnifierEx3: delayed: " ++ (show $ fmap showEmbeddedFuns $ fmap stripTermLabelsRec $ a :=: b) ++ "\n") $ Right (a :=: b)
-- |Extends the unification function to simplify any embedded functions
-- |before trying to unify.
simplifyFunsUniferEx3 :: (Monad m, MonadCatch m) =>
IM.IntMap Expr -> IM.IntMap TySchemeEx ->
MonadicUnifierExtension ExpLbl (FunctionToken TyToken) (StateT ([TyConstr], Int) (IdxMonad m))
simplifyFunsUniferEx3 expEnv varTys env con@(a :=: b) = do
-- if fun terms/simplifyable
if isFunTerm a && isFunTerm b
then do
-- simplify both terms
(a', cl1) <- lift $ evalEmFunM (fullySimplifyFun a) expEnv varTys
(b', cl2) <- lift $ evalEmFunM (fullySimplifyFun b) expEnv varTys
-- TODO CURRENTLY IGNORES cl1 and cl2
--if cl1 /= [] then error $ "DepTypeAssignment:simplifyFunUnifierEx:fullySimplifyFun a: returned non empty constraints: " ++ (show cl1) else return ()
--if cl2 /= [] then error $ "DepTypeAssignment:simplifyFunUnifierEx:fullySimplifyFun b: returned non empty constraints: " ++ (show cl2) else return ()
-- get FBoth lists
let al = fromFBoth a'
let bl = fromFBoth b'
let allpairs = [ (at :=: bt) | at <- al, bt <- bl ]
-- try all combinations of terms from each fboth until one unifies
resl <- mapM (trySimplifiedPair env) {- trace ("allpairs: " ++ (show allpairs) ++ "\nal:" ++ (show al) ++ "\nbl: " ++ (show bl) ++ "\n" ++ (show a) ++ "\n" ++ (show b) ++ "\n\n")-} allpairs
let res = find isLeft resl
case res of
-- if at least one pair of constraints unified, then inc pass count
Just (Left conl) -> do
modify (\(cl,passCount) -> (cl,passCount+1))
return $ Left conl
-- if no pair of constraints unified, then add con to state to be unified later
Nothing -> do
modify (\(cl,passCount) -> ((a :=: b):cl, passCount))
return $ Left []
-- if not simplifyable, then fail
else return $ Right con
-- TODO debug!!!
-- |Unify all constraints. If a constraint doesn't pass and is simplifyable
-- |it is simplified and then re-tried. If a simplifyable constraint fails
-- |it is saved to be tried again later. Unification fails if either a
-- |non-simplifyable constraint is broken, or if we get to a fixed point where
-- |none of the remaining saved simplifyable constraints will pass.
unify3 :: (Monad m, MonadCatch m) =>
IM.IntMap Expr -> IM.IntMap TySchemeEx -> VarSubsts TyTerm -> [TyConstr] ->
(IdxMonad m) (Either (VarSubsts TyTerm) (TyConstr, VarSubsts TyTerm))
unify3 expEnv varTys subsSoFar cl = do
-- check for empty constraint list
if cl == []
then return $ Left subsSoFar
else do
-- unify constraints
(either, (residualCl, passCount)) <- runStateT (evalStateT (evalStateT (monadicUnifyTrans [Tok $ Ty "FBoth"] cl) $ simplifyFunsUniferEx3 expEnv {-(trace ("cl: " ++ (intercalate "\n" $ map show cl) ++ "\n\n"))-} varTys) emptyTermEnv) ([],0)
case either of
-- if success then check for any residual constraints
(Left sl) -> do
-- transform subs
let subs2 = Variables.fromList $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2/DepTyAss:unify3:lambda only takes vars! " ++ (show v)) $ isVar v, e)) sl
let subs3 = Variables.composeVarSubsts subs2 subsSoFar
-- if there are residual constraints
if residualCl /= []
then if passCount > 0
-- and some constraints passed then iterate
then do
-- apply subs to cons
let residualCl' = map (\(a :=: b) -> (applyVarSubsts subs3 a) :=: (applyVarSubsts subs3 b)) residualCl
-- iterate (tail recur)
unify3 expEnv varTys subs3 residualCl'
-- or no constraints passed then fail
else return $ Right (head residualCl, subs3)
-- else if there are no residual constraints then pass
else return $ Left subs3
-- if fail, then failed
(Right (con,sl)) -> do
let subs2 = Variables.fromList $ map (\(v :|-> e) -> (fromMaybe (error $ "Types2/DepTyAss:unify3:lambda only takes vars! " ++ (show v)) $ isVar v, e)) sl
let subs3 = Variables.composeVarSubsts subs2 subsSoFar
return $ Right (con, subs3)
-- |solveDepConstrs3 expEnv varTys tyEnv consL. Tries to solve all constraints
-- |in consL, returning the substitutions that make the constraints in consL
-- |unify if they unify, or the subsititutions so far and the failing constraint
-- |if it fails.
solveDepConstrs3 :: (Monad m, MonadCatch m) =>
IM.IntMap Expr -> IM.IntMap TySchemeEx ->
TyEnv -> [TyConstr] -> IdxMonad m (Either TyEnv (TyConstr,TyEnv))
solveDepConstrs3 expEnv varTys tyEnv cl = do
-- check constaints are disjoint (no circular vars)
let cl1 = checkConstraints cl
-- try and unify them (ignoring refs)
res <- unify3 expEnv varTys Variables.emptyVarSubsts cl1
case res of
-- passed
Left subs -> do
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs s)) tyEnv
return $ Left tyEnv2
-- failed
Right (c@(a :=: b), subs) -> do
-- apply substituions to type env
let tyEnv2 = map (\(i,s) -> (i, applyVarSubstsToScheme subs s)) tyEnv
return $ Right (c, tyEnv2)
-- |assignDepTypes3 varEnv expr. Tries to infer the types for expr, building and solving constraints
-- |and simplifying those constraints that can be (i.e. embedded functions).
assignDepTypes3' :: (Monad m, MonadCatch m) => VarMap TySchemeEx -> Expr -> IM.IntMap Expr -> IdxMonad m (Either TyEnv (TyConstr, TyEnv))
assignDepTypes3' varEnv expr expEnv = do
-- create constraints
((cl,_),tyEnv) <- runStateT (buildConstrs varEnv IM.empty expr) emptyTermEnv
-- solve constrs
res <- solveDepConstrs3 expEnv varEnv tyEnv $ trace' (
"Constraints:\n" ++ (intercalate "\n" $ map show cl) ++ "\n" ++
"TyEnv:\n" ++ (intercalate "\n" $ map show tyEnv) ++ "\n") $ cl
--error $ intercalate "\n" $ map show cl
return res
-- |assignDepTypes3 varEnv expr. Tries to infer the types for expr, building and solving constraints
-- |and simplifying those constraints that can be (i.e. embedded functions).
assignDepTypes3 :: (Monad m, MonadCatch m) => VarMap TySchemeEx -> Expr -> IdxMonad m (Either TyEnv (TyConstr, TyEnv))
assignDepTypes3 varEnv expr = do
-- create expr environment
let expEnv = IM.fromList $ E.makeExprMap expr
-- assign types
assignDepTypes3' varEnv expr expEnv
| flocc-net/flocc | v0.1/Compiler/Types2/DepTypeAssignment.hs | apache-2.0 | 31,359 | 38 | 25 | 6,506 | 7,376 | 3,898 | 3,478 | 336 | 13 |
module FP_Core where
import FPPrac.Trees
{-
Extension of CoreIntro.hs:
- instructions as program *in* the processor,
- stack now is list of fixed length,i
- clock added
- program counter + stack pointer added,
- instruction EndProg added,
- update operaton (<~) added,
-}
-- ========================================================================
type Stack = [Int]
-- Excercise 4 --
type Heap = [Int]
data Op = Add | Mul | Sub
deriving Show
data Instr = PushConst Int
| PushAddr Int
| Store Int
| Calc Op
| PushPC
| EndRep
| EndProg
deriving Show
-----------------
data Tick = Tick
-- Excercise 5 --
data Expr = Const Int -- for constants
| Variable Int -- for variables
| BinExpr Op Expr Expr -- for ``binary expressions''
-----------------
-- Excercise 5 --
data Stmnt = Assign Int Expr
| Repeat Expr [Stmnt]
-----------------
class CodeGen a where
codeGen :: a -> [Instr]
-- Excercise 2,6 --
instance CodeGen Expr where
codeGen (BinExpr op l r) = codeGen l ++ codeGen r ++ [Calc op]
codeGen (Variable i) = [PushAddr i]
codeGen (Const n) = [PushConst n]
-----------------
-- Excercise 5,6,7 --
instance CodeGen Stmnt where
codeGen (Assign i expr) = codeGen expr ++ [Store i]
codeGen (Repeat expr stmnts) = codeGen expr ++ [PushPC] ++ concat (map codeGen stmnts) ++ [EndRep]
-----------------
-- Excercise 3,6,7 --
class ToRose a where
toRose :: a -> RoseTree
instance ToRose Stmnt where
toRose (Assign n expr) = RoseNode ("var " ++ show n ++ " :=") [toRose expr]
toRose (Repeat expr stmnts) = RoseNode ("repeat") [toRose expr, RoseNode ("block") $ map toRose stmnts]
instance ToRose Expr where
toRose (Const n) = RoseNode (show n) []
toRose (Variable i) = RoseNode ("var " ++ show i) []
toRose (BinExpr op l r) = RoseNode (show op) [toRose l, toRose r]
-----------------
-- ========================================================================
-- Processor functions
xs <~ (i,a) = take i xs ++ [a] ++ drop (i+1) xs
-- Put value a on position i in list xs
alu op = case op of
Add -> (+)
Mul -> (*)
Sub -> (-)
{-core :: [Instr] -> (Int,Int,Stack) -> Tick -> (Int,Int,Stack)
core instrs (pc,sp,stack) tick = case instrs!!pc of
Push n -> (pc+1, sp+1 , stack <~ (sp,n))
Calc op -> (pc+1, sp-1 , stack <~ (sp-2,v))
where
v = alu op (stack!!(sp-2)) (stack!!(sp-1))
EndProg -> (-1, sp, stack)-}
core :: [Instr] -> (Int,Int,Heap,Stack) -> Tick -> (Int,Int,Heap,Stack)
core instrs (pc,sp,heap,stack) tick = case instrs!!pc of
-- Excercise 4 --
PushConst n -> (pc+1, sp+1 , heap, stack <~ (sp,n))
PushAddr i -> (pc+1, sp+1, heap, stack <~ (sp,heap!!i))
Store i -> (pc+1, sp-1, heap <~ (i,stack!!(sp-1)), stack)
-----------------
Calc op -> (pc+1, sp-1 , heap, stack <~ (sp-2,v))
where
v = alu op (stack!!(sp-2)) (stack!!(sp-1))
-- Excercise 7 --
PushPC -> (pc+1, sp+1, heap, stack <~ (sp,pc+1))
EndRep -> (progc, sp', heap, stack <~ (sp-2, stack!!(sp-2)-1))
where progc | stack!!(sp-2) > 1 = stack!!(sp-1)
| otherwise = pc+1
sp' | stack!!(sp-2) > 1 = sp
| otherwise = sp-2
-----------------
EndProg -> (-1, sp, heap, stack)
-- ========================================================================
-- example Program for expression: (((2*10) + (3*(4+11))) * (12+5))
-- Tree of this expression of type Expr (result of parsing):
expr = BinExpr Mul
(BinExpr Add
(BinExpr Mul
(Const 2)
(Const 10))
(BinExpr Mul
(Const 3)
(BinExpr Add
(Const 4)
(Const 11))))
(BinExpr Add
(Const 12)
(Const 5))
stmnt = Assign 1 (BinExpr Mul
(BinExpr Add
(BinExpr Mul
(Const 2)
(Const 10))
(BinExpr Mul
(Const 3)
(BinExpr Add
(Const 4)
(Const 11))))
(BinExpr Add
(Const 12)
(Const 5)))
stmnt2 = Assign 1 (BinExpr Mul
(BinExpr Add
(BinExpr Mul
(Variable 1)
(Const 10))
(BinExpr Mul
(Const 3)
(BinExpr Add
(Const 4)
(Const 11))))
(BinExpr Add
(Const 12)
(Const 5)))
stmnt3 = Assign 5 (BinExpr Mul
(BinExpr Add
(BinExpr Mul
(Variable 1)
(Const 10))
(BinExpr Mul
(Const 3)
(BinExpr Add
(Const 4)
(Const 11))))
(BinExpr Add
(Const 12)
(Const 5)))
stmnt4 = Repeat expr [stmnt2, stmnt3]
stmnt5 = Repeat (
BinExpr Add
(Const 3)
(Const 5)
)
[
(
Assign 4
(BinExpr Mul
(BinExpr Add
(BinExpr Mul
(Const 2)
(Const 10))
(BinExpr Mul
(Const 3)
(BinExpr Add
(Const 4)
(Const 11)
)
)
)
(BinExpr Add
(Const 12)
(Const 5)
)
)
)
]
stmnt6 = Repeat ( Const 5 )
[
Repeat (Const 4)
[Assign 4 (BinExpr Add (Const 1) (Variable 4))]
]
onetotenprog = [
(Assign 1 (Const 1)),
(Repeat ( Const 10 )
[
Assign 2 (
BinExpr Add
(Variable 2)
(Variable 1)
),
Assign 1 (
BinExpr Add
(Variable 1)
(Const 1)
)
])
]
-- The program that results in the value of the expression (1105):
{-prog = [ Push 2
, Push 10
, Calc Mul
, Push 3
, Push 4
, Push 11
, Calc Add
, Calc Mul
, Calc Add
, Push 12
, Push 5
, Calc Add
, Calc Mul
, EndProg
]-}
prog = [ PushConst 2
, PushConst 10
, Calc Mul
, PushConst 3
, PushConst 4
, PushConst 11
, Calc Add
, Calc Mul
, Calc Add
, PushConst 12
, PushConst 5
, Calc Add
, Calc Mul
, Store 5
, PushConst 111
, PushAddr 5
, EndProg
]
-- Testing
clock = repeat Tick
emptyStack = replicate 16 0
emptyHeap = replicate 8 0
test = putStr
$ unlines
$ map show
$ takeWhile (\(pc,_,_,_) -> pc /= -1)
$ scanl (core prog) (0,0,emptyHeap,emptyStack) clock
test2 p = putStr
$ unlines
$ map show
$ takeWhile (\(pc,_,_,_) -> pc /= -1)
$ scanl (core p) (0,0,emptyHeap,emptyStack) clock
-- ========================================================================
-- New Stuff
-- ========================================================================
{-codeGen :: Expr -> [Instr]
codeGen expr = codeGen' expr ++ [EndProg]
codeGen' :: Expr -> [Instr]
codeGen' (BinExpr op l r) = codeGen' l ++ codeGen' r ++ [Calc op]
codeGen' (Variable i) = [PushAddr i]
codeGen' (Const n) = [PushConst n]
codeGen'' :: Stmnt -> [Instr]
codeGen'' (Assign i expr) = codeGen' expr ++ [Store i, EndProg]-}
codeGen' :: (CodeGen a) => [a] -> [Instr]
codeGen' a = concat (map (codeGen) a) ++ [EndProg]
{-codeGen' :: (CodeGen a) => a -> [Instr]
codeGen' a = codeGen a ++ [EndProg]-}
{-exprToRose :: Expr -> RoseTree
exprToRose (Const n) = RoseNode (show n) []
exprToRose (Variable i) = RoseNode ("var " ++ show i) []
exprToRose (BinExpr op l r) = RoseNode (show op) [exprToRose l, exprToRose r]-}
| wouwouwou/2017_module_8 | src/haskell/series5/FP_Core.hs | apache-2.0 | 8,849 | 0 | 18 | 3,793 | 2,257 | 1,203 | 1,054 | 178 | 7 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE Unsafe #-}
{-# OPTIONS_HADDOCK show-extensions #-}
{-|
Copyright : (C) 2015, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
= Initialising a BlockRAM with a data file #usingramfiles#
BlockRAM primitives that can be initialised with a data file. The BNF grammar
for this data file is simple:
@
FILE = LINE+
LINE = BIT+
BIT = '0'
| '1'
@
Consecutive @LINE@s correspond to consecutive memory addresses starting at @0@.
For example, a data file @memory.bin@ containing the 9-bit unsigned number
@7@ to @13@ looks like:
@
000000111
000001000
000001001
000001010
000001011
000001100
000001101
@
We can instantiate a BlockRAM using the content of the above file like so:
@
topEntity :: Signal (Unsigned 3) -> Signal (Unsigned 9)
topEntity rd = 'CLaSH.Class.BitPack.unpack' '<$>' 'blockRamFile' d7 \"memory.bin\" 0 rd (signal False) 0
@
In the example above, we basically treat the BlockRAM as an synchronous ROM.
We can see that it works as expected:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ topEntity (fromList [3..5])__
[10,11,12]
@
However, we can also interpret the same data as a tuple of a 6-bit unsigned
number, and a 3-bit signed number:
@
topEntity2 :: Signal (Unsigned 3) -> Signal (Unsigned 6,Signed 3)
topEntity2 rd = 'CLaSH.Class.BitPack.unpack' '<$>' 'blockRamFile' d7 \"memory.bin\" 0 rd (signal False) 0
@
And then we would see:
@
__>>> import qualified Data.List as L__
__>>> L.tail $ sampleN 4 $ topEntity2 (fromList [3..5])__
[(1,2),(1,3)(1,-4)]
@
-}
module CLaSH.Prelude.BlockRam.File
( -- * BlockRAM synchronised to the system clock
blockRamFile
, blockRamFilePow2
-- * BlockRAM synchronised to an arbitrary clock
, blockRamFile'
, blockRamFilePow2'
-- * Internal
, blockRamFile#
, initMem
)
where
import Control.Monad (when)
import Control.Monad.ST.Lazy (ST,runST)
import Data.Array.MArray (newListArray,readArray,writeArray)
import Data.Array.ST (STArray)
import Data.Char (digitToInt)
import Data.Maybe (listToMaybe)
import GHC.TypeLits (KnownNat, type (^))
import Numeric (readInt)
import System.IO.Unsafe (unsafePerformIO)
import CLaSH.Promoted.Nat (SNat,snat,snatToInteger)
import CLaSH.Sized.BitVector (BitVector)
import CLaSH.Signal (Signal)
import CLaSH.Signal.Explicit (Signal', SClock, register', systemClock)
import CLaSH.Signal.Bundle (bundle')
import CLaSH.Sized.Unsigned (Unsigned)
{-# INLINE blockRamFile #-}
-- | Create a blockRAM with space for @n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
-- * See "CLaSH.Prelude.BlockRam.File#usingramfiles" for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFile :: (KnownNat m, Enum addr)
=> SNat n -- ^ Size of the blockRAM
-> FilePath -- ^ File describing the initial content
-- of the blockRAM
-> Signal addr -- ^ Write address @w@
-> Signal addr -- ^ Read address @r@
-> Signal Bool -- ^ Write enable
-> Signal (BitVector m) -- ^ Value to write (at address @w@)
-> Signal (BitVector m)
-- ^ Value of the @blockRAM@ at address @r@ from the previous clock
-- cycle
blockRamFile = blockRamFile' systemClock
{-# INLINE blockRamFilePow2 #-}
-- | Create a blockRAM with space for 2^@n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
-- * See "CLaSH.Prelude.BlockRam.File#usingramfiles" for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFilePow2 :: forall n m . (KnownNat m, KnownNat n, KnownNat (2^n))
=> FilePath -- ^ File describing the initial
-- content of the blockRAM
-> Signal (Unsigned n) -- ^ Write address @w@
-> Signal (Unsigned n) -- ^ Read address @r@
-> Signal Bool -- ^ Write enable
-> Signal (BitVector m) -- ^ Value to write (at address @w@)
-> Signal (BitVector m)
-- ^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFilePow2 = blockRamFile' systemClock (snat :: SNat (2^n))
{-# INLINE blockRamFilePow2' #-}
-- | Create a blockRAM with space for 2^@n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
-- * See "CLaSH.Prelude.BlockRam.File#usingramfiles" for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFilePow2' :: forall clk n m . (KnownNat m, KnownNat n, KnownNat (2^n))
=> SClock clk -- ^ 'Clock' to synchronize to
-> FilePath -- ^ File describing the initial
-- content of the blockRAM
-> Signal' clk (Unsigned n) -- ^ Write address @w@
-> Signal' clk (Unsigned n) -- ^ Read address @r@
-> Signal' clk Bool -- ^ Write enable
-> Signal' clk (BitVector m) -- ^ Value to write (at address @w@)
-> Signal' clk (BitVector m)
-- ^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFilePow2' clk = blockRamFile' clk (snat :: SNat (2^n))
{-# INLINE blockRamFile' #-}
-- | Create a blockRAM with space for @n@ elements
--
-- * __NB__: Read value is delayed by 1 cycle
-- * __NB__: Initial output value is 'undefined'
-- * __NB__: This function might not work for specific combinations of
-- code-generation backends and hardware targets. Please check the support table
-- below:
--
-- @
-- | VHDL | Verilog | SystemVerilog |
-- ===============+==========+==========+===============+
-- Altera/Quartus | Broken | Works | Works |
-- Xilinx/ISE | Works | Works | Works |
-- ASIC | Untested | Untested | Untested |
-- ===============+==========+==========+===============+
-- @
--
-- Additional helpful information:
--
-- * See "CLaSH.Prelude.BlockRam#usingrams" for more information on how to use a
-- Block RAM.
-- * See "CLaSH.Prelude.BlockRam.File#usingramfiles" for more information on how
-- to instantiate a Block RAM with the contents of a data file.
-- * See "CLaSH.Sized.Fixed#creatingdatafiles" for ideas on how to create your
-- own data files.
blockRamFile' :: (KnownNat m, Enum addr)
=> SClock clk -- ^ 'Clock' to synchronize to
-> SNat n -- ^ Size of the blockRAM
-> FilePath -- ^ File describing the initial
-- content of the blockRAM
-> Signal' clk addr -- ^ Write address @w@
-> Signal' clk addr -- ^ Read address @r@
-> Signal' clk Bool -- ^ Write enable
-> Signal' clk (BitVector m) -- ^ Value to write (at address @w@)
-> Signal' clk (BitVector m)
-- ^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFile' clk sz file wr rd en din = blockRamFile# clk sz file
(fromEnum <$> wr)
(fromEnum <$> rd)
en din
{-# NOINLINE blockRamFile# #-}
-- | blockRamFile primitive
blockRamFile# :: KnownNat m
=> SClock clk -- ^ 'Clock' to synchronize to
-> SNat n -- ^ Size of the blockRAM
-> FilePath -- ^ File describing the initial
-- content of the blockRAM
-> Signal' clk Int -- ^ Write address @w@
-> Signal' clk Int -- ^ Read address @r@
-> Signal' clk Bool -- ^ Write enable
-> Signal' clk (BitVector m) -- ^ Value to write (at address @w@)
-> Signal' clk (BitVector m)
-- ^ Value of the @blockRAM@ at address @r@ from the previous
-- clock cycle
blockRamFile# clk sz file wr rd en din = register' clk undefined dout
where
szI = fromInteger $ snatToInteger sz
dout = runST $ do
arr <- newListArray (0,szI-1) (initMem file)
traverse (ramT arr) (bundle' clk (wr,rd,en,din))
ramT :: STArray s Int e -> (Int,Int,Bool,e) -> ST s e
ramT ram (w,r,e,d) = do
d' <- readArray ram r
when e (writeArray ram w d)
return d'
{-# NOINLINE initMem #-}
-- | __NB:__ Not synthesisable
initMem :: KnownNat n => FilePath -> [BitVector n]
initMem = unsafePerformIO . fmap (map parseBV . lines) . readFile
where
parseBV s = case parseBV' s of
Just i -> fromInteger i
Nothing -> error ("Failed to parse: " ++ s)
parseBV' = fmap fst . listToMaybe . readInt 2 (`elem` "01") digitToInt
| Ericson2314/clash-prelude | src/CLaSH/Prelude/BlockRam/File.hs | bsd-2-clause | 12,033 | 0 | 15 | 3,642 | 1,285 | 751 | 534 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Application.HXournal.Coroutine.Default
-- Copyright : (c) 2011, 2012 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Application.HXournal.Coroutine.Default where
import Graphics.UI.Gtk hiding (get,set)
import Application.HXournal.Type.Event
import Application.HXournal.Type.Enum
import Application.HXournal.Type.Coroutine
import Application.HXournal.Type.Canvas
import Application.HXournal.Type.XournalState
import Application.HXournal.Type.Clipboard
import Application.HXournal.Accessor
import Application.HXournal.GUI.Menu
import Application.HXournal.Script
import Application.HXournal.Coroutine.Callback
import Application.HXournal.Coroutine.Commit
import Application.HXournal.Coroutine.Draw
import Application.HXournal.Coroutine.Pen
import Application.HXournal.Coroutine.Eraser
import Application.HXournal.Coroutine.Highlighter
import Application.HXournal.Coroutine.Scroll
import Application.HXournal.Coroutine.Page
import Application.HXournal.Coroutine.Select
import Application.HXournal.Coroutine.File
import Application.HXournal.Coroutine.Mode
import Application.HXournal.Coroutine.Window
-- import Application.HXournal.Coroutine.Network
import Application.HXournal.Coroutine.Layer
import Application.HXournal.ModelAction.Window
import Application.HXournal.Type.Window
import Application.HXournal.Device
import Control.Applicative ((<$>))
import Control.Monad.Coroutine
import Control.Monad.Coroutine.SuspensionFunctors
import qualified Control.Monad.State as St
import Control.Monad.Trans
import qualified Data.IntMap as M
import Data.Maybe
import Control.Category
import Data.Label
import Prelude hiding ((.), id)
import Data.IORef
import Application.HXournal.Type.PageArrangement
import Data.Xournal.Simple (Dimension(..))
import Data.Xournal.Generic
-- |
initViewModeIOAction :: MainCoroutine HXournalState
initViewModeIOAction = do
oxstate <- getSt
let ui = get gtkUIManager oxstate
agr <- liftIO $ uiManagerGetActionGroups ui
Just ra <- liftIO $ actionGroupGetAction (head agr) "CONTA"
let wra = castToRadioAction ra
connid <- liftIO $ wra `on` radioActionChanged $ \x -> do
y <- viewModeToMyEvent x
get callBack oxstate y
return ()
let xstate = set pageModeSignal (Just connid) oxstate
putSt xstate
return xstate
-- |
guiProcess :: MainCoroutine ()
guiProcess = do
initialize
liftIO $ putStrLn "hi!"
liftIO $ putStrLn "welcome to hxournal"
changePage (const 0)
xstate <- initViewModeIOAction
let cinfoMap = getCanvasInfoMap xstate
assocs = M.toList cinfoMap
f (cid,cinfobox) = do let canvas = getDrawAreaFromBox cinfobox
(w',h') <- liftIO $ widgetGetSize canvas
defaultEventProcess (CanvasConfigure cid
(fromIntegral w')
(fromIntegral h'))
mapM_ f assocs
sequence_ (repeat dispatchMode)
-- |
initCoroutine :: DeviceList -> Window -> IO (TRef,SRef)
initCoroutine devlst window = do
let st0 = (emptyHXournalState :: HXournalState)
sref <- newIORef st0
tref <- newIORef (undefined :: SusAwait)
(r,st') <- St.runStateT (resume guiProcess) st0
writeIORef sref st'
either (writeIORef tref) (error "what?") r
let st0new = set deviceList devlst
. set rootOfRootWindow window
. set callBack (bouncecallback tref sref)
$ st'
writeIORef sref st0new
ui <- getMenuUI tref sref
putStrLn "hi"
let st1 = set gtkUIManager ui st0new
initcvs = defaultCvsInfoSinglePage { _canvasId = 1 }
initcvsbox = CanvasInfoBox initcvs
st2 = set frameState (Node 1)
. updateFromCanvasInfoAsCurrentCanvas initcvsbox
$ st1 { _cvsInfoMap = M.empty }
(st3,cvs,_wconf) <- constructFrame st2 (get frameState st2)
(st4,wconf') <- eventConnect st3 (get frameState st3)
let startingXstate = set frameState wconf' . set rootWindow cvs $ st4
writeIORef sref startingXstate
return (tref,sref)
-- |
initialize :: MainCoroutine ()
initialize = do ev <- await
liftIO $ putStrLn $ show ev
case ev of
Initialized -> return ()
_ -> initialize
-- |
dispatchMode :: MainCoroutine ()
dispatchMode = getSt >>= return . xojstateEither . get xournalstate
>>= either (const viewAppendMode) (const selectMode)
-- |
viewAppendMode :: MainCoroutine ()
viewAppendMode = do
r1 <- await
case r1 of
PenDown cid pbtn pcoord -> do
ptype <- getPenType
case (ptype,pbtn) of
(PenWork,PenButton1) -> penStart cid pcoord
(PenWork,PenButton2) -> eraserStart cid pcoord
(PenWork,PenButton3) -> do
updateXState (return . set isOneTimeSelectMode YesBeforeSelect)
modeChange ToSelectMode
selectLassoStart cid pcoord
(EraserWork,_) -> eraserStart cid pcoord
(HighlighterWork,_) -> highlighterStart cid pcoord
_ -> return ()
_ -> defaultEventProcess r1
-- |
selectMode :: MainCoroutine ()
selectMode = do
r1 <- await
case r1 of
PenDown cid _pbtn pcoord -> do
ptype <- return . get (selectType.selectInfo) =<< lift St.get
case ptype of
SelectRectangleWork -> selectRectStart cid pcoord
SelectRegionWork -> selectLassoStart cid pcoord
_ -> return ()
PenColorChanged c -> selectPenColorChanged c
PenWidthChanged w -> selectPenWidthChanged w
_ -> defaultEventProcess r1
-- |
defaultEventProcess :: MyEvent -> MainCoroutine ()
defaultEventProcess (UpdateCanvas cid) = invalidate cid
defaultEventProcess (Menu m) = menuEventProcess m
defaultEventProcess (HScrollBarMoved cid v) = hscrollBarMoved cid v
defaultEventProcess (VScrollBarMoved cid v) = vscrollBarMoved cid v
defaultEventProcess (VScrollBarStart cid _v) = vscrollStart cid
defaultEventProcess PaneMoveStart = paneMoveStart
defaultEventProcess (CanvasConfigure cid w' h') =
doCanvasConfigure cid (CanvasDimension (Dim w' h'))
defaultEventProcess ToViewAppendMode = modeChange ToViewAppendMode
defaultEventProcess ToSelectMode = modeChange ToSelectMode
defaultEventProcess ToSinglePage = viewModeChange ToSinglePage
defaultEventProcess ToContSinglePage = viewModeChange ToContSinglePage
defaultEventProcess _ = return ()
-- |
askQuitProgram :: MainCoroutine ()
askQuitProgram = do
dialog <- liftIO $ messageDialogNew Nothing [DialogModal]
MessageQuestion ButtonsOkCancel
"Current canvas is not saved yet. Will you close hxournal?"
res <- liftIO $ dialogRun dialog
case res of
ResponseOk -> do
liftIO $ widgetDestroy dialog
liftIO $ mainQuit
_ -> do
liftIO $ widgetDestroy dialog
return ()
-- |
menuEventProcess :: MenuEvent -> MainCoroutine ()
menuEventProcess MenuQuit = do
xstate <- getSt
liftIO $ putStrLn "MenuQuit called"
if get isSaved xstate
then liftIO $ mainQuit
else askQuitProgram
menuEventProcess MenuPreviousPage = changePage (\x->x-1)
menuEventProcess MenuNextPage = changePage (+1)
menuEventProcess MenuFirstPage = changePage (const 0)
menuEventProcess MenuLastPage = do
totalnumofpages <- (either (M.size. get g_pages) (M.size . get g_selectAll)
. xojstateEither . get xournalstate) <$> getSt
changePage (const (totalnumofpages-1))
menuEventProcess MenuNewPageBefore = newPage PageBefore
menuEventProcess MenuNewPageAfter = newPage PageAfter
menuEventProcess MenuDeletePage = deleteCurrentPage
menuEventProcess MenuNew = askIfSave fileNew
menuEventProcess MenuAnnotatePDF = askIfSave fileAnnotatePDF
menuEventProcess MenuUndo = undo
menuEventProcess MenuRedo = redo
menuEventProcess MenuOpen = askIfSave fileOpen
menuEventProcess MenuSave = fileSave
menuEventProcess MenuSaveAs = fileSaveAs
menuEventProcess MenuCut = cutSelection
menuEventProcess MenuCopy = copySelection
menuEventProcess MenuPaste = pasteToSelection
menuEventProcess MenuDelete = deleteSelection
-- menuEventProcess MenuNetCopy = clipCopyToNetworkClipboard
-- menuEventProcess MenuNetPaste = clipPasteFromNetworkClipboard
menuEventProcess MenuZoomIn = pageZoomChangeRel ZoomIn
menuEventProcess MenuZoomOut = pageZoomChangeRel ZoomOut
menuEventProcess MenuNormalSize = pageZoomChange Original
menuEventProcess MenuPageWidth = pageZoomChange FitWidth
menuEventProcess MenuPageHeight = pageZoomChange FitHeight
menuEventProcess MenuHSplit = eitherSplit SplitHorizontal
menuEventProcess MenuVSplit = eitherSplit SplitVertical
menuEventProcess MenuDelCanvas = deleteCanvas
menuEventProcess MenuNewLayer = makeNewLayer
menuEventProcess MenuNextLayer = gotoNextLayer
menuEventProcess MenuPrevLayer = gotoPrevLayer
menuEventProcess MenuGotoLayer = startGotoLayerAt
menuEventProcess MenuDeleteLayer = deleteCurrentLayer
menuEventProcess MenuUseXInput = do
xstate <- getSt
let ui = get gtkUIManager xstate
agr <- liftIO ( uiManagerGetActionGroups ui >>= \x ->
case x of
[] -> error "No action group? "
y:_ -> return y )
uxinputa <- liftIO (actionGroupGetAction agr "UXINPUTA")
>>= maybe (error "MenuUseXInput") (return . castToToggleAction)
b <- liftIO $ toggleActionGetActive uxinputa
let cmap = getCanvasInfoMap xstate
canvases = map (getDrawAreaFromBox) . M.elems $ cmap
if b
then mapM_ (\x->liftIO $ widgetSetExtensionEvents x [ExtensionEventsAll]) canvases
else mapM_ (\x->liftIO $ widgetSetExtensionEvents x [ExtensionEventsNone] ) canvases
menuEventProcess MenuPressureSensitivity = updateXState pressSensAction
where pressSensAction xstate = do
let ui = get gtkUIManager xstate
agr <- liftIO ( uiManagerGetActionGroups ui >>= \x ->
case x of
[] -> error "No action group? "
y:_ -> return y )
pressrsensa <- liftIO (actionGroupGetAction agr "PRESSRSENSA")
>>= maybe (error "MenuPressureSensitivity")
(return . castToToggleAction)
b <- liftIO $ toggleActionGetActive pressrsensa
return (set (variableWidthPen.penInfo) b xstate)
menuEventProcess MenuRelaunch = liftIO $ relaunchApplication
menuEventProcess m = liftIO $ putStrLn $ "not implemented " ++ show m
| wavewave/hxournal | lib/Application/HXournal/Coroutine/Default.hs | bsd-2-clause | 10,812 | 0 | 20 | 2,284 | 2,693 | 1,355 | 1,338 | 234 | 7 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDragEnterEvent.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:22
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QDragEnterEvent (
QqqDragEnterEvent(..), QqDragEnterEvent(..)
,QqqDragEnterEvent_nf(..), QqDragEnterEvent_nf(..)
,qDragEnterEvent_delete
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqqDragEnterEvent x1 where
qqDragEnterEvent :: x1 -> IO (QDragEnterEvent ())
class QqDragEnterEvent x1 where
qDragEnterEvent :: x1 -> IO (QDragEnterEvent ())
instance QqDragEnterEvent ((QDragEnterEvent t1)) where
qDragEnterEvent (x1)
= withQDragEnterEventResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragEnterEvent cobj_x1
foreign import ccall "qtc_QDragEnterEvent" qtc_QDragEnterEvent :: Ptr (TQDragEnterEvent t1) -> IO (Ptr (TQDragEnterEvent ()))
instance QqqDragEnterEvent ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragEnterEvent (x1, x2, x3, x4, x5)
= withQDragEnterEventResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragEnterEvent1" qtc_QDragEnterEvent1 :: Ptr (TQPoint t1) -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragEnterEvent ()))
instance QqDragEnterEvent ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragEnterEvent (x1, x2, x3, x4, x5)
= withQDragEnterEventResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
foreign import ccall "qtc_QDragEnterEvent2" qtc_QDragEnterEvent2 :: CInt -> CInt -> CLong -> Ptr (TQMimeData t3) -> CLong -> CLong -> IO (Ptr (TQDragEnterEvent ()))
class QqqDragEnterEvent_nf x1 where
qqDragEnterEvent_nf :: x1 -> IO (QDragEnterEvent ())
class QqDragEnterEvent_nf x1 where
qDragEnterEvent_nf :: x1 -> IO (QDragEnterEvent ())
instance QqDragEnterEvent_nf ((QDragEnterEvent t1)) where
qDragEnterEvent_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QDragEnterEvent cobj_x1
instance QqqDragEnterEvent_nf ((QPoint t1, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qqDragEnterEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent1 cobj_x1 (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
instance QqDragEnterEvent_nf ((Point, DropActions, QMimeData t3, MouseButtons, KeyboardModifiers)) where
qDragEnterEvent_nf (x1, x2, x3, x4, x5)
= withObjectRefResult $
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QDragEnterEvent2 cpoint_x1_x cpoint_x1_y (toCLong $ qFlags_toInt x2) cobj_x3 (toCLong $ qFlags_toInt x4) (toCLong $ qFlags_toInt x5)
qDragEnterEvent_delete :: QDragEnterEvent a -> IO ()
qDragEnterEvent_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QDragEnterEvent_delete cobj_x0
foreign import ccall "qtc_QDragEnterEvent_delete" qtc_QDragEnterEvent_delete :: Ptr (TQDragEnterEvent a) -> IO ()
| keera-studios/hsQt | Qtc/Gui/QDragEnterEvent.hs | bsd-2-clause | 3,847 | 0 | 17 | 581 | 1,060 | 566 | 494 | 66 | 1 |
{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Numeric.MixedType.Eq
Description : Bottom-up typed equality comparisons
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module Numeric.MixedTypes.Eq
(
-- * Equality checks
HasEq, HasEqAsymmetric(..), (==), (/=)
, HasEqCertainly, HasEqCertainlyAsymmetric
, notCertainlyDifferentFrom, certainlyEqualTo, certainlyNotEqualTo
, (?==?), (!==!), (!/=!)
-- ** Tests
, specHasEq, specHasEqNotMixed
, specConversion
-- ** Specific comparisons
, CanTestNaN(..)
, CanTestFinite(..)
, CanTestInteger(..)
, CanTestZero(..), specCanTestZero
, CanPickNonZero(..), specCanPickNonZero
)
where
import Utils.TH.DeclForTypes
import Numeric.MixedTypes.PreludeHiding
import qualified Prelude as P
import Text.Printf
import Data.Ratio
import Test.Hspec
import Test.QuickCheck as QC
import Control.CollectErrors ( CollectErrors, CanBeErrors )
import qualified Control.CollectErrors as CE
import Numeric.MixedTypes.Literals
import Numeric.MixedTypes.Bool
infix 4 ==, /=
infix 4 ?==?
infix 4 !==!, !/=!
{---- Equality tests -----}
type HasEq t1 t2 =
(HasEqAsymmetric t1 t2, HasEqAsymmetric t2 t1,
EqCompareType t1 t2 ~ EqCompareType t2 t1)
type HasEqCertainlyAsymmetric t1 t2 =
(HasEqAsymmetric t1 t2, CanTestCertainly (EqCompareType t1 t2))
type HasEqCertainly t1 t2 =
(HasEq t1 t2, CanTestCertainly (EqCompareType t1 t2))
class (IsBool (EqCompareType a b)) => HasEqAsymmetric a b where
type EqCompareType a b
type EqCompareType a b = Bool -- default
equalTo :: a -> b -> (EqCompareType a b)
-- default equalToA via Prelude for (->) and Bool:
default equalTo :: (EqCompareType a b ~ Bool, a~b, P.Eq a) => a -> b -> EqCompareType a b
equalTo = (P.==)
notEqualTo :: a -> b -> (EqCompareType a b)
-- default notEqualToA via equalToA for Bool:
default notEqualTo ::
(CanNegSameType (EqCompareType a b)) =>
a -> b -> (EqCompareType a b)
notEqualTo a b = not $ equalTo a b
(==) :: (HasEqAsymmetric a b) => a -> b -> EqCompareType a b
(==) = equalTo
(/=) :: (HasEqAsymmetric a b) => a -> b -> EqCompareType a b
(/=) = notEqualTo
certainlyEqualTo :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
certainlyEqualTo a b = isCertainlyTrue $ a == b
certainlyNotEqualTo :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
certainlyNotEqualTo a b = isCertainlyTrue $ a /= b
notCertainlyDifferentFrom :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
notCertainlyDifferentFrom a b = isNotFalse $ a == b
(?==?) :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
(?==?) = notCertainlyDifferentFrom
(!==!) :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
(!==!) = certainlyEqualTo
(!/=!) :: (HasEqCertainlyAsymmetric a b) => a -> b -> Bool
(!/=!) = certainlyNotEqualTo
{-|
HSpec properties that each implementation of HasEq should satisfy.
-}
specHasEq ::
_ => T t1 -> T t2 -> T t3 -> Spec
specHasEq (T typeName1 :: T t1) (T typeName2 :: T t2) (T typeName3 :: T t3) =
describe (printf "HasEq %s %s, HasEq %s %s" typeName1 typeName2 typeName2 typeName3) $ do
it "has reflexive ==" $ do
property $ \ (x :: t1) -> not $ isCertainlyFalse (x == x)
it "has anti-reflexive /=" $ do
property $ \ (x :: t1) -> not $ isCertainlyTrue (x /= x)
it "has stronly commutative ==" $ do
property $ \ (x :: t1) (y :: t2) -> (x == y) `stronglyEquivalentTo` (y == x)
it "has stronly commutative /=" $ do
property $ \ (x :: t1) (y :: t2) -> (x /= y) `stronglyEquivalentTo` (y /= x)
it "has stronly transitive ==" $ do
property $ \ (x :: t1) (y :: t2) (z :: t3) -> ((x == y) && (y == z)) `stronglyImplies` (y == z)
{-|
HSpec properties that each implementation of HasEq should satisfy.
-}
specHasEqNotMixed ::
_ => T t -> Spec
specHasEqNotMixed (t :: T t) = specHasEq t t t
{-|
HSpec property of there-and-back conversion.
-}
specConversion :: -- this definition cannot be in Literals because it needs HasEq
(Arbitrary t1, Show t1, HasEqCertainly t1 t1) =>
T t1 -> T t2 -> (t1 -> t2) -> (t2 -> t1) -> Spec
specConversion (T typeName1 :: T t1) (T typeName2 :: T t2) conv12 conv21 =
describe "conversion" $ do
it (printf "%s -> %s -> %s" typeName1 typeName2 typeName1) $ do
property $ \ (x1 :: t1) ->
x1 ?==? (conv21 $ conv12 x1)
instance HasEqAsymmetric () ()
instance HasEqAsymmetric Bool Bool
instance HasEqAsymmetric Char Char
instance HasEqAsymmetric Int Int
instance HasEqAsymmetric Integer Integer
instance HasEqAsymmetric Rational Rational
instance HasEqAsymmetric Double Double
instance HasEqAsymmetric Int Integer where
equalTo = convertFirst equalTo
instance HasEqAsymmetric Integer Int where
equalTo = convertSecond equalTo
instance HasEqAsymmetric Int Rational where
equalTo = convertFirst equalTo
instance HasEqAsymmetric Rational Int where
equalTo = convertSecond equalTo
instance HasEqAsymmetric Integer Rational where
equalTo = convertFirst equalTo
instance HasEqAsymmetric Rational Integer where
equalTo = convertSecond equalTo
instance HasEqAsymmetric Integer Double where
equalTo n d = ((P.floor d :: Integer) == n) && (n == (P.ceiling d :: Integer))
instance HasEqAsymmetric Double Integer where
equalTo d n = ((P.floor d :: Integer) == n) && (n == (P.ceiling d :: Integer))
instance HasEqAsymmetric Int Double where
equalTo n d = equalTo (integer n) d
instance HasEqAsymmetric Double Int where
equalTo d n = equalTo (integer n) d
instance
(HasEqAsymmetric a1 b1,
HasEqAsymmetric a2 b2,
CanAndOrAsymmetric (EqCompareType a1 b1) (EqCompareType a2 b2),
IsBool (AndOrType (EqCompareType a1 b1) (EqCompareType a2 b2))
) =>
HasEqAsymmetric (a1,a2) (b1,b2) where
type EqCompareType (a1,a2) (b1,b2) =
AndOrType (EqCompareType a1 b1) (EqCompareType a2 b2)
equalTo (a1,a2) (b1,b2) =
(a1 == b1) && (a2 == b2)
instance
(HasEqAsymmetric ((a1,a2), a3) ((b1,b2), b3))
=>
HasEqAsymmetric (a1,a2,a3) (b1,b2,b3) where
type EqCompareType (a1,a2,a3) (b1,b2,b3) =
EqCompareType ((a1,a2), a3) ((b1,b2), b3)
equalTo (a1,a2,a3) (b1,b2,b3) =
((a1,a2), a3) == ((b1,b2), b3)
instance
(HasEqAsymmetric ((a1,a2,a3), a4) ((b1,b2,b3), b4))
=>
HasEqAsymmetric (a1,a2,a3,a4) (b1,b2,b3,b4) where
type EqCompareType (a1,a2,a3,a4) (b1,b2,b3,b4) =
EqCompareType ((a1,a2,a3), a4) ((b1,b2,b3), b4)
equalTo (a1,a2,a3,a4) (b1,b2,b3,b4) =
((a1,a2,a3), a4) == ((b1,b2,b3), b4)
instance
(HasEqAsymmetric ((a1,a2,a3,a4), a5) ((b1,b2,b3,b4), b5))
=>
HasEqAsymmetric (a1,a2,a3,a4,a5) (b1,b2,b3,b4,b5) where
type EqCompareType (a1,a2,a3,a4,a5) (b1,b2,b3,b4,b5) =
EqCompareType ((a1,a2,a3,a4), a5) ((b1,b2,b3,b4), b5)
equalTo (a1,a2,a3,a4,a5) (b1,b2,b3,b4,b5) =
((a1,a2,a3,a4), a5) == ((b1,b2,b3,b4), b5)
instance (HasEqAsymmetric a b) => HasEqAsymmetric [a] [b] where
type EqCompareType [a] [b] = EqCompareType a b
equalTo [] [] = convertExactly True
equalTo (x:xs) (y:ys) = (x == y) && (xs == ys)
equalTo _ _ = convertExactly False
instance (HasEqAsymmetric a b) => HasEqAsymmetric (Maybe a) (Maybe b) where
type EqCompareType (Maybe a) (Maybe b) = EqCompareType a b
equalTo Nothing Nothing = convertExactly True
equalTo (Just x) (Just y) = (x == y)
equalTo _ _ = convertExactly False
instance
(HasEqAsymmetric a b, CanBeErrors es)
=>
HasEqAsymmetric (CollectErrors es a) (CollectErrors es b)
where
type EqCompareType (CollectErrors es a) (CollectErrors es b) =
CollectErrors es (EqCompareType a b)
equalTo = CE.lift2 equalTo
$(declForTypes
[[t| Bool |], [t| Maybe Bool |], [t| Integer |], [t| Int |], [t| Rational |], [t| Double |]]
(\ t -> [d|
instance
(HasEqAsymmetric $t b, CanBeErrors es)
=>
HasEqAsymmetric $t (CollectErrors es b)
where
type EqCompareType $t (CollectErrors es b) =
CollectErrors es (EqCompareType $t b)
equalTo = CE.liftT1 equalTo
instance
(HasEqAsymmetric a $t, CanBeErrors es)
=>
HasEqAsymmetric (CollectErrors es a) $t
where
type EqCompareType (CollectErrors es a) $t =
CollectErrors es (EqCompareType a $t)
equalTo = CE.lift1T equalTo
|]))
{---- Checking whether it is finite -----}
class CanTestNaN t where
isNaN :: t -> Bool
default isNaN :: (P.RealFloat t) => t -> Bool
isNaN = P.isNaN
class CanTestFinite t where
isInfinite :: t -> Bool
default isInfinite :: (P.RealFloat t) => t -> Bool
isInfinite = P.isInfinite
isFinite :: t -> Bool
default isFinite :: (P.RealFloat t) => t -> Bool
isFinite x = (not $ P.isNaN x) && (not $ P.isInfinite x)
instance CanTestNaN Double
instance CanTestFinite Double
instance CanTestNaN Integer where
isNaN = const False
instance CanTestNaN Rational where
isNaN = const False
instance CanTestFinite Int where
isInfinite = const False
isFinite = const True
instance CanTestFinite Integer where
isInfinite = const False
isFinite = const True
instance CanTestFinite Rational where
isInfinite = const False
isFinite = const True
instance (CanTestNaN t, CanBeErrors es) => (CanTestNaN (CollectErrors es t)) where
isNaN = CE.withErrorOrValue (const False) isNaN
instance (CanTestFinite t, CanBeErrors es) => (CanTestFinite (CollectErrors es t)) where
isInfinite = CE.withErrorOrValue (const False) isInfinite
isFinite = CE.withErrorOrValue (const False) isFinite
{---- Checking whether it is an integer -----}
class CanTestInteger t where
certainlyNotInteger :: t -> Bool
certainlyInteger :: t -> Bool
certainlyInteger s = case certainlyIntegerGetIt s of Just _ -> True; _ -> False
certainlyIntegerGetIt :: t -> Maybe Integer
instance CanTestInteger Integer where
certainlyNotInteger _ = False
certainlyInteger _ = True
certainlyIntegerGetIt n = Just n
instance CanTestInteger Int where
certainlyNotInteger _ = False
certainlyInteger _ = True
certainlyIntegerGetIt n = Just (integer n)
instance CanTestInteger Rational where
certainlyNotInteger q = (denominator q /= 1)
certainlyInteger q = (denominator q == 1)
certainlyIntegerGetIt q
| denominator q == 1 = Just (numerator q)
| otherwise = Nothing
instance CanTestInteger Double where
certainlyNotInteger d =
isInfinite d || isNaN d ||
(P.floor d :: Integer) P.< P.ceiling d
certainlyIntegerGetIt d
| isFinite d && (dF P.== dC) = Just dF
| otherwise = Nothing
where
dF = P.floor d
dC = P.ceiling d
instance (CanTestInteger t, CanBeErrors es) => (CanTestInteger (CollectErrors es t)) where
certainlyNotInteger = CE.withErrorOrValue (const False) certainlyNotInteger
certainlyIntegerGetIt = CE.withErrorOrValue (const Nothing) certainlyIntegerGetIt
{---- Checking whether it is zero -----}
class CanTestZero t where
isCertainlyZero :: t -> Bool
isCertainlyNonZero :: t -> Bool
default isCertainlyZero :: (HasEqCertainly t Integer) => t -> Bool
isCertainlyZero a = isCertainlyTrue (a == 0)
default isCertainlyNonZero :: (HasEqCertainly t Integer) => t -> Bool
isCertainlyNonZero a = isCertainlyTrue (a /= 0)
{-|
HSpec properties that each implementation of CanTestZero should satisfy.
-}
specCanTestZero ::
(CanTestZero t, ConvertibleExactly Integer t)
=>
T t -> Spec
specCanTestZero (T typeName :: T t) =
describe (printf "CanTestZero %s" typeName) $ do
it "converted non-zero Integer is not isCertainlyZero" $ do
property $ \ (x :: Integer) ->
x /= 0 ==> (not $ isCertainlyZero (convertExactly x :: t))
it "converted non-zero Integer is isCertainlyNonZero" $ do
property $ \ (x :: Integer) ->
x /= 0 ==> (isCertainlyNonZero (convertExactly x :: t))
it "converted 0.0 is not isCertainlyNonZero" $ do
(isCertainlyNonZero (convertExactly 0 :: t)) `shouldBe` False
instance CanTestZero Int
instance CanTestZero Integer
instance CanTestZero Rational
instance CanTestZero Double
instance (CanTestZero t, CanBeErrors es) => (CanTestZero (CollectErrors es t)) where
isCertainlyZero = CE.withErrorOrValue (const False) isCertainlyZero
isCertainlyNonZero = CE.withErrorOrValue (const False) isCertainlyNonZero
class CanPickNonZero t where
{-|
Given a list @[(a1,b1),(a2,b2),...]@ and assuming that
at least one of @a1,a2,...@ is non-zero, pick one of them
and return the corresponding pair @(ai,bi)@.
If none of @a1,a2,...@ is zero, either throws an exception
or loops forever.
The default implementation is based on a `CanTestZero` instance
and is not parallel.
-}
pickNonZero :: [(t,s)] -> Maybe (t,s)
default pickNonZero :: (CanTestZero t, Show t) => [(t,s)] -> Maybe (t,s)
pickNonZero list = aux list
where
aux ((a,b):rest)
| isCertainlyNonZero a = Just (a,b)
| otherwise = aux rest
aux [] = Nothing
{-|
HSpec properties that each implementation of CanPickNonZero should satisfy.
-}
specCanPickNonZero ::
(CanPickNonZero t, CanTestZero t, ConvertibleExactly Integer t, Show t, Arbitrary t)
=>
T t -> Spec
specCanPickNonZero (T typeName :: T t) =
describe (printf "CanPickNonZero %s" typeName) $ do
it "picks a non-zero element if there is one" $ do
property $ \ (xs :: [(t, ())]) ->
or (map (isCertainlyNonZero . fst) xs) -- if at least one is non-zero
==>
(case pickNonZero xs of
Just (v, _) -> isCertainlyNonZero v
_ -> False)
it "returns Nothing when all the elements are 0" $ do
case pickNonZero [(convertExactly i :: t, ()) | i <- [0,0,0]] of
Nothing -> True
_ -> False
instance CanPickNonZero Int
instance CanPickNonZero Integer
instance CanPickNonZero Rational
instance (CanPickNonZero a, CanBeErrors es) => (CanPickNonZero (CollectErrors es a)) where
pickNonZero =
fmap (\(v,s) -> (pure v,s))
. pickNonZero
. CE.filterValuesWithoutError
. (map (\(vCN,s) -> fmap (\v -> (v,s)) vCN))
| michalkonecny/mixed-types-num | src/Numeric/MixedTypes/Eq.hs | bsd-3-clause | 14,141 | 49 | 21 | 2,911 | 4,289 | 2,393 | 1,896 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Lazyfoo.Lesson05 (main) where
import Control.Applicative
import Control.Monad
import Foreign.C.Types
import Linear
import qualified SDL
import Paths_sdl2 (getDataFileName)
screenWidth, screenHeight :: CInt
(screenWidth, screenHeight) = (640, 480)
loadSurface :: SDL.Surface -> FilePath -> IO SDL.Surface
loadSurface screenSurface path = do
loadedSurface <- getDataFileName path >>= SDL.loadBMP
desiredFormat <- SDL.surfaceFormat screenSurface
SDL.convertSurface loadedSurface desiredFormat <* SDL.freeSurface loadedSurface
main :: IO ()
main = do
SDL.initialize [SDL.InitVideo]
window <- SDL.createWindow "SDL Tutorial" SDL.defaultWindow { SDL.windowInitialSize = V2 screenWidth screenHeight }
SDL.showWindow window
screenSurface <- SDL.getWindowSurface window
stretchedSurface <- loadSurface screenSurface "examples/lazyfoo/stretch.bmp"
let
loop = do
let collectEvents = do
e <- SDL.pollEvent
case e of
Nothing -> return []
Just e' -> (e' :) <$> collectEvents
events <- collectEvents
let quit = any (== SDL.QuitEvent) $ map SDL.eventPayload events
SDL.blitScaled stretchedSurface Nothing screenSurface Nothing
SDL.updateWindowSurface window
unless quit loop
loop
SDL.freeSurface stretchedSurface
SDL.destroyWindow window
SDL.quit
| svenkeidel/sdl2 | examples/lazyfoo/Lesson05.hs | bsd-3-clause | 1,403 | 0 | 21 | 277 | 388 | 188 | 200 | 38 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Graphics.GChart.ChartItems.Labels where
import Graphics.GChart.Types
import Graphics.GChart.ChartItems.Util
import Data.List(intercalate)
import Control.Monad(liftM)
import Data.Maybe(catMaybes, fromJust)
-- Chart Title
instance ChartItem ChartTitle where
set title = updateChart $ \chart -> chart { chartTitle = Just title }
encode title = ("chtt", titleStr title) : [("chts", chts) | chts /= ""]
where chts = encodeColorAndFontSize title
encodeColorAndFontSize title =
intercalate "," $ catMaybes [titleColor title,
liftM show . titleFontSize $ title]
-- Chart Legend
instance ChartItem ChartLegend where
set legend = updateChart $ \chart -> chart { chartLegend = Just legend }
encode (Legend labels position) = encodeTitle : encodePosition position where
encodeTitle = ("chdl", intercalate "|" labels)
encodePosition Nothing = []
encodePosition (Just p) = let pos = case p of
LegendBottom -> "b"
LegendTop -> "t"
LegendVBottom -> "bv"
LegendVTop -> "tv"
LegendRight -> "r"
LegendLeft -> "l"
in asList ("chdlp",pos)
-- Chart Labels (Pie Chart, Google-O-Meter)
instance ChartItem ChartLabels where
set labels = updateChart $ \chart -> chart { chartLabels = Just labels }
encode (ChartLabels labels) = asList ("chl", intercalate "|" labels)
-- Axis Styles and Labels
instance ChartItem ChartAxes where
set axes = updateChart $ \chart -> chart { chartAxes = Just axes }
encode axes = filter (/= ("","")) $ map (\f -> f axes) [encodeAxesTypes,
encodeAxesLabels,
encodeAxesPositions,
encodeAxesRanges,
encodeAxesStyles]
convertFieldToString encoder field = intercalate "|" .
map encoder .
filter (\(_,maybeField) -> maybeField /= Nothing) .
indexed . map field
indexed = zip [0..]
encodeFieldToParams fieldParam fieldStr | fieldStr == "" = ("","")
| otherwise = (fieldParam, fieldStr)
encodeAxesTypes axes = ("chxt",a) where
a = intercalate "," $ map toParam axes
toParam axes = case axisType axes of
AxisBottom -> "x"
AxisTop -> "t"
AxisLeft -> "y"
AxisRight -> "r"
-- axis labels
strAxisLabels (idx,Just labels) = show idx ++ ":|" ++ intercalate "|" labels
strAxesLabels = convertFieldToString strAxisLabels axisLabels
encodeAxesLabels = encodeFieldToParams "chxl" . strAxesLabels
-- axis positions
strAxisPositions (idx, Just positions) = show idx ++ "," ++ intercalate "," (map show positions)
strAxesPositions = convertFieldToString strAxisPositions axisPositions
encodeAxesPositions = encodeFieldToParams "chxp" . strAxesPositions
-- axis ranges
strAxisRange (idx, Just range) = show idx ++ "," ++ intercalate "," (encodeRange range)
where encodeRange (Range (start,end) interval) | interval == Nothing = [show start, show end]
| otherwise = [show start, show end, show (fromJust interval)]
strAxesRanges = convertFieldToString strAxisRange axisRange
encodeAxesRanges = encodeFieldToParams "chxr" . strAxesRanges
-- axis style
strAxisStyle (idx, Just style) = show idx ++ "," ++ intercalate "," (catMaybes (encodeStyle style))
where encodeStyle (Style a b c d e) = [Just a,
liftM show b,
liftM encodeAlign c,
liftM encodeDrawingControl d,
liftM id e]
encodeAlign c = case c of
AxisStyleLeft -> "-1"
AxisStyleCenter -> "0"
AxisStyleRight -> "1"
encodeDrawingControl d = case d of
DrawLines -> "l"
DrawTicks -> "t"
DrawLinesTicks -> "lt"
strAxesStyles = convertFieldToString strAxisStyle axisStyle
encodeAxesStyles = encodeFieldToParams "chxs" . strAxesStyles
-- TODO: Data Point Labels
| deepakjois/hs-gchart | Graphics/GChart/ChartItems/Labels.hs | bsd-3-clause | 5,684 | 0 | 14 | 2,702 | 1,131 | 587 | 544 | 79 | 5 |
{-# OPTIONS -Wall -fno-warn-unused-do-bind #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RankNTypes #-}
-- | Generate a flow chart by from annotations from a code base.
--
-- The syntax is as follows:
--
-- @
-- expr <- label \/ next \/ do \/ if \/ task
-- label <- \"label\" name
-- task <- \"task\" text
-- next <- \"next\" name \/ \"trigger\" name
-- do <- \"do\" text
-- if <- \"if\" name \"\\n\" \"then\" name (\"\\n\" \"else\" name)?
-- @
--
-- where @name@ and @text@ are both arbitrary text.
--
-- A @label@ is used to label a node in the graph. @next@ is used to
-- link the current node to another node by its label. The text for a
-- node is written by @do@, which explains what this node does, or by
-- using @if@ which makes this node a conditional which goes to one of
-- two possible nodes.
--
-- Example (assuming '\/\//' to be the declaration prefix):
--
-- @
-- \/\/\/ label main
-- \/\/\/ if Logged in?
-- \/\/\/ then display_overview
-- \/\/\/ else display_login
-- \/\/\/ label display_overview
-- \/\/\/ do Display overview.
-- \/\/\/ next display_event
-- \/\/\/ next display_paper
-- \/\/ Event list code here.
-- event_list();
-- \/\/\/ label display_login
-- \/\/\/ do Display login.
-- \/\/\/ next try_login
-- \/\/ Login display code here.
-- display_login();
-- \/\/\/ label try_login
-- \/\/\/ do Check login.
-- \/\/\/ next main
-- \/\/\/ trigger log_access_time
-- \/\/ Login attempt code here.
-- if(check_login()) log_attempt_success();
-- \/\/\/ label display_event
-- \/\/\/ do Display a single event.
-- \/\/\/ next display_paper
-- \/\/ Event list code here.
-- display_event();
-- \/\/\/ label display_paper
-- \/\/\/ do Display a single paper.
-- \/\/ Paper display code here.
-- display_paper();
-- \/\/\/ label log_access_time
-- \/\/\/ task Log login accesses.
-- log_login();
-- @
--
-- In other words: You have a main page which either displays a login
-- screen or lists the user's events if logged in. From the events
-- page you can get to the event page.
--
-- Custom syntax can be used, too. Example:
--
-- @
-- {- # bar -}
-- SELECT * FROM mysql;
-- @
--
module Development.Flo
(-- * Types
Node (..),
Type (..),
Edge (..),
Decl (..),
Name,
-- * Functions
digraph,
nodesToDot,
declsToNodes,
parseFile)
where
import Control.Applicative
import Control.Monad.Error ()
import Control.Monad.State
import Control.Monad.Writer
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Char
import Data.Maybe
import Data.List
import Text.Parsec hiding ((<|>))
-- | A workflow node.
data Node =
Node { nodeName :: Name
, nodeEdges :: [Edge]
, nodeDesc :: String
, nodeType :: Type
} deriving Show
-- | Type of the node.
data Type = Action | Condition | Background
deriving (Eq,Enum,Show)
-- | A workflow connection.
data Edge =
Edge { edgeLabel :: String
, edgeTo :: Name
} deriving Show
-- | A workflow declaration.
data Decl
= Label Name -- ^ Sets the current node.
| Next Name -- ^ Links to a next node (an edge).
| Do String -- ^ Describes this node.
| Task String -- ^ Run some task (create db entry,
-- delete file, send email etc.).
| If String Name (Maybe Name) -- ^ Makes this node a conditional.
deriving Show
-- | A node name.
newtype Name = Name String
deriving (Eq,Show)
-- | Simple alias for the parser type.
type P = Parsec ByteString ()
-- | Wrap a string up in a digraph.
digraph :: String -> String
digraph x = "digraph G {\n" ++ x ++ "\n}"
-- | Convert a list of nodes to a Graphviz dot document.
nodesToDot :: [Node] -> String
nodesToDot nodes = concat . map nodeToDot $ nodes where
nodeToDot Node{..} =
normalizeName nodeName ++ " [" ++ props ++ "]\n" ++
concat (map (edgeToDot nodeName) nodeEdges)
where props = intercalate ","
["label=" ++ show nodeDesc
,"shape=" ++ case nodeType of
Condition -> "house"
Action -> "box"
Background -> "oval"
]
edgeToDot from Edge{..} = normalizeName from ++ " -> " ++ normalizeName edgeTo ++
" [label=" ++ show edgeLabel ++
",style=" ++ (if trig then "dotted" else "solid") ++
"]\n"
where trig = maybe False ((==Background).nodeType) $
find ((==edgeTo).nodeName) nodes
-- | Normalize a node name to fit Dot syntax.
normalizeName :: Name -> String
normalizeName (Name name) = replace name where
replace [] = []
replace (x:xs) | isDigit x || isLetter x || x== '_' = x : replace xs
| otherwise = "_" ++ show (fromEnum x) ++ replace xs
-- | Converts a list of declarations to a list of nodes.
declsToNodes :: [Decl] -> [Node]
declsToNodes ds = snd $ runWriter (runStateT (go ds) Nothing) where
go (Label name@(Name desc):xs) = do
let setNew = put (Just $ Node name [] desc Action)
get >>= maybe setNew (\x -> do tell [x]; setNew)
go xs
go (Next edge:xs) = do
modify $ fmap $ \node ->
if nodeType node /= Condition
then node { nodeEdges = Edge "" edge : nodeEdges node }
else node
go xs
go (Do desc:xs) = do
modify $ fmap $ \node -> node { nodeDesc = desc }
go xs
go (Task desc:xs) = do
modify $ fmap $ \node -> node { nodeDesc = desc, nodeType = Background }
go xs
go (If cond xthen xelse:xs) = do
modify $ fmap $ \node ->
node { nodeType = Condition
, nodeDesc = cond
, nodeEdges = [Edge "Yes" xthen] ++
maybe [] (return . Edge "No") xelse
}
go xs
go [] = get >>= maybe (return ()) (tell . return)
-- | Parse a source file containing commented declarations.
parseFile :: FilePath -> String -> Maybe String -> IO (Either ParseError [Decl])
parseFile path start end = do
contents <- B.readFile path
return $ parse (parseDeclsInSource startP endP)
path
(contents `mappend` "\n")
where startP = spaces *> string start *> pure ()
endP = maybe (void $ lookAhead newline)
(void.string)
end
void p = p *> pure ()
-- | Parse all line-separated prefixed declarations in a source file.
parseDeclsInSource :: P () -> P () -> P [Decl]
parseDeclsInSource start end = do
ls <- many1 (floComment <|> normalSource) <* eof
return $ catMaybes ls
where floComment = try (Just <$> parseDecl start end)
normalSource = const Nothing <$> manyTill anyChar newline
-- | Parse a declaration (spanning many lines in some cases e.g. "if").
parseDecl :: P () -> P () -> P Decl
parseDecl start end = do
start
keyword <- choice $ map (try.string) ["label","next","do","if","trigger","task"]
space; spaces
value <- manyTill anyChar (try $ lookAhead end)
end
case keyword of
"if" -> parseIfClauses value start end
"next" -> return $ Next $ Name value
"trigger" -> return $ Next $ Name value
"do" -> return $ Do value
"task" -> return $ Task value
_ -> return $ Label $ Name value
-- | Parse the then/else clauses of the if with the given condition.
parseIfClauses :: String -> P () -> P () -> P Decl
parseIfClauses cond start end = do
start
string "then"
space; spaces
value <- manyTill anyChar (try $ lookAhead end)
end
elseClause <- Just <$> (parseElseClause start end) <|> return Nothing
return $ If cond (Name value) elseClause
-- | Parse the else clause for an `if' expression.
parseElseClause :: P () -> P () -> P Name
parseElseClause start end = do
start
string "else"
space; spaces
value <- manyTill anyChar (try $ lookAhead newline)
end
return $ Name value
| sjakobi/flo | src/Development/Flo.hs | bsd-3-clause | 8,160 | 0 | 17 | 2,315 | 1,899 | 1,015 | 884 | 146 | 7 |
import Data.List (sort)
import Data.Function (on)
import Common.Numbers.Primes (primesTo)
import Common.List (minimumBy')
main = print $ (fst answer) * (snd answer) where
primes = primesTo 5000
candidate = [ (p,q) | p <- primes, q <- primes, p*q <= 10000000, check p q ]
value :: (Int, Int) -> Double
value (p,q) = p' * q' / (p' - 1) / (q' - 1) where
p' = fromIntegral p
q' = fromIntegral q
check p q = f (p * q) == f (phi p q) where
f = sort . show
phi p q = (p - 1) * (q - 1)
answer = minimumBy' (compare `on` value) candidate
-- nice try!
-- although I can't ensure this method produces the best answer :(
| foreverbell/project-euler-solutions | src/70.hs | bsd-3-clause | 669 | 0 | 11 | 185 | 296 | 161 | 135 | 15 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Language.Epilog.MIPS.MIPS
( MIPS (..)
, Emips (..)
, BOp (..)
, Register (Zero, Scratch, ScratchF, GP, SP, FP, RA)
, num
, snum
, isFloatReg
, Label
, emitMIPS
, nGeneralRegs
, nFloatRegs
, nTotalRegs
, mkRegister
, mkFloatR
, mkGeneral
) where
--------------------------------------------------------------------------------
import Language.Epilog.Common
import Language.Epilog.IR.TAC (BOp (..), Constant (..), Label (..),
divZeroLabel)
import qualified Language.Epilog.IR.TAC as IR
--------------------------------------------------------------------------------
import Safe (atDef)
import Control.Monad.RWS (RWS, evalRWS, modify, gets, tell)
import Data.Text (Text, pack)
import qualified Prelude as Pre (show)
import Prelude hiding (show)
--------------------------------------------------------------------------------
emitMIPS :: ([Int32], Seq MIPS) -> Text
emitMIPS (sss, mips) = snd $ evalRWS (emips mips) () sss
class Emips a where
emips :: a -> RWS () Text [Int32] ()
instance (Emips a, Foldable f) => Emips (f a) where
emips = mapM_ emips
instance Emips Label where
emips = tpack . IR.lblstr
show :: Show a => a -> Text
show = pack . Pre.show
chow :: Show a => a -> RWS r Text s ()
chow = tell . show
tpack :: String -> RWS r Text s ()
tpack = tell . pack
--------------------------------------------------------------------------------
data Register -- = Zero | V Int | A Int | T Int | S Int | GP | SP | FP | RA
= Zero
| General { num :: Word32 }
| FloatR { num :: Word32 } -- Actually holds (n + nGeneralRegs), i.e., FloatR 30 == $f9
| Scratch { snum :: Word32 } -- different function since Scratch and ScratchF
| ScratchF { snum :: Word32 } -- registers don't have descriptors.
| GP
| SP
| FP
| RA
deriving (Eq, Show, Read, Ord)
generalRegs, floatRegs, scratchRegs, scratchFloatRegs :: [Text]
generalRegs = ("$" <>) <$>
[ "a1", "a2", "a3", "t0", "t1", "t2", "t3", "t4", "t5", "t6"
, "t7", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "t8"
, "t9" ]
floatRegs = ("$f" <>) <$>
[ "1", "2", "3", "4", "5", "6", "7", "8", "9"
, "10", "11" , "13", "14", "15", "16", "17", "18", "19"
, "20", "21", "22", "23", "24", "25", "26", "27", "28", "29"
, "30", "31" ]
scratchRegs = ("$" <>) <$>
["v0", "v1", "a0"]
scratchFloatRegs = ("$f" <>) <$>
[ "0", "12" ]
nGeneralRegs, nFloatRegs, nTotalRegs :: Word32
nGeneralRegs = fromIntegral . length $ generalRegs
nFloatRegs = fromIntegral . length $ floatRegs
nTotalRegs = nGeneralRegs + nFloatRegs
mkGeneral, mkFloatR, mkRegister :: Word32 -> Register
mkGeneral i
| 0 <= i && i < nGeneralRegs = General i
| otherwise = error $ "Invalid general register number " <> Pre.show i
mkFloatR i
| nGeneralRegs <= i && i < nTotalRegs = FloatR i
| otherwise = error $ "Invalid float register number " <> Pre.show i
mkRegister i
| 0 <= i && i < nGeneralRegs = General i
| nGeneralRegs <= i && i < nTotalRegs = FloatR i
| otherwise = error $ "Invalid register number " <> Pre.show i
isFloatReg :: Register -> Bool
isFloatReg = \case
FloatR {} -> True
ScratchF {} -> True
_ -> False
instance Emips Register where
emips Zero = tell "$0"
emips (General n) = tell $ atDef
(internal $ "no general use register " <> Pre.show n)
generalRegs
(fromIntegral n)
emips (FloatR n) = tell $ atDef
(internal $ "no float use register " <> Pre.show n)
floatRegs
(fromIntegral (n - nGeneralRegs))
emips (Scratch n) = tell $ atDef
(internal $ "can't scratch" <> Pre.show n)
scratchRegs
(fromIntegral n)
emips (ScratchF n) = tell $ atDef
(internal $ "can't float scratch" <> Pre.show n)
scratchFloatRegs
(fromIntegral n)
emips GP = tell "$gp"
emips SP = tell "$sp"
emips FP = tell "$fp"
emips RA = tell "$ra"
--------------------------------------------------------------------------------
instance Emips Constant where
emips = tell . \case
IC a -> show a
FC f -> show f
BC b -> if b then "1" else "0"
CC c -> show c
--------------------------------------------------------------------------------
data MIPS
= Comment String
| MLabel Label
-- Sections
| Align
| DataSection
| TextSection
| Global String
-- Declarations
| Data Name Int32
| MString Name String
-- Instructions
| BinOp BOp Register Register Register
| BinOpi BOp Register Register Constant
| I2F Register Register
| I2Fi Register Constant
| F2I Register Register
| F2Ii Register Constant
| LoadA Register String
| LoadI Register Constant
| LoadW Register (Int32, Register)
| LoadWG Register (String, Int32)
| LoadWGR Register (String, Register)
-- | LoadWGRO Register (String, Int32, Register)
| LoadFI Register Constant
| LoadF Register (Int32, Register)
| LoadFG Register (String, Int32)
| LoadFGR Register (String, Register)
-- | LoadFGRO Register (String, Int32, Register)
| Move Register Register
| StoreW Register (Int32, Register)
| StoreWG Register (String, Int32)
| StoreWGR Register (String, Register)
| StoreF Register (Int32, Register)
| StoreFG Register (String, Int32)
| StoreFGR Register (String, Register)
| Syscall
| Slt Register Register Register
| Clts Register Register
| Cles Register Register
| Ceqs Register Register
-- Terminators
| Beq Register Register Label
| Bne Register Register Label
| Bc1t Label
| Bc1f Label
| J Label
| Jr Register
| Jal String
| MIPSProlog
deriving (Eq, Show, Read)
instance Emips MIPS where
emips l = tell (tab l) >> aux l >> tell "\n"
where
tab = \case
Comment {} -> ""
MLabel {} -> ""
Data {} -> ""
MString {} -> ""
F2Ii {} -> ""
_ -> "\t"
aux = \case
Comment str -> tell $ "# " <> pack str
MLabel lbl -> emips lbl >> tell ":"
Data dName dSpace ->
tpack dName >> tell ": .space " >> chow dSpace
MString dName dString ->
tpack dName >> tell ": .asciiz " >> chow dString
Align -> tell ".align 2"
DataSection -> tell ".data"
TextSection -> tell ".text"
Global name -> tell $ ".globl " <> pack name
BinOp op r1 r2 r3 -> case op of
DivI ->
emips (Beq r3 Zero divZeroLabel) >>
tpack "\t" >> emips DivI >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips r3
RemI ->
emips (Beq r3 Zero divZeroLabel) >>
tpack "\t" >> emips DivI >>
emips r2 >> tpack ", " >>
emips r3 >>
tpack "\n\tmfhi " >>
emips r1
_ ->
emips op >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips r3
BinOpi op r1 r2 c -> case op of
DivI ->
emips DivI >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips c
RemI ->
emips DivI >>
emips (Scratch 0) >> tpack ", " >>
emips r2 >> tpack ", " >>
emips c >>
tpack "\n\tmfhi " >>
emips r1
_ ->
emips op >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips c
I2F fr gr ->
tpack "mtc1 " >>
emips gr >> tpack ", " >> emips fr >>
tpack "\n\tcvt.s.w " >>
emips fr >> tpack ", " >> emips fr
I2Fi fr c ->
emips (LoadI (Scratch 0) c) >>
tpack "\tmtc1 " >>
emips (Scratch 0) >> tpack ", " >> emips fr >>
tpack "\n\tcvt.s.w " >>
emips fr >> tpack ", " >> emips fr
F2I gr fr ->
tpack "cvt.w.s " >>
emips (ScratchF 0) >> tpack ", " >> emips fr >>
tpack "\n\tmfc1 " >>
emips gr >> tpack ", " >> emips (ScratchF 0)
F2Ii gr c ->
emips (LoadFI (ScratchF 0) c) >>
tpack "\tcvt.w.s " >>
emips (ScratchF 0) >> tpack ", " >> emips (ScratchF 0) >>
tpack "\n\tmfc1 " >>
emips gr >> tpack ", " >> emips (ScratchF 0)
LoadA r1 s -> tpack "la " >> emips r1 >> tpack ", " >> tpack s
LoadI r1 i -> tpack "li " >> emips r1 >> tpack ", " >> emips i
LoadW r1 (c,r2) ->
tpack "lw " >> emips r1 >> tpack ", " >> chow c >>
tpack "(" >> emips r2 >> tpack ")"
LoadWG r (name, c) ->
tpack "lw " >> emips r >> tpack ", " >>
tpack name >> tpack "+" >> chow c
LoadWGR r1 (name, r2) ->
tpack "lw " >> emips r1 >> tpack ", " >>
tpack name >> tpack "(" >> emips r2 >> tpack ")"
-- LoadWGRO r1 (name, c, r2) ->
-- tpack "lw " >> emips r1 >> tpack ", " >>
-- tpack name >> tpack "+" >> chow c >>
-- tpack "(" >> emips r2 >> tpack ")"
LoadFI r1 i -> tpack "li.s " >> emips r1 >> tpack ", " >> emips i
LoadF r1 (c,r2) ->
tpack "l.s " >> emips r1 >> tpack ", " >> chow c >>
tpack "(" >> emips r2 >> tpack ")"
LoadFG r (name, c) ->
tpack "l.s " >> emips r >> tpack ", " >>
tpack name >> tpack "+" >> chow c
LoadFGR r1 (name, r2) ->
tpack "l.s " >> emips r1 >> tpack ", " >>
tpack name >> tpack "(" >> emips r2 >> tpack ")"
-- LoadFGRO r1 (name, c, r2) ->
-- tpack "l.s " >> emips r1 >> tpack ", " >>
-- tpack name >> tpack "+" >> chow c >>
-- tpack "(" >> emips r2 >> tpack ")"
Move r1 r2 ->
tpack "move " >>
emips r1 >> tpack ", " >>
emips r2
StoreW r1 (c,r2) ->
tpack "sw " >> emips r1 >> tpack ", " >> chow c >>
tpack "(" >> emips r2 >> tpack ")"
StoreWG r (name, c) ->
tpack "sw " >> emips r >> tpack ", " >>
tpack name >> tpack "+" >> chow c
StoreWGR r1 (name, r2) ->
tpack "sw " >> emips r1 >> tpack ", " >>
tpack name >> tpack "(" >> emips r2 >> tpack ")"
StoreF r1 (c,r2) ->
tpack "s.s " >> emips r1 >> tpack ", " >> chow c >>
tpack "(" >> emips r2 >> tpack ")"
StoreFG r (name, c) ->
tpack "s.s " >> emips r >> tpack ", " >>
tpack name >> tpack "+" >> chow c
StoreFGR r1 (name, r2) ->
tpack "s.s " >> emips r1 >> tpack ", " >>
tpack name >> tpack "(" >> emips r2 >> tpack ")"
Syscall -> tpack "syscall"
Slt r1 r2 r3 ->
tpack "slt " >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips r3
Clts r1 r2 ->
tpack "c.lt.s " >>
emips r1 >> tpack ", " >>
emips r2
Cles r1 r2 ->
tpack "c.le.s " >>
emips r1 >> tpack ", " >>
emips r2
Ceqs r1 r2 ->
tpack "c.eq.s " >>
emips r1 >> tpack ", " >>
emips r2
Beq r1 r2 label ->
tpack "beq " >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips label
Bne r1 r2 label ->
tpack "bne " >>
emips r1 >> tpack ", " >>
emips r2 >> tpack ", " >>
emips label
Bc1t r -> tpack "bc1t " >> emips r
Bc1f r -> tpack "bc1f " >> emips r
J label -> tpack "j " >> emips label
Jr r -> tpack "jr " >> emips r
Jal str -> tell $ "jal " <> pack str
MIPSProlog -> do
n <- gets head
emips . Comment $ "Prolog " <> Pre.show n
emips $ Move FP SP
emips $ StoreW RA (4, FP)
emips $ BinOpi SubI SP SP (IC . fromIntegral $ n)
modify tail
instance Emips BOp where
emips op = aux >> tell " "
where
aux = tell $ case op of
AddI -> "add"
SubI -> "sub"
MulI -> "mul"
DivI -> "div"
RemI -> "div"
AddF -> "add.s"
SubF -> "sub.s"
MulF -> "mul.s"
DivF -> "div.s"
BSL -> "sll"
BSR -> "srl"
BAnd -> "and"
BOr -> "or"
BXor -> "xor"
| adgalad/Epilog | src/Haskell/Language/Epilog/MIPS/MIPS.hs | bsd-3-clause | 12,802 | 0 | 23 | 4,561 | 4,147 | 2,082 | 2,065 | 345 | 3 |
-- Copyright (c) 2014, Dmitry Zuikov
-- All rights reserved.
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of emufat nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module EncodeVM where
import Prelude hiding (EQ)
import Data.Word
import Data.Maybe
import qualified Data.Map as M
import Data.Functor.Identity
import Text.Printf
import Data.Binary.Put
import Control.Monad.State
import Control.Monad.Writer
import qualified Data.ByteString.Lazy as BS
class OpcodeCL a where
isRLE :: a -> Bool
arity0 :: a -> Bool
arity1 :: a -> Bool
arity2 :: a -> Bool
arity3 :: a -> Bool
firstCode :: a
lastCode :: a
data Opcode = DUP | DROP
| CONST | CRNG
| JNZ | JZ | JGQ | JNE | JMP | CALLT | CALL | RET
| NOT | EQ | NEQ | GT | LE | GQ | LQ | RNG
| LOADS2 | LOADS3 | LOADS4 | LOADS5 | LOADS6 | LOADS7
| LOADS8 | LOADS9 | LOADS10 | LOADSN
| SER | NSER | NSER128
| RLE1 | RLE2 | RLE3 | RLE4 | RLE5 | RLE6 | RLE7 | RLE8
| RLE16 | RLE32 | RLE64 | RLE128 | RLE256 | RLE512 | RLEN
| OUTLE | OUTBE | OUTB
| NOP
| CALLN
| DEBUG
| EXIT
deriving (Eq, Ord, Enum, Show)
instance OpcodeCL Opcode where
isRLE x = x `elem` [RLE1 .. RLEN]
arity0 x =
x `elem` ([DUP, DROP] ++ [NOT .. RNG] ++ [CALLT, RET, NOP, DEBUG, EXIT] ++ [LOADS2 .. LOADS10] ++ [OUTLE .. OUTB])
arity1 x = x `elem` ([CONST] ++ [JNZ .. JMP] ++ [LOADSN] ++ [RLE1 .. RLEN] ++ [CALL] ++ [CALLN])
arity2 x = x `elem` ([SER, NSER128, CRNG])
arity3 x = x `elem` ([NSER])
firstCode = DUP
lastCode = EXIT
data CmdArg = W32 Word32 | W16 Word16 | W8 Word8 | ADDR Addr
data Addr = ALabel Label | AOffset Int
data Cmd = Cmd0 Opcode
| CmdConst Word32
| Cmd1 Opcode CmdArg
| Cmd2 Opcode CmdArg CmdArg
| Cmd3 Opcode CmdArg CmdArg CmdArg
| CmdJmp Opcode Addr
| CmdCondJmp Opcode Addr
| CmdLabel Label
| RawByte Word8
type Label = Int
type Block = (Label, [Cmd])
labelOf :: Block -> Label
labelOf = fst
instance Show CmdArg where
show (W32 x) = printf "%08X" x
show (W16 x) = printf "%04X" x
show (W8 x) = printf "%02X" x
show (ADDR a) = (show a)
instance Show Addr where
show (ALabel l) = "L" ++ show l
show (AOffset o) = printf "%04X" o
instance Show Cmd where
show (Cmd0 code) = ind 1 $ show code
show (CmdConst w) = ind 1 $ printf "CONST %d" w
show (Cmd1 code a) = ind 1 $ show code ++ " " ++ show a
show (Cmd2 code a b) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b
show (Cmd3 code a b c) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c
show (CmdJmp code a) = ind 1 $ show code ++ " " ++ show a
show (CmdCondJmp code a) = ind 1 $ show code ++ " " ++ show a
show (RawByte m) = ind 1 $ "BYTE " ++ printf "%02X" m
show (CmdLabel lbl) = "L" ++ show lbl ++ ":"
unArg (W8 a) = fromIntegral a
unArg (W16 a) = fromIntegral a
unArg (W32 a) = fromIntegral a
unArg (ADDR (ALabel a)) = a
unArg (ADDR (AOffset a)) = a
ind x s = concat (replicate x " ") ++ s
toBinary :: [(Label, [Cmd])] -> BS.ByteString
toBinary cmds = encodeM (pass3 (pass2 (pass1 cmds)))
where
pass3 m = execWriter $ forM_ cmds $ \(l, cs) -> mapM_ (repl m) cs
pass2 :: [(Label, Int)] -> M.Map Label Int
pass2 xs = M.fromList (execWriter (foldM_ blockOff 0 xs))
pass1 = map (\(l,c) -> (l, fromIntegral $ BS.length $ encodeM c))
encodeM :: [Cmd] -> BS.ByteString
encodeM c = runPut (mapM_ encode c)
encode (Cmd0 x) = putOpcode x
encode (CmdConst x) = putOpcode CONST >> putWord32be x
encode (Cmd1 CALLN a) = putOpcode CALLN >> putArg8 a
encode (Cmd1 LOADSN a) | (unArg a) < 256 = putOpcode LOADSN >> putArg8 a
| otherwise = error $ "BAD LOADSN ARG" ++ show a
encode (Cmd1 x a) | isRLE x = putOpcode x >> putArg8 a
| otherwise = putOpcode x >> putArg32 a
encode (RawByte b) = putWord8 b
encode (CmdLabel _) = return ()
encode (CmdJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (CmdCondJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (Cmd2 SER a b) = putOpcode SER >> putArg32 a >> putArg32 b
encode (Cmd2 NSER128 a b) = putOpcode NSER128 >> putArg32 a >> putArg32 b
encode (Cmd2 CRNG a b) = putOpcode CRNG >> putArg32 a >> putArg32 b
encode (Cmd3 NSER a b c) = putOpcode NSER >> putArg32 a >> putArg32 b >> putArg32 c
encode x = error $ "BAD COMMAND " ++ show x
putOpcode = putWord8 . op
putArg8 (W32 a) = putWord8 (fromIntegral a)
putArg8 (W16 a) = putWord8 (fromIntegral a)
putArg8 (W8 a) = putWord8 (fromIntegral a)
putArg8 (ADDR _ ) = error "BAD W8 (ADDRESS)"
putArg32 (W32 a) = putWord32be (fromIntegral a)
putArg32 (W16 a) = putWord32be (fromIntegral a)
putArg32 (W8 a) = putWord8 (fromIntegral a)
putArg32 (ADDR (ALabel a)) = putWord32be (fromIntegral 0)
putArg32 (ADDR (AOffset a)) = putWord32be (fromIntegral a)
op :: Opcode -> Word8
op = fromIntegral . fromEnum
blockOff sz (l', c) = tell [(l', sz)] >> return (sz + c)
repl m x@(Cmd1 CALL (ADDR (ALabel n))) = repl' (M.lookup n m) x
repl m x@(CmdJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x@(CmdCondJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x = tell [x]
repl' (Just n) (Cmd1 CALL x) = tell [Cmd1 CALL (ADDR (AOffset n))]
repl' (Just n) (CmdJmp op x) = tell [CmdJmp op (AOffset n)]
repl' (Just n) (CmdCondJmp op x) = tell [CmdCondJmp op (AOffset n)]
repl' Nothing x = error $ "BAD LABEL " ++ show x
| voidlizard/emufat | src/EncodeVM.hs | bsd-3-clause | 7,096 | 0 | 14 | 1,895 | 2,538 | 1,324 | 1,214 | 127 | 27 |
import Lib
main :: IO ()
main = threadedTest "main"
| willdonnelly/dyre | Tests/threaded/Main.hs | bsd-3-clause | 53 | 0 | 6 | 11 | 22 | 11 | 11 | 3 | 1 |
module Policy where
import System.Directory ( getDirectoryContents )
import System.FilePath ( (<.>), (</>) )
-- import Prelude hiding (catch)
import qualified Control.Exception as E
import Data.Either (lefts)
import qualified System.IO
import qualified Data.Char as Char
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import Lobster.Monad
import Lobster.Policy ( Domain, Policy )
import qualified Lobster.Lex as Lex
import qualified Lobster.Par as Par
import qualified Lobster.ErrM as ErrM
import qualified Lobster.Policy as P
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.API ( Test )
import Test.HUnit hiding ( Test )
testCases :: [(Bool, FilePath)] -> [Test]
testCases lobsterPolicies = map buildCase $ zip [1 .. ] lobsterPolicies
buildCase (i, params) = do
testCase ("Policy test #"++show i) $ checkPolicy params
checkPolicy :: (Bool, FilePath) -> IO ()
checkPolicy (shouldFail, testPolicyFilename) =
do succeeded <- testPolicy testPolicyFilename
case succeeded of
Left e -> if shouldFail
then return ()
else do
error $ "should have succeeded on " ++ testPolicyFilename ++ "\n"
++ "Output: \n" ++ e
Right _ -> if shouldFail
then error $ "should have failed on " ++ testPolicyFilename
else return ()
testappDirectory :: String
testappDirectory = "../SELinux/testapp"
lobsterExamplePoliciesDirectory :: String
lobsterExamplePoliciesDirectory = "test/examples"
testappPolicy :: String
testappPolicy = testappDirectory </> "testapp.lsr"
-- | Retrieves all the tests from the test/examples directory,
-- creating a @(True, <path>)@ entry for all files named
-- @exampleN.lsr@ and a @(False, <path>)@ entry for all files named
-- @errorN.lsr@
getLobsterExamplePolicies :: IO [(Bool,FilePath)]
getLobsterExamplePolicies = do
fns <- getDirectoryContents lobsterExamplePoliciesDirectory
return (map rejoin $ List.sort $ Maybe.mapMaybe split fns)
where
split :: String -> Maybe (String,Int,String,String)
split f =
let (v,f') = List.span Char.isAlpha f in
let (n,f'') = List.span Char.isDigit f' in
if f'' == ".lsr" then Just (v, length n, n, f) else Nothing
rejoin :: (String,Int,String,String) -> (Bool,String)
rejoin (v,_,_,f) =
let b = if v == "example" then False
else if v == "error" then True
else error $ "bad test file prefix: " ++ v in
(b, lobsterExamplePoliciesDirectory </> f)
getLobsterPolicies :: IO [(Bool,FilePath)]
getLobsterPolicies = do
fns <- getLobsterExamplePolicies
return $ fns ++ [(False,testappPolicy)]
-- | Test a lobster file to see if it will parse, interpret, and
-- flatten. This is a wrapper around 'checkFile' that catches
-- exceptions and transforms them into @False@ return values.
testPolicy :: FilePath -> IO (Either String ())
testPolicy file = E.catch (checkFile file) handler
where handler :: E.SomeException -> IO (Either String ())
handler e = return $ Left (show e)
-- | Attempt to parse, interpret, and flatten a lobster source file.
-- Throws exceptions in some failure cases.
checkFile :: FilePath -> IO (Either String ())
checkFile file = do
policy <- P.parsePolicyFile file
let (es, domain) = P.interpretPolicy policy
case lefts es of
[] -> case runP (P.flattenDomain domain ) of
Left e -> return $ Left e
Right _ -> return $ Right ()
xs -> return $ Left (unlines xs)
| GaloisInc/sk-dev-platform | libs/lobster/testsrc/Policy.hs | bsd-3-clause | 3,609 | 0 | 17 | 831 | 978 | 536 | 442 | 72 | 4 |
module GameOver where
import Data.IORef
import Graphics.Rendering.OpenGL hiding (($=))
import Graphics.UI.GLUT
type Vertice = (GLfloat, GLfloat)
type Cor = (GLfloat, GLfloat, GLfloat)
game :: IO ()
game = do
clear [ColorBuffer]
renderPrimitive Quads $ do
desenhaMapa ((-1)::GLfloat, 1::GLfloat) ((-0.9)::GLfloat, 1::GLfloat) ((-0.9)::GLfloat, 0.9::GLfloat) ((-1)::GLfloat, 0.9::GLfloat) gameOver
flush
-- Desenha uma linha do mapa
linha :: Vertice -> Vertice -> Vertice -> Vertice -> [Cor] -> IO ()
linha v1 v2 v3 v4 [cor] = desenhaQuadrado cor v1 v2 v3 v4
linha v1 v2 v3 v4 (cor:ls) = do
desenhaQuadrado cor v1 v2 v3 v4
linha (mais v1 0.05) (mais v2 0.05) (mais v3 0.05) (mais v4 0.05) ls
where mais = (\(vx,vy) x -> (vx + x, vy))
-- Chama a função para desenhar cada linha do mapa
desenhaMapa :: Vertice -> Vertice -> Vertice -> Vertice -> [[Cor]] -> IO ()
desenhaMapa v1 v2 v3 v4 [cor] = linha v1 v2 v3 v4 cor
desenhaMapa v1 v2 v3 v4 (cor:ls) = do
linha v1 v2 v3 v4 cor
desenhaMapa (menos v1 0.1) (menos v2 0.1) (menos v3 0.1) (menos v4 0.1) ls
where menos = (\(vx,vy) y -> (vx, vy - y))
-- Utilizado para chamar color3f em vez de chamar color $ Color3 r g b
color3f :: Cor -> IO ()
color3f (r, g, b) = color $ Color3 r g (b :: GLfloat)
-- Utilizado para chamar vertex2f em vez de chamar vertex $ Vertex2 x y
vertex2f :: Vertice -> IO ()
vertex2f (x, y) = vertex $ Vertex2 x y
-- Desenha apenas um quadrado
desenhaQuadrado :: Cor -> Vertice -> Vertice -> Vertice -> Vertice -> IO ()
desenhaQuadrado cor v1 v2 v3 v4 = do
color3f cor
vertex2f v1
vertex2f v2
vertex2f v3
vertex2f v4
{--
###### ### ## ## ######
## ## ##### ### ### ######
## ## ## ## # # ## ##
## ### ######### ## # ## ####
## ## ## ## ## ## ##
## ## ## ## ## ## ######
###### ## ## ## ## ######
###### ## ## ###### #######
## ## ## ## ###### ## ##
## ## ## ## ## ## ##
## ## ## ## #### ######
## ## ## ## ## ## ##
## ## #### ###### ## ##
###### ## ###### ## ##
--}
gameOver = [linhaBranca, linhaBranca,
linha1, linha2, linha3, linha4, linha5, linha6, linha7, linhaBranca,
linha8, linha9, linha10, linha11, linha12, linha13, linha14,
linhaBranca,linhaBranca,linhaBranca]
linhaBranca = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha1 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha2 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha3 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha4 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha5 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha6 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha7 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha8 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha9 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha10 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha11 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha12 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha13 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
linha14 = [
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(0::GLfloat,0::GLfloat,0::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat),
(1::GLfloat,1::GLfloat,1::GLfloat)]
| jailson-dias/Arca | src/GameOver.hs | bsd-3-clause | 29,947 | 0 | 13 | 7,081 | 13,443 | 8,863 | 4,580 | 654 | 1 |
{-# LANGUAGE EmptyDataDecls, TypeSynonymInstances #-}
{-# OPTIONS_GHC -fcontext-stack42 #-}
module Games.Chaos2010.Database.Wizard_spell_choices where
import Games.Chaos2010.Database.Fields
import Database.HaskellDB.DBLayout
type Wizard_spell_choices =
Record
(HCons (LVPair Wizard_name (Expr (Maybe String)))
(HCons (LVPair Spell_name (Expr (Maybe String))) HNil))
wizard_spell_choices :: Table Wizard_spell_choices
wizard_spell_choices = baseTable "wizard_spell_choices" | JakeWheat/Chaos-2010 | Games/Chaos2010/Database/Wizard_spell_choices.hs | bsd-3-clause | 499 | 0 | 15 | 67 | 104 | 58 | 46 | 11 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
module GHC.Types.RepType
(
-- * Code generator views onto Types
UnaryType, NvUnaryType, isNvUnaryType,
unwrapType,
-- * Predicates on types
isVoidTy,
-- * Type representation for the code generator
typePrimRep, typePrimRep1,
runtimeRepPrimRep, typePrimRepArgs,
PrimRep(..), primRepToType,
countFunRepArgs, countConRepArgs, tyConPrimRep, tyConPrimRep1,
-- * Unboxed sum representation type
ubxSumRepType, layoutUbxSum, typeSlotTy, SlotTy (..),
slotPrimRep, primRepSlot
) where
#include "HsVersions.h"
import GhcPrelude
import BasicTypes (Arity, RepArity)
import DataCon
import Outputable
import PrelNames
import Coercion
import TyCon
import TyCoRep
import Type
import Util
import TysPrim
import {-# SOURCE #-} TysWiredIn ( anyTypeOfKind )
import Data.List (sort)
import qualified Data.IntSet as IS
{- **********************************************************************
* *
Representation types
* *
********************************************************************** -}
type NvUnaryType = Type
type UnaryType = Type
-- Both are always a value type; i.e. its kind is TYPE rr
-- for some rr; moreover the rr is never a variable.
--
-- NvUnaryType : never an unboxed tuple or sum, or void
--
-- UnaryType : never an unboxed tuple or sum;
-- can be Void# or (# #)
isNvUnaryType :: Type -> Bool
isNvUnaryType ty
| [_] <- typePrimRep ty
= True
| otherwise
= False
-- INVARIANT: the result list is never empty.
typePrimRepArgs :: HasDebugCallStack => Type -> [PrimRep]
typePrimRepArgs ty
| [] <- reps
= [VoidRep]
| otherwise
= reps
where
reps = typePrimRep ty
-- | Gets rid of the stuff that prevents us from understanding the
-- runtime representation of a type. Including:
-- 1. Casts
-- 2. Newtypes
-- 3. Foralls
-- 4. Synonyms
-- But not type/data families, because we don't have the envs to hand.
unwrapType :: Type -> Type
unwrapType ty
| Just (_, unwrapped)
<- topNormaliseTypeX stepper mappend inner_ty
= unwrapped
| otherwise
= inner_ty
where
inner_ty = go ty
go t | Just t' <- coreView t = go t'
go (ForAllTy _ t) = go t
go (CastTy t _) = go t
go t = t
-- cf. Coercion.unwrapNewTypeStepper
stepper rec_nts tc tys
| Just (ty', _) <- instNewTyCon_maybe tc tys
= case checkRecTc rec_nts tc of
Just rec_nts' -> NS_Step rec_nts' (go ty') ()
Nothing -> NS_Abort -- infinite newtypes
| otherwise
= NS_Done
countFunRepArgs :: Arity -> Type -> RepArity
countFunRepArgs 0 _
= 0
countFunRepArgs n ty
| FunTy _ arg res <- unwrapType ty
= length (typePrimRepArgs arg) + countFunRepArgs (n - 1) res
| otherwise
= pprPanic "countFunRepArgs: arity greater than type can handle" (ppr (n, ty, typePrimRep ty))
countConRepArgs :: DataCon -> RepArity
countConRepArgs dc = go (dataConRepArity dc) (dataConRepType dc)
where
go :: Arity -> Type -> RepArity
go 0 _
= 0
go n ty
| FunTy _ arg res <- unwrapType ty
= length (typePrimRep arg) + go (n - 1) res
| otherwise
= pprPanic "countConRepArgs: arity greater than type can handle" (ppr (n, ty, typePrimRep ty))
-- | True if the type has zero width.
isVoidTy :: Type -> Bool
isVoidTy = null . typePrimRep
{- **********************************************************************
* *
Unboxed sums
See Note [Translating unboxed sums to unboxed tuples] in GHC.Stg.Unarise
* *
********************************************************************** -}
type SortedSlotTys = [SlotTy]
-- | Given the arguments of a sum type constructor application,
-- return the unboxed sum rep type.
--
-- E.g.
--
-- (# Int# | Maybe Int | (# Int#, Float# #) #)
--
-- We call `ubxSumRepType [ [IntRep], [LiftedRep], [IntRep, FloatRep] ]`,
-- which returns [WordSlot, PtrSlot, WordSlot, FloatSlot]
--
-- INVARIANT: Result slots are sorted (via Ord SlotTy), except that at the head
-- of the list we have the slot for the tag.
ubxSumRepType :: [[PrimRep]] -> [SlotTy]
ubxSumRepType constrs0
-- These first two cases never classify an actual unboxed sum, which always
-- has at least two disjuncts. But it could happen if a user writes, e.g.,
-- forall (a :: TYPE (SumRep [IntRep])). ...
-- which could never be instantiated. We still don't want to panic.
| constrs0 `lengthLessThan` 2
= [WordSlot]
| otherwise
= let
combine_alts :: [SortedSlotTys] -- slots of constructors
-> SortedSlotTys -- final slots
combine_alts constrs = foldl' merge [] constrs
merge :: SortedSlotTys -> SortedSlotTys -> SortedSlotTys
merge existing_slots []
= existing_slots
merge [] needed_slots
= needed_slots
merge (es : ess) (s : ss)
| Just s' <- s `fitsIn` es
= -- found a slot, use it
s' : merge ess ss
| s < es
= -- we need a new slot and this is the right place for it
s : merge (es : ess) ss
| otherwise
= -- keep searching for a slot
es : merge ess (s : ss)
-- Nesting unboxed tuples and sums is OK, so we need to flatten first.
rep :: [PrimRep] -> SortedSlotTys
rep ty = sort (map primRepSlot ty)
sumRep = WordSlot : combine_alts (map rep constrs0)
-- WordSlot: for the tag of the sum
in
sumRep
layoutUbxSum :: SortedSlotTys -- Layout of sum. Does not include tag.
-- We assume that they are in increasing order
-> [SlotTy] -- Slot types of things we want to map to locations in the
-- sum layout
-> [Int] -- Where to map 'things' in the sum layout
layoutUbxSum sum_slots0 arg_slots0 =
go arg_slots0 IS.empty
where
go :: [SlotTy] -> IS.IntSet -> [Int]
go [] _
= []
go (arg : args) used
= let slot_idx = findSlot arg 0 sum_slots0 used
in slot_idx : go args (IS.insert slot_idx used)
findSlot :: SlotTy -> Int -> SortedSlotTys -> IS.IntSet -> Int
findSlot arg slot_idx (slot : slots) useds
| not (IS.member slot_idx useds)
, Just slot == arg `fitsIn` slot
= slot_idx
| otherwise
= findSlot arg (slot_idx + 1) slots useds
findSlot _ _ [] _
= pprPanic "findSlot" (text "Can't find slot" $$ ppr sum_slots0 $$ ppr arg_slots0)
--------------------------------------------------------------------------------
-- We have 3 kinds of slots:
--
-- - Pointer slot: Only shared between actual pointers to Haskell heap (i.e.
-- boxed objects)
--
-- - Word slots: Shared between IntRep, WordRep, Int64Rep, Word64Rep, AddrRep.
--
-- - Float slots: Shared between floating point types.
--
-- - Void slots: Shared between void types. Not used in sums.
--
-- TODO(michalt): We should probably introduce `SlotTy`s for 8-/16-/32-bit
-- values, so that we can pack things more tightly.
data SlotTy = PtrSlot | WordSlot | Word64Slot | FloatSlot | DoubleSlot
deriving (Eq, Ord)
-- Constructor order is important! If slot A could fit into slot B
-- then slot A must occur first. E.g. FloatSlot before DoubleSlot
--
-- We are assuming that WordSlot is smaller than or equal to Word64Slot
-- (would not be true on a 128-bit machine)
instance Outputable SlotTy where
ppr PtrSlot = text "PtrSlot"
ppr Word64Slot = text "Word64Slot"
ppr WordSlot = text "WordSlot"
ppr DoubleSlot = text "DoubleSlot"
ppr FloatSlot = text "FloatSlot"
typeSlotTy :: UnaryType -> Maybe SlotTy
typeSlotTy ty
| isVoidTy ty
= Nothing
| otherwise
= Just (primRepSlot (typePrimRep1 ty))
primRepSlot :: PrimRep -> SlotTy
primRepSlot VoidRep = pprPanic "primRepSlot" (text "No slot for VoidRep")
primRepSlot LiftedRep = PtrSlot
primRepSlot UnliftedRep = PtrSlot
primRepSlot IntRep = WordSlot
primRepSlot Int8Rep = WordSlot
primRepSlot Int16Rep = WordSlot
primRepSlot Int32Rep = WordSlot
primRepSlot Int64Rep = Word64Slot
primRepSlot WordRep = WordSlot
primRepSlot Word8Rep = WordSlot
primRepSlot Word16Rep = WordSlot
primRepSlot Word32Rep = WordSlot
primRepSlot Word64Rep = Word64Slot
primRepSlot AddrRep = WordSlot
primRepSlot FloatRep = FloatSlot
primRepSlot DoubleRep = DoubleSlot
primRepSlot VecRep{} = pprPanic "primRepSlot" (text "No slot for VecRep")
slotPrimRep :: SlotTy -> PrimRep
slotPrimRep PtrSlot = LiftedRep -- choice between lifted & unlifted seems arbitrary
slotPrimRep Word64Slot = Word64Rep
slotPrimRep WordSlot = WordRep
slotPrimRep DoubleSlot = DoubleRep
slotPrimRep FloatSlot = FloatRep
-- | Returns the bigger type if one fits into the other. (commutative)
fitsIn :: SlotTy -> SlotTy -> Maybe SlotTy
fitsIn ty1 ty2
| isWordSlot ty1 && isWordSlot ty2
= Just (max ty1 ty2)
| isFloatSlot ty1 && isFloatSlot ty2
= Just (max ty1 ty2)
| isPtrSlot ty1 && isPtrSlot ty2
= Just PtrSlot
| otherwise
= Nothing
where
isPtrSlot PtrSlot = True
isPtrSlot _ = False
isWordSlot Word64Slot = True
isWordSlot WordSlot = True
isWordSlot _ = False
isFloatSlot DoubleSlot = True
isFloatSlot FloatSlot = True
isFloatSlot _ = False
{- **********************************************************************
* *
PrimRep
* *
*************************************************************************
Note [RuntimeRep and PrimRep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This Note describes the relationship between GHC.Types.RuntimeRep
(of levity-polymorphism fame) and TyCon.PrimRep, as these types
are closely related.
A "primitive entity" is one that can be
* stored in one register
* manipulated with one machine instruction
Examples include:
* a 32-bit integer
* a 32-bit float
* a 64-bit float
* a machine address (heap pointer), etc.
* a quad-float (on a machine with SIMD register and instructions)
* ...etc...
The "representation or a primitive entity" specifies what kind of register is
needed and how many bits are required. The data type TyCon.PrimRep
enumerates all the possibilities.
data PrimRep
= VoidRep
| LiftedRep -- ^ Lifted pointer
| UnliftedRep -- ^ Unlifted pointer
| Int8Rep -- ^ Signed, 8-bit value
| Int16Rep -- ^ Signed, 16-bit value
...etc...
| VecRep Int PrimElemRep -- ^ SIMD fixed-width vector
The Haskell source language is a bit more flexible: a single value may need multiple PrimReps.
For example
utup :: (# Int, Int #) -> Bool
utup x = ...
Here x :: (# Int, Int #), and that takes two registers, and two instructions to move around.
Unboxed sums are similar.
Every Haskell expression e has a type ty, whose kind is of form TYPE rep
e :: ty :: TYPE rep
where rep :: RuntimeRep. Here rep describes the runtime representation for e's value,
but RuntimeRep has some extra cases:
data RuntimeRep = VecRep VecCount VecElem -- ^ a SIMD vector type
| TupleRep [RuntimeRep] -- ^ An unboxed tuple of the given reps
| SumRep [RuntimeRep] -- ^ An unboxed sum of the given reps
| LiftedRep -- ^ lifted; represented by a pointer
| UnliftedRep -- ^ unlifted; represented by a pointer
| IntRep -- ^ signed, word-sized value
...etc...
It's all in 1-1 correspondence with PrimRep except for TupleRep and SumRep,
which describe unboxed products and sums respectively. RuntimeRep is defined
in the library ghc-prim:GHC.Types. It is also "wired-in" to GHC: see
TysWiredIn.runtimeRepTyCon. The unarisation pass, in GHC.Stg.Unarise, transforms the
program, so that that every variable has a type that has a PrimRep. For
example, unarisation transforms our utup function above, to take two Int
arguments instead of one (# Int, Int #) argument.
See also Note [Getting from RuntimeRep to PrimRep] and Note [VoidRep].
Note [VoidRep]
~~~~~~~~~~~~~~
PrimRep contains a constructor VoidRep, while RuntimeRep does
not. Yet representations are often characterised by a list of PrimReps,
where a void would be denoted as []. (See also Note [RuntimeRep and PrimRep].)
However, after the unariser, all identifiers have exactly one PrimRep, but
void arguments still exist. Thus, PrimRep includes VoidRep to describe these
binders. Perhaps post-unariser representations (which need VoidRep) should be
a different type than pre-unariser representations (which use a list and do
not need VoidRep), but we have what we have.
RuntimeRep instead uses TupleRep '[] to denote a void argument. When
converting a TupleRep '[] into a list of PrimReps, we get an empty list.
Note [Getting from RuntimeRep to PrimRep]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
General info on RuntimeRep and PrimRep is in Note [RuntimeRep and PrimRep].
How do we get from an Id to the the list or PrimReps used to store it? We get
the Id's type ty (using idType), then ty's kind ki (using typeKind), then
pattern-match on ki to extract rep (in kindPrimRep), then extract the PrimRep
from the RuntimeRep (in runtimeRepPrimRep).
We now must convert the RuntimeRep to a list of PrimReps. Let's look at two
examples:
1. x :: Int#
2. y :: (# Int, Word# #)
With these types, we can extract these kinds:
1. Int# :: TYPE IntRep
2. (# Int, Word# #) :: TYPE (TupleRep [LiftedRep, WordRep])
In the end, we will get these PrimReps:
1. [IntRep]
2. [LiftedRep, WordRep]
It would thus seem that we should have a function somewhere of
type `RuntimeRep -> [PrimRep]`. This doesn't work though: when we
look at the argument of TYPE, we get something of type Type (of course).
RuntimeRep exists in the user's program, but not in GHC as such.
Instead, we must decompose the Type of kind RuntimeRep into tycons and
extract the PrimReps from the TyCons. This is what runtimeRepPrimRep does:
it takes a Type and returns a [PrimRep]
runtimeRepPrimRep works by using tyConRuntimeRepInfo. That function
should be passed the TyCon produced by promoting one of the constructors
of RuntimeRep into type-level data. The RuntimeRep promoted datacons are
associated with a RuntimeRepInfo (stored directly in the PromotedDataCon
constructor of TyCon). This pairing happens in TysWiredIn. A RuntimeRepInfo
usually(*) contains a function from [Type] to [PrimRep]: the [Type] are
the arguments to the promoted datacon. These arguments are necessary
for the TupleRep and SumRep constructors, so that this process can recur,
producing a flattened list of PrimReps. Calling this extracted function
happens in runtimeRepPrimRep; the functions themselves are defined in
tupleRepDataCon and sumRepDataCon, both in TysWiredIn.
The (*) above is to support vector representations. RuntimeRep refers
to VecCount and VecElem, whose promoted datacons have nuggets of information
related to vectors; these form the other alternatives for RuntimeRepInfo.
Returning to our examples, the Types we get (after stripping off TYPE) are
1. TyConApp (PromotedDataCon "IntRep") []
2. TyConApp (PromotedDataCon "TupleRep")
[TyConApp (PromotedDataCon ":")
[ TyConApp (AlgTyCon "RuntimeRep") []
, TyConApp (PromotedDataCon "LiftedRep") []
, TyConApp (PromotedDataCon ":")
[ TyConApp (AlgTyCon "RuntimeRep") []
, TyConApp (PromotedDataCon "WordRep") []
, TyConApp (PromotedDataCon "'[]")
[TyConApp (AlgTyCon "RuntimeRep") []]]]]
runtimeRepPrimRep calls tyConRuntimeRepInfo on (PromotedDataCon "IntRep"), resp.
(PromotedDataCon "TupleRep"), extracting a function that will produce the PrimReps.
In example 1, this function is passed an empty list (the empty list of args to IntRep)
and returns the PrimRep IntRep. (See the definition of runtimeRepSimpleDataCons in
TysWiredIn and its helper function mk_runtime_rep_dc.) Example 2 passes the promoted
list as the one argument to the extracted function. The extracted function is defined
as prim_rep_fun within tupleRepDataCon in TysWiredIn. It takes one argument, decomposes
the promoted list (with extractPromotedList), and then recurs back to runtimeRepPrimRep
to process the LiftedRep and WordRep, concatentating the results.
-}
-- | Discovers the primitive representation of a 'Type'. Returns
-- a list of 'PrimRep': it's a list because of the possibility of
-- no runtime representation (void) or multiple (unboxed tuple/sum)
-- See also Note [Getting from RuntimeRep to PrimRep]
typePrimRep :: HasDebugCallStack => Type -> [PrimRep]
typePrimRep ty = kindPrimRep (text "typePrimRep" <+>
parens (ppr ty <+> dcolon <+> ppr (typeKind ty)))
(typeKind ty)
-- | Like 'typePrimRep', but assumes that there is precisely one 'PrimRep' output;
-- an empty list of PrimReps becomes a VoidRep.
-- This assumption holds after unarise, see Note [Post-unarisation invariants].
-- Before unarise it may or may not hold.
-- See also Note [RuntimeRep and PrimRep] and Note [VoidRep]
typePrimRep1 :: HasDebugCallStack => UnaryType -> PrimRep
typePrimRep1 ty = case typePrimRep ty of
[] -> VoidRep
[rep] -> rep
_ -> pprPanic "typePrimRep1" (ppr ty $$ ppr (typePrimRep ty))
-- | Find the runtime representation of a 'TyCon'. Defined here to
-- avoid module loops. Returns a list of the register shapes necessary.
-- See also Note [Getting from RuntimeRep to PrimRep]
tyConPrimRep :: HasDebugCallStack => TyCon -> [PrimRep]
tyConPrimRep tc
= kindPrimRep (text "kindRep tc" <+> ppr tc $$ ppr res_kind)
res_kind
where
res_kind = tyConResKind tc
-- | Like 'tyConPrimRep', but assumed that there is precisely zero or
-- one 'PrimRep' output
-- See also Note [Getting from RuntimeRep to PrimRep] and Note [VoidRep]
tyConPrimRep1 :: HasDebugCallStack => TyCon -> PrimRep
tyConPrimRep1 tc = case tyConPrimRep tc of
[] -> VoidRep
[rep] -> rep
_ -> pprPanic "tyConPrimRep1" (ppr tc $$ ppr (tyConPrimRep tc))
-- | Take a kind (of shape @TYPE rr@) and produce the 'PrimRep's
-- of values of types of this kind.
-- See also Note [Getting from RuntimeRep to PrimRep]
kindPrimRep :: HasDebugCallStack => SDoc -> Kind -> [PrimRep]
kindPrimRep doc ki
| Just ki' <- coreView ki
= kindPrimRep doc ki'
kindPrimRep doc (TyConApp typ [runtime_rep])
= ASSERT( typ `hasKey` tYPETyConKey )
runtimeRepPrimRep doc runtime_rep
kindPrimRep doc ki
= pprPanic "kindPrimRep" (ppr ki $$ doc)
-- | Take a type of kind RuntimeRep and extract the list of 'PrimRep' that
-- it encodes. See also Note [Getting from RuntimeRep to PrimRep]
runtimeRepPrimRep :: HasDebugCallStack => SDoc -> Type -> [PrimRep]
runtimeRepPrimRep doc rr_ty
| Just rr_ty' <- coreView rr_ty
= runtimeRepPrimRep doc rr_ty'
| TyConApp rr_dc args <- rr_ty
, RuntimeRep fun <- tyConRuntimeRepInfo rr_dc
= fun args
| otherwise
= pprPanic "runtimeRepPrimRep" (doc $$ ppr rr_ty)
-- | Convert a PrimRep back to a Type. Used only in the unariser to give types
-- to fresh Ids. Really, only the type's representation matters.
-- See also Note [RuntimeRep and PrimRep]
primRepToType :: PrimRep -> Type
primRepToType = anyTypeOfKind . tYPE . primRepToRuntimeRep
| sdiehl/ghc | compiler/GHC/Types/RepType.hs | bsd-3-clause | 19,963 | 0 | 14 | 4,892 | 2,496 | 1,297 | 1,199 | 222 | 6 |
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE NoRebindableSyntax #-}
{-# OPTIONS_GHC -Wno-missing-methods #-}
module Homogeneous.PreludeInstances
where
import Homogeneous.FAlgebra
import Homogeneous.Variety
import Prelude
mkFAlgebra ''Num
mkFAlgebra ''Fractional
mkFAlgebra ''Floating
-- mkFAlgebra ''Eq
instance FAlgebra Eq
instance Functor (Sig Eq)
instance Foldable (Sig Eq)
instance Show (Sig Eq a)
instance Eq (Sig Eq a)
mkFAlgebra ''Ord
class (Floating a, Ord a) => FloatingOrd a
instance {-#OVERLAPPABLE#-} (Floating a, Ord a) => FloatingOrd a
mkFAlgebra ''FloatingOrd
associator :: Num a => a -> a -> a -> a
associator a1 a2 a3
= ((a1+a2)+a3) - (a1+(a2+a3))
--------------------------------------------------------------------------------
instance Variety Num where
laws =
[ Law
{ lawName = "associative"
, lhs = (var1+var2)+var3
, rhs = var1+(var2+var3)
}
, Law
{ lawName = "commutative"
, lhs = var1*var2
, rhs = var2*var1
}
]
instance Approximate Num Float where
lawError (Law "associative" _ _) [a1,a2,a3] = abs $ ((a1+a2)+a3)-(a1+(a2+a3))
----------------------------------------
data Vec3 a = Vec3 {a::a, b::a, c::a}
instance Num a => Num (Vec3 a) where
(Vec3 a1 a2 a3)+(Vec3 b1 b2 b3) = Vec3 (a1+b1) (a2+b2) (a3+b3)
(Vec3 a1 a2 a3)-(Vec3 b1 b2 b3) = Vec3 (a1-b1) (a2-b2) (a3-b3)
(Vec3 a1 a2 a3)*(Vec3 b1 b2 b3) = Vec3 (a1*b1) (a2*b2) (a3*b3)
-- instance Approximate Num a => Approximate Num (Vec3 a) where
-- lawError law xs = Vec3
-- (lawError law $ map a xs)
-- (lawError law $ map b xs)
-- (lawError law $ map c xs)
--------------------------------------------------------------------------------
toAST1
:: ( AST alg x -> y)
-> ( x -> y)
toAST1 f x1 = f (Pure x1)
transform1 :: forall alg x.
( FAlgebra alg
, alg x
) => (AST alg x -> AST alg x)
-> (AST alg x -> AST alg x)
-> (x -> x)
transform1 go f x = runAST $ go $ f (Pure x)
--------------------
toAST2
:: ( AST alg x -> AST alg x -> y)
-> ( x -> x -> y)
toAST2 f x1 x2 = f (Pure x1) (Pure x2)
transform2 :: forall alg x.
( FAlgebra alg
, alg x
, alg (AST alg x)
) => (AST alg x -> AST alg x)
-> (AST alg x -> AST alg x -> AST alg x)
-> (x -> x -> x)
transform2 go f x1 x2 = runAST $ go $ toAST2 (f :: AST alg x -> AST alg x -> AST alg x) x1 x2
--------------------------------------------------------------------------------
logexpAST1 :: AST Floating a -> AST Floating a
logexpAST1 (Free (Sig_log (Free (Sig_exp a)))) = a
logexpAST2 :: View Floating alg => AST alg a -> AST alg a
logexpAST2 (Free (unsafeExtractSig -> Sig_log
(Free (unsafeExtractSig -> Sig_exp a)))) = a
-- pattern AST_log ::
-- ( View Floating alg
-- ) => AST alg a -> AST alg a
-- pattern AST_log e <- Free (unsafeExtractSig -> Sig_log e) where
-- AST_log e = Free (embedSig (Sig_log e))
--
-- pattern AST_exp ::
-- ( View Floating alg
-- ) => AST alg a -> AST alg a
-- pattern AST_exp e <- Free (unsafeExtractSig -> Sig_exp e) where
-- AST_exp e = Free (embedSig (Sig_exp e))
logexpAST3 :: View Floating alg => AST alg a -> AST alg a
logexpAST3 (AST_log (AST_exp a)) = a
logexpAST4 :: View Floating alg => AST alg a -> AST alg a
logexpAST4 (AST_log (AST_exp a)) = a
logexpAST4 (Free f) = Free $ fmap logexpAST4 f
logexpAST4 (Pure a) = Pure a
testFunc1 :: Floating a => a -> a
testFunc1 a = log(exp a)
testFunc2 :: Floating a => a -> a
testFunc2 a = 1+log(exp a)
-- ghci> logexpAST4 $ testFunc 2 :: AST Floating Double
-- ((fromInteger 1)+(fromInteger 2))
testFunc3 :: Floating a => a -> a
testFunc3 a = 1+log(log(log(exp(exp(exp a)))))
-- ghci> fixAST stabilizeAST (testFunc2 var1 :: AST Floating Var)
-- ((fromInteger 1)+var1)
----------------------------------------
stabAST :: Eq a => AST FloatingOrd a -> AST FloatingOrd a
stabAST
(AST_log
(AST_div
(AST_fromInteger 1)
(AST_plus
(AST_fromInteger 1)
(AST_exp
(AST_negate x)
)
)
)
)
= logLogistic2 x
logLogistic1 :: Floating x => x -> x
logLogistic1 x = log(1/(1+exp(-x)))
logLogistic2 :: FloatingOrd x => x -> x
logLogistic2 x = m+log(1/(exp(m)+exp(-x+m)))
where
m = min 0 x
----------------------------------------
whereTest :: AST Num a -> AST Num a
whereTest x = y+y*y
where
y=3*x+1
----------------------------------------
fixAST :: (Eq (Sig alg (Free (Sig alg) a)), Eq a) => (AST alg a -> AST alg a) -> AST alg a -> AST alg a
fixAST f ast = if ast==ast'
then ast
else fixAST f ast'
where
ast' = f ast
foldConstants :: View Num alg => AST alg a -> AST alg a
foldConstants (AST_plus (AST_fromInteger a1) (AST_fromInteger a2)) = AST_fromInteger (a1+a2)
foldConstants (AST_minus (AST_fromInteger a1) (AST_fromInteger a2)) = AST_fromInteger (a1-a2)
foldConstants (AST_mul (AST_fromInteger a1) (AST_fromInteger a2)) = AST_fromInteger (a1*a2)
foldConstants (AST_negate (AST_fromInteger a1)) = AST_fromInteger (negate a1)
foldConstants (Free sig) = Free $ fmap foldConstants sig
foldConstants (Pure a ) = Pure a
constExpr :: Num a => a
constExpr = 4+2*(8-2)-1
-- ghci> fixAST foldConstants constExpr
-- (fromInteger 18)
constFunc :: Num a => a -> a -> a
constFunc x1 x2 = x1*2+(7+2)*x2
--------------------------------------------------------------------------------
instance
( FAlgebra alg
, Show (Sig alg (Free (Sig alg) Var))
) => Show (AST alg Var -> AST alg Var) where
show f = show (f var1)
--------------------------------------------------------------------------------
-- type family Scalar a
-- -- mkAT ''Scalar
--
-- class (Num a, Floating (Scalar a)) => Vector a where
-- (.*) :: Scalar a -> a -> a
--
-- instance FAlgebra Vector where
-- data Sig Vector a
-- = Sig_dotmul (Scalar a) a
-- | Sig_Vector_Num (Sig Num a)
-- | Sig_Vector_Floating (Sig Floating (Scalar a))
-- runSig (Sig_dotmul s a) = s.* a
-- runSig (Sig_Vector_Num s) = runSig s
-- runSig (Sig_Vector_Floating s) = runSig s
--
-- instance Functor (Sig Vector) where
-- fmap f (Sig_dotmul s a) = Sig_dotmul (f s) (f a)
-- fmap f (Sig_Vector_Num s) = Sig_Vector_Num (fmap f s)
-- fmap f (Sig_Vector_Floating s) = Sig_Vector_Floating (fmap f s)
--
-- instance Foldable (Sig Vector)
--
-- -- mkFAlgebra ''Vector
--------------------------------------------------------------------------------
data Matrix a = Matrix a a a a
instance Num a => Num (Matrix a) where
(Matrix a1 b1 c1 d1)+(Matrix a2 b2 c2 d2)
=Matrix (a1+a2) (b1+b2) (c1+c2) (d1+d2)
(Matrix a1 b1 c1 d1)-(Matrix a2 b2 c2 d2)
=Matrix (a1-a2) (b1-b2) (c1-c2) (d1-d2)
(Matrix a1 b1 c1 d1)*(Matrix a2 b2 c2 d2)
= Matrix
(a1*a2+b1*c2)
(a1*b2+b1*d2)
(c1*a2+d1*c2)
(c1*b2+d1*d2)
| mikeizbicki/homoiconic | src/Homoiconic/Homogeneous/Example.hs | bsd-3-clause | 7,244 | 0 | 16 | 1,795 | 2,488 | 1,288 | 1,200 | -1 | -1 |
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GADTs #-}
module Control.LnMonad.Focus where
import Data.LnFunctor
import Data.LnFunctor.Apply
import Data.LnFunctor.Bind
import Data.LnFunctor.Mono
import Control.LnApplicative
import Control.LnMonad.Infer
import Type.Families
import Control.Lens
import Data.Proxy
import GHC.Prim (Any)
newtype Focus s t a b r = Focus
{ unFocus :: (ReifiedLens s t a b,r)
}
type FocusK = K (Any :: Pr * *)
instance IxMono Focus FocusK where
type Mono Focus FocusK i j = Focus (Fst i) (Snd i) (Fst j) (Snd j)
instance IxFunctorMono Focus FocusK where
imapMono f (Focus (l,a)) _ = Focus (l,f a)
instance LnFunctorMono Focus FocusK where
type LMono Focus FocusK i k = i ~ k
type RMono Focus FocusK j l = j ~ l
weakenMono _ (Focus (l,a)) _ = Focus (l,a)
strengthenMono _ (Focus (l,a)) _ = Focus (l,a)
instance LnApplyMono Focus FocusK where
type LinkMono Focus FocusK i j k l h m = (h ~ i, j ~ k, l ~ m)
lapMono _ _ (Focus (l1,f)) (Focus (l2,a)) _ = Focus (l1 `o` l2,f a)
instance LnBindMono Focus FocusK where
lbindMono _ _ (Focus (l1,a)) f _ = Focus (l1 `o` l2,b)
where
Focus (l2,b) = f a
o :: ReifiedLens s t a' b' -> ReifiedLens a' b' a b -> ReifiedLens s t a b
o (Lens l1) (Lens l2) = Lens $ l1 . l2
| kylcarte/lnfunctors | src/Control/LnMonad/Focus.hs | bsd-3-clause | 1,605 | 1 | 9 | 312 | 605 | 335 | 270 | 43 | 1 |
module UI
( run
) where
import Brick (App (..), AttrName, BrickEvent (..),
EventM, Location (..), Next,
Padding (..), Widget, attrMap,
attrName, continue, defaultMain,
emptyWidget, fg, halt, padAll,
padBottom, showCursor, showFirstCursor,
str, withAttr, (<+>), (<=>))
import Brick.Widgets.Center (center)
import Control.Monad.IO.Class (liftIO)
import Data.Char (isSpace)
import Data.Maybe (fromMaybe)
import Data.Time (getCurrentTime)
import Data.Word (Word8)
import Graphics.Vty (Attr, Color (..), Event (..), Key (..),
Modifier (..), bold, defAttr,
withStyle)
import Text.Printf (printf)
import GottaGoFast
emptyAttrName :: AttrName
emptyAttrName = attrName "empty"
errorAttrName :: AttrName
errorAttrName = attrName "error"
resultAttrName :: AttrName
resultAttrName = attrName "result"
drawCharacter :: Character -> Widget ()
drawCharacter (Hit c) = str [c]
drawCharacter (Miss ' ') = withAttr errorAttrName $ str ['_']
drawCharacter (Miss c) = withAttr errorAttrName $ str [c]
drawCharacter (Empty c) = withAttr emptyAttrName $ str [c]
drawLine :: Line -> Widget ()
-- We display an empty line as a single space so that it still occupies
-- vertical space.
drawLine [] = str " "
drawLine ls = foldl1 (<+>) $ map drawCharacter ls
drawText :: State -> Widget ()
drawText s = padBottom (Pad 2) . foldl (<=>) emptyWidget . map drawLine $ page s
drawResults :: State -> Widget ()
drawResults s =
withAttr resultAttrName . str $
printf "%.f words per minute • %.f%% accuracy" (wpm s) (accuracy s * 100)
draw :: State -> [Widget ()]
draw s
| hasEnded s = pure . center . padAll 1 $ drawText s <=> drawResults s
| otherwise =
pure . center . padAll 1 . showCursor () (Location $ cursor s) $
drawText s <=> str " "
handleChar :: Char -> State -> EventM () (Next State)
handleChar c s
| not $ hasStarted s = do
now <- liftIO getCurrentTime
continue $ startClock now s'
| isComplete s' = do
now <- liftIO getCurrentTime
continue $ stopClock now s'
| otherwise = continue s'
where
s' = applyChar c s
handleEvent :: State -> BrickEvent () e -> EventM () (Next State)
handleEvent s (VtyEvent (EvKey key [MCtrl])) =
case key of
KChar 'c' -> halt s
KChar 'd' -> halt s
KChar 'w' -> continue $ applyBackspaceWord s
KBS -> continue $ applyBackspaceWord s
_ -> continue s
handleEvent s (VtyEvent (EvKey key [MAlt])) =
case key of
KBS -> continue $ applyBackspaceWord s
_ -> continue s
handleEvent s (VtyEvent (EvKey key [MMeta])) =
case key of
KBS -> continue $ applyBackspaceWord s
_ -> continue s
handleEvent s (VtyEvent (EvKey key []))
| hasEnded s =
case key of
KEnter -> halt s
KEsc -> halt $ s {loop = True}
_ -> continue s
| otherwise =
case key of
KChar c -> handleChar c s
KEnter -> handleChar '\n' s
KBS -> continue $ applyBackspace s
KEsc -> halt $ s {loop = True}
_ -> continue s
handleEvent s _ = continue s
app :: Attr -> Attr -> Attr -> App State e ()
app emptyAttr errorAttr resultAttr =
App
{ appDraw = draw
, appChooseCursor = showFirstCursor
, appHandleEvent = handleEvent
, appStartEvent = return
, appAttrMap =
const $
attrMap
defAttr
[ (emptyAttrName, emptyAttr)
, (errorAttrName, errorAttr)
, (resultAttrName, resultAttr)
]
}
run :: Word8 -> Word8 -> String -> IO Bool
run fgEmptyCode fgErrorCode t = do
s <- defaultMain (app emptyAttr errorAttr resultAttr) $ initialState t
return $ loop s
where
emptyAttr = fg . ISOColor $ fgEmptyCode
errorAttr = flip withStyle bold . fg . ISOColor $ fgErrorCode
-- abusing the fgErrorCode to use as a highlight colour for the results here
resultAttr = fg . ISOColor $ fgErrorCode
| hot-leaf-juice/gotta-go-fast | src/UI.hs | bsd-3-clause | 4,369 | 0 | 12 | 1,446 | 1,410 | 727 | 683 | 107 | 13 |
module ErrMsg (
LogReader
, setLogger
, handleErrMsg
) where
import Bag
import Control.Applicative
import Data.IORef
import Data.Maybe
import DynFlags
import ErrUtils
import GHC
import qualified Gap
import HscTypes
import Outputable
import System.FilePath
----------------------------------------------------------------
type LogReader = IO [String]
----------------------------------------------------------------
setLogger :: Bool -> DynFlags -> IO (DynFlags, LogReader)
setLogger False df = return (newdf, undefined)
where
newdf = df { log_action = \_ _ _ _ -> return () }
setLogger True df = do
ref <- newIORef [] :: IO (IORef [String])
let newdf = df { log_action = appendLog ref }
return (newdf, reverse <$> readIORef ref)
where
appendLog ref _ src stl msg = modifyIORef ref (\ls -> ppMsg src msg stl : ls)
----------------------------------------------------------------
handleErrMsg :: SourceError -> Ghc [String]
handleErrMsg = return . errBagToStrList . srcErrorMessages
errBagToStrList :: Bag ErrMsg -> [String]
errBagToStrList = map ppErrMsg . reverse . bagToList
----------------------------------------------------------------
ppErrMsg :: ErrMsg -> String
ppErrMsg err = ppMsg spn msg defaultUserStyle ++ ext
where
spn = head (errMsgSpans err)
msg = errMsgShortDoc err
ext = showMsg (errMsgExtraInfo err) defaultUserStyle
ppMsg :: SrcSpan -> Message -> PprStyle -> String
ppMsg spn msg stl = fromMaybe def $ do
(line,col,_,_) <- Gap.getSrcSpan spn
file <- Gap.getSrcFile spn
return $ takeFileName file ++ ":" ++ show line ++ ":" ++ show col ++ ":" ++ cts ++ "\0"
where
def = "ghc-mod:0:0:Probably mutual module import occurred\0"
cts = showMsg msg stl
----------------------------------------------------------------
showMsg :: SDoc -> PprStyle -> String
showMsg d stl = map toNull $ Gap.renderMsg d stl
where
toNull '\n' = '\0'
toNull x = x
| himura/ghc-mod | ErrMsg.hs | bsd-3-clause | 1,955 | 0 | 16 | 362 | 579 | 303 | 276 | 44 | 2 |
module Model.IO where
import Control.Monad.Trans (liftIO)
import Data.List
import Log
import Model
import Model.Repa
import Model.Types
import System.Directory
import System.FilePath
import Words
trainFiles :: (Progress m) => Int -> [String] -> m Model
trainFiles numFeatures txts = do
(dict, contents) <- tokenizeFiles txts
progress Fine (EncodedDictionary dict)
trainModel numFeatures dict contents
analyzeDirectory :: (Progress m) => Int -> String -> m Model
analyzeDirectory numFeatures dir = do
txts <- filter (isSuffixOf ".txt") <$> liftIO (getDirectoryContents dir)
trainFiles numFeatures $ map (dir </>) txts
| abailly/hs-word2vec | src/Model/IO.hs | bsd-3-clause | 720 | 0 | 11 | 186 | 212 | 110 | 102 | 19 | 1 |
-- |Composes NetCore policies and predicates, and defines how these policies
-- interpret abstract packets.
module Frenetic.NetCore.Semantics
( evalProgram
, Id (..)
, Act (..)
, Pol (..)
, In (..)
, Out (..)
, Callback (..)
, Callbacks
, callbackDelayStream
, callbackInterval
, evalPol
, evalAct
, desugarPolicy
, synthRestrictPol
, isForward
, isGetPacket
, isQuery
, matchPkt
, actOnMatch
, preimgOfAct
, seqAct
, outToMicroflowAction
) where
import Prelude hiding (pred)
import Nettle.OpenFlow.Match
import Nettle.OpenFlow.Packet (BufferID)
import Nettle.IPv4.IPAddress
import Frenetic.NetCore.Reduce (isEmptyPredicate)
import Frenetic.Pattern
import Frenetic.Common
import Frenetic.Topo (Switch,Port,Loc)
import Frenetic.NetCore.Types
import Frenetic.NetCore.Short
import qualified Data.ByteString.Lazy as BS
import Control.Monad.State
import qualified Data.Map as M
import Data.Generics
{-# LANGUAGE DeriveDataTypeable #-}
type Id = Int
data Prog
= ProgPol Pol
| ProgLetQueue Switch Port Word16 (Queue -> Prog)
| ProgUnion Prog Prog
data Pol
= PolEmpty
| PolProcessIn Predicate [Act]
| PolUnion Pol Pol
| PolRestrict Pol Predicate
| PolGenPacket Id
-- | PolSeq Pol Pol
deriving (Show, Eq, Data, Typeable)
data Act
= ActFwd PseudoPort Modification
| ActQueryPktCounter Id Int
| ActQueryByteCounter Id Int
| ActGetPkt Id
| ActMonSwitch Id
deriving (Show, Eq, Data, Typeable)
data In
= InPkt Loc Packet (Maybe BufferID)
| InGenPkt Id Switch PseudoPort Packet ByteString
| InCounters Id Switch Predicate Integer {- packets -} Integer {- bytes -}
| InSwitchEvt SwitchEvent
deriving (Show, Eq, Data, Typeable)
data Out
= OutPkt Switch PseudoPort Packet (Either BufferID ByteString)
| OutIncrPktCounter Id
| OutIncrByteCounter Id Integer
| OutUpdPktCounter Id Switch Predicate Integer
| OutUpdByteCounter Id Switch Predicate Integer
| OutGetPkt Id Loc Packet
| OutNothing
| OutSwitchEvt Id SwitchEvent
deriving (Show, Eq, Data, Typeable)
data Callback
= CallbackByteCounter Int ((Switch, Integer) -> IO ())
| CallbackPktCounter Int ((Switch, Integer) -> IO ())
| CallbackGetPkt ((Loc, Packet) -> IO ())
| CallbackMonSwitch (SwitchEvent -> IO ())
instance Show Callback where
show (CallbackByteCounter n _) = "CallbackByteCounter " ++ show n
show (CallbackPktCounter n _) = "CallbackPktCounter " ++ show n
show (CallbackGetPkt _) = "CallbackGetPkt"
show (CallbackMonSwitch _) = "CallbackMonSwitch"
type Callbacks = Map Id Callback
outToMicroflowAction (OutPkt _ pt _ (Left _)) = Just (ActFwd pt unmodified)
outToMicroflowAction (OutGetPkt x _ _) = Just (ActGetPkt x)
outToMicroflowAction _ = Nothing
seqAct :: Act -> Act -> Maybe Act
seqAct (ActFwd p mods1) (ActFwd InPort mods2) = Just (ActFwd p mods3)
where mods3 = Modification
(modifyDlSrc mods2 `ifLeft` modifyDlSrc mods1)
(modifyDlDst mods2 `ifLeft` modifyDlDst mods1)
(modifyDlVlan mods2 `ifLeft` modifyDlVlan mods1)
(modifyDlVlanPcp mods2 `ifLeft` modifyDlVlanPcp mods1)
(modifyNwSrc mods2 `ifLeft` modifyNwSrc mods1)
(modifyNwDst mods2 `ifLeft` modifyNwDst mods1)
(modifyNwTos mods2 `ifLeft` modifyNwTos mods1)
(modifyTpSrc mods2 `ifLeft` modifyTpSrc mods1)
(modifyTpDst mods2 `ifLeft` modifyTpDst mods1)
seqAct (ActFwd _ mods1) (ActFwd p mods2) = Just (ActFwd p mods3)
where mods3 = Modification
(modifyDlSrc mods2 `ifLeft` modifyDlSrc mods1)
(modifyDlDst mods2 `ifLeft` modifyDlDst mods1)
(modifyDlVlan mods2 `ifLeft` modifyDlVlan mods1)
(modifyDlVlanPcp mods2 `ifLeft` modifyDlVlanPcp mods1)
(modifyNwSrc mods2 `ifLeft` modifyNwSrc mods1)
(modifyNwDst mods2 `ifLeft` modifyNwDst mods1)
(modifyNwTos mods2 `ifLeft` modifyNwTos mods1)
(modifyTpSrc mods2 `ifLeft` modifyTpSrc mods1)
(modifyTpDst mods2 `ifLeft` modifyTpDst mods1)
seqAct _ _ = Nothing
outToIn :: Out -> Maybe In
-- TODO(arjun): pol1;pol2 doesn't work if pol1 emits to a pseudoport?
outToIn (OutPkt sw (Physical pt) pk (Left buf)) =
Just (InPkt (Loc sw pt) pk (Just buf))
-- TODO(arjun): perhaps Out should carry the channel ID
-- outToIn (OutPkt sw pt pk (Right bytes)) = Just (InGenPkt ??? sw pt pk bytes)
outToIn _ = Nothing
isGetPacket (ActGetPkt{}) = True
isGetPacket _ = False
isForward :: Act -> Bool
isForward (ActFwd _ _) = True
isForward _ = False
isQuery :: Act -> Bool
isQuery act = case act of
ActQueryPktCounter {} -> True
ActQueryByteCounter {} -> True
ActGetPkt {} -> True
ActFwd {} -> False
ActMonSwitch {} -> True
-- |Restricts the policy's domain to 'pred'. Does not eliminate
-- 'Restrict' expressions, but does restrict their restrictions.
synthRestrictPol :: Pol -> Predicate -> Pol
synthRestrictPol pol pred = case pol of
PolEmpty -> PolEmpty
PolProcessIn pred' acts ->
PolProcessIn (And pred' pred) acts
PolUnion pol1 pol2 ->
PolUnion (synthRestrictPol pol1 pred) (synthRestrictPol pol2 pred)
-- PolSeq pol1 pol2 ->
-- PolSeq (synthRestrictPol pol1 pred) pol2 -- No need to restrict pol2!
PolRestrict (PolGenPacket chan) pred' ->
PolRestrict (PolGenPacket chan) (And pred pred')
PolRestrict pol pred' ->
PolRestrict pol (And pred pred')
PolGenPacket chan ->
PolRestrict (PolGenPacket chan) pred
inPacket :: In -> Maybe Packet
inPacket (InPkt _ pkt _) = Just pkt
inPacket (InGenPkt _ _ _ pkt _) = Just pkt
inPacket (InCounters _ _ _ _ _) = Nothing
inPacket (InSwitchEvt _) = Nothing
evalPol = pol
evalAct = action
pol :: Pol -> In -> [Out]
pol PolEmpty _ = []
pol (PolUnion p1 p2) inp = pol p1 inp ++ pol p2 inp
pol (PolProcessIn pr acts) inp =
if pred pr inp then map (\a -> action a inp) acts else []
pol (PolRestrict p pr) inp =
if pred pr inp then pol p inp else []
pol (PolGenPacket x) inp = case inp of
InGenPkt y sw pt pkt raw ->
if x == y then [OutPkt sw pt pkt (Right raw)] else []
otherwise -> []
-- pol (PolSeq p1 p2) inp = concatMap (pol p2) (mapMaybe outToIn (pol p1 inp))
action :: Act -> In -> Out
action (ActFwd pt mods) (InPkt (Loc sw _) hdrs maybePkt) = case maybePkt of
Just pkt -> OutPkt sw pt hdrs (Left pkt)
Nothing -> OutNothing
action (ActFwd _ _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActFwd _ _) (InCounters _ _ _ _ _) = OutNothing
action (ActFwd _ _) (InSwitchEvt _) = OutNothing
action (ActQueryPktCounter x _) (InCounters y sw pred numPkts _) =
if x == y then
OutUpdPktCounter x sw pred numPkts
else
OutNothing
action (ActQueryPktCounter _ _) (InPkt _ _ _) = OutNothing
action (ActQueryPktCounter x _) (InGenPkt _ _ _ _ _) = OutIncrPktCounter x
action (ActQueryPktCounter _ _) (InSwitchEvt _) = OutNothing
action (ActQueryByteCounter x _) (InCounters y sw pred _ numBytes) =
if x == y then
OutUpdByteCounter x sw pred numBytes
else
OutNothing
action (ActQueryByteCounter _ _) (InPkt _ _ _) = OutNothing
action (ActQueryByteCounter x _) (InGenPkt _ _ _ _ pkt) =
OutIncrByteCounter x (fromIntegral (BS.length pkt))
action (ActQueryByteCounter _ _) (InSwitchEvt _) = OutNothing
action (ActGetPkt x) (InPkt loc hdrs _) = OutGetPkt x loc hdrs
action (ActGetPkt _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActGetPkt _) (InCounters _ _ _ _ _) = OutNothing
action (ActGetPkt _) (InSwitchEvt _) = OutNothing
action (ActMonSwitch x) (InSwitchEvt evt) = OutSwitchEvt x evt
action (ActMonSwitch _) (InPkt _ _ _) = OutNothing
action (ActMonSwitch _) (InGenPkt _ _ _ _ _) = OutNothing
action (ActMonSwitch _) (InCounters _ _ _ _ _) = OutNothing
ifLeft :: Maybe a -> Maybe a -> Maybe a
ifLeft (Just x) _ = Just x
ifLeft Nothing y = y
eqIfJust :: Eq a => Maybe a -> Maybe a -> Maybe (Maybe a)
eqIfJust (Just x) (Just y) = if x == y then Just Nothing else Nothing
eqIfJust (Just x) Nothing = Just Nothing
eqIfJust Nothing rhs = Just rhs
eqIfJustIP :: Maybe IPAddress
-> IPAddressPrefix
-> Maybe IPAddressPrefix
eqIfJustIP (Just x) y =
if x `elemOfPrefix` y then Just (IPAddressPrefix (IPAddress 0) 0) else Nothing
eqIfJustIP Nothing rhs = Just rhs
preimgOfAct :: Act -> Match -> Maybe Match
preimgOfAct (ActFwd (Physical pt) (Modification{..})) (Match{..}) = do
inPort <- eqIfJust (Just pt) inPort
srcEthAddress <- eqIfJust modifyDlSrc srcEthAddress
dstEthAddress <- eqIfJust modifyDlDst dstEthAddress
let unvlan Nothing = 0xffff
unvlan (Just v) = v
vLANID <- eqIfJust (fmap unvlan modifyDlVlan) vLANID
vLANPriority <- eqIfJust modifyDlVlanPcp vLANPriority
ipTypeOfService <- eqIfJust modifyNwTos ipTypeOfService
srcIPAddress <- eqIfJustIP modifyNwSrc srcIPAddress
dstIPAddress <- eqIfJustIP modifyNwDst dstIPAddress
srcTransportPort <- eqIfJust modifyTpSrc srcTransportPort
dstTransportPort <- eqIfJust modifyTpDst dstTransportPort
return $ Match inPort srcEthAddress dstEthAddress vLANID vLANPriority
ethFrameType ipTypeOfService matchIPProtocol srcIPAddress
dstIPAddress srcTransportPort dstTransportPort
preimgOfAct (ActFwd InPort (Modification{..})) (Match{..}) = do
srcEthAddress <- eqIfJust modifyDlSrc srcEthAddress
dstEthAddress <- eqIfJust modifyDlDst dstEthAddress
let unvlan Nothing = 0xffff
unvlan (Just v) = v
vLANID <- eqIfJust (fmap unvlan modifyDlVlan) vLANID
vLANPriority <- eqIfJust modifyDlVlanPcp vLANPriority
ipTypeOfService <- eqIfJust modifyNwTos ipTypeOfService
srcIPAddress <- eqIfJustIP modifyNwSrc srcIPAddress
dstIPAddress <- eqIfJustIP modifyNwDst dstIPAddress
srcTransportPort <- eqIfJust modifyTpSrc srcTransportPort
dstTransportPort <- eqIfJust modifyTpDst dstTransportPort
return $ Match Nothing srcEthAddress dstEthAddress vLANID vLANPriority
ethFrameType ipTypeOfService matchIPProtocol srcIPAddress
dstIPAddress srcTransportPort dstTransportPort
preimgOfAct _ _ = Nothing
actOnMatch :: Act -> Match -> Maybe Match
actOnMatch (ActFwd (Physical pt) (Modification{..})) (Match{..}) =
Just $ Match (Just pt)
(modifyDlSrc `ifLeft` srcEthAddress)
(modifyDlDst `ifLeft` dstEthAddress)
(case modifyDlVlan of
Just Nothing -> Just 0xffff
Just (Just vlan) -> Just vlan
Nothing -> vLANID)
(modifyDlVlanPcp `ifLeft` vLANPriority)
ethFrameType
(modifyNwTos `ifLeft` ipTypeOfService)
matchIPProtocol
(case modifyNwSrc of
Just ip -> IPAddressPrefix ip 32
Nothing -> srcIPAddress)
(case modifyNwDst of
Just ip -> IPAddressPrefix ip 32
Nothing -> dstIPAddress)
(modifyTpSrc `ifLeft` srcTransportPort)
(modifyTpDst `ifLeft` dstTransportPort)
actOnMatch (ActFwd AllPorts _) _ = Nothing
actOnMatch (ActFwd InPort _) _ = Nothing -- TODO(mjr): Not sure what this func is...
actOnMatch (ActFwd (ToQueue _) _) _ = Nothing -- TODO(arjun): easy IMO
actOnMatch (ActQueryPktCounter _ _) _ = Nothing
actOnMatch (ActQueryByteCounter _ _) _ = Nothing
actOnMatch (ActGetPkt _) _ = Nothing
actOnMatch (ActMonSwitch _) _ = Nothing
-- |When a packet-specific predicate is applied to a non-packet input, we
-- produce this default value.
nonPktDefault = False
counterMatches :: In -> Predicate -> Bool
counterMatches (InCounters _ _ pred _ _) pred' =
isEmptyPredicate (And pred (Not pred'))
counterMatches _ _ = False
-- |'pktHeaderIs inPkt sel v' tests if the input packet's header is 'v'. If
-- 'inPkt' is not a packet, but some other type of input, 'pktHeaderIs' returns
-- 'False'.
pktHeaderIs :: Eq a => In -> (Packet -> a) -> a -> Bool
pktHeaderIs inp sel v = case inPacket inp of
Just pkt -> sel pkt == v
Nothing -> nonPktDefault
-- |Use 'tpPktHeaderIs' it match OpenFlow headers that only meaningful for
-- certain types of packets (e.g., TCP ports and IP protocol.)
tpPktHeaderIs :: Eq a => In -> (Packet -> Maybe a) -> a -> Bool
tpPktHeaderIs inp sel v = case inPacket inp of
Just pkt -> case sel pkt of
Nothing -> False
Just v' -> v' == v
Nothing -> nonPktDefault
pred :: Predicate -> In -> Bool
pred Any _ = True
pred None _ = False
pred (Or pr1 pr2) inp = pred pr1 inp || pred pr2 inp
pred (And pr1 pr2) inp = pred pr1 inp && pred pr2 inp
pred (Not pr) inp = not (pred pr inp)
pred (DlSrc eth) inp =
pktHeaderIs inp pktDlSrc eth || counterMatches inp (DlSrc eth)
pred (DlDst eth) inp =
pktHeaderIs inp pktDlDst eth || counterMatches inp (DlDst eth)
pred (DlTyp typ) inp =
pktHeaderIs inp pktDlTyp typ || counterMatches inp (DlTyp typ)
pred (DlVlan vlan) inp =
pktHeaderIs inp pktDlVlan vlan || counterMatches inp (DlVlan vlan)
pred (DlVlanPcp pcp) inp =
pktHeaderIs inp pktDlVlanPcp pcp || counterMatches inp (DlVlanPcp pcp)
pred (NwSrc (IPAddressPrefix prefix len)) inp = case inPacket inp of
Just Packet{..} -> case pktNwSrc of
Nothing -> len == 0
Just ip -> ip `elemOfPrefix` (IPAddressPrefix prefix len)
Nothing -> nonPktDefault
pred (NwDst (IPAddressPrefix prefix len)) inp = case inPacket inp of
Just Packet{..} -> case pktNwDst of
Nothing -> len == 0
Just ip -> ip `elemOfPrefix` (IPAddressPrefix prefix len)
Nothing -> nonPktDefault
pred (NwProto proto) inp =
pktHeaderIs inp pktNwProto proto || counterMatches inp (NwProto proto)
pred (TpSrcPort pt) inp =
tpPktHeaderIs inp pktTpSrc pt || counterMatches inp (TpSrcPort pt)
pred (TpDstPort pt) inp =
tpPktHeaderIs inp pktTpDst pt || counterMatches inp (TpDstPort pt)
pred (NwTos tos) inp =
pktHeaderIs inp pktNwTos tos || counterMatches inp (NwTos tos)
pred (Switch sw) inp = case inp of
InPkt (Loc sw' _) _ _ -> sw' == sw
InGenPkt _ sw' _ _ _ -> sw' == sw
InSwitchEvt (SwitchConnected sw' _) -> sw == sw'
InSwitchEvt (SwitchDisconnected sw') -> sw == sw'
InSwitchEvt (PortEvent sw' _ _ _) -> sw == sw'
InCounters _ _ pred _ _ -> isEmptyPredicate (And pred (Not (Switch sw)))
pred (IngressPort pt) inp = case inp of
InPkt (Loc _ pt') _ _ -> pt == pt'
InGenPkt _ _ pt' _ _ -> case pt' of
Physical p -> p == pt
otherwise -> False
InSwitchEvt (PortEvent _ pt' _ _) -> pt == pt'
InSwitchEvt (SwitchConnected _ _) -> nonPktDefault
InSwitchEvt (SwitchDisconnected _) -> nonPktDefault
InCounters _ _ pred _ _ -> isEmptyPredicate (And pred (Not (IngressPort pt)))
callbackInterval :: Callback -> Maybe Int
callbackInterval (CallbackByteCounter n _) = Just n
callbackInterval (CallbackPktCounter n _) = Just n
callbackInterval (CallbackGetPkt _) = Nothing
callbackInterval (CallbackMonSwitch _) = Nothing
insDelayStream :: Int
-> a
-> [Either a Int]
-> [Either a Int]
insDelayStream delay evt [] = [Right delay, Left evt]
insDelayStream delay evt (Right delay' : rest) =
let delay'' = delay - delay'
in if delay'' > 0 then
(Right delay') : (insDelayStream delay'' evt rest)
else if delay'' == 0 then
(Right delay) : (Left evt) : rest
else {- delay'' < 0 -}
(Right delay) : (Left evt) : (Right (delay' - delay)) : rest
insDelayStream delay evt (Left evt' : rest) =
(Left evt') : (insDelayStream delay evt rest)
-- |Returns an infinite stream of callbacks and delays. The controller should
-- invoke callbacks with the current counter or pause for the delay.
--
-- The delay is in millseconds. (Note that 'threadDelay' takes a
-- nanosecond argument.)
callbackDelayStream :: Callbacks -> [Either (Id, Callback) Int]
callbackDelayStream callbacks = loop initial
where loop :: [Either (Int, Id, Callback) Int] -> [Either (Id, Callback) Int]
loop [] = []
loop (Right delay : future) = (Right delay) : (loop future)
loop (Left evt@(delay, x, cb) : future) =
let future' = insDelayStream delay evt future
in (Left (x, cb)) : (loop future')
select :: (Id, Callback) -> Maybe (Int, Id, Callback)
select (x, cb) = case callbackInterval cb of
Nothing -> Nothing
Just delay -> Just (delay, x, cb)
initial :: [Either (Int, Id, Callback) Int]
initial = foldr (\evt@(delay, _,_) acc -> insDelayStream delay evt acc)
[]
(mapMaybe select (M.toList callbacks))
type DSState = (Id, Map Id Callback, [(Id, Chan (Loc, ByteString))])
type DS a = State DSState a
newCallback :: Callback -> DS Id
newCallback cb = do
(x, cbs, gens) <- get
put (x+1, M.insert x cb cbs, gens)
return x
newGenPacket :: Chan (Loc, ByteString) -> DS Id
newGenPacket chan = do
(x, cbs, gens) <- get
put (x+1, cbs, (x,chan):gens)
return x
dsPolicy :: Policy -> DS Pol
dsPolicy PoBottom = return PolEmpty
dsPolicy (PoBasic pred actions) = do
actions' <- mapM dsAction actions
return (PolProcessIn pred actions')
dsPolicy (PoUnion pol1 pol2) = do
pol1' <- dsPolicy pol1
pol2' <- dsPolicy pol2
return (PolUnion pol1' pol2')
dsPolicy (Restrict pol pred) = do
pol' <- dsPolicy pol
return (PolRestrict pol' pred)
dsPolicy (SendPackets chan) = do
x <- newGenPacket chan
return (PolGenPacket x)
dsPolicy (Sequence pol1 pol2) = do
pol1' <- dsPolicy pol1
pol2' <- dsPolicy pol2
return (unionClean $ deSeq pol1' pol2')
unionClean (PolUnion PolEmpty a) = unionClean a
unionClean (PolUnion a PolEmpty) = unionClean a
unionClean (PolUnion a b) = PolUnion (unionClean a) (unionClean b)
unionClean (PolRestrict a pred) = PolRestrict (unionClean a) pred
unionClean a = a
deSeq (PolUnion p1 p2) p3 = PolUnion (deSeq p1 p3) (deSeq p2 p3)
deSeq (PolRestrict p1 pred) p3 = PolRestrict (deSeq p1 p3) pred
deSeq (PolGenPacket id) _ = PolGenPacket id
deSeq PolEmpty _ = PolEmpty
deSeq (PolProcessIn pred acts) pol = (foldl PolUnion PolEmpty) $ map (deSeq1 pred pol) acts
rightIfJust Nothing a = a
rightIfJust a Nothing = a
rightIfJust _ b = b
-- This may not handle the semantics of 'stripVlan' correctly
unionModR Modification{..} (Modification
modifyDlSrc1
modifyDlDst1
(Just Nothing)
modifyDlVlanPcp1
modifyNwSrc1
modifyNwDst1
modifyNwTos1
modifyTpSrc1
modifyTpDst1)
=
Modification (modifyDlSrc `rightIfJust` modifyDlSrc1)
(modifyDlDst `rightIfJust` modifyDlDst1)
(Just Nothing)
Nothing
(modifyNwSrc `rightIfJust` modifyNwSrc1)
(modifyNwDst `rightIfJust` modifyNwDst1)
(modifyNwTos `rightIfJust` modifyNwTos1)
(modifyTpSrc `rightIfJust` modifyTpSrc1)
(modifyTpDst `rightIfJust` modifyTpDst1)
unionModR Modification{..} (Modification
modifyDlSrc1
modifyDlDst1
modifyDlVlan1
modifyDlVlanPcp1
modifyNwSrc1
modifyNwDst1
modifyNwTos1
modifyTpSrc1
modifyTpDst1)
=
Modification (modifyDlSrc `rightIfJust` modifyDlSrc1)
(modifyDlDst `rightIfJust` modifyDlDst1)
(modifyDlVlan `rightIfJust` modifyDlVlan1)
(modifyDlVlanPcp `rightIfJust` modifyDlVlanPcp1)
(modifyNwSrc `rightIfJust` modifyNwSrc1)
(modifyNwDst `rightIfJust` modifyNwDst1)
(modifyNwTos `rightIfJust` modifyNwTos1)
(modifyTpSrc `rightIfJust` modifyTpSrc1)
(modifyTpDst `rightIfJust` modifyTpDst1)
deSeq1 pred pol act = PolRestrict (transformPol pol act) pred
transformPol (PolUnion p1 p2) a = PolUnion (transformPol p1 a) (transformPol p2 a)
transformPol (PolProcessIn pred acts) act = PolProcessIn (transformPred pred act) (map (transformAct act) acts)
transformAct (ActFwd pOld modOld) (ActFwd InPort modNew) = ActFwd pOld (modOld `unionModR` modNew)
transformAct (ActFwd pOld modOld) (ActFwd pNew modNew) = ActFwd pNew (modOld `unionModR` modNew)
-- transformAct a b = error "Don't know how to sequences actions " ++ (show a) ++ " " ++ (show b)
transformPred (And p1 p2) act = And (transformPred p1 act) (transformPred p2 act)
transformPred (Or p1 p2) act = Or (transformPred p1 act) (transformPred p2 act)
transformPred (Not p) act = Not (transformPred p act)
transformPred (DlSrc val) (ActFwd p Modification{..}) = (deletePred val modifyDlSrc DlSrc)
transformPred (DlDst val) (ActFwd p Modification{..}) = (deletePred val modifyDlDst DlDst)
transformPred (DlTyp val) (ActFwd p Modification{..}) = DlTyp val
transformPred (DlVlan val) (ActFwd p Modification{..}) = (deletePred val modifyDlVlan DlVlan)
transformPred (DlVlanPcp val) (ActFwd p Modification{..}) = (deletePred val modifyDlVlanPcp DlVlanPcp)
{- Need to handle IP prefix matching over set ip addresses. Avoiding for now -}
-- transformPred (NwSrc val) (ActFwd p Modification{..}) = (deletePred val modifyNwSrc NwSrc)
-- transformPred (NwDst val) (ActFwd p Modification{..}) = (deletePred val modifyNwDst NwDst)
transformPred (NwProto val) (ActFwd p Modification{..}) = NwProto val
transformPred (NwTos val) (ActFwd p Modification{..}) = (deletePred val modifyNwTos NwTos)
transformPred (TpSrcPort val) (ActFwd p Modification{..}) = (deletePred val modifyTpSrc TpSrcPort)
transformPred (TpDstPort val) (ActFwd p Modification{..}) = (deletePred val modifyTpDst TpDstPort)
transformPred (IngressPort val) (ActFwd (Physical p) Modification{..}) = (deletePred val (Just p) IngressPort)
transformPred (IngressPort val) (ActFwd InPort Modification{..}) = IngressPort val
transformPred (Switch val) (ActFwd p Modification{..}) = Switch val
transformPred Any act = Any
transformPred None act = None
deletePred a (Just b) field = if (a == b) then Any else None
deletePred a Nothing field = field a
-- getModVal Modification{..} DlSrc = modifyDlSrc
-- getModVal Modification{..} DlDst = modifyDlDst
-- getModVal Modification{..} DlVlan = modifyDlVlan
-- getModVal Modification{..} DlVlanPcp = modifyDlVlanPcp
-- getModVal Modification{..} NwSrc = modifyNwSrc
-- getModVal Modification{..} NwDst = modifyNwDst
-- getModVal Modification{..} NwTos = modifyNwTos
-- getModVal Modification{..} TpSrcPort = modifyTpSrc
-- getModVal Modification{..} TpDstPort = modifyTpDst
-- getModVal _ _ = Nothing
dsAction :: Action -> DS Act
dsAction (Forward pt mods) =
return (ActFwd pt mods)
dsAction (CountPackets _ interval cb) = do
x <- newCallback (CallbackPktCounter interval cb)
return (ActQueryPktCounter x interval)
dsAction (CountBytes _ interval cb) = do
x <- newCallback (CallbackByteCounter interval cb)
return (ActQueryByteCounter x interval)
dsAction (GetPacket _ cb) = do
x <- newCallback (CallbackGetPkt cb)
return (ActGetPkt x)
dsAction (MonitorSwitch cb) = do
x <- newCallback (CallbackMonSwitch cb)
return (ActMonSwitch x)
desugarPolicy :: Policy
-> (Callbacks,
[(Id, Chan (Loc, ByteString))],
Pol)
desugarPolicy pol = (cbs, gens, pol')
where (pol', (_, cbs, gens)) = runState (dsPolicy pol) (0, M.empty, [])
evalProgram :: Program
-> (Map Switch [Queue], Policy)
evalProgram prog = (M.fromListWith (++) queues, pol)
where (qMap, pol) = eval M.empty prog
queues = concatMap (\((sw, _), (_, qs)) -> zip [sw ..] (map (:[]) qs))
-- I assume nobody is reading this code.
(M.toList qMap)
eval qMap prog = case prog of
Policy pol -> (qMap, pol)
ProgramUnion prog1 prog2 ->
let (qMap', pol1) = eval qMap prog1
(qMap'', pol2) = eval qMap' prog2
in (qMap'', pol1 `mappend` pol2)
WithQueue sw pt rate fn -> case M.lookup (sw,pt) qMap of
Nothing ->
let q = Queue sw pt 1 rate
in eval (M.insert (sw,pt) (1, [q]) qMap) (fn q)
Just (n, qs) ->
let q = Queue sw pt (n+1) rate
in eval (M.insert (sw,pt) (n+1, q : qs) qMap) (fn q)
matchHdr :: Eq a => a -> Maybe a -> Bool
matchHdr _ Nothing = True
matchHdr v (Just v') = v == v'
matchNwHdr :: Eq a => Maybe a -> Maybe a -> Bool
matchNwHdr _ Nothing = True
matchNwHdr Nothing (Just _) = False
matchNwHdr (Just v) (Just v') = v == v'
matchPkt :: Match -> Port -> Packet -> Bool
matchPkt (Match {..}) pktInPort (Packet{..}) =
pktInPort `matchHdr` inPort &&
pktDlSrc `matchHdr` srcEthAddress &&
pktDlDst `matchHdr` dstEthAddress &&
pktDlVlan' `matchHdr` vLANID &&
pktDlVlanPcp `matchHdr` vLANPriority &&
pktDlTyp `matchHdr` ethFrameType &&
pktNwProto `matchHdr` matchIPProtocol &&
pktNwTos `matchHdr` ipTypeOfService &&
pktNwSrc `matchIP` srcIPAddress &&
pktNwDst `matchIP` dstIPAddress &&
pktTpSrc `matchNwHdr` srcTransportPort &&
pktTpDst `matchNwHdr` dstTransportPort
where pktDlVlan' = case pktDlVlan of
Just v -> v
Nothing -> 0xffff
matchIP Nothing (IPAddressPrefix _ 0) = True
matchIP Nothing (IPAddressPrefix _ _) = False
matchIP (Just ip) prefix = elemOfPrefix ip prefix
| frenetic-lang/netcore-1.0 | src/Frenetic/NetCore/Semantics.hs | bsd-3-clause | 25,513 | 0 | 27 | 6,023 | 8,548 | 4,370 | 4,178 | -1 | -1 |
{-# LANGUAGE CPP, ViewPatterns, DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
------------------------------------------------------------------------------
-- |
-- Module: Database.PostgreSQL.Simple.HStore.Implementation
-- Copyright: (c) 2013 Leon P Smith
-- License: BSD3
-- Maintainer: Leon P Smith <[email protected]>
-- Stability: experimental
--
-- This code has yet to be profiled and optimized.
--
------------------------------------------------------------------------------
module Database.PostgreSQL.Simple.HStore.Implementation where
import Control.Applicative
import qualified Data.Attoparsec.ByteString as P
import qualified Data.Attoparsec.ByteString.Char8 as P (isSpace_w8)
import qualified Data.ByteString as BS
import Data.ByteString.Builder (Builder, byteString, char8)
import qualified Data.ByteString.Builder as BU
import Data.ByteString.Internal (c2w, w2c)
import qualified Data.ByteString.Lazy as BL
#if !MIN_VERSION_bytestring(0,10,0)
import qualified Data.ByteString.Lazy.Internal as BL (foldrChunks)
#endif
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Text(Text)
import qualified Data.Text as TS
import qualified Data.Text.Encoding as TS
import Data.Text.Encoding.Error(UnicodeException)
import qualified Data.Text.Lazy as TL
import Data.Typeable
import Data.Monoid(Monoid(..))
import Data.Semigroup
import Database.PostgreSQL.Simple.FromField
import Database.PostgreSQL.Simple.ToField
class ToHStore a where
toHStore :: a -> HStoreBuilder
-- | Represents valid hstore syntax.
data HStoreBuilder
= Empty
| Comma !Builder
deriving (Typeable)
instance ToHStore HStoreBuilder where
toHStore = id
toBuilder :: HStoreBuilder -> Builder
toBuilder x = case x of
Empty -> mempty
Comma c -> c
toLazyByteString :: HStoreBuilder -> BL.ByteString
toLazyByteString x = case x of
Empty -> BL.empty
Comma c -> BU.toLazyByteString c
instance Semigroup HStoreBuilder where
Empty <> x = x
Comma a <> x
= Comma (a `mappend` case x of
Empty -> mempty
Comma b -> char8 ',' `mappend` b)
instance Monoid HStoreBuilder where
mempty = Empty
#if !(MIN_VERSION_base(4,11,0))
mappend = (<>)
#endif
class ToHStoreText a where
toHStoreText :: a -> HStoreText
-- | Represents escape text, ready to be the key or value to a hstore value
newtype HStoreText = HStoreText Builder deriving (Typeable, Semigroup, Monoid)
instance ToHStoreText HStoreText where
toHStoreText = id
-- | Assumed to be UTF-8 encoded
instance ToHStoreText BS.ByteString where
toHStoreText str = HStoreText (escapeAppend str mempty)
-- | Assumed to be UTF-8 encoded
instance ToHStoreText BL.ByteString where
toHStoreText = HStoreText . BL.foldrChunks escapeAppend mempty
instance ToHStoreText TS.Text where
toHStoreText str = HStoreText (escapeAppend (TS.encodeUtf8 str) mempty)
instance ToHStoreText TL.Text where
toHStoreText = HStoreText . TL.foldrChunks (escapeAppend . TS.encodeUtf8) mempty
escapeAppend :: BS.ByteString -> Builder -> Builder
escapeAppend = loop
where
loop (BS.break quoteNeeded -> (a,b)) rest
= byteString a `mappend`
case BS.uncons b of
Nothing -> rest
Just (c,d) -> quoteChar c `mappend` loop d rest
quoteNeeded c = c == c2w '\"' || c == c2w '\\'
quoteChar c
| c == c2w '\"' = byteString "\\\""
| otherwise = byteString "\\\\"
hstore :: (ToHStoreText a, ToHStoreText b) => a -> b -> HStoreBuilder
hstore (toHStoreText -> (HStoreText key)) (toHStoreText -> (HStoreText val)) =
Comma (char8 '"' `mappend` key `mappend` byteString "\"=>\""
`mappend` val `mappend` char8 '"')
instance ToField HStoreBuilder where
toField Empty = toField (BS.empty)
toField (Comma x) = toField (BU.toLazyByteString x)
newtype HStoreList = HStoreList {fromHStoreList :: [(Text,Text)]} deriving (Typeable, Show)
-- | hstore
instance ToHStore HStoreList where
toHStore (HStoreList xs) = mconcat (map (uncurry hstore) xs)
instance ToField HStoreList where
toField xs = toField (toHStore xs)
-- | hstore
instance FromField HStoreList where
fromField f mdat = do
typ <- typename f
if typ /= "hstore"
then returnError Incompatible f ""
else case mdat of
Nothing -> returnError UnexpectedNull f ""
Just dat ->
case P.parseOnly (parseHStore <* P.endOfInput) dat of
Left err ->
returnError ConversionFailed f err
Right (Left err) ->
returnError ConversionFailed f "unicode exception" <|>
conversionError err
Right (Right val) ->
return val
newtype HStoreMap = HStoreMap {fromHStoreMap :: Map Text Text} deriving (Eq, Ord, Typeable, Show)
instance ToHStore HStoreMap where
toHStore (HStoreMap xs) = Map.foldrWithKey f mempty xs
where f k v xs' = hstore k v `mappend` xs'
instance ToField HStoreMap where
toField xs = toField (toHStore xs)
instance FromField HStoreMap where
fromField f mdat = convert <$> fromField f mdat
where convert (HStoreList xs) = HStoreMap (Map.fromList xs)
parseHStoreList :: BS.ByteString -> Either String HStoreList
parseHStoreList dat =
case P.parseOnly (parseHStore <* P.endOfInput) dat of
Left err -> Left (show err)
Right (Left err) -> Left (show err)
Right (Right val) -> Right val
parseHStore :: P.Parser (Either UnicodeException HStoreList)
parseHStore = do
kvs <- P.sepBy' (skipWhiteSpace *> parseHStoreKeyVal)
(skipWhiteSpace *> P.word8 (c2w ','))
return $ HStoreList <$> sequence kvs
parseHStoreKeyVal :: P.Parser (Either UnicodeException (Text,Text))
parseHStoreKeyVal = do
mkey <- parseHStoreText
case mkey of
Left err -> return (Left err)
Right key -> do
skipWhiteSpace
_ <- P.string "=>"
skipWhiteSpace
mval <- parseHStoreText
case mval of
Left err -> return (Left err)
Right val -> return (Right (key,val))
skipWhiteSpace :: P.Parser ()
skipWhiteSpace = P.skipWhile P.isSpace_w8
parseHStoreText :: P.Parser (Either UnicodeException Text)
parseHStoreText = do
_ <- P.word8 (c2w '"')
mtexts <- parseHStoreTexts id
case mtexts of
Left err -> return (Left err)
Right texts -> do
_ <- P.word8 (c2w '"')
return (Right (TS.concat texts))
parseHStoreTexts :: ([Text] -> [Text])
-> P.Parser (Either UnicodeException [Text])
parseHStoreTexts acc = do
mchunk <- TS.decodeUtf8' <$> P.takeWhile (not . isSpecialChar)
case mchunk of
Left err -> return (Left err)
Right chunk ->
(do
_ <- P.word8 (c2w '\\')
c <- TS.singleton . w2c <$> P.satisfy isSpecialChar
parseHStoreTexts (acc . (chunk:) . (c:))
) <|> return (Right (acc [chunk]))
where
isSpecialChar c = c == c2w '\\' || c == c2w '"'
| tomjaguarpaw/postgresql-simple | src/Database/PostgreSQL/Simple/HStore/Implementation.hs | bsd-3-clause | 7,352 | 0 | 18 | 1,909 | 2,081 | 1,084 | 997 | 159 | 3 |
-- | This module provides numerical routines for minimizing/maximizing one dimensional functions.
-- All function are translated from "Numerical Recipes in C".
-- The module is divided into simple and advanced sections.
module HLearn.Optimization.Univariate
(
-- * Simple interface
-- | These simple functions provide an interface similar to Matlab/Ocatave's optimization toolkit.
-- They are recommended for quick prototypes and working from within GHCI.
-- Here's an example:
--
-- >>> let f x = (x-5)**2 :: Double
-- >>> fminunc f
-- 5.000000000000001
--
-- In many applications, we want to nest these optimization calls.
-- Debugging these nested optimiztions is notoriously difficult.
-- Consider the following example:
--
-- >>> let g x y = x*x + (y-5)**2
-- >>> fminunc (\x -> fminunc (\y -> g y x))
-- -2.821859578658409
--
-- It's clear that the value of @x@ that minimizes @g x y@ should be zero;
-- but we get a ridiculous answer instead.
-- The advanced interface gives us much more debugging information and control over the optimization process.
-- We can use it to solve problems that can't be solved with the simple interface.
fminunc
, fmaxunc
, fminuncM
, fmaxuncM
-- * Advanced interface
-- | The advanced interface is more complex, but has two advantages.
-- First, it lets us specify a level of debugging information we want.
-- Second, it lets us specify in more detail the algorithms used in the optimization.
--
-- Let's repeat the first example from the simple interface.
-- This time we will use Brent's method on "Rational" numbers and ask for higher precision than we could get with floating point numbers.
--
-- >>> let f x = (x-5)*(x-5) :: Rational
-- >>> :{
-- >>> traceHistory $ do
-- >>> lb <- lineBracket f 0 1
-- >>> fminuncM_brent_ (return . f) lb (maxIterations 10 || stop_brent 1e-10)
-- >>> }:
-- Iterator_brent; x=5%1; f(x)=0%1
--
-- In this case, we get an exact answer.
-- The "traceHistory" command also gives us a record of how our optimization proceded.
-- ** Brent's Method
-- | Brent's method uses parabolic interpolation to find the minimum.
--
-- See <http://en.wikipedia.org/wiki/Iterator_brent%27s_method wikipedia>
-- and Section 10.2 of "Numerical Recipes in C" for more details.
, fminunc_brent
, fminuncM_brent
, fminuncM_brent_
, stop_brent
, Iterator_brent (..)
-- ** Brent's method with derivatives
-- | We can make Brent's method a bit faster sometimes by using the function's derivative.
--
-- See section 10.3 of "Numerical Recipes in C" for more details.
, fminunc_dbrent
, fminuncM_dbrent
, fminuncM_dbrent_
, stop_dbrent
, Iterator_dbrent (..)
-- ** Golden section search
-- | Golden section search is used to find the minimum of "poorly behaved" functions.
-- Other methods almost always converge faster.
--
-- See <http://en.wikipedia.org/wiki/Golden_section_search wikipedia>
-- and Section 10.1 of "Numerical Recipes in C" for more details.
, fminunc_gss
, fminuncM_gss
, fminuncM_gss_
, stop_gss
, Iterator_gss (..)
-- ** Line bracketing
-- | The univariate optimization methods above require an interval within which a minimum is guaranteed to exist.
--
-- FIXME: switch LineBracket to the Interval type provided by subhask
--
-- See Section 10.1 of "Numerical Recipes in C" for more details.
, lineBracket
, lineBracketM
, LineBracket (..)
)
where
import SubHask
import HLearn.History
-------------------------------------------------------------------------------
tester :: History Double
tester = do
lb <- lineBracketM f 0 1
gss <- fminuncM_gss_ f lb (maxIterations 5)
return $ gss_x gss
where
f x = do
let f a = abs x + (a+5-x)*(a+5)
lb <- lineBracket f 0 1
b <- fminuncM_brent_
(return . f)
lb
(maxIterations 10)
return $ _brent_fx b
-------------------------------------------------------------------------------
-- | Finds the minimum of a function
fminunc :: (Optimizable a, OrdField a) => (a -> a) -> a
fminunc = fminunc_brent
-- | Finds the maximum of a function
fmaxunc :: (Optimizable a, OrdField a) => (a -> a) -> a
fmaxunc f = fminunc_brent (-f)
-- | Finds the minimum of a monadic function
fminuncM :: (Optimizable a, OrdField a) => (a -> History a) -> a
fminuncM = fminuncM_brent
-- | Finds the maximum of a monadic function
fmaxuncM :: (Optimizable a, OrdField a) => (a -> History a) -> a
fmaxuncM f = fminuncM_brent (-f)
-------------------------------------------------------------------------------
-- line bracketing
-- | Variable names correspond to the algorithm in "Numerical Recipes in C"
data LineBracket a = LineBracket
{ _ax :: !a
, _bx :: !a
, _cx :: !a
, _fa :: !a
, _fb :: !a
, _fc :: !a
}
deriving (Typeable)
instance Show a => Show (LineBracket a) where
show lb = "LineBracket; a="++show (_ax lb)++"; b="++show (_bx lb)++"; c="++show (_cx lb)
-- | finds two points ax and cx between which a minimum is guaranteed to exist
-- this is a transliteration of the 'lineBracket' function from the \"Numerical
-- Recipes\" series
lineBracket ::
( OrdField a
) => (a -> a) -- ^ the function we're bracketing
-> a -- ^ an initial guess for the lower bound
-> a -- ^ an initial guess for the upper bound
-> Optimizable a => History (LineBracket a)
lineBracket f = lineBracketM (return . f)
lineBracketM ::
( OrdField a
) => (a -> History a) -- ^ the function we're bracketing
-> a -- ^ an initial guess for the lower bound
-> a -- ^ an initial guess for the upper bound
-> Optimizable a => History (LineBracket a)
lineBracketM !f !pt1 !pt2 = beginFunction "lineBracketM" $ do
let gold = 1.618034
fpt1 <- f pt1
fpt2 <- f pt2
let (ax,fax,bx,fbx) = if fpt1 > fpt2
then (pt1,fpt1,pt2,fpt2)
else (pt2,fpt2,pt1,fpt1)
let cx = bx+gold*(bx-ax)
fcx <- f cx
let lb0 = LineBracket
{ _ax = ax
, _bx = bx
, _cx = cx
, _fa = fax
, _fb = fbx
, _fc = fcx
}
iterate
(step_LineBracket f)
lb0
stop_LineBracket
stop_LineBracket :: OrdField a => LineBracket a -> LineBracket a -> History Bool
stop_LineBracket _ lb = if _fb lb /= _fb lb
then error "NaN in linebracket"
else return $ _fb lb <= _fc lb
step_LineBracket :: OrdField a
=> (a -> History a)
-> LineBracket a
-> History (LineBracket a)
step_LineBracket !f lb@(LineBracket ax bx cx fa fb fc) = do
let sign a b = if b>0 then abs a else -(abs a)
tiny = 1e-20
glimit = 100
gold = 1.618034
r = (bx-ax)*(fb-fc)
q = (bx-cx)*(fb-fa)
u = bx-((bx-cx)*q-(bx-ax)*r)/2*(sign (max (abs $ q-r) tiny) (q-r))
u' = cx+gold*(cx-bx)
ulim = bx+glimit*(cx-bx)
-- due to laziness, we will only evaluate the function if we absolutely have to
fu <- f u
fu' <- f u'
fulim <- f ulim
return $ if (bx-u)*(u-cx) > 0
then if fu < fc -- Got a minimum between a and c
then lb
{ _ax = bx
, _bx = u
, _fa = fb
, _fb = fu
}
else if fu > fb -- Got a minimum between a and u
then lb
{ _cx = u
, _fc = fu
}
else lb -- Parabolic fit was no use. Use default magnification
{ _ax = bx
, _bx = cx
, _cx = u'
, _fa = fb
, _fb = fc
, _fc = fu'
}
else if (cx-u)*(u-ulim) > 0 -- parabolic fit is between c and its allowed limit
then if fu < fc
then lb
{ _ax = cx
, _bx = u
, _cx = u'
, _fa = fc
, _fb = fu
, _fc = fu'
}
else lb
{ _ax = bx
, _bx = cx
, _cx = u
, _fa = fb
, _fb = fc
, _fc = fu
}
else if (u-ulim)*(ulim-cx) >= 0
then lb -- limit parabolic u to maximum allowed value
{ _ax = bx
, _bx = cx
, _cx = ulim
, _fa = fb
, _fb = fc
, _fc = fulim
}
else lb -- reject parabolic u, use default magnification
{ _ax = bx
, _bx = cx
, _cx = u'
, _fa = fb
, _fb = fc
, _fc = fu'
}
-------------------------------------------------------------------------------
-- golden section search
-- | Variable names correspond to the algorithm in "Numerical Recipes in C"
data Iterator_gss a = Iterator_gss
{ _gss_fxb :: !a
, _gss_fxc :: !a
, _gss_xa :: !a
, _gss_xb :: !a
, _gss_xc :: !a
, _gss_xd :: !a
}
deriving (Typeable)
instance (ClassicalLogic a, Show a, OrdField a) => Show (Iterator_gss a) where
show gss = "Iterator_gss; "++"x="++show x++"; f(x)="++show fx
where
x = gss_x gss
fx = gss_fx gss
gss_x gss = if _gss_fxb gss < _gss_fxc gss
then _gss_xb gss
else _gss_xc gss
gss_fx gss = min (_gss_fxb gss) (_gss_fxc gss)
---------------------------------------
-- | A simple interface to golden section search
fminunc_gss :: ( Optimizable a , OrdField a ) => (a -> a) -> a
fminunc_gss f = fminuncM_gss (return . f)
-- | A simple monadic interface to golden section search
fminuncM_gss :: forall a. ( Optimizable a , OrdField a ) => (a -> History a) -> a
fminuncM_gss f = evalHistory $ do
lb <- lineBracketM f 0 1
gss <- fminuncM_gss_ f lb (maxIterations 200 || stop_gss (1e-12 :: a))
return $ gss_x gss
-- | The most generic interface to golden section search
fminuncM_gss_ :: ( Optimizable a , OrdField a )
=> (a -> History a) -- ^ the function we're minimizing
-> LineBracket a -- ^ bounds between which a minimum must exist
-> StopCondition_ (Iterator_gss a) -- ^ controls the number of iterations
-> History (Iterator_gss a)
fminuncM_gss_ f (LineBracket ax bx cx fa fb fc) stop = beginFunction "goldenSectionSearch_" $ do
let r = 0.61803399
c = 1-r
let xb = if abs (cx-bx) > abs (bx-ax) then bx else bx-c*(bx-ax)
xc = if abs (cx-bx) > abs (bx-ax) then bx+c*(cx-bx) else bx
fxb <- f xb
fxc <- f xc
let gss0 = Iterator_gss
{ _gss_fxb = fxb
, _gss_fxc = fxc
, _gss_xa = ax
, _gss_xb = xb
, _gss_xc = xc
, _gss_xd = cx
}
iterate
(step_gss f)
gss0
stop
where
step_gss :: OrdField a => (a -> History a) -> Iterator_gss a -> History (Iterator_gss a)
step_gss f (Iterator_gss f1 f2 x0 x1 x2 x3) = if f2 < f1
then do
let x' = r*x2+c*x3
fx' <- f x'
return $ Iterator_gss f2 fx' x1 x2 x' x3
else do
let x' = r*x1+c*x0
fx' <- f x'
return $ Iterator_gss fx' f1 x0 x' x1 x2
where
r = 0.61803399
c = 1-r
-- | Does not stop until the independent variable is accurate to within the tolerance passed in.
stop_gss :: OrdField a => a -> StopCondition_ (Iterator_gss a)
stop_gss tol _ (Iterator_gss _ _ !x0 !x1 !x2 !x3 )
= return $ abs (x3-x0) <= tol*(abs x1+abs x2)
-------------------------------------------------------------------------------
-- Brent's method
-- | Variable names correspond to the algorithm in "Numerical Recipes in C"
data Iterator_brent a = Iterator_brent
{ _brent_a :: !a
, _brent_b :: !a
, _brent_d :: !a
, _brent_e :: !a
, _brent_fv :: !a
, _brent_fw :: !a
, _brent_fx :: !a
, _brent_v :: !a
, _brent_w :: !a
, _brent_x :: !a
}
deriving Typeable
instance Show a => Show (Iterator_brent a) where
show b = "Iterator_brent; x="++show (_brent_x b)++"; f(x)="++show (_brent_fx b)
instance IsScalar a => Has_x1 Iterator_brent a where
x1 = _brent_x
instance IsScalar a => Has_fx1 Iterator_brent a where
fx1 = _brent_fx
-- | A simple interface to Brent's method
fminunc_brent :: ( Optimizable a, OrdField a ) => (a -> a) -> a
fminunc_brent f = fminuncM_brent (return . f)
-- | A simple monadic interface to Brent's method
fminuncM_brent :: ( Optimizable a, OrdField a ) => (a -> History a) -> a
fminuncM_brent f = evalHistory $ do
lb <- lineBracketM f 0 1
b <- fminuncM_brent_ f lb ( maxIterations 200 || stop_brent 1e-12 )
return $ _brent_x b
-- | The most generic interface to Brent's method
fminuncM_brent_ ::
( Optimizable a , OrdField a
) => (a -> History a) -- ^ the function we're minimizing
-> LineBracket a -- ^ bounds between which a minimum must exist
-> StopCondition_ (Iterator_brent a) -- ^ controls the number of iterations
-> History (Iterator_brent a)
fminuncM_brent_ f (LineBracket ax bx cx fa fb fc) stop = beginFunction "brent" $ do
fbx <- f bx
iterate
(step_brent f)
( Iterator_brent
{ _brent_a = min ax cx
, _brent_b = max ax cx
, _brent_d = zero
, _brent_e = zero
, _brent_v = bx
, _brent_w = bx
, _brent_x = bx
, _brent_fv = fbx
, _brent_fw = fbx
, _brent_fx = fbx
}
)
stop
where
step_brent ::
( OrdField a
) => (a -> History a) -> Iterator_brent a -> History (Iterator_brent a)
step_brent f brent@(Iterator_brent a b d e fv fw fx v w x) = do
let cgold = 0.3819660
zeps = 1e-10
sign a b = if b>0 then abs a else -(abs a)
tol = 1e-6
xm = 0.5*(a+b)
tol1' = tol*(abs x)+zeps
tol2' = 2*tol1'
(d',e') = if abs e > tol1'
then let
r' = (x-w)*(fx-fv)
q' = (x-v)*(fx-fw)
p' = (x-v)*q'-(x-w)*r'
q'' = 2*(q'-r')
p'' = if q''>0 then -p' else p'
q''' = abs q''
etemp' = e
in if abs p'' >= abs (0.5*q'''*etemp') || p'' <= q'''*(a-x) || p'' >= q'''*(b-x)
then let e'' = if x>=xm then a-x else b-x in (cgold*e'',e'')
else let d''=p''/q'''; u''=x+d'' in
if u''-a < tol2' || b-u'' < tol2'
then (sign tol1' (xm-x),d)
else (d'',d)
else let e'' = if x>=xm then a-x else b-x in (cgold*e'',e'')
u' = if abs d' >= tol1'
then x+d'
else x+sign tol1' d'
fu' <- f u'
return $ if fu' <= fx
then brent
{ _brent_e = e'
, _brent_d = d'
, _brent_a = if u' >= x then x else a
, _brent_b = if u' >= x then b else x
, _brent_v = w
, _brent_w = x
, _brent_x = u'
, _brent_fv = fw
, _brent_fw = fx
, _brent_fx = fu'
}
else brent
{ _brent_e = e'
, _brent_d = d'
, _brent_a = if u' < x then u' else a
, _brent_b = if u' < x then b else u'
, _brent_v = if fu' <= fw || w==x then w else if fu' <= fv || v==x || v==w then u' else v
, _brent_fv = if fu' <= fw || w==x then fw else if fu' <= fv || v==x || v==w then fu' else fv
, _brent_w = if fu' <= fw || w==x then u' else w
, _brent_fw = if fu' <= fw || w==x then fu' else fw
}
-- | Does not stop until the independent variable is accurate to within the tolerance passed in.
--
-- FIXME: if we get an exact solution this doesn't stop the optimization
stop_brent :: OrdField a => a -> StopCondition_ (Iterator_brent a)
stop_brent tol _ opt = return $ abs (x-xm) < tol2'-0.5*(b-a)
where
(Iterator_brent a b d e fv fw fx v w x) = opt
xm = 0.5*(a+b)
tol1' = tol*(abs x)+zeps
tol2' = 2*tol1'
zeps = 1e-10
-------------------------------------------------------------------------------
-- Brent's method with derivatives
-- | Variable names correspond to the algorithm in "Numerical Recipes in C"
data Iterator_dbrent a = Iterator_dbrent
{ _dbrent_a :: !a
, _dbrent_b :: !a
, _dbrent_d :: !a
, _dbrent_e :: !a
, _dbrent_fv :: !a
, _dbrent_fw :: !a
, _dbrent_fx :: !a
, _dbrent_dv :: !a
, _dbrent_dw :: !a
, _dbrent_dx :: !a
, _dbrent_v :: !a
, _dbrent_w :: !a
, _dbrent_x :: !a
, _dbrent_break :: Bool
}
deriving Typeable
instance Show a => Show (Iterator_dbrent a) where
show b = "Iterator_brent; x="++show (_dbrent_x b)++"; f(x)="++show (_dbrent_fx b)
-- | A simple interface to Brent's method with derivatives
fminunc_dbrent :: ( Optimizable a, OrdField a ) => (a -> a) -> (a -> a) -> a
fminunc_dbrent f df = fminuncM_dbrent (return . f) (return . df)
-- | A simple monadic interface to Brent's method with derivatives
fminuncM_dbrent :: ( Optimizable a, OrdField a ) => (a -> History a) -> (a -> History a) -> a
fminuncM_dbrent f df = evalHistory $ do
lb <- lineBracketM f 0 1
b <- fminuncM_dbrent_ f df lb ( maxIterations 200 || stop_dbrent 1e-12 )
return $ _dbrent_x b
-- | The most generic interface to Brent's method with derivatives
fminuncM_dbrent_ ::
( Optimizable a , OrdField a
) => (a -> History a) -- ^ the function we're minimizing
-> (a -> History a) -- ^ the function's derivative
-> LineBracket a -- ^ bounds between which a minimum must exist
-> StopCondition_ (Iterator_dbrent a) -- ^ controls the number of iterations
-> History (Iterator_dbrent a)
fminuncM_dbrent_ f df (LineBracket ax bx cx fa fb fc) stop = beginFunction "dbrent" $ do
fbx <- f bx
dfx <- df bx
iterate
(step_dbrent f df)
( Iterator_dbrent
{ _dbrent_a = min ax cx
, _dbrent_b = max ax cx
, _dbrent_d = zero
, _dbrent_e = zero
, _dbrent_v = bx
, _dbrent_w = bx
, _dbrent_x = bx
, _dbrent_fv = fbx
, _dbrent_fw = fbx
, _dbrent_fx = fbx
, _dbrent_dv = dfx
, _dbrent_dw = dfx
, _dbrent_dx = dfx
, _dbrent_break = False
}
)
stop
where
step_dbrent ::
( OrdField a
) => (a -> History a) -> (a -> History a) -> Iterator_dbrent a -> History (Iterator_dbrent a)
step_dbrent f df dbrent@(Iterator_dbrent a b d e fv fw fx dv dw dx v w x _) = do
let zeps = 1e-10
sign a b = if b>0 then abs a else -(abs a)
tol = 1e-6
xm = 0.5*(a+b)
tol1' = tol*(abs x)+zeps
tol2' = 2*tol1'
(d',e') = if abs e > tol1'
then let
d1 = if dw /= dx then (w-x)*dx/(dx-dw) else 2*(b-a)
d2 = if dv /= dx then (v-x)*dx/(dx-dv) else 2*(b-a)
u1 = x+d1
u2 = x+d2
ok1 = (a-u1)*(u1-b) > 0 && dx*d1 <= 0
ok2 = (a-u2)*(u2-b) > 0 && dx*d2 <= 0
in if ok1 || ok2
then let
d'' = if ok1 && ok2
then if abs d1 < abs d2 then d1 else d2
else if ok1 then d1 else d2
in if abs d'' <= abs (0.5 * e)
then let u' = x + d''
in if u'-a < tol2' || b-u' < tol2'
then (sign tol1' xm-x, d)
else (d'', d)
else
let e'' = if dx>=0 then a-x else b-x
in (0.5*e'',e'')
else
let e'' = if dx>=0 then a-x else b-x
in (0.5*e'',e'')
else
let e'' = if dx>=0 then a-x else b-x
in (0.5*e'',e'')
u' = if abs d' >= tol1' then x+d' else x+sign tol1' d'
fu' <- f u'
du' <- df u'
return $ if abs d' < tol1' && fu' > fx
then dbrent
{ _dbrent_x = x
, _dbrent_fx = fx
, _dbrent_break = True
}
else
if fu' <= fx
then dbrent
{ _dbrent_e = e'
, _dbrent_d = d'
, _dbrent_a = if u' >= x then x else a
, _dbrent_b = if u' >= x then b else x
, _dbrent_v = w
, _dbrent_w = x
, _dbrent_x = u'
, _dbrent_fv = fw
, _dbrent_fw = fx
, _dbrent_fx = fu'
, _dbrent_dv = dw
, _dbrent_dw = dx
, _dbrent_dx = du'
}
else dbrent
{ _dbrent_e = e'
, _dbrent_d = d'
, _dbrent_a = if u' < x then u' else a
, _dbrent_b = if u' < x then b else u'
, _dbrent_v = if fu' <= fw || w==x then w else if fu' <= fv || v==x || v==w then u' else v
, _dbrent_fv = if fu' <= fw || w==x then fw else if fu' <= fv || v==x || v==w then fu' else fv
, _dbrent_dv = if fu' <= fw || w==x then dw else if fu' <= fv || v==x || v==w then du' else dv
, _dbrent_w = if fu' <= fw || w==x then u' else w
, _dbrent_fw = if fu' <= fw || w==x then fu' else fw
, _dbrent_dw = if fu' <= fw || w==x then du' else dw
}
-- | Does not stop until the independent variable is accurate to within the tolerance passed in.
--
-- FIXME: if we get an exact solution this doesn't stop the optimization
stop_dbrent :: OrdField a => a -> StopCondition_ (Iterator_dbrent a)
stop_dbrent tol _ opt = return $ should_break || abs (x-xm) < tol2'-0.5*(b-a)
where
(Iterator_dbrent a b d e fv fw fx dv dw dx v w x should_break) = opt
xm = 0.5*(a+b)
tol1' = tol*(abs x)+zeps
tol2' = 2*tol1'
zeps = 1e-10
| iamkingmaker/HLearn | src/HLearn/Optimization/Univariate.hs | bsd-3-clause | 24,260 | 0 | 26 | 9,724 | 6,307 | 3,430 | 2,877 | -1 | -1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-------------------------------------------------------------------------------
-- |
-- Module : Fluorine.Attributes
-- Copyright : (c) 2015 Jeffrey Rosenbluth
-- License : BSD-style (see LICENSE)
-- Maintainer : [email protected]
--
-- This module defines the `EventHandler` functor, which can be used
-- to perform standard operations on HTML events.
----------------------------------------------------------------------------
module Fluorine.HTML.Events.Handler
( EventHandler
, preventDefault
, stopPropagation
, stopImmediatePropagation
) where
import Control.Monad.Writer
data EventUpdate
= PreventDefault
| StopPropagation
| StopImmediatePropagation
-- | This monad supports the following operations on events:
--
-- - `preventDefault`
-- - `stopPropagation`
-- - `stopImmediatePropagation`
--
-- It can be used as follows:
--
-- import Control.Functor (($>))
--
-- H.a (E.onclick \_ -> E.preventDefault $> ClickHandler) (H.text "Click here")
newtype EventHandler a = EventHandler (Writer [EventUpdate] a)
deriving (Functor, Applicative, Monad)
unEventHandler :: EventHandler a -> Writer [EventUpdate] a
unEventHandler (EventHandler mw) = mw
-- | Call the `preventDefault` method on the current event
preventDefault :: EventHandler ()
preventDefault = EventHandler (tell [PreventDefault])
-- | Call the `stopPropagation` method on the current event
stopPropagation :: EventHandler ()
stopPropagation = EventHandler (tell [StopPropagation])
-- | Call the `stopImmediatePropagation` method on the current event
stopImmediatePropagation :: EventHandler ()
stopImmediatePropagation = EventHandler (tell [StopImmediatePropagation])
| jeffreyrosenbluth/flourine | src/Fluorine/HTML/Events/Handler.hs | bsd-3-clause | 1,747 | 0 | 8 | 255 | 216 | 131 | 85 | 21 | 1 |
{-# LANGUAGE RankNTypes, OverloadedStrings #-}
module Protocol.ROC where
import System.Hardware.Serialport
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LB
import Protocol.ROC.Utils
import Protocol.ROC.PointTypes
import Protocol.ROC.FullyDefinedPointType
import Protocol.ROC.ROCConfig
import Protocol.ROC.OpCodes
import Protocol.ROC.RocSerialize
-- import Control.Applicative
import Numeric
-- import Data.Int
-- import Data.ByteString.Builder
-- import Data.Word
getPointType :: RocConfig -> DefaultPointType -> PointNumber -> IO ()
getPointType cfg fdpt pn = do
let fdataBytes = fdptRxProtocol fdpt
ptid = fdptPointTypeID fdpt
pc = fdptParameterCount fdpt
sp = fdptStartParameter fdpt
dataBytes <- fdataBytes cfg pn ptid pc sp
let fetchedPointType = fetchPointType ptid (LB.fromStrict dataBytes)
print fetchedPointType
writePointType :: RocSerialize a => RocConfig -> DefaultPointType -> PointNumber -> ParameterNumber -> a -> IO ()
writePointType cfg fdpt pn prn pdata = do
let port = rocConfigPort cfg
commRate = rocCommSpeed cfg
ptid = fdptPointTypeID fdpt
pt = decodePTID ptid
databytes = BS.append (opCode166 pt pn prn pdata cfg) (lzyBSto16BScrc.pack8to16 $ BS.unpack $ opCode166 pt pn prn pdata cfg)
s <- openSerial port defaultSerialSettings { commSpeed = commRate }
print $ showInt <$> BS.unpack databytes <*> [""]
_ <- send s databytes
receivebs <- recvAllBytes s 255
closeSerial s
print $ showInt <$> BS.unpack receivebs <*> [""]
runOpCodeRaw :: RocConfig -> (RocConfig -> BS.ByteString) -> IO BS.ByteString
runOpCodeRaw cfg opCode = do
let port = rocConfigPort cfg
commRate = rocCommSpeed cfg
s <- openSerial port defaultSerialSettings { commSpeed = commRate }
_ <- send s $ BS.append (opCode cfg) (lzyBSto16BScrc.pack8to16 $ BS.unpack $ opCode cfg)
receivebs <- recvAllBytes s 255
closeSerial s
print $ showInt <$> BS.unpack receivebs <*> [""]
return receivebs
testRocConfig :: RocConfig
testRocConfig = RocConfig "/dev/ttyUSB0" [240,240] [1,3] CS19200 "LOI" 1000
| jqpeterson/roc-translator | src/Protocol/ROC.hs | bsd-3-clause | 2,165 | 0 | 14 | 425 | 630 | 318 | 312 | 46 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Air.Logger where
import Prelude hiding (log)
import Control.Monad (forM_, join)
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as BS
import Data.Time (UTCTime, getCurrentTime)
import System.Log.FastLogger
import Air.Domain
username = userCata id
balance = balanceCata readableMoney
depositMsg = depositCata readableMoney
payment :: Payment -> [LogStr]
payment = paymentCata username id id logLines where
logLines rationals money name = header:(map logLine rationals) where
header = toLogStr . join $ ["The ", name, " is payed with ", readableMoney money]
logLine (user, ratio) = toLogStr . join $ [
user, " pays ", readableMoney $ (ratio * money)
, " for ", name, "."
]
account :: Account -> [LogStr]
account = accountCata username balance logLine id where
logLine (name,bal) = toLogStr . join $ [name, " has ", bal]
flatBalance :: FlatBalance -> LogStr
flatBalance = flatBalanceCata $ \b -> toLogStr . join $ ["The total amount is: ", readableMoney b]
deposit :: User -> Deposit -> LogStr
deposit u d = toLogStr . join $ [username u, " deposits ", depositMsg d]
-- Logs the given log message attaching the actual time-stamp and the newline character
-- at the end of the string
log :: LoggerSet -> [LogStr] -> IO ()
log logger lines = do
now <- getCurrentTime
forM_ lines $ \line -> do
pushLogStr logger . toLogStr $ concat ["[", show now, "] "]
pushLogStr logger line
pushLogStr logger $ toLogStr ("\n" :: String)
-- Logs a single line log message attaching the actual time-stamp and the newline character
-- at the end of the string
log' :: LoggerSet -> LogStr -> IO ()
log' l m = log l [m]
| andorp/air | src/Air/Logger.hs | bsd-3-clause | 1,730 | 0 | 14 | 336 | 524 | 287 | 237 | 35 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Arrow
import Data.Maybe (fromJust)
import Data.Profunctor.Product.TH (makeAdaptorAndInstance)
import qualified Database.PostgreSQL.Simple as PSQL
import Opaleye
import Opaleye.Trans
data Rose a = Node a [Rose a]
deriving (Show, Eq)
instance Functor Rose where
fmap f (Node x rs) = Node (f x) (map (fmap f) rs)
data NodeP i b n a = NodeP
{ nodeId :: i
, nodeBranchId :: b
, nextBranchId :: n
, value :: a
} deriving (Show, Eq)
type WriteNode a = NodeP (Maybe (Column PGInt4)) (Column PGInt4) (Column PGInt4) (Column a)
type ReadNode a = NodeP (Column PGInt4) (Column PGInt4) (Column PGInt4) (Column a)
newtype BranchP i = BranchP
{ branchId :: i
} deriving (Show, Eq)
type WriteBranch = BranchP (Maybe (Column PGInt4))
type ReadBranch = BranchP (Column PGInt4)
data TreeP i r = TreeP
{ treeId :: i
, rootId :: r
} deriving (Show, Eq)
type WriteTree = TreeP (Maybe (Column PGInt4)) (Column PGInt4)
type ReadTree = TreeP (Column PGInt4) (Column PGInt4)
makeAdaptorAndInstance "pNode" ''NodeP
makeAdaptorAndInstance "pBranch" ''BranchP
makeAdaptorAndInstance "pTree" ''TreeP
nodeTable :: Table (WriteNode a) (ReadNode a)
nodeTable = Table "node" $ pNode NodeP
{ nodeId = optional "id"
, nodeBranchId = required "branch_id"
, nextBranchId = required "next_branch_id"
, value = required "value"
}
branchTable :: Table WriteBranch ReadBranch
branchTable = Table "branch" $ pBranch (BranchP (optional "id"))
treeTable :: Table WriteTree ReadTree
treeTable = Table "rosetree" $ pTree TreeP
{ treeId = optional "id"
, rootId = required "root_id"
}
newTree :: Int -> Transaction (Maybe Int)
newTree rootId = insertReturningFirst treeTable treeId (TreeP Nothing (pgInt4 rootId))
newBranch :: Transaction (Maybe Int)
newBranch = insertReturningFirst branchTable branchId (BranchP Nothing)
insertNode :: Int -> Int -> Int -> Transaction (Maybe Int)
insertNode bid nbid x =
insertReturningFirst nodeTable nodeId
(NodeP Nothing (pgInt4 bid) (pgInt4 nbid) (pgInt4 x))
insertTree :: MonadIO m => Rose Int -> OpaleyeT m Int
insertTree (Node x xs) = transaction $ do
bid <- fromJust <$> newBranch
rootId <- fromJust <$> insertNode 0 bid x
treeId <- fromJust <$> newTree rootId
mapM_ (insertTree' bid) xs
return treeId
insertTree' :: Int -> Rose Int -> Transaction ()
insertTree' bid (Node x xs) = do
nbid <- fromJust <$> newBranch
insertNode bid nbid x
mapM_ (insertTree' nbid) xs
selectTree :: Int -> Transaction (Rose Int)
selectTree treeId = do
rootId <- fromJust <$> selectRootNode treeId
(NodeP _ _ nbid x) <- fromJust <$> selectNode rootId
xs <- selectBranch nbid
return (Node x xs)
selectRootNode :: Int -> Transaction (Maybe Int)
selectRootNode tid = queryFirst rootNode
where
rootNode :: Query (Column PGInt4)
rootNode = proc () -> do
tree <- queryTable treeTable -< ()
restrict -< treeId tree .== pgInt4 tid
returnA -< rootId tree
selectNode :: Int -> Transaction (Maybe (NodeP Int Int Int Int))
selectNode nid = queryFirst nodeById
where
nodeById :: Query (ReadNode PGInt4)
nodeById = proc () -> do
node <- queryTable nodeTable -< ()
restrict -< nodeId node .== pgInt4 nid
returnA -< node
selectBranch :: Int -> Transaction [Rose Int]
selectBranch bid = do
nodes <- query nodeByBranchId
sequence (mkNode <$> nodes)
where
nodeByBranchId :: Query (ReadNode PGInt4)
nodeByBranchId = proc () -> do
row@(NodeP _ bid' _ _) <- queryTable nodeTable -< ()
restrict -< bid' .== pgInt4 bid
returnA -< row
mkNode :: NodeP Int Int Int Int -> Transaction (Rose Int)
mkNode (NodeP _ _ nbid x) = do
xs <- selectBranch nbid
return (Node x xs)
main :: IO ()
main = do
conn <- PSQL.connectPostgreSQL "dbname='rosetree' user='postgres'"
let tree :: Rose Int
tree =
Node 6
[ Node 7
[ Node 1425
[ Node 42 []
, Node 2354 []
, Node 4245 []]]
, Node 10 []
, Node 6
[ Node 12 []
, Node 14 []]]
tree' <- runOpaleyeT conn $ run . selectTree =<< insertTree tree
print (tree, tree')
print (tree == tree')
| WraithM/opaleye-trans | examples/v1/RoseTree.hs | bsd-3-clause | 4,759 | 3 | 17 | 1,327 | 1,625 | 811 | 814 | 122 | 1 |
module Main where
mingle :: String -> String -> String
mingle [] [] = []
mingle (x:xs) (y:ys) = x:y:(mingle xs ys)
main :: IO ()
main = do p <- getLine
q <- getLine
putStrLn $ mingle p q
| everyevery/programming_study | hackerrank/functional/string-mingling/string-mingling.hs | mit | 209 | 0 | 8 | 62 | 114 | 58 | 56 | 8 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Tests.Readers.Markdown (tests) where
import Text.Pandoc.Definition
import Test.Framework
import Tests.Helpers
import Tests.Arbitrary()
import Text.Pandoc.Builder
-- import Text.Pandoc.Shared ( normalize )
import Text.Pandoc
import Data.Sequence (singleton)
markdown :: String -> Pandoc
markdown = readMarkdown defaultParserState{ stateStandalone = True }
markdownSmart :: String -> Pandoc
markdownSmart = readMarkdown defaultParserState{ stateSmart = True }
infix 5 =:
(=:) :: ToString c
=> String -> (String, c) -> Test
(=:) = test markdown
{-
p_markdown_round_trip :: Block -> Bool
p_markdown_round_trip b = matches d' d''
where d' = normalize $ Pandoc (Meta [] [] []) [b]
d'' = normalize
$ readMarkdown defaultParserState{ stateSmart = True }
$ writeMarkdown defaultWriterOptions d'
matches (Pandoc _ [Plain []]) (Pandoc _ []) = True
matches (Pandoc _ [Para []]) (Pandoc _ []) = True
matches (Pandoc _ [Plain xs]) (Pandoc _ [Para xs']) = xs == xs'
matches x y = x == y
-}
tests :: [Test]
tests = [ testGroup "inline code"
[ "with attribute" =:
"`document.write(\"Hello\");`{.javascript}"
=?> para
(codeWith ("",["javascript"],[]) "document.write(\"Hello\");")
, "with attribute space" =:
"`*` {.haskell .special x=\"7\"}"
=?> para (codeWith ("",["haskell","special"],[("x","7")]) "*")
]
, testGroup "smart punctuation"
[ test markdownSmart "quote before ellipses"
("'...hi'"
=?> para (singleQuoted (singleton Ellipses +++ "hi")))
]
, testGroup "mixed emphasis and strong"
[ "emph and strong emph alternating" =:
"*xxx* ***xxx*** xxx\n*xxx* ***xxx*** xxx"
=?> para (emph "xxx" +++ space +++ strong (emph "xxx") +++
space +++ "xxx" +++ space +++
emph "xxx" +++ space +++ strong (emph "xxx") +++
space +++ "xxx")
, "emph with spaced strong" =:
"*x **xx** x*"
=?> para (emph ("x" +++ space +++ strong "xx" +++ space +++ "x"))
]
, testGroup "footnotes"
[ "indent followed by newline and flush-left text" =:
"[^1]\n\n[^1]: my note\n\n \nnot in note\n"
=?> para (note (para "my note")) +++ para "not in note"
, "indent followed by newline and indented text" =:
"[^1]\n\n[^1]: my note\n \n in note\n"
=?> para (note (para "my note" +++ para "in note"))
, "recursive note" =:
"[^1]\n\n[^1]: See [^1]\n"
=?> para (note (para "See [^1]"))
]
, testGroup "lhs"
[ test (readMarkdown defaultParserState{stateLiterateHaskell = True})
"inverse bird tracks and html" $
"> a\n\n< b\n\n<div>\n"
=?> codeBlockWith ("",["sourceCode","literate","haskell"],[]) "a"
+++
codeBlockWith ("",["sourceCode","haskell"],[]) "b"
+++
rawBlock "html" "<div>\n\n"
]
-- the round-trip properties frequently fail
-- , testGroup "round trip"
-- [ property "p_markdown_round_trip" p_markdown_round_trip
-- ]
]
| Lythimus/lptv | sites/all/modules/jgm-pandoc-8be6cc2/src/Tests/Readers/Markdown.hs | gpl-2.0 | 3,414 | 0 | 22 | 1,079 | 633 | 344 | 289 | 59 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Redshift.DescribeClusterSecurityGroups
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns information about Amazon Redshift security groups. If the name
-- of a security group is specified, the response will contain only
-- information about only that security group.
--
-- For information about managing security groups, go to
-- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-security-groups.html Amazon Redshift Cluster Security Groups>
-- in the /Amazon Redshift Cluster Management Guide/.
--
-- If you specify both tag keys and tag values in the same request, Amazon
-- Redshift returns all security groups that match any combination of the
-- specified keys and values. For example, if you have 'owner' and
-- 'environment' for tag keys, and 'admin' and 'test' for tag values, all
-- security groups that have any combination of those values are returned.
--
-- If both tag keys and values are omitted from the request, security
-- groups are returned regardless of whether they have tag keys or values
-- associated with them.
--
-- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusterSecurityGroups.html AWS API Reference> for DescribeClusterSecurityGroups.
--
-- This operation returns paginated results.
module Network.AWS.Redshift.DescribeClusterSecurityGroups
(
-- * Creating a Request
describeClusterSecurityGroups
, DescribeClusterSecurityGroups
-- * Request Lenses
, dcsgTagValues
, dcsgTagKeys
, dcsgClusterSecurityGroupName
, dcsgMarker
, dcsgMaxRecords
-- * Destructuring the Response
, describeClusterSecurityGroupsResponse
, DescribeClusterSecurityGroupsResponse
-- * Response Lenses
, dcsgsrsClusterSecurityGroups
, dcsgsrsMarker
, dcsgsrsResponseStatus
) where
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Redshift.Types
import Network.AWS.Redshift.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- | ???
--
-- /See:/ 'describeClusterSecurityGroups' smart constructor.
data DescribeClusterSecurityGroups = DescribeClusterSecurityGroups'
{ _dcsgTagValues :: !(Maybe [Text])
, _dcsgTagKeys :: !(Maybe [Text])
, _dcsgClusterSecurityGroupName :: !(Maybe Text)
, _dcsgMarker :: !(Maybe Text)
, _dcsgMaxRecords :: !(Maybe Int)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeClusterSecurityGroups' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcsgTagValues'
--
-- * 'dcsgTagKeys'
--
-- * 'dcsgClusterSecurityGroupName'
--
-- * 'dcsgMarker'
--
-- * 'dcsgMaxRecords'
describeClusterSecurityGroups
:: DescribeClusterSecurityGroups
describeClusterSecurityGroups =
DescribeClusterSecurityGroups'
{ _dcsgTagValues = Nothing
, _dcsgTagKeys = Nothing
, _dcsgClusterSecurityGroupName = Nothing
, _dcsgMarker = Nothing
, _dcsgMaxRecords = Nothing
}
-- | A tag value or values for which you want to return all matching cluster
-- security groups that are associated with the specified tag value or
-- values. For example, suppose that you have security groups that are
-- tagged with values called 'admin' and 'test'. If you specify both of
-- these tag values in the request, Amazon Redshift returns a response with
-- the security groups that have either or both of these tag values
-- associated with them.
dcsgTagValues :: Lens' DescribeClusterSecurityGroups [Text]
dcsgTagValues = lens _dcsgTagValues (\ s a -> s{_dcsgTagValues = a}) . _Default . _Coerce;
-- | A tag key or keys for which you want to return all matching cluster
-- security groups that are associated with the specified key or keys. For
-- example, suppose that you have security groups that are tagged with keys
-- called 'owner' and 'environment'. If you specify both of these tag keys
-- in the request, Amazon Redshift returns a response with the security
-- groups that have either or both of these tag keys associated with them.
dcsgTagKeys :: Lens' DescribeClusterSecurityGroups [Text]
dcsgTagKeys = lens _dcsgTagKeys (\ s a -> s{_dcsgTagKeys = a}) . _Default . _Coerce;
-- | The name of a cluster security group for which you are requesting
-- details. You can specify either the __Marker__ parameter or a
-- __ClusterSecurityGroupName__ parameter, but not both.
--
-- Example: 'securitygroup1'
dcsgClusterSecurityGroupName :: Lens' DescribeClusterSecurityGroups (Maybe Text)
dcsgClusterSecurityGroupName = lens _dcsgClusterSecurityGroupName (\ s a -> s{_dcsgClusterSecurityGroupName = a});
-- | An optional parameter that specifies the starting point to return a set
-- of response records. When the results of a DescribeClusterSecurityGroups
-- request exceed the value specified in 'MaxRecords', AWS returns a value
-- in the 'Marker' field of the response. You can retrieve the next set of
-- response records by providing the returned marker value in the 'Marker'
-- parameter and retrying the request.
--
-- Constraints: You can specify either the __ClusterSecurityGroupName__
-- parameter or the __Marker__ parameter, but not both.
dcsgMarker :: Lens' DescribeClusterSecurityGroups (Maybe Text)
dcsgMarker = lens _dcsgMarker (\ s a -> s{_dcsgMarker = a});
-- | The maximum number of response records to return in each call. If the
-- number of remaining response records exceeds the specified 'MaxRecords'
-- value, a value is returned in a 'marker' field of the response. You can
-- retrieve the next set of records by retrying the command with the
-- returned marker value.
--
-- Default: '100'
--
-- Constraints: minimum 20, maximum 100.
dcsgMaxRecords :: Lens' DescribeClusterSecurityGroups (Maybe Int)
dcsgMaxRecords = lens _dcsgMaxRecords (\ s a -> s{_dcsgMaxRecords = a});
instance AWSPager DescribeClusterSecurityGroups where
page rq rs
| stop (rs ^. dcsgsrsMarker) = Nothing
| stop (rs ^. dcsgsrsClusterSecurityGroups) = Nothing
| otherwise =
Just $ rq & dcsgMarker .~ rs ^. dcsgsrsMarker
instance AWSRequest DescribeClusterSecurityGroups
where
type Rs DescribeClusterSecurityGroups =
DescribeClusterSecurityGroupsResponse
request = postQuery redshift
response
= receiveXMLWrapper
"DescribeClusterSecurityGroupsResult"
(\ s h x ->
DescribeClusterSecurityGroupsResponse' <$>
(x .@? "ClusterSecurityGroups" .!@ mempty >>=
may (parseXMLList "ClusterSecurityGroup"))
<*> (x .@? "Marker")
<*> (pure (fromEnum s)))
instance ToHeaders DescribeClusterSecurityGroups
where
toHeaders = const mempty
instance ToPath DescribeClusterSecurityGroups where
toPath = const "/"
instance ToQuery DescribeClusterSecurityGroups where
toQuery DescribeClusterSecurityGroups'{..}
= mconcat
["Action" =:
("DescribeClusterSecurityGroups" :: ByteString),
"Version" =: ("2012-12-01" :: ByteString),
"TagValues" =:
toQuery (toQueryList "TagValue" <$> _dcsgTagValues),
"TagKeys" =:
toQuery (toQueryList "TagKey" <$> _dcsgTagKeys),
"ClusterSecurityGroupName" =:
_dcsgClusterSecurityGroupName,
"Marker" =: _dcsgMarker,
"MaxRecords" =: _dcsgMaxRecords]
-- | Contains the output from the DescribeClusterSecurityGroups action.
--
-- /See:/ 'describeClusterSecurityGroupsResponse' smart constructor.
data DescribeClusterSecurityGroupsResponse = DescribeClusterSecurityGroupsResponse'
{ _dcsgsrsClusterSecurityGroups :: !(Maybe [ClusterSecurityGroup])
, _dcsgsrsMarker :: !(Maybe Text)
, _dcsgsrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeClusterSecurityGroupsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dcsgsrsClusterSecurityGroups'
--
-- * 'dcsgsrsMarker'
--
-- * 'dcsgsrsResponseStatus'
describeClusterSecurityGroupsResponse
:: Int -- ^ 'dcsgsrsResponseStatus'
-> DescribeClusterSecurityGroupsResponse
describeClusterSecurityGroupsResponse pResponseStatus_ =
DescribeClusterSecurityGroupsResponse'
{ _dcsgsrsClusterSecurityGroups = Nothing
, _dcsgsrsMarker = Nothing
, _dcsgsrsResponseStatus = pResponseStatus_
}
-- | A list of ClusterSecurityGroup instances.
dcsgsrsClusterSecurityGroups :: Lens' DescribeClusterSecurityGroupsResponse [ClusterSecurityGroup]
dcsgsrsClusterSecurityGroups = lens _dcsgsrsClusterSecurityGroups (\ s a -> s{_dcsgsrsClusterSecurityGroups = a}) . _Default . _Coerce;
-- | A value that indicates the starting point for the next set of response
-- records in a subsequent request. If a value is returned in a response,
-- you can retrieve the next set of records by providing this returned
-- marker value in the 'Marker' parameter and retrying the command. If the
-- 'Marker' field is empty, all response records have been retrieved for
-- the request.
dcsgsrsMarker :: Lens' DescribeClusterSecurityGroupsResponse (Maybe Text)
dcsgsrsMarker = lens _dcsgsrsMarker (\ s a -> s{_dcsgsrsMarker = a});
-- | The response status code.
dcsgsrsResponseStatus :: Lens' DescribeClusterSecurityGroupsResponse Int
dcsgsrsResponseStatus = lens _dcsgsrsResponseStatus (\ s a -> s{_dcsgsrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-redshift/gen/Network/AWS/Redshift/DescribeClusterSecurityGroups.hs | mpl-2.0 | 10,364 | 0 | 16 | 2,060 | 1,151 | 691 | 460 | 126 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.StorageGateway.UpdateSnapshotSchedule
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- This operation updates a snapshot schedule configured for a gateway
-- volume.
--
-- The default snapshot schedule for volume is once every 24 hours,
-- starting at the creation time of the volume. You can use this API to
-- change the snapshot schedule configured for the volume.
--
-- In the request you must identify the gateway volume whose snapshot
-- schedule you want to update, and the schedule information, including
-- when you want the snapshot to begin on a day and the frequency (in
-- hours) of snapshots.
--
-- /See:/ <http://docs.aws.amazon.com/storagegateway/latest/APIReference/API_UpdateSnapshotSchedule.html AWS API Reference> for UpdateSnapshotSchedule.
module Network.AWS.StorageGateway.UpdateSnapshotSchedule
(
-- * Creating a Request
updateSnapshotSchedule
, UpdateSnapshotSchedule
-- * Request Lenses
, ussDescription
, ussVolumeARN
, ussStartAt
, ussRecurrenceInHours
-- * Destructuring the Response
, updateSnapshotScheduleResponse
, UpdateSnapshotScheduleResponse
-- * Response Lenses
, ussrsVolumeARN
, ussrsResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
import Network.AWS.StorageGateway.Types
import Network.AWS.StorageGateway.Types.Product
-- | A JSON object containing one or more of the following fields:
--
-- - UpdateSnapshotScheduleInput$Description
-- - UpdateSnapshotScheduleInput$RecurrenceInHours
-- - UpdateSnapshotScheduleInput$StartAt
-- - UpdateSnapshotScheduleInput$VolumeARN
--
-- /See:/ 'updateSnapshotSchedule' smart constructor.
data UpdateSnapshotSchedule = UpdateSnapshotSchedule'
{ _ussDescription :: !(Maybe Text)
, _ussVolumeARN :: !Text
, _ussStartAt :: !Nat
, _ussRecurrenceInHours :: !Nat
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateSnapshotSchedule' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ussDescription'
--
-- * 'ussVolumeARN'
--
-- * 'ussStartAt'
--
-- * 'ussRecurrenceInHours'
updateSnapshotSchedule
:: Text -- ^ 'ussVolumeARN'
-> Natural -- ^ 'ussStartAt'
-> Natural -- ^ 'ussRecurrenceInHours'
-> UpdateSnapshotSchedule
updateSnapshotSchedule pVolumeARN_ pStartAt_ pRecurrenceInHours_ =
UpdateSnapshotSchedule'
{ _ussDescription = Nothing
, _ussVolumeARN = pVolumeARN_
, _ussStartAt = _Nat # pStartAt_
, _ussRecurrenceInHours = _Nat # pRecurrenceInHours_
}
-- | Optional description of the snapshot that overwrites the existing
-- description.
ussDescription :: Lens' UpdateSnapshotSchedule (Maybe Text)
ussDescription = lens _ussDescription (\ s a -> s{_ussDescription = a});
-- | The Amazon Resource Name (ARN) of the volume. Use the ListVolumes
-- operation to return a list of gateway volumes.
ussVolumeARN :: Lens' UpdateSnapshotSchedule Text
ussVolumeARN = lens _ussVolumeARN (\ s a -> s{_ussVolumeARN = a});
-- | The hour of the day at which the snapshot schedule begins represented as
-- /hh/, where /hh/ is the hour (0 to 23). The hour of the day is in the
-- time zone of the gateway.
ussStartAt :: Lens' UpdateSnapshotSchedule Natural
ussStartAt = lens _ussStartAt (\ s a -> s{_ussStartAt = a}) . _Nat;
-- | Frequency of snapshots. Specify the number of hours between snapshots.
ussRecurrenceInHours :: Lens' UpdateSnapshotSchedule Natural
ussRecurrenceInHours = lens _ussRecurrenceInHours (\ s a -> s{_ussRecurrenceInHours = a}) . _Nat;
instance AWSRequest UpdateSnapshotSchedule where
type Rs UpdateSnapshotSchedule =
UpdateSnapshotScheduleResponse
request = postJSON storageGateway
response
= receiveJSON
(\ s h x ->
UpdateSnapshotScheduleResponse' <$>
(x .?> "VolumeARN") <*> (pure (fromEnum s)))
instance ToHeaders UpdateSnapshotSchedule where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("StorageGateway_20130630.UpdateSnapshotSchedule" ::
ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON UpdateSnapshotSchedule where
toJSON UpdateSnapshotSchedule'{..}
= object
(catMaybes
[("Description" .=) <$> _ussDescription,
Just ("VolumeARN" .= _ussVolumeARN),
Just ("StartAt" .= _ussStartAt),
Just ("RecurrenceInHours" .= _ussRecurrenceInHours)])
instance ToPath UpdateSnapshotSchedule where
toPath = const "/"
instance ToQuery UpdateSnapshotSchedule where
toQuery = const mempty
-- | A JSON object containing the of the updated storage volume.
--
-- /See:/ 'updateSnapshotScheduleResponse' smart constructor.
data UpdateSnapshotScheduleResponse = UpdateSnapshotScheduleResponse'
{ _ussrsVolumeARN :: !(Maybe Text)
, _ussrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateSnapshotScheduleResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ussrsVolumeARN'
--
-- * 'ussrsResponseStatus'
updateSnapshotScheduleResponse
:: Int -- ^ 'ussrsResponseStatus'
-> UpdateSnapshotScheduleResponse
updateSnapshotScheduleResponse pResponseStatus_ =
UpdateSnapshotScheduleResponse'
{ _ussrsVolumeARN = Nothing
, _ussrsResponseStatus = pResponseStatus_
}
-- | Undocumented member.
ussrsVolumeARN :: Lens' UpdateSnapshotScheduleResponse (Maybe Text)
ussrsVolumeARN = lens _ussrsVolumeARN (\ s a -> s{_ussrsVolumeARN = a});
-- | The response status code.
ussrsResponseStatus :: Lens' UpdateSnapshotScheduleResponse Int
ussrsResponseStatus = lens _ussrsResponseStatus (\ s a -> s{_ussrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-storagegateway/gen/Network/AWS/StorageGateway/UpdateSnapshotSchedule.hs | mpl-2.0 | 6,744 | 0 | 13 | 1,407 | 857 | 515 | 342 | 107 | 1 |
{-# LANGUAGE CPP, NondecreasingIndentation, TupleSections #-}
{-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
-----------------------------------------------------------------------------
--
-- GHC Driver program
--
-- (c) The University of Glasgow 2005
--
-----------------------------------------------------------------------------
module Main (main) where
-- The official GHC API
import qualified GHC
import GHC ( -- DynFlags(..), HscTarget(..),
-- GhcMode(..), GhcLink(..),
Ghc, GhcMonad(..),
LoadHowMuch(..) )
import CmdLineParser
-- Implementations of the various modes (--show-iface, mkdependHS. etc.)
import LoadIface ( showIface )
import HscMain ( newHscEnv )
import DriverPipeline ( oneShot, compileFile, mergeRequirement )
import DriverMkDepend ( doMkDependHS )
#ifdef GHCI
import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
#endif
-- Various other random stuff that we need
import Config
import Constants
import HscTypes
import Packages ( pprPackages, pprPackagesSimple, pprModuleMap )
import DriverPhases
import BasicTypes ( failed )
import StaticFlags
import DynFlags
import ErrUtils
import FastString
import Outputable
import SrcLoc
import Util
import Panic
import MonadUtils ( liftIO )
-- Imports for --abi-hash
import LoadIface ( loadUserInterface )
import Module ( mkModuleName )
import Finder ( findImportedModule, cannotFindInterface )
import TcRnMonad ( initIfaceCheck )
import Binary ( openBinMem, put_, fingerprintBinMem )
-- Standard Haskell libraries
import System.IO
import System.Environment
import System.Exit
import System.FilePath
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
-----------------------------------------------------------------------------
-- ToDo:
-- time commands when run with -v
-- user ways
-- Win32 support: proper signal handling
-- reading the package configuration file is too slow
-- -K<size>
-----------------------------------------------------------------------------
-- GHC's command-line interface
main :: IO ()
main = do
initGCStatistics -- See Note [-Bsymbolic and hooks]
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
-- Handle GHC-specific character encoding flags, allowing us to control how
-- GHC produces output regardless of OS.
env <- getEnvironment
case lookup "GHC_CHARENC" env of
Just "UTF-8" -> do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
_ -> do
-- Avoid GHC erroring out when trying to display unhandled characters
hSetTranslit stdout
hSetTranslit stderr
GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
-- 1. extract the -B flag from the args
argv0 <- getArgs
let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
mbMinusB | null minusB_args = Nothing
| otherwise = Just (drop 2 (last minusB_args))
let argv1' = map (mkGeneralLocated "on the commandline") argv1
(argv2, staticFlagWarnings) <- parseStaticFlags argv1'
-- 2. Parse the "mode" flags (--make, --interactive etc.)
(mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
-- If all we want to do is something like showing the version number
-- then do it now, before we start a GHC session etc. This makes
-- getting basic information much more resilient.
-- In particular, if we wait until later before giving the version
-- number then bootstrapping gets confused, as it tries to find out
-- what version of GHC it's using before package.conf exists, so
-- starting the session fails.
case mode of
Left preStartupMode ->
do case preStartupMode of
ShowSupportedExtensions -> showSupportedExtensions
ShowVersion -> showVersion
ShowNumVersion -> putStrLn cProjectVersion
ShowOptions isInteractive -> showOptions isInteractive
Right postStartupMode ->
-- start our GHC session
GHC.runGhc mbMinusB $ do
dflags <- GHC.getSessionDynFlags
case postStartupMode of
Left preLoadMode ->
liftIO $ do
case preLoadMode of
ShowInfo -> showInfo dflags
ShowGhcUsage -> showGhcUsage dflags
ShowGhciUsage -> showGhciUsage dflags
PrintWithDynFlags f -> putStrLn (f dflags)
Right postLoadMode ->
main' postLoadMode dflags argv3 flagWarnings
main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
-> Ghc ()
main' postLoadMode dflags0 args flagWarnings = do
-- set the default GhcMode, HscTarget and GhcLink. The HscTarget
-- can be further adjusted on a module by module basis, using only
-- the -fvia-C and -fasm flags. If the default HscTarget is not
-- HscC or HscAsm, -fvia-C and -fasm have no effect.
let dflt_target = hscTarget dflags0
(mode, lang, link)
= case postLoadMode of
DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
DoMake -> (CompManager, dflt_target, LinkBinary)
DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
DoAbiHash -> (OneShot, dflt_target, LinkBinary)
DoMergeRequirements -> (OneShot, dflt_target, LinkBinary)
_ -> (OneShot, dflt_target, LinkBinary)
let dflags1 = case lang of
HscInterpreted ->
let platform = targetPlatform dflags0
dflags0a = updateWays $ dflags0 { ways = interpWays }
dflags0b = foldl gopt_set dflags0a
$ concatMap (wayGeneralFlags platform)
interpWays
dflags0c = foldl gopt_unset dflags0b
$ concatMap (wayUnsetGeneralFlags platform)
interpWays
in dflags0c
_ ->
dflags0
dflags2 = dflags1{ ghcMode = mode,
hscTarget = lang,
ghcLink = link,
verbosity = case postLoadMode of
DoEval _ -> 0
_other -> 1
}
-- turn on -fimplicit-import-qualified for GHCi now, so that it
-- can be overriden from the command-line
-- XXX: this should really be in the interactive DynFlags, but
-- we don't set that until later in interactiveUI
dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled
| DoEval _ <- postLoadMode = imp_qual_enabled
| otherwise = dflags2
where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified
-- The rest of the arguments are "dynamic"
-- Leftover ones are presumably files
(dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args
GHC.prettyPrintGhcErrors dflags4 $ do
let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
liftIO $ handleFlagWarnings dflags4 flagWarnings'
-- make sure we clean up after ourselves
GHC.defaultCleanupHandler dflags4 $ do
liftIO $ showBanner postLoadMode dflags4
let
-- To simplify the handling of filepaths, we normalise all filepaths right
-- away - e.g., for win32 platforms, backslashes are converted
-- into forward slashes.
normal_fileish_paths = map (normalise . unLoc) fileish_args
(srcs, objs) = partition_args normal_fileish_paths [] []
dflags5 = dflags4 { ldInputs = map (FileOption "") objs
++ ldInputs dflags4 }
-- we've finished manipulating the DynFlags, update the session
_ <- GHC.setSessionDynFlags dflags5
dflags6 <- GHC.getSessionDynFlags
hsc_env <- GHC.getSession
---------------- Display configuration -----------
case verbosity dflags6 of
v | v == 4 -> liftIO $ dumpPackagesSimple dflags6
| v >= 5 -> liftIO $ dumpPackages dflags6
| otherwise -> return ()
when (verbosity dflags6 >= 3) $ do
liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
when (dopt Opt_D_dump_mod_map dflags6) . liftIO $
printInfoForUser (dflags6 { pprCols = 200 })
(pkgQual dflags6) (pprModuleMap dflags6)
---------------- Final sanity checking -----------
liftIO $ checkOptions postLoadMode dflags6 srcs objs
---------------- Do the business -----------
handleSourceError (\e -> do
GHC.printException e
liftIO $ exitWith (ExitFailure 1)) $ do
case postLoadMode of
ShowInterface f -> liftIO $ doShowIface dflags6 f
DoMake -> doMake srcs
DoMkDependHS -> doMkDependHS (map fst srcs)
StopBefore p -> liftIO (oneShot hsc_env p srcs)
DoInteractive -> ghciUI srcs Nothing
DoEval exprs -> ghciUI srcs $ Just $ reverse exprs
DoAbiHash -> abiHash (map fst srcs)
DoMergeRequirements -> doMergeRequirements (map fst srcs)
ShowPackages -> liftIO $ showPackages dflags6
liftIO $ dumpFinalStats dflags6
ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
#ifndef GHCI
ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use")
#else
ghciUI = interactiveUI defaultGhciSettings
#endif
-- -----------------------------------------------------------------------------
-- Splitting arguments into source files and object files. This is where we
-- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
-- file indicating the phase specified by the -x option in force, if any.
partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
-> ([(String, Maybe Phase)], [String])
partition_args [] srcs objs = (reverse srcs, reverse objs)
partition_args ("-x":suff:args) srcs objs
| "none" <- suff = partition_args args srcs objs
| StopLn <- phase = partition_args args srcs (slurp ++ objs)
| otherwise = partition_args rest (these_srcs ++ srcs) objs
where phase = startPhase suff
(slurp,rest) = break (== "-x") args
these_srcs = zip slurp (repeat (Just phase))
partition_args (arg:args) srcs objs
| looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
| otherwise = partition_args args srcs (arg:objs)
{-
We split out the object files (.o, .dll) and add them
to ldInputs for use by the linker.
The following things should be considered compilation manager inputs:
- haskell source files (strings ending in .hs, .lhs or other
haskellish extension),
- module names (not forgetting hierarchical module names),
- things beginning with '-' are flags that were not recognised by
the flag parser, and we want them to generate errors later in
checkOptions, so we class them as source files (#5921)
- and finally we consider everything not containing a '.' to be
a comp manager input, as shorthand for a .hs or .lhs filename.
Everything else is considered to be a linker object, and passed
straight through to the linker.
-}
looks_like_an_input :: String -> Bool
looks_like_an_input m = isSourceFilename m
|| looksLikeModuleName m
|| "-" `isPrefixOf` m
|| '.' `notElem` m
-- -----------------------------------------------------------------------------
-- Option sanity checks
-- | Ensure sanity of options.
--
-- Throws 'UsageError' or 'CmdLineError' if not.
checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
-- Final sanity checking before kicking off a compilation (pipeline).
checkOptions mode dflags srcs objs = do
-- Complain about any unknown flags
let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
when (notNull (filter wayRTSOnly (ways dflags))
&& isInterpretiveMode mode) $
hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
-- -prof and --interactive are not a good combination
when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
&& isInterpretiveMode mode) $
do throwGhcException (UsageError
"--interactive can't be used with -prof.")
-- -ohi sanity check
if (isJust (outputHi dflags) &&
(isCompManagerMode mode || srcs `lengthExceeds` 1))
then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
else do
-- -o sanity checking
if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
&& not (isLinkMode mode))
then throwGhcException (UsageError "can't apply -o to multiple source files")
else do
let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
when (not_linking && not (null objs)) $
hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
-- Check that there are some input files
-- (except in the interactive case)
if null srcs && (null objs || not_linking) && needsInputsMode mode
then throwGhcException (UsageError "no input files")
else do
case mode of
StopBefore HCc | hscTarget dflags /= HscC
-> throwGhcException $ UsageError $
"the option -C is only available with an unregisterised GHC"
_ -> return ()
-- Verify that output files point somewhere sensible.
verifyOutputFiles dflags
-- Compiler output options
-- Called to verify that the output files point somewhere valid.
--
-- The assumption is that the directory portion of these output
-- options will have to exist by the time 'verifyOutputFiles'
-- is invoked.
--
-- We create the directories for -odir, -hidir, -outputdir etc. ourselves if
-- they don't exist, so don't check for those here (#2278).
verifyOutputFiles :: DynFlags -> IO ()
verifyOutputFiles dflags = do
let ofile = outputFile dflags
when (isJust ofile) $ do
let fn = fromJust ofile
flg <- doesDirNameExist fn
when (not flg) (nonExistentDir "-o" fn)
let ohi = outputHi dflags
when (isJust ohi) $ do
let hi = fromJust ohi
flg <- doesDirNameExist hi
when (not flg) (nonExistentDir "-ohi" hi)
where
nonExistentDir flg dir =
throwGhcException (CmdLineError ("error: directory portion of " ++
show dir ++ " does not exist (used with " ++
show flg ++ " option.)"))
-----------------------------------------------------------------------------
-- GHC modes of operation
type Mode = Either PreStartupMode PostStartupMode
type PostStartupMode = Either PreLoadMode PostLoadMode
data PreStartupMode
= ShowVersion -- ghc -V/--version
| ShowNumVersion -- ghc --numeric-version
| ShowSupportedExtensions -- ghc --supported-extensions
| ShowOptions Bool {- isInteractive -} -- ghc --show-options
showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
showVersionMode = mkPreStartupMode ShowVersion
showNumVersionMode = mkPreStartupMode ShowNumVersion
showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
showOptionsMode = mkPreStartupMode (ShowOptions False)
mkPreStartupMode :: PreStartupMode -> Mode
mkPreStartupMode = Left
isShowVersionMode :: Mode -> Bool
isShowVersionMode (Left ShowVersion) = True
isShowVersionMode _ = False
isShowNumVersionMode :: Mode -> Bool
isShowNumVersionMode (Left ShowNumVersion) = True
isShowNumVersionMode _ = False
data PreLoadMode
= ShowGhcUsage -- ghc -?
| ShowGhciUsage -- ghci -?
| ShowInfo -- ghc --info
| PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
showGhcUsageMode = mkPreLoadMode ShowGhcUsage
showGhciUsageMode = mkPreLoadMode ShowGhciUsage
showInfoMode = mkPreLoadMode ShowInfo
printSetting :: String -> Mode
printSetting k = mkPreLoadMode (PrintWithDynFlags f)
where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
$ lookup k (compilerInfo dflags)
mkPreLoadMode :: PreLoadMode -> Mode
mkPreLoadMode = Right . Left
isShowGhcUsageMode :: Mode -> Bool
isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
isShowGhcUsageMode _ = False
isShowGhciUsageMode :: Mode -> Bool
isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
isShowGhciUsageMode _ = False
data PostLoadMode
= ShowInterface FilePath -- ghc --show-iface
| DoMkDependHS -- ghc -M
| StopBefore Phase -- ghc -E | -C | -S
-- StopBefore StopLn is the default
| DoMake -- ghc --make
| DoInteractive -- ghc --interactive
| DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
| DoAbiHash -- ghc --abi-hash
| ShowPackages -- ghc --show-packages
| DoMergeRequirements -- ghc --merge-requirements
doMkDependHSMode, doMakeMode, doInteractiveMode,
doAbiHashMode, showPackagesMode, doMergeRequirementsMode :: Mode
doMkDependHSMode = mkPostLoadMode DoMkDependHS
doMakeMode = mkPostLoadMode DoMake
doInteractiveMode = mkPostLoadMode DoInteractive
doAbiHashMode = mkPostLoadMode DoAbiHash
showPackagesMode = mkPostLoadMode ShowPackages
doMergeRequirementsMode = mkPostLoadMode DoMergeRequirements
showInterfaceMode :: FilePath -> Mode
showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
stopBeforeMode :: Phase -> Mode
stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
doEvalMode :: String -> Mode
doEvalMode str = mkPostLoadMode (DoEval [str])
mkPostLoadMode :: PostLoadMode -> Mode
mkPostLoadMode = Right . Right
isDoInteractiveMode :: Mode -> Bool
isDoInteractiveMode (Right (Right DoInteractive)) = True
isDoInteractiveMode _ = False
isStopLnMode :: Mode -> Bool
isStopLnMode (Right (Right (StopBefore StopLn))) = True
isStopLnMode _ = False
isDoMakeMode :: Mode -> Bool
isDoMakeMode (Right (Right DoMake)) = True
isDoMakeMode _ = False
#ifdef GHCI
isInteractiveMode :: PostLoadMode -> Bool
isInteractiveMode DoInteractive = True
isInteractiveMode _ = False
#endif
-- isInterpretiveMode: byte-code compiler involved
isInterpretiveMode :: PostLoadMode -> Bool
isInterpretiveMode DoInteractive = True
isInterpretiveMode (DoEval _) = True
isInterpretiveMode _ = False
needsInputsMode :: PostLoadMode -> Bool
needsInputsMode DoMkDependHS = True
needsInputsMode (StopBefore _) = True
needsInputsMode DoMake = True
needsInputsMode _ = False
-- True if we are going to attempt to link in this mode.
-- (we might not actually link, depending on the GhcLink flag)
isLinkMode :: PostLoadMode -> Bool
isLinkMode (StopBefore StopLn) = True
isLinkMode DoMake = True
isLinkMode DoInteractive = True
isLinkMode (DoEval _) = True
isLinkMode _ = False
isCompManagerMode :: PostLoadMode -> Bool
isCompManagerMode DoMake = True
isCompManagerMode DoInteractive = True
isCompManagerMode (DoEval _) = True
isCompManagerMode _ = False
-- -----------------------------------------------------------------------------
-- Parsing the mode flag
parseModeFlags :: [Located String]
-> IO (Mode,
[Located String],
[Located String])
parseModeFlags args = do
let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
runCmdLine (processArgs mode_flags args)
(Nothing, [], [])
mode = case mModeFlag of
Nothing -> doMakeMode
Just (m, _) -> m
-- See Note [Handling errors when parsing commandline flags]
unless (null errs1 && null errs2) $ throwGhcException $ errorsToGhcException $
map (("on the commandline", )) $ map unLoc errs1 ++ errs2
return (mode, flags' ++ leftover, warns)
type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
-- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
-- so we collect the new ones and return them.
mode_flags :: [Flag ModeM]
mode_flags =
[ ------- help / version ----------------------------------------------
defFlag "?" (PassFlag (setMode showGhcUsageMode))
, defFlag "-help" (PassFlag (setMode showGhcUsageMode))
, defFlag "V" (PassFlag (setMode showVersionMode))
, defFlag "-version" (PassFlag (setMode showVersionMode))
, defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode))
, defFlag "-info" (PassFlag (setMode showInfoMode))
, defFlag "-show-options" (PassFlag (setMode showOptionsMode))
, defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
, defFlag "-show-packages" (PassFlag (setMode showPackagesMode))
] ++
[ defFlag k' (PassFlag (setMode (printSetting k)))
| k <- ["Project version",
"Project Git commit id",
"Booter version",
"Stage",
"Build platform",
"Host platform",
"Target platform",
"Have interpreter",
"Object splitting supported",
"Have native code generator",
"Support SMP",
"Unregisterised",
"Tables next to code",
"RTS ways",
"Leading underscore",
"Debug on",
"LibDir",
"Global Package DB",
"C compiler flags",
"Gcc Linker flags",
"Ld Linker flags"],
let k' = "-print-" ++ map (replaceSpace . toLower) k
replaceSpace ' ' = '-'
replaceSpace c = c
] ++
------- interfaces ----------------------------------------------------
[ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
"--show-iface"))
------- primary modes ------------------------------------------------
, defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
addFlag "-no-link" f))
, defFlag "M" (PassFlag (setMode doMkDependHSMode))
, defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
, defFlag "C" (PassFlag (setMode (stopBeforeMode HCc)))
, defFlag "S" (PassFlag (setMode (stopBeforeMode (As False))))
, defFlag "-make" (PassFlag (setMode doMakeMode))
, defFlag "-merge-requirements" (PassFlag (setMode doMergeRequirementsMode))
, defFlag "-interactive" (PassFlag (setMode doInteractiveMode))
, defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode))
, defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
]
setMode :: Mode -> String -> EwM ModeM ()
setMode newMode newFlag = liftEwM $ do
(mModeFlag, errs, flags') <- getCmdLineState
let (modeFlag', errs') =
case mModeFlag of
Nothing -> ((newMode, newFlag), errs)
Just (oldMode, oldFlag) ->
case (oldMode, newMode) of
-- -c/--make are allowed together, and mean --make -no-link
_ | isStopLnMode oldMode && isDoMakeMode newMode
|| isStopLnMode newMode && isDoMakeMode oldMode ->
((doMakeMode, "--make"), [])
-- If we have both --help and --interactive then we
-- want showGhciUsage
_ | isShowGhcUsageMode oldMode &&
isDoInteractiveMode newMode ->
((showGhciUsageMode, oldFlag), [])
| isShowGhcUsageMode newMode &&
isDoInteractiveMode oldMode ->
((showGhciUsageMode, newFlag), [])
-- Otherwise, --help/--version/--numeric-version always win
| isDominantFlag oldMode -> ((oldMode, oldFlag), [])
| isDominantFlag newMode -> ((newMode, newFlag), [])
-- We need to accumulate eval flags like "-e foo -e bar"
(Right (Right (DoEval esOld)),
Right (Right (DoEval [eNew]))) ->
((Right (Right (DoEval (eNew : esOld))), oldFlag),
errs)
-- Saying e.g. --interactive --interactive is OK
_ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
-- --interactive and --show-options are used together
(Right (Right DoInteractive), Left (ShowOptions _)) ->
((Left (ShowOptions True),
"--interactive --show-options"), errs)
(Left (ShowOptions _), (Right (Right DoInteractive))) ->
((Left (ShowOptions True),
"--show-options --interactive"), errs)
-- Otherwise, complain
_ -> let err = flagMismatchErr oldFlag newFlag
in ((oldMode, oldFlag), err : errs)
putCmdLineState (Just modeFlag', errs', flags')
where isDominantFlag f = isShowGhcUsageMode f ||
isShowGhciUsageMode f ||
isShowVersionMode f ||
isShowNumVersionMode f
flagMismatchErr :: String -> String -> String
flagMismatchErr oldFlag newFlag
= "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
addFlag :: String -> String -> EwM ModeM ()
addFlag s flag = liftEwM $ do
(m, e, flags') <- getCmdLineState
putCmdLineState (m, e, mkGeneralLocated loc s : flags')
where loc = "addFlag by " ++ flag ++ " on the commandline"
-- ----------------------------------------------------------------------------
-- Run --make mode
doMake :: [(String,Maybe Phase)] -> Ghc ()
doMake srcs = do
let (hs_srcs, non_hs_srcs) = partition haskellish srcs
haskellish (f,Nothing) =
looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
haskellish (_,Just phase) =
phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcxx, CmmCpp, Cmm
, StopLn]
hsc_env <- GHC.getSession
-- if we have no haskell sources from which to do a dependency
-- analysis, then just do one-shot compilation and/or linking.
-- This means that "ghc Foo.o Bar.o -o baz" links the program as
-- we expect.
if (null hs_srcs)
then liftIO (oneShot hsc_env StopLn srcs)
else do
o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
non_hs_srcs
dflags <- GHC.getSessionDynFlags
let dflags' = dflags { ldInputs = map (FileOption "") o_files
++ ldInputs dflags }
_ <- GHC.setSessionDynFlags dflags'
targets <- mapM (uncurry GHC.guessTarget) hs_srcs
GHC.setTargets targets
ok_flag <- GHC.load LoadAllTargets
when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
return ()
-- ----------------------------------------------------------------------------
-- Run --merge-requirements mode
doMergeRequirements :: [String] -> Ghc ()
doMergeRequirements srcs = mapM_ doMergeRequirement srcs
doMergeRequirement :: String -> Ghc ()
doMergeRequirement src = do
hsc_env <- getSession
liftIO $ mergeRequirement hsc_env (mkModuleName src)
-- ---------------------------------------------------------------------------
-- --show-iface mode
doShowIface :: DynFlags -> FilePath -> IO ()
doShowIface dflags file = do
hsc_env <- newHscEnv dflags
showIface hsc_env file
-- ---------------------------------------------------------------------------
-- Various banners and verbosity output.
showBanner :: PostLoadMode -> DynFlags -> IO ()
showBanner _postLoadMode dflags = do
let verb = verbosity dflags
#ifdef GHCI
-- Show the GHCi banner
when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
#endif
-- Display details of the configuration in verbose mode
when (verb >= 2) $
do hPutStr stderr "Glasgow Haskell Compiler, Version "
hPutStr stderr cProjectVersion
hPutStr stderr ", stage "
hPutStr stderr cStage
hPutStr stderr " booted by GHC version "
hPutStrLn stderr cBooterVersion
-- We print out a Read-friendly string, but a prettier one than the
-- Show instance gives us
showInfo :: DynFlags -> IO ()
showInfo dflags = do
let sq x = " [" ++ x ++ "\n ]"
putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
showSupportedExtensions :: IO ()
showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
showVersion :: IO ()
showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
showOptions :: Bool -> IO ()
showOptions isInteractive = putStr (unlines availableOptions)
where
availableOptions = concat [
flagsForCompletion isInteractive,
map ('-':) (concat [
getFlagNames mode_flags
, (filterUnwantedStatic . getFlagNames $ flagsStatic)
, flagsStaticNames
])
]
getFlagNames opts = map flagName opts
-- this is a hack to get rid of two unwanted entries that get listed
-- as static flags. Hopefully this hack will disappear one day together
-- with static flags
filterUnwantedStatic = filter (`notElem`["f", "fno-"])
showGhcUsage :: DynFlags -> IO ()
showGhcUsage = showUsage False
showGhciUsage :: DynFlags -> IO ()
showGhciUsage = showUsage True
showUsage :: Bool -> DynFlags -> IO ()
showUsage ghci dflags = do
let usage_path = if ghci then ghciUsagePath dflags
else ghcUsagePath dflags
usage <- readFile usage_path
dump usage
where
dump "" = return ()
dump ('$':'$':s) = putStr progName >> dump s
dump (c:s) = putChar c >> dump s
dumpFinalStats :: DynFlags -> IO ()
dumpFinalStats dflags =
when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
dumpFastStringStats :: DynFlags -> IO ()
dumpFastStringStats dflags = do
buckets <- getFastStringTable
let (entries, longest, has_z) = countFS 0 0 0 buckets
msg = text "FastString stats:" $$
nest 4 (vcat [text "size: " <+> int (length buckets),
text "entries: " <+> int entries,
text "longest chain: " <+> int longest,
text "has z-encoding: " <+> (has_z `pcntOf` entries)
])
-- we usually get more "has z-encoding" than "z-encoded", because
-- when we z-encode a string it might hash to the exact same string,
-- which will is not counted as "z-encoded". Only strings whose
-- Z-encoding is different from the original string are counted in
-- the "z-encoded" total.
putMsg dflags msg
where
x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
countFS entries longest has_z [] = (entries, longest, has_z)
countFS entries longest has_z (b:bs) =
let
len = length b
longest' = max len longest
entries' = entries + len
has_zs = length (filter hasZEncoding b)
in
countFS entries' longest' (has_z + has_zs) bs
showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO ()
showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags))
dumpPackages dflags = putMsg dflags (pprPackages dflags)
dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags)
-- -----------------------------------------------------------------------------
-- ABI hash support
{-
ghc --abi-hash Data.Foo System.Bar
Generates a combined hash of the ABI for modules Data.Foo and
System.Bar. The modules must already be compiled, and appropriate -i
options may be necessary in order to find the .hi files.
This is used by Cabal for generating the InstalledPackageId for a
package. The InstalledPackageId must change when the visible ABI of
the package chagnes, so during registration Cabal calls ghc --abi-hash
to get a hash of the package's ABI.
-}
-- | Print ABI hash of input modules.
--
-- The resulting hash is the MD5 of the GHC version used (Trac #5328,
-- see 'hiVersion') and of the existing ABI hash from each module (see
-- 'mi_mod_hash').
abiHash :: [String] -- ^ List of module names
-> Ghc ()
abiHash strs = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
liftIO $ do
let find_it str = do
let modname = mkModuleName str
r <- findImportedModule hsc_env modname Nothing
case r of
Found _ m -> return m
_error -> throwGhcException $ CmdLineError $ showSDoc dflags $
cannotFindInterface dflags modname r
mods <- mapM find_it strs
let get_iface modl = loadUserInterface False (text "abiHash") modl
ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
bh <- openBinMem (3*1024) -- just less than a block
put_ bh hiVersion
-- package hashes change when the compiler version changes (for now)
-- see #5328
mapM_ (put_ bh . mi_mod_hash) ifaces
f <- fingerprintBinMem bh
putStrLn (showPpr dflags f)
-- -----------------------------------------------------------------------------
-- Util
unknownFlagsErr :: [String] -> a
unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
where
oneError f =
"unrecognised flag: " ++ f ++ "\n" ++
(case fuzzyMatch f (nub allFlags) of
[] -> ""
suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
{- Note [-Bsymbolic and hooks]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Bsymbolic is a flag that prevents the binding of references to global
symbols to symbols outside the shared library being compiled (see `man
ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
package: that is because we want hooks to be overridden by the user,
we don't want to constrain them to the RTS package.
Unfortunately this seems to have broken somehow on OS X: as a result,
defaultHooks (in hschooks.c) is not called, which does not initialize
the GC stats. As a result, this breaks things like `:set +s` in GHCi
(#8754). As a hacky workaround, we instead call 'defaultHooks'
directly to initalize the flags in the RTS.
A byproduct of this, I believe, is that hooks are likely broken on OS
X when dynamically linking. But this probably doesn't affect most
people since we're linking GHC dynamically, but most things themselves
link statically.
-}
foreign import ccall safe "initGCStatistics"
initGCStatistics :: IO ()
| ml9951/ghc | ghc/Main.hs | bsd-3-clause | 36,132 | 0 | 27 | 9,975 | 7,364 | 3,796 | 3,568 | 566 | 17 |
module PackageTests.BenchmarkOptions.Check where
import Test.HUnit
import System.FilePath
import PackageTests.PackageTester
suite :: Test
suite = TestCase $ do
let directory = "PackageTests" </> "BenchmarkOptions"
pdFile = directory </> "BenchmarkOptions" <.> "cabal"
spec = PackageSpec directory ["--enable-benchmarks"]
_ <- cabal_build spec
result <- cabal_bench spec ["--benchmark-options=1 2 3"]
let message = "\"cabal bench\" did not pass the correct options to the "
++ "benchmark executable with \"--benchmark-options\""
assertEqual message True $ successful result
result' <- cabal_bench spec [ "--benchmark-option=1"
, "--benchmark-option=2"
, "--benchmark-option=3"
]
let message = "\"cabal bench\" did not pass the correct options to the "
++ "benchmark executable with \"--benchmark-option\""
assertEqual message True $ successful result'
| IreneKnapp/Faction | libfaction/tests/PackageTests/BenchmarkOptions/Check.hs | bsd-3-clause | 1,033 | 0 | 12 | 289 | 177 | 88 | 89 | 20 | 1 |
module TPM (
module TPM.Admin,
module TPM.Capability,
module TPM.Const,
module TPM.Driver,
module TPM.Driver.Socket,
module TPM.Error,
module TPM.Key,
module TPM.Nonce,
module TPM.PCR,
module TPM.Digest,
module TPM.Session,
module TPM.Storage,
module TPM.Types,
module TPM.Utils,
module TPM.Cipher,
module TPM.Eviction,
tpm_with_socket
) where
import TPM.Admin
import TPM.Capability
import TPM.Const
import TPM.Driver
import TPM.Driver.Socket
import TPM.Error
import TPM.Key
import TPM.Nonce
import TPM.PCR
import TPM.Digest
import TPM.Session
import TPM.Types
import TPM.Utils
import TPM.Cipher
import TPM.Storage
import TPM.Eviction
import Control.Exception
import TPM.SignTest
tpm_with_socket c = c (tpm_socket "/var/run/tpm/tpmd_socket:0")
tpm_with_socket' c = c (tpm_logging_socket "/var/run/tpm/tpmd_socket:0")
tpm_with_oiap c = tpm_with_socket $ \s -> do
oiap <- tpm_session_oiap s
c s oiap
tpm_session_close s oiap
return ()
tpm_take = tpm_with_socket $ \tpm -> do
(pub,_) <- tpm_key_pubek tpm
key <- bracket (tpm_session_oiap tpm)
(tpm_session_close tpm)
(\sess -> tpm_takeownership tpm sess pub (tpm_digest_pass "wesley") (tpm_digest_pass ""))
putStrLn $ show key
return ()
| armoredsoftware/protocol | tpm/mainline/src/TPM.hs | bsd-3-clause | 1,321 | 0 | 15 | 277 | 387 | 215 | 172 | 50 | 1 |
{-# LANGUAGE Haskell98, MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, FlexibleInstances, FlexibleContexts #-}
{-# LINE 1 "Text/Regex/Base.hs" #-}
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies #-}
-----------------------------------------------------------------------------
-- |
--
-- Module : Text.Regex.Base
-- Copyright : (c) Chris Kuklewicz 2006
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected], [email protected]
-- Stability : experimental
-- Portability : non-portable (MPTC+FD)
--
-- Classes and instances for Regex matching.
--
--
-- This module merely imports and re-exports the common part of the new
-- api: "Text.Regex.Base.RegexLike" and "Text.Regex.Base.Context".
--
-- To see what result types the instances of RegexContext can produce,
-- please read the "Text.Regex.Base.Context" haddock documentation.
--
-- This does not provide any of the backends, just the common interface
-- they all use. The modules which provide the backends and their cabal
-- packages are:
--
-- * @Text.Regex.Posix@ from regex-posix
--
-- * @Text.Regex@ from regex-compat (uses regex-posix)
--
-- * @Text.Regex.Parsec@ from regex-parsec
--
-- * @Text.Regex.DFA@ from regex-dfa
--
-- * @Text.Regex.PCRE@ from regex-pcre
--
-- * @Test.Regex.TRE@ from regex-tre
--
-- In fact, just importing one of the backends is adequate, you do not
-- also need to import this module.
--
-- TODO: Copy Example*hs files into this haddock comment
-----------------------------------------------------------------------------
module Text.Regex.Base (getVersion_Text_Regex_Base
-- | RegexLike defines classes and type, and 'Extract' instances
,module Text.Regex.Base.RegexLike) where
import Data.Version(Version(..))
import Text.Regex.Base.RegexLike
import Text.Regex.Base.Context()
getVersion_Text_Regex_Base :: Version
getVersion_Text_Regex_Base =
Version { versionBranch = [0,93,2]
, versionTags = ["unstable"]
}
| phischu/fragnix | tests/packages/scotty/Text.Regex.Base.hs | bsd-3-clause | 2,056 | 0 | 7 | 311 | 132 | 103 | 29 | 12 | 1 |
module PLpatt.Parse_PLpatt where
import PLpatt.AS_BASIC_PLpatt
import Text.ParserCombinators.Parsec
import Common.Result
import Control.Monad
import Haskell.Wrapper
import qualified Data.Text as Tx
parsemmt :: String -> IO (Result Basic_spec)
parsemmt s = do
putStr $ "----> input: " ++
s ++ "-------------\n"
let decls = map
(Tx.unpack . Tx.strip . Tx.pack)
$ lines s
let dcls = Result [] (Just decls)
let bs = liftM Basic_spec dcls
print bs
return bs
procLines :: String -> Result Basic_spec
procLines s = let
decls = map
(Tx.unpack . Tx.strip . Tx.pack)
$ lines s
dcls = Result [] (Just decls)
bs = liftM Basic_spec dcls
in
bs
parse1 :: GenParser Char st Basic_spec
parse1 = do
s <- hStuff
let x = procLines s
resultToMonad "MMT parser" x
| mariefarrell/Hets | PLpatt/Parse_PLpatt.hs | gpl-2.0 | 1,108 | 0 | 15 | 488 | 295 | 145 | 150 | 31 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE MagicHash #-}
#if !defined(__PARALLEL_HASKELL__)
{-# LANGUAGE UnboxedTuples #-}
#endif
-----------------------------------------------------------------------------
-- |
-- Module : System.Mem.StableName
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable
--
-- Stable names are a way of performing fast (O(1)), not-quite-exact
-- comparison between objects.
--
-- Stable names solve the following problem: suppose you want to build
-- a hash table with Haskell objects as keys, but you want to use
-- pointer equality for comparison; maybe because the keys are large
-- and hashing would be slow, or perhaps because the keys are infinite
-- in size. We can\'t build a hash table using the address of the
-- object as the key, because objects get moved around by the garbage
-- collector, meaning a re-hash would be necessary after every garbage
-- collection.
--
-------------------------------------------------------------------------------
module System.Mem.StableName (
-- * Stable Names
StableName,
makeStableName,
hashStableName,
eqStableName
) where
import GHC.IO ( IO(..) )
import GHC.Base ( Int(..), StableName#, makeStableName#
, eqStableName#, stableNameToInt# )
-----------------------------------------------------------------------------
-- Stable Names
{-|
An abstract name for an object, that supports equality and hashing.
Stable names have the following property:
* If @sn1 :: StableName@ and @sn2 :: StableName@ and @sn1 == sn2@
then @sn1@ and @sn2@ were created by calls to @makeStableName@ on
the same object.
The reverse is not necessarily true: if two stable names are not
equal, then the objects they name may still be equal. Note in particular
that `mkStableName` may return a different `StableName` after an
object is evaluated.
Stable Names are similar to Stable Pointers ("Foreign.StablePtr"),
but differ in the following ways:
* There is no @freeStableName@ operation, unlike "Foreign.StablePtr"s.
Stable names are reclaimed by the runtime system when they are no
longer needed.
* There is no @deRefStableName@ operation. You can\'t get back from
a stable name to the original Haskell object. The reason for
this is that the existence of a stable name for an object does not
guarantee the existence of the object itself; it can still be garbage
collected.
-}
data StableName a = StableName (StableName# a)
-- | Makes a 'StableName' for an arbitrary object. The object passed as
-- the first argument is not evaluated by 'makeStableName'.
makeStableName :: a -> IO (StableName a)
#if defined(__PARALLEL_HASKELL__)
makeStableName a =
error "makeStableName not implemented in parallel Haskell"
#else
makeStableName a = IO $ \ s ->
case makeStableName# a s of (# s', sn #) -> (# s', StableName sn #)
#endif
-- | Convert a 'StableName' to an 'Int'. The 'Int' returned is not
-- necessarily unique; several 'StableName's may map to the same 'Int'
-- (in practice however, the chances of this are small, so the result
-- of 'hashStableName' makes a good hash key).
hashStableName :: StableName a -> Int
#if defined(__PARALLEL_HASKELL__)
hashStableName (StableName sn) =
error "hashStableName not implemented in parallel Haskell"
#else
hashStableName (StableName sn) = I# (stableNameToInt# sn)
#endif
instance Eq (StableName a) where
#if defined(__PARALLEL_HASKELL__)
(StableName sn1) == (StableName sn2) =
error "eqStableName not implemented in parallel Haskell"
#else
(StableName sn1) == (StableName sn2) =
case eqStableName# sn1 sn2 of
0# -> False
_ -> True
#endif
-- | Equality on 'StableName' that does not require that the types of
-- the arguments match.
--
-- @since 4.7.0.0
eqStableName :: StableName a -> StableName b -> Bool
eqStableName (StableName sn1) (StableName sn2) =
case eqStableName# sn1 sn2 of
0# -> False
_ -> True
-- Requested by Emil Axelsson on glasgow-haskell-users, who wants to
-- use it for implementing observable sharing.
| christiaanb/ghc | libraries/base/System/Mem/StableName.hs | bsd-3-clause | 4,360 | 0 | 8 | 846 | 292 | 181 | 111 | 29 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module T12583 where
import Data.Ix
data Foo a where
MkFoo :: (Eq a, Ord a, Ix a) => Foo a
deriving instance Eq (Foo a)
deriving instance Ord (Foo a)
deriving instance Ix (Foo a)
| snoyberg/ghc | testsuite/tests/deriving/should_compile/T12583.hs | bsd-3-clause | 243 | 0 | 7 | 49 | 87 | 48 | 39 | 9 | 0 |
{-# OPTIONS_GHC -w #-}
import Control.Monad(when)
import System.Exit
-- parser produced by Happy Version 1.18.6
data HappyAbsSyn t14 t15 t16 t17 t18 t19 t20 t21 t22 t23 t24 t25 t26 t27 t28 t29 t30 t31 t32 t33 t34 t35 t36 t37 t38 t39 t40 t41 t42 t43 t44 t45 t46 t47 t48 t49 t50 t51 t52 t53 t54 t55 t56 t57 t58 t59 t60 t61
= HappyTerminal (Char)
| HappyErrorToken Int
| HappyAbsSyn14 t14
| HappyAbsSyn15 t15
| HappyAbsSyn16 t16
| HappyAbsSyn17 t17
| HappyAbsSyn18 t18
| HappyAbsSyn19 t19
| HappyAbsSyn20 t20
| HappyAbsSyn21 t21
| HappyAbsSyn22 t22
| HappyAbsSyn23 t23
| HappyAbsSyn24 t24
| HappyAbsSyn25 t25
| HappyAbsSyn26 t26
| HappyAbsSyn27 t27
| HappyAbsSyn28 t28
| HappyAbsSyn29 t29
| HappyAbsSyn30 t30
| HappyAbsSyn31 t31
| HappyAbsSyn32 t32
| HappyAbsSyn33 t33
| HappyAbsSyn34 t34
| HappyAbsSyn35 t35
| HappyAbsSyn36 t36
| HappyAbsSyn37 t37
| HappyAbsSyn38 t38
| HappyAbsSyn39 t39
| HappyAbsSyn40 t40
| HappyAbsSyn41 t41
| HappyAbsSyn42 t42
| HappyAbsSyn43 t43
| HappyAbsSyn44 t44
| HappyAbsSyn45 t45
| HappyAbsSyn46 t46
| HappyAbsSyn47 t47
| HappyAbsSyn48 t48
| HappyAbsSyn49 t49
| HappyAbsSyn50 t50
| HappyAbsSyn51 t51
| HappyAbsSyn52 t52
| HappyAbsSyn53 t53
| HappyAbsSyn54 t54
| HappyAbsSyn55 t55
| HappyAbsSyn56 t56
| HappyAbsSyn57 t57
| HappyAbsSyn58 t58
| HappyAbsSyn59 t59
| HappyAbsSyn60 t60
| HappyAbsSyn61 t61
action_0 (62) = happyShift action_22
action_0 (14) = happyGoto action_66
action_0 (17) = happyGoto action_12
action_0 (18) = happyGoto action_13
action_0 (19) = happyGoto action_14
action_0 (31) = happyGoto action_15
action_0 (32) = happyGoto action_16
action_0 (33) = happyGoto action_17
action_0 (35) = happyGoto action_18
action_0 (43) = happyGoto action_19
action_0 (44) = happyGoto action_20
action_0 (45) = happyGoto action_21
action_0 _ = happyFail
action_1 (62) = happyShift action_22
action_1 (15) = happyGoto action_63
action_1 (34) = happyGoto action_64
action_1 (35) = happyGoto action_65
action_1 _ = happyReduce_32
action_2 (62) = happyShift action_62
action_2 (16) = happyGoto action_56
action_2 (25) = happyGoto action_57
action_2 (36) = happyGoto action_58
action_2 (46) = happyGoto action_59
action_2 (53) = happyGoto action_60
action_2 (60) = happyGoto action_61
action_2 _ = happyReduce_35
action_3 (62) = happyShift action_22
action_3 (17) = happyGoto action_55
action_3 (18) = happyGoto action_13
action_3 (19) = happyGoto action_14
action_3 (32) = happyGoto action_16
action_3 (33) = happyGoto action_17
action_3 (35) = happyGoto action_18
action_3 (44) = happyGoto action_20
action_3 (45) = happyGoto action_21
action_3 _ = happyFail
action_4 (62) = happyShift action_22
action_4 (18) = happyGoto action_54
action_4 (19) = happyGoto action_14
action_4 (33) = happyGoto action_17
action_4 (35) = happyGoto action_18
action_4 (45) = happyGoto action_21
action_4 _ = happyFail
action_5 (62) = happyShift action_22
action_5 (19) = happyGoto action_53
action_5 (35) = happyGoto action_18
action_5 _ = happyFail
action_6 (62) = happyShift action_52
action_6 (20) = happyGoto action_47
action_6 (26) = happyGoto action_48
action_6 (38) = happyGoto action_49
action_6 (47) = happyGoto action_50
action_6 (55) = happyGoto action_51
action_6 _ = happyFail
action_7 (62) = happyShift action_46
action_7 (21) = happyGoto action_41
action_7 (27) = happyGoto action_42
action_7 (39) = happyGoto action_43
action_7 (48) = happyGoto action_44
action_7 (56) = happyGoto action_45
action_7 _ = happyFail
action_8 (62) = happyShift action_40
action_8 (22) = happyGoto action_35
action_8 (28) = happyGoto action_36
action_8 (40) = happyGoto action_37
action_8 (49) = happyGoto action_38
action_8 (57) = happyGoto action_39
action_8 _ = happyFail
action_9 (62) = happyShift action_34
action_9 (23) = happyGoto action_29
action_9 (29) = happyGoto action_30
action_9 (41) = happyGoto action_31
action_9 (50) = happyGoto action_32
action_9 (58) = happyGoto action_33
action_9 _ = happyFail
action_10 (62) = happyShift action_28
action_10 (24) = happyGoto action_23
action_10 (30) = happyGoto action_24
action_10 (42) = happyGoto action_25
action_10 (51) = happyGoto action_26
action_10 (59) = happyGoto action_27
action_10 _ = happyFail
action_11 (62) = happyShift action_22
action_11 (17) = happyGoto action_12
action_11 (18) = happyGoto action_13
action_11 (19) = happyGoto action_14
action_11 (31) = happyGoto action_15
action_11 (32) = happyGoto action_16
action_11 (33) = happyGoto action_17
action_11 (35) = happyGoto action_18
action_11 (43) = happyGoto action_19
action_11 (44) = happyGoto action_20
action_11 (45) = happyGoto action_21
action_11 _ = happyFail
action_12 _ = happyReduce_43
action_13 _ = happyReduce_45
action_14 _ = happyReduce_47
action_15 _ = happyReduce_11
action_16 _ = happyReduce_14
action_17 _ = happyReduce_15
action_18 _ = happyReduce_16
action_19 (62) = happyShift action_22
action_19 (17) = happyGoto action_86
action_19 (18) = happyGoto action_13
action_19 (19) = happyGoto action_14
action_19 (32) = happyGoto action_16
action_19 (33) = happyGoto action_17
action_19 (35) = happyGoto action_18
action_19 (44) = happyGoto action_20
action_19 (45) = happyGoto action_21
action_19 _ = happyReduce_28
action_20 (62) = happyShift action_22
action_20 (18) = happyGoto action_85
action_20 (19) = happyGoto action_14
action_20 (33) = happyGoto action_17
action_20 (35) = happyGoto action_18
action_20 (45) = happyGoto action_21
action_20 _ = happyReduce_29
action_21 (62) = happyShift action_22
action_21 (19) = happyGoto action_84
action_21 (35) = happyGoto action_18
action_21 _ = happyReduce_30
action_22 (63) = happyShift action_83
action_22 (37) = happyGoto action_79
action_22 (52) = happyGoto action_80
action_22 (54) = happyGoto action_81
action_22 (61) = happyGoto action_82
action_22 _ = happyReduce_37
action_23 (64) = happyAccept
action_23 _ = happyFail
action_24 _ = happyReduce_21
action_25 _ = happyReduce_27
action_26 _ = happyReduce_66
action_27 (62) = happyShift action_28
action_27 (51) = happyGoto action_78
action_27 _ = happyReduce_42
action_28 (62) = happyShift action_22
action_28 (19) = happyGoto action_77
action_28 (35) = happyGoto action_18
action_28 _ = happyFail
action_29 (64) = happyAccept
action_29 _ = happyFail
action_30 _ = happyReduce_20
action_31 _ = happyReduce_26
action_32 _ = happyReduce_64
action_33 (62) = happyShift action_34
action_33 (50) = happyGoto action_76
action_33 _ = happyReduce_41
action_34 (62) = happyShift action_22
action_34 (18) = happyGoto action_75
action_34 (19) = happyGoto action_14
action_34 (33) = happyGoto action_17
action_34 (35) = happyGoto action_18
action_34 (45) = happyGoto action_21
action_34 _ = happyFail
action_35 (64) = happyAccept
action_35 _ = happyFail
action_36 _ = happyReduce_19
action_37 _ = happyReduce_25
action_38 _ = happyReduce_62
action_39 (62) = happyShift action_40
action_39 (49) = happyGoto action_74
action_39 _ = happyReduce_40
action_40 (62) = happyShift action_22
action_40 (17) = happyGoto action_73
action_40 (18) = happyGoto action_13
action_40 (19) = happyGoto action_14
action_40 (32) = happyGoto action_16
action_40 (33) = happyGoto action_17
action_40 (35) = happyGoto action_18
action_40 (44) = happyGoto action_20
action_40 (45) = happyGoto action_21
action_40 _ = happyFail
action_41 (64) = happyAccept
action_41 _ = happyFail
action_42 _ = happyReduce_18
action_43 _ = happyReduce_24
action_44 _ = happyReduce_60
action_45 (62) = happyShift action_46
action_45 (48) = happyGoto action_72
action_45 _ = happyReduce_39
action_46 (62) = happyShift action_62
action_46 (16) = happyGoto action_71
action_46 (25) = happyGoto action_57
action_46 (36) = happyGoto action_58
action_46 (46) = happyGoto action_59
action_46 (53) = happyGoto action_60
action_46 (60) = happyGoto action_61
action_46 _ = happyReduce_35
action_47 (64) = happyAccept
action_47 _ = happyFail
action_48 _ = happyReduce_17
action_49 _ = happyReduce_23
action_50 _ = happyReduce_58
action_51 (62) = happyShift action_52
action_51 (47) = happyGoto action_70
action_51 _ = happyReduce_38
action_52 (62) = happyShift action_22
action_52 (15) = happyGoto action_69
action_52 (34) = happyGoto action_64
action_52 (35) = happyGoto action_65
action_52 _ = happyReduce_32
action_53 (64) = happyAccept
action_53 _ = happyFail
action_54 (64) = happyAccept
action_54 _ = happyFail
action_55 (64) = happyAccept
action_55 _ = happyFail
action_56 (64) = happyAccept
action_56 _ = happyFail
action_57 _ = happyReduce_13
action_58 _ = happyReduce_22
action_59 _ = happyReduce_68
action_60 _ = happyReduce_34
action_61 (62) = happyShift action_62
action_61 (46) = happyGoto action_68
action_61 _ = happyReduce_56
action_62 (63) = happyShift action_67
action_62 _ = happyFail
action_63 (64) = happyAccept
action_63 _ = happyFail
action_64 _ = happyReduce_12
action_65 _ = happyReduce_31
action_66 (64) = happyAccept
action_66 _ = happyFail
action_67 _ = happyReduce_49
action_68 _ = happyReduce_69
action_69 _ = happyReduce_50
action_70 _ = happyReduce_59
action_71 _ = happyReduce_51
action_72 _ = happyReduce_61
action_73 _ = happyReduce_52
action_74 _ = happyReduce_63
action_75 _ = happyReduce_53
action_76 _ = happyReduce_65
action_77 _ = happyReduce_54
action_78 _ = happyReduce_67
action_79 _ = happyReduce_33
action_80 _ = happyReduce_70
action_81 _ = happyReduce_36
action_82 (63) = happyShift action_83
action_82 (52) = happyGoto action_88
action_82 _ = happyReduce_57
action_83 (62) = happyShift action_87
action_83 _ = happyFail
action_84 _ = happyReduce_48
action_85 _ = happyReduce_46
action_86 _ = happyReduce_44
action_87 _ = happyReduce_55
action_88 _ = happyReduce_71
happyReduce_11 = happySpecReduce_1 14 happyReduction_11
happyReduction_11 (HappyAbsSyn31 happy_var_1)
= HappyAbsSyn14
(happy_var_1
)
happyReduction_11 _ = notHappyAtAll
happyReduce_12 = happySpecReduce_1 15 happyReduction_12
happyReduction_12 (HappyAbsSyn34 happy_var_1)
= HappyAbsSyn15
(happy_var_1
)
happyReduction_12 _ = notHappyAtAll
happyReduce_13 = happySpecReduce_1 16 happyReduction_13
happyReduction_13 (HappyAbsSyn25 happy_var_1)
= HappyAbsSyn16
(happy_var_1
)
happyReduction_13 _ = notHappyAtAll
happyReduce_14 = happySpecReduce_1 17 happyReduction_14
happyReduction_14 (HappyAbsSyn32 happy_var_1)
= HappyAbsSyn17
(happy_var_1
)
happyReduction_14 _ = notHappyAtAll
happyReduce_15 = happySpecReduce_1 18 happyReduction_15
happyReduction_15 (HappyAbsSyn33 happy_var_1)
= HappyAbsSyn18
(happy_var_1
)
happyReduction_15 _ = notHappyAtAll
happyReduce_16 = happySpecReduce_1 19 happyReduction_16
happyReduction_16 (HappyAbsSyn35 happy_var_1)
= HappyAbsSyn19
(happy_var_1
)
happyReduction_16 _ = notHappyAtAll
happyReduce_17 = happySpecReduce_1 20 happyReduction_17
happyReduction_17 (HappyAbsSyn26 happy_var_1)
= HappyAbsSyn20
(happy_var_1
)
happyReduction_17 _ = notHappyAtAll
happyReduce_18 = happySpecReduce_1 21 happyReduction_18
happyReduction_18 (HappyAbsSyn27 happy_var_1)
= HappyAbsSyn21
(happy_var_1
)
happyReduction_18 _ = notHappyAtAll
happyReduce_19 = happySpecReduce_1 22 happyReduction_19
happyReduction_19 (HappyAbsSyn28 happy_var_1)
= HappyAbsSyn22
(happy_var_1
)
happyReduction_19 _ = notHappyAtAll
happyReduce_20 = happySpecReduce_1 23 happyReduction_20
happyReduction_20 (HappyAbsSyn29 happy_var_1)
= HappyAbsSyn23
(happy_var_1
)
happyReduction_20 _ = notHappyAtAll
happyReduce_21 = happySpecReduce_1 24 happyReduction_21
happyReduction_21 (HappyAbsSyn30 happy_var_1)
= HappyAbsSyn24
(happy_var_1
)
happyReduction_21 _ = notHappyAtAll
happyReduce_22 = happySpecReduce_1 25 happyReduction_22
happyReduction_22 (HappyAbsSyn36 happy_var_1)
= HappyAbsSyn25
(happy_var_1
)
happyReduction_22 _ = notHappyAtAll
happyReduce_23 = happySpecReduce_1 26 happyReduction_23
happyReduction_23 (HappyAbsSyn38 happy_var_1)
= HappyAbsSyn26
(happy_var_1
)
happyReduction_23 _ = notHappyAtAll
happyReduce_24 = happySpecReduce_1 27 happyReduction_24
happyReduction_24 (HappyAbsSyn39 happy_var_1)
= HappyAbsSyn27
(happy_var_1
)
happyReduction_24 _ = notHappyAtAll
happyReduce_25 = happySpecReduce_1 28 happyReduction_25
happyReduction_25 (HappyAbsSyn40 happy_var_1)
= HappyAbsSyn28
(happy_var_1
)
happyReduction_25 _ = notHappyAtAll
happyReduce_26 = happySpecReduce_1 29 happyReduction_26
happyReduction_26 (HappyAbsSyn41 happy_var_1)
= HappyAbsSyn29
(happy_var_1
)
happyReduction_26 _ = notHappyAtAll
happyReduce_27 = happySpecReduce_1 30 happyReduction_27
happyReduction_27 (HappyAbsSyn42 happy_var_1)
= HappyAbsSyn30
(happy_var_1
)
happyReduction_27 _ = notHappyAtAll
happyReduce_28 = happySpecReduce_1 31 happyReduction_28
happyReduction_28 (HappyAbsSyn43 happy_var_1)
= HappyAbsSyn31
(reverse happy_var_1
)
happyReduction_28 _ = notHappyAtAll
happyReduce_29 = happySpecReduce_1 32 happyReduction_29
happyReduction_29 (HappyAbsSyn44 happy_var_1)
= HappyAbsSyn32
(reverse happy_var_1
)
happyReduction_29 _ = notHappyAtAll
happyReduce_30 = happySpecReduce_1 33 happyReduction_30
happyReduction_30 (HappyAbsSyn45 happy_var_1)
= HappyAbsSyn33
(reverse happy_var_1
)
happyReduction_30 _ = notHappyAtAll
happyReduce_31 = happySpecReduce_1 34 happyReduction_31
happyReduction_31 (HappyAbsSyn35 happy_var_1)
= HappyAbsSyn34
(happy_var_1
)
happyReduction_31 _ = notHappyAtAll
happyReduce_32 = happySpecReduce_0 34 happyReduction_32
happyReduction_32 = HappyAbsSyn34
([]
)
happyReduce_33 = happySpecReduce_2 35 happyReduction_33
happyReduction_33 (HappyAbsSyn37 happy_var_2)
(HappyTerminal happy_var_1)
= HappyAbsSyn35
(happy_var_1 : happy_var_2
)
happyReduction_33 _ _ = notHappyAtAll
happyReduce_34 = happySpecReduce_1 36 happyReduction_34
happyReduction_34 (HappyAbsSyn53 happy_var_1)
= HappyAbsSyn36
(happy_var_1
)
happyReduction_34 _ = notHappyAtAll
happyReduce_35 = happySpecReduce_0 36 happyReduction_35
happyReduction_35 = HappyAbsSyn36
([]
)
happyReduce_36 = happySpecReduce_1 37 happyReduction_36
happyReduction_36 (HappyAbsSyn54 happy_var_1)
= HappyAbsSyn37
(happy_var_1
)
happyReduction_36 _ = notHappyAtAll
happyReduce_37 = happySpecReduce_0 37 happyReduction_37
happyReduction_37 = HappyAbsSyn37
([]
)
happyReduce_38 = happySpecReduce_1 38 happyReduction_38
happyReduction_38 (HappyAbsSyn55 happy_var_1)
= HappyAbsSyn38
(reverse happy_var_1
)
happyReduction_38 _ = notHappyAtAll
happyReduce_39 = happySpecReduce_1 39 happyReduction_39
happyReduction_39 (HappyAbsSyn56 happy_var_1)
= HappyAbsSyn39
(reverse happy_var_1
)
happyReduction_39 _ = notHappyAtAll
happyReduce_40 = happySpecReduce_1 40 happyReduction_40
happyReduction_40 (HappyAbsSyn57 happy_var_1)
= HappyAbsSyn40
(reverse happy_var_1
)
happyReduction_40 _ = notHappyAtAll
happyReduce_41 = happySpecReduce_1 41 happyReduction_41
happyReduction_41 (HappyAbsSyn58 happy_var_1)
= HappyAbsSyn41
(reverse happy_var_1
)
happyReduction_41 _ = notHappyAtAll
happyReduce_42 = happySpecReduce_1 42 happyReduction_42
happyReduction_42 (HappyAbsSyn59 happy_var_1)
= HappyAbsSyn42
(reverse happy_var_1
)
happyReduction_42 _ = notHappyAtAll
happyReduce_43 = happySpecReduce_1 43 happyReduction_43
happyReduction_43 (HappyAbsSyn17 happy_var_1)
= HappyAbsSyn43
([happy_var_1]
)
happyReduction_43 _ = notHappyAtAll
happyReduce_44 = happySpecReduce_2 43 happyReduction_44
happyReduction_44 (HappyAbsSyn17 happy_var_2)
(HappyAbsSyn43 happy_var_1)
= HappyAbsSyn43
(happy_var_2 : happy_var_1
)
happyReduction_44 _ _ = notHappyAtAll
happyReduce_45 = happySpecReduce_1 44 happyReduction_45
happyReduction_45 (HappyAbsSyn18 happy_var_1)
= HappyAbsSyn44
([happy_var_1]
)
happyReduction_45 _ = notHappyAtAll
happyReduce_46 = happySpecReduce_2 44 happyReduction_46
happyReduction_46 (HappyAbsSyn18 happy_var_2)
(HappyAbsSyn44 happy_var_1)
= HappyAbsSyn44
(happy_var_2 : happy_var_1
)
happyReduction_46 _ _ = notHappyAtAll
happyReduce_47 = happySpecReduce_1 45 happyReduction_47
happyReduction_47 (HappyAbsSyn19 happy_var_1)
= HappyAbsSyn45
([happy_var_1]
)
happyReduction_47 _ = notHappyAtAll
happyReduce_48 = happySpecReduce_2 45 happyReduction_48
happyReduction_48 (HappyAbsSyn19 happy_var_2)
(HappyAbsSyn45 happy_var_1)
= HappyAbsSyn45
(happy_var_2 : happy_var_1
)
happyReduction_48 _ _ = notHappyAtAll
happyReduce_49 = happySpecReduce_2 46 happyReduction_49
happyReduction_49 _
(HappyTerminal happy_var_1)
= HappyAbsSyn46
(happy_var_1
)
happyReduction_49 _ _ = notHappyAtAll
happyReduce_50 = happySpecReduce_2 47 happyReduction_50
happyReduction_50 _
(HappyTerminal happy_var_1)
= HappyAbsSyn47
(happy_var_1
)
happyReduction_50 _ _ = notHappyAtAll
happyReduce_51 = happySpecReduce_2 48 happyReduction_51
happyReduction_51 _
(HappyTerminal happy_var_1)
= HappyAbsSyn48
(happy_var_1
)
happyReduction_51 _ _ = notHappyAtAll
happyReduce_52 = happySpecReduce_2 49 happyReduction_52
happyReduction_52 _
(HappyTerminal happy_var_1)
= HappyAbsSyn49
(happy_var_1
)
happyReduction_52 _ _ = notHappyAtAll
happyReduce_53 = happySpecReduce_2 50 happyReduction_53
happyReduction_53 _
(HappyTerminal happy_var_1)
= HappyAbsSyn50
(happy_var_1
)
happyReduction_53 _ _ = notHappyAtAll
happyReduce_54 = happySpecReduce_2 51 happyReduction_54
happyReduction_54 _
(HappyTerminal happy_var_1)
= HappyAbsSyn51
(happy_var_1
)
happyReduction_54 _ _ = notHappyAtAll
happyReduce_55 = happySpecReduce_2 52 happyReduction_55
happyReduction_55 (HappyTerminal happy_var_2)
_
= HappyAbsSyn52
(happy_var_2
)
happyReduction_55 _ _ = notHappyAtAll
happyReduce_56 = happySpecReduce_1 53 happyReduction_56
happyReduction_56 (HappyAbsSyn60 happy_var_1)
= HappyAbsSyn53
(reverse happy_var_1
)
happyReduction_56 _ = notHappyAtAll
happyReduce_57 = happySpecReduce_1 54 happyReduction_57
happyReduction_57 (HappyAbsSyn61 happy_var_1)
= HappyAbsSyn54
(reverse happy_var_1
)
happyReduction_57 _ = notHappyAtAll
happyReduce_58 = happySpecReduce_1 55 happyReduction_58
happyReduction_58 (HappyAbsSyn47 happy_var_1)
= HappyAbsSyn55
([happy_var_1]
)
happyReduction_58 _ = notHappyAtAll
happyReduce_59 = happySpecReduce_2 55 happyReduction_59
happyReduction_59 (HappyAbsSyn47 happy_var_2)
(HappyAbsSyn55 happy_var_1)
= HappyAbsSyn55
(happy_var_2 : happy_var_1
)
happyReduction_59 _ _ = notHappyAtAll
happyReduce_60 = happySpecReduce_1 56 happyReduction_60
happyReduction_60 (HappyAbsSyn48 happy_var_1)
= HappyAbsSyn56
([happy_var_1]
)
happyReduction_60 _ = notHappyAtAll
happyReduce_61 = happySpecReduce_2 56 happyReduction_61
happyReduction_61 (HappyAbsSyn48 happy_var_2)
(HappyAbsSyn56 happy_var_1)
= HappyAbsSyn56
(happy_var_2 : happy_var_1
)
happyReduction_61 _ _ = notHappyAtAll
happyReduce_62 = happySpecReduce_1 57 happyReduction_62
happyReduction_62 (HappyAbsSyn49 happy_var_1)
= HappyAbsSyn57
([happy_var_1]
)
happyReduction_62 _ = notHappyAtAll
happyReduce_63 = happySpecReduce_2 57 happyReduction_63
happyReduction_63 (HappyAbsSyn49 happy_var_2)
(HappyAbsSyn57 happy_var_1)
= HappyAbsSyn57
(happy_var_2 : happy_var_1
)
happyReduction_63 _ _ = notHappyAtAll
happyReduce_64 = happySpecReduce_1 58 happyReduction_64
happyReduction_64 (HappyAbsSyn50 happy_var_1)
= HappyAbsSyn58
([happy_var_1]
)
happyReduction_64 _ = notHappyAtAll
happyReduce_65 = happySpecReduce_2 58 happyReduction_65
happyReduction_65 (HappyAbsSyn50 happy_var_2)
(HappyAbsSyn58 happy_var_1)
= HappyAbsSyn58
(happy_var_2 : happy_var_1
)
happyReduction_65 _ _ = notHappyAtAll
happyReduce_66 = happySpecReduce_1 59 happyReduction_66
happyReduction_66 (HappyAbsSyn51 happy_var_1)
= HappyAbsSyn59
([happy_var_1]
)
happyReduction_66 _ = notHappyAtAll
happyReduce_67 = happySpecReduce_2 59 happyReduction_67
happyReduction_67 (HappyAbsSyn51 happy_var_2)
(HappyAbsSyn59 happy_var_1)
= HappyAbsSyn59
(happy_var_2 : happy_var_1
)
happyReduction_67 _ _ = notHappyAtAll
happyReduce_68 = happySpecReduce_1 60 happyReduction_68
happyReduction_68 (HappyAbsSyn46 happy_var_1)
= HappyAbsSyn60
([happy_var_1]
)
happyReduction_68 _ = notHappyAtAll
happyReduce_69 = happySpecReduce_2 60 happyReduction_69
happyReduction_69 (HappyAbsSyn46 happy_var_2)
(HappyAbsSyn60 happy_var_1)
= HappyAbsSyn60
(happy_var_2 : happy_var_1
)
happyReduction_69 _ _ = notHappyAtAll
happyReduce_70 = happySpecReduce_1 61 happyReduction_70
happyReduction_70 (HappyAbsSyn52 happy_var_1)
= HappyAbsSyn61
([happy_var_1]
)
happyReduction_70 _ = notHappyAtAll
happyReduce_71 = happySpecReduce_2 61 happyReduction_71
happyReduction_71 (HappyAbsSyn52 happy_var_2)
(HappyAbsSyn61 happy_var_1)
= HappyAbsSyn61
(happy_var_2 : happy_var_1
)
happyReduction_71 _ _ = notHappyAtAll
happyNewToken action sts stk [] =
action 64 64 notHappyAtAll (HappyState action) sts stk []
happyNewToken action sts stk (tk:tks) =
let cont i = action i i tk (HappyState action) sts stk tks in
case tk of {
'a' -> cont 62;
'b' -> cont 63;
_ -> happyError' (tk:tks)
}
happyError_ tk tks = happyError' (tk:tks)
happyThen :: () => Maybe a -> (a -> Maybe b) -> Maybe b
happyThen = ((>>=))
happyReturn :: () => a -> Maybe a
happyReturn = (return)
happyThen1 m k tks = ((>>=)) m (\a -> k a tks)
happyReturn1 :: () => a -> b -> Maybe a
happyReturn1 = \a tks -> (return) a
happyError' :: () => [(Char)] -> Maybe a
happyError' = happyError
test0 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_0 tks) (\x -> case x of {HappyAbsSyn14 z -> happyReturn z; _other -> notHappyAtAll })
test1 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_1 tks) (\x -> case x of {HappyAbsSyn15 z -> happyReturn z; _other -> notHappyAtAll })
test2 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_2 tks) (\x -> case x of {HappyAbsSyn16 z -> happyReturn z; _other -> notHappyAtAll })
test3 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_3 tks) (\x -> case x of {HappyAbsSyn17 z -> happyReturn z; _other -> notHappyAtAll })
test4 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_4 tks) (\x -> case x of {HappyAbsSyn18 z -> happyReturn z; _other -> notHappyAtAll })
test5 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_5 tks) (\x -> case x of {HappyAbsSyn19 z -> happyReturn z; _other -> notHappyAtAll })
test6 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_6 tks) (\x -> case x of {HappyAbsSyn20 z -> happyReturn z; _other -> notHappyAtAll })
test7 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_7 tks) (\x -> case x of {HappyAbsSyn21 z -> happyReturn z; _other -> notHappyAtAll })
test8 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_8 tks) (\x -> case x of {HappyAbsSyn22 z -> happyReturn z; _other -> notHappyAtAll })
test9 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_9 tks) (\x -> case x of {HappyAbsSyn23 z -> happyReturn z; _other -> notHappyAtAll })
test10 tks = happySomeParser where
happySomeParser = happyThen (happyParse action_10 tks) (\x -> case x of {HappyAbsSyn24 z -> happyReturn z; _other -> notHappyAtAll })
happySeq = happyDontSeq
happyError _ = Nothing
tests = [ test1 "" == Just ""
, test1 "a" == Just "a"
, test1 "ab" == Nothing
, test1 "aba" == Just "aa"
, test1 "abab" == Nothing
, test2 "" == Just ""
, test2 "a" == Nothing
, test2 "ab" == Just "a"
, test2 "aba" == Nothing
, test2 "abab" == Just "aa"
]
main = do let failed = filter (not . snd) (zip [0..] tests)
when (not (null failed)) $
do putStrLn ("Failed tests: " ++ show (map fst failed))
exitFailure
putStrLn "Tests passed."
{-# LINE 1 "templates/GenericTemplate.hs" #-}
{-# LINE 1 "templates/GenericTemplate.hs" #-}
{-# LINE 1 "<built-in>" #-}
{-# LINE 1 "<command-line>" #-}
{-# LINE 1 "templates/GenericTemplate.hs" #-}
-- Id: GenericTemplate.hs,v 1.26 2005/01/14 14:47:22 simonmar Exp
{-# LINE 30 "templates/GenericTemplate.hs" #-}
{-# LINE 51 "templates/GenericTemplate.hs" #-}
{-# LINE 61 "templates/GenericTemplate.hs" #-}
{-# LINE 70 "templates/GenericTemplate.hs" #-}
infixr 9 `HappyStk`
data HappyStk a = HappyStk a (HappyStk a)
-----------------------------------------------------------------------------
-- starting the parse
happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll
-----------------------------------------------------------------------------
-- Accepting the parse
-- If the current token is (1), it means we've just accepted a partial
-- parse (a %partial parser). We must ignore the saved token on the top of
-- the stack in this case.
happyAccept (1) tk st sts (_ `HappyStk` ans `HappyStk` _) =
happyReturn1 ans
happyAccept j tk st sts (HappyStk ans _) =
(happyReturn1 ans)
-----------------------------------------------------------------------------
-- Arrays only: do the next action
{-# LINE 148 "templates/GenericTemplate.hs" #-}
-----------------------------------------------------------------------------
-- HappyState data type (not arrays)
newtype HappyState b c = HappyState
(Int -> -- token number
Int -> -- token number (yes, again)
b -> -- token semantic value
HappyState b c -> -- current state
[HappyState b c] -> -- state stack
c)
-----------------------------------------------------------------------------
-- Shifting a token
happyShift new_state (1) tk st sts stk@(x `HappyStk` _) =
let (i) = (case x of { HappyErrorToken (i) -> i }) in
-- trace "shifting the error token" $
new_state i i tk (HappyState (new_state)) ((st):(sts)) (stk)
happyShift new_state i tk st sts stk =
happyNewToken new_state ((st):(sts)) ((HappyTerminal (tk))`HappyStk`stk)
-- happyReduce is specialised for the common cases.
happySpecReduce_0 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_0 nt fn j tk st@((HappyState (action))) sts stk
= action nt j tk st ((st):(sts)) (fn `HappyStk` stk)
happySpecReduce_1 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_1 nt fn j tk _ sts@(((st@(HappyState (action))):(_))) (v1`HappyStk`stk')
= let r = fn v1 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_2 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_2 nt fn j tk _ ((_):(sts@(((st@(HappyState (action))):(_))))) (v1`HappyStk`v2`HappyStk`stk')
= let r = fn v1 v2 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happySpecReduce_3 i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happySpecReduce_3 nt fn j tk _ ((_):(((_):(sts@(((st@(HappyState (action))):(_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk')
= let r = fn v1 v2 v3 in
happySeq r (action nt j tk st sts (r `HappyStk` stk'))
happyReduce k i fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyReduce k nt fn j tk st sts stk
= case happyDrop (k - ((1) :: Int)) sts of
sts1@(((st1@(HappyState (action))):(_))) ->
let r = fn stk in -- it doesn't hurt to always seq here...
happyDoSeq r (action nt j tk st1 sts1 r)
happyMonadReduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonadReduce k nt fn j tk st sts stk =
happyThen1 (fn stk tk) (\r -> action nt j tk st1 sts1 (r `HappyStk` drop_stk))
where (sts1@(((st1@(HappyState (action))):(_)))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
happyMonad2Reduce k nt fn (1) tk st sts stk
= happyFail (1) tk st sts stk
happyMonad2Reduce k nt fn j tk st sts stk =
happyThen1 (fn stk tk) (\r -> happyNewToken new_state sts1 (r `HappyStk` drop_stk))
where (sts1@(((st1@(HappyState (action))):(_)))) = happyDrop k ((st):(sts))
drop_stk = happyDropStk k stk
new_state = action
happyDrop (0) l = l
happyDrop n ((_):(t)) = happyDrop (n - ((1) :: Int)) t
happyDropStk (0) l = l
happyDropStk n (x `HappyStk` xs) = happyDropStk (n - ((1)::Int)) xs
-----------------------------------------------------------------------------
-- Moving to a new state after a reduction
{-# LINE 246 "templates/GenericTemplate.hs" #-}
happyGoto action j tk st = action j j tk (HappyState action)
-----------------------------------------------------------------------------
-- Error recovery ((1) is the error token)
-- parse error if we are in recovery and we fail again
happyFail (1) tk old_st _ stk =
-- trace "failing" $
happyError_ tk
{- We don't need state discarding for our restricted implementation of
"error". In fact, it can cause some bogus parses, so I've disabled it
for now --SDM
-- discard a state
happyFail (1) tk old_st (((HappyState (action))):(sts))
(saved_tok `HappyStk` _ `HappyStk` stk) =
-- trace ("discarding state, depth " ++ show (length stk)) $
action (1) (1) tk (HappyState (action)) sts ((saved_tok`HappyStk`stk))
-}
-- Enter error recovery: generate an error token,
-- save the old token and carry on.
happyFail i tk (HappyState (action)) sts stk =
-- trace "entering error recovery" $
action (1) (1) tk (HappyState (action)) sts ( (HappyErrorToken (i)) `HappyStk` stk)
-- Internal happy errors:
notHappyAtAll :: a
notHappyAtAll = error "Internal Happy error\n"
-----------------------------------------------------------------------------
-- Hack to get the typechecker to accept our action functions
-----------------------------------------------------------------------------
-- Seq-ing. If the --strict flag is given, then Happy emits
-- happySeq = happyDoSeq
-- otherwise it emits
-- happySeq = happyDontSeq
happyDoSeq, happyDontSeq :: a -> b -> b
happyDoSeq a b = a `seq` b
happyDontSeq a b = b
-----------------------------------------------------------------------------
-- Don't inline any functions from the template. GHC has a nasty habit
-- of deciding to inline happyGoto everywhere, which increases the size of
-- the generated parser quite a bit.
{-# LINE 311 "templates/GenericTemplate.hs" #-}
{-# NOINLINE happyShift #-}
{-# NOINLINE happySpecReduce_0 #-}
{-# NOINLINE happySpecReduce_1 #-}
{-# NOINLINE happySpecReduce_2 #-}
{-# NOINLINE happySpecReduce_3 #-}
{-# NOINLINE happyReduce #-}
{-# NOINLINE happyMonadReduce #-}
{-# NOINLINE happyGoto #-}
{-# NOINLINE happyFail #-}
-- end of Happy Template.
| urbanslug/ghc | testsuite/tests/perf/compiler/T5631.hs | bsd-3-clause | 31,315 | 424 | 20 | 5,516 | 9,183 | 4,780 | 4,403 | 759 | 3 |
module IntegratorForward where
import qualified Clamp
import qualified Vector3f
import qualified Input
forward_speed :: Input.T -> Float -> Float -> Float -> Float
forward_speed i sf a delta =
if (Input.is_moving_forward i)
then sf + (a * delta)
else sf
backward_speed :: Input.T -> Float -> Float -> Float -> Float
backward_speed i sf a delta =
if (Input.is_moving_backward i)
then sf - (a * delta)
else sf
forward :: (Vector3f.T, Vector3f.T, Float, Input.T, Float, Float, Float) -> Float -> (Vector3f.T, Float)
forward (p, v_forward, sf, i, a, d, ms) delta =
let
sf0 = backward_speed i (forward_speed i sf a delta) a delta
sf1 = Clamp.clamp sf0 (-ms, ms)
pr = Vector3f.add3 p (Vector3f.scale v_forward (sf1 * delta))
sfr = sf1 * (d ** delta)
in
(pr, sfr) | io7m/jcamera | com.io7m.jcamera.documentation/src/main/resources/com/io7m/jcamera/documentation/haskell/IntegratorForward.hs | isc | 801 | 0 | 13 | 173 | 326 | 182 | 144 | 22 | 2 |
module Engine where
import Control.Monad
import Board
import Geometry
import Data.List (nub)
-- | Return the white pieces from the board
whites :: Board -> [Piece]
whites = filter (\piece -> color piece == White)
-- | Return the black pieces from the board
blacks :: Board -> [Piece]
blacks = filter (\piece -> color piece == Black)
-- | Return the value of the piece
valuePiece :: Piece -> Int
valuePiece (Piece _ Pawn _) = 1
valuePiece (Piece _ Knight _) = 3
valuePiece (Piece _ Bishop _) = 3
valuePiece (Piece _ Rook _) = 5
valuePiece (Piece _ Queen _) = 9
valuePiece (Piece _ King _) = 1000
-- | Return the possible moves for any piece
moves :: Piece -> [Pos]
moves (Piece White Pawn (x,y)) = [(x,y+1)]
moves (Piece Black Pawn (x,y)) = [(x,y-1)]
moves (Piece _ Bishop p) = diagonals p
moves (Piece _ Rook p) = cross p
moves (Piece _ Queen p) = allDirections p
moves (Piece _ King p) = ambientPos p
moves (Piece _ Knight (x,y)) = do
let ds = [-2, -1, 1, 2]
dx <- ds
dy <- ds
guard $ abs dx /= abs dy && onBoard (x+dx,y+dy)
return (x+dx, y+dy)
-- | Return the legal moves of the piece
legalMoves :: Board -> Piece -> [Pos]
legalMoves b piece@(Piece c King _) = filter (emptyOrEnemy b c) $ moves piece
legalMoves b piece@(Piece c Knight _) = filter (emptyOrEnemy b c) $ moves piece
legalMoves b piece@(Piece c Pawn _) = filter (emptyOrEnemy b c) $ moves piece
legalMoves b piece@(Piece c Bishop p) = nub $ legalMovesInLine b p (moves piece)
legalMoves b piece@(Piece c Rook _) = filter (emptyOrEnemy b c) $ moves piece
legalMoves b piece@(Piece c Queen _) = filter (emptyOrEnemy b c) $ moves piece
legalMovesInLine :: Board -> Pos -> [Pos] -> [Pos]
legalMovesInLine _ _ [] = []
legalMovesInLine b start (p:ps) =
if emptySegment b (segment start p)
then p : legalMovesInLine b start ps
else legalMovesInLine b start ps
-- | Check if a position is empty or contains an enemy piece
emptyOrEnemy :: Board -> PieceColor -> Pos -> Bool
emptyOrEnemy b c p = enemy b c p || empty b p
-- | Check if a position is contains an enemy piece
enemy :: Board -> PieceColor -> Pos -> Bool
enemy b c p = case pieceAt b p of
Just piece -> color piece == enemyColor c
Nothing -> False
-- | Check if a position is empty
empty :: Board -> Pos -> Bool
empty b p = case pieceAt b p of
Just _ -> False
Nothing -> True
-- | Check if every position of a line is empty
emptySegment :: Board -> Maybe Segment -> Bool
emptySegment _ Nothing = False
emptySegment b (Just s) = all (empty b) (points s) | nagyf/hs-chess | src/Engine.hs | mit | 2,550 | 0 | 11 | 564 | 1,084 | 555 | 529 | 55 | 2 |
module Handler.Run where
import Import
import Util.Handler (maybeApiUser)
import Network.Wai (lazyRequestBody)
import Model.Run.Api (runSnippet)
import Model.Snippet.Api (getSnippet)
import Settings.Environment (runApiAnonymousToken)
postRunR :: Language -> Handler Value
postRunR lang = do
langVersion <- fromMaybe "latest" <$> lookupGetParam "version"
req <- reqWaiRequest <$> getRequest
body <- liftIO $ lazyRequestBody req
mUserId <- maybeAuthId
mApiUser <- maybeApiUser mUserId
runAnonToken <- liftIO runApiAnonymousToken
res <- liftIO $ runSnippet (pack $ show lang) langVersion body $ runApiToken mApiUser runAnonToken
case res of
Left errorMsg ->
sendResponseStatus status400 $ object ["message" .= errorMsg]
Right (runStdout, runStderr, runError) -> do
mSnippetId <- lookupGetParam "snippet"
persistRunResult lang mSnippetId (apiUserToken <$> mApiUser) (snippetContentHash' body) (runStdout, runStderr, runError)
return $ object [
"stdout" .= runStdout,
"stderr" .= runStderr,
"error" .= runError]
runApiToken :: Maybe ApiUser -> Text -> Text
runApiToken (Just user) _ = apiUserToken user
runApiToken _ token = token
persistRunResult :: Language -> Maybe Text -> Maybe Text -> Text -> (Text, Text, Text) -> Handler ()
persistRunResult lang (Just snippetId) mToken localFilesHash (runStdout, runStderr, runError)
| (length runStdout > 0 || length runStderr > 0) && length runError == 0 = do
eSnippet <- liftIO $ safeGetSnippet snippetId mToken
case eSnippet of
Left _ -> return ()
Right snippet -> do
persistRunResult' lang snippetId localFilesHash
(snippetContentHash snippet) (runStdout, runStderr, runError)
persistRunResult _ _ _ _ _ = return ()
persistRunResult' :: Language -> Text -> Text -> Text -> (Text, Text, Text) -> Handler ()
persistRunResult' lang snippetId localHash remoteHash (runStdout, runStderr, runError)
| localHash == remoteHash = do
now <- liftIO getCurrentTime
_ <- runDB $ do
deleteBy $ UniqueRunResult snippetId
insertUnique $ RunResult snippetId localHash
(pack $ show lang) runStdout runStderr runError now
return ()
persistRunResult' _ _ _ _ _ = return ()
safeGetSnippet :: Text -> Maybe Text -> IO (Either SomeException Snippet)
safeGetSnippet snippetId mToken = try $ getSnippet snippetId mToken
| vinnymac/glot-www | Handler/Run.hs | mit | 2,536 | 0 | 16 | 608 | 782 | 384 | 398 | 51 | 2 |
module Control.Concurrent.STM.ClosableChan where
import Control.Concurrent.STM
import Control.Concurrent.STM.TBMChan
import Control.Concurrent.STM.TMChan
class ClosableChan q where
isClosedChan :: q -> STM Bool
closeChan :: q -> STM ()
instance ClosableChan (TMChan a) where
isClosedChan = isClosedTMChan
closeChan = closeTMChan
instance ClosableChan (TBMChan a) where
isClosedChan = isClosedTBMChan
closeChan = closeTBMChan
| MRudolph/stm-chans-class | src/Control/Concurrent/STM/ClosableChan.hs | mit | 444 | 0 | 9 | 66 | 111 | 63 | 48 | 13 | 0 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Selection.RadioButtons (
-- * The RadioButtons Widget
RadioButtons,
-- * Constructor
mkRadioButtons) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Control.Monad (when, join, void)
import Data.Aeson
import qualified Data.HashMap.Strict as HM
import Data.IORef (newIORef)
import Data.Text (Text)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | A 'RadioButtons' represents a RadioButtons widget from IPython.html.widgets.
type RadioButtons = IPythonWidget RadioButtonsType
-- | Create a new RadioButtons widget
mkRadioButtons :: IO RadioButtons
mkRadioButtons = do
-- Default properties, with a random uuid
uuid <- U.random
let widgetState = WidgetState $ defaultSelectionWidget "RadioButtonsView"
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay RadioButtons where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget RadioButtons where
getCommUUID = uuid
comm widget (Object dict1) _ = do
let key1 = "sync_data" :: Text
key2 = "selected_label" :: Text
Just (Object dict2) = HM.lookup key1 dict1
Just (String label) = HM.lookup key2 dict2
opts <- getField widget Options
case opts of
OptionLabels _ -> void $ do
setField' widget SelectedLabel label
setField' widget SelectedValue label
OptionDict ps ->
case lookup label ps of
Nothing -> return ()
Just value -> void $ do
setField' widget SelectedLabel label
setField' widget SelectedValue value
triggerSelection widget
| beni55/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/RadioButtons.hs | mit | 2,265 | 0 | 17 | 566 | 474 | 248 | 226 | 51 | 1 |
module Callbacks where
import Gol3d.Render
import Gol3d.Life
import Control.Monad ( when )
import Data.IORef
import Graphics.UI.GLUT
import System.Exit ( exitWith, ExitCode(ExitSuccess) )
import qualified Data.Map as M
import Util
import Input
import Types
import App
keyPollMap :: IORef State -> [(Key, IO ())]
keyPollMap stateR = [ (Char 'w', advanceCamera' stateR 1)
, (Char 'a', transCamera' stateR (Vector2 (-1) 0))
, (Char 'd', transCamera' stateR (Vector2 1 0))
, (Char 's', advanceCamera' stateR (-1))
, (Char 'q', transCamera' stateR (Vector2 0 (-1)))
, (Char 'e', transCamera' stateR (Vector2 0 1))
]
-- | An input handler that uses polling.
keyPollHandler stateR = do
s@(State { kbdState = kbd }) <- get stateR
let whenDown key action = whenKey' kbd key Down $
do action
postRedisplay Nothing
mapM_ (uncurry whenDown) (keyPollMap stateR)
et <- get elapsedTime
s <- get stateR
stateR $= s { lastKeyPoll = et }
inputHandler stateR key state mods pos = do
s@(State { kbdState = kbd
, gameMode = mode
, isPlaying = playing
}) <- get stateR
let kbd' = M.insert key state kbd
let mode' = case (state, key) of
(Down, Char 'b') -> toggleMode mode
_ -> mode
let isPlaying' = case (state, key) of
(Down, Char 'p') -> not playing
_ -> playing
writeIORef stateR $ s { kbdState = kbd'
, gameMode = mode'
, isPlaying = isPlaying'
}
case state of
Down ->
case key of
Char ' ' -> evolveState stateR
Char 'x' -> exitWith ExitSuccess
_ -> return ()
_ -> return ()
postRedisplay Nothing
mouseHandler stateR btn keyState pos = do
s@(State { camState = cs
, gameMode = mode
, cellMap = cm
}) <- get stateR
let (f, act) = case keyState of
Down ->
( case btn of
LeftButton -> insertCell' $
fmap fromIntegral $
gameCursorLocation cs
RightButton -> deleteCell' $
fmap fromIntegral $
gameCursorLocation cs
_ -> id
, postRedisplay Nothing
)
_ -> (id, return ())
writeIORef stateR (s { cellMap = f cm })
act
motionHandler stateR p = do
s@(State { camState = cs
, angleSpeed = aspd
}) <- get stateR
d@(dx, dy) <- mouseDelta p
when (dx /= 0 || dy /= 0) $ do
let cs' = adjustCameraAngle aspd (Vector2 dx dy) cs
writeIORef stateR (s { camState = cs' })
centerMouse
postRedisplay Nothing
idleHandler stateR = do
s@(State { lastEvolve = le
, evolveDelta = ed
, lastKeyPoll = lkp
, keyPollDelta = kpd
, isPlaying = ip
}) <- get stateR
et <- get elapsedTime
when (et >= lkp + kpd) $ keyPollHandler stateR
when (ip && et >= le + ed) $ evolveState stateR
display :: IORef State -> DisplayCallback
display stateR = do
s@(State { cellDrawConfig = celldc
, cursorDrawConfig = cursordc
, camState = cs
, cellMap = cm
, evolveDelta = ed
, lastEvolve = le
, gameMode = mode
}) <- get stateR
clear [ColorBuffer, DepthBuffer]
setCamera cs
blend $= Disabled
drawCellMap celldc (vector3toVertex3 $ camPos cs) cm
blend $= Enabled
when (mode == BuildMode) $ do
blendFunc $= (SrcAlpha, OneMinusSrcAlpha)
drawCell cursordc (vector3toVertex3 $ camPos cs) $
newCell $ fmap fromIntegral $ gameCursorLocation cs
swapBuffers
| labcoders/gol3d-hs | src/Callbacks.hs | mit | 4,291 | 4 | 20 | 1,838 | 1,275 | 650 | 625 | 110 | 6 |
{-# LANGUAGE NamedFieldPuns #-}
{-
Copyright (C) 2012-2017 Jimmy Liang <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Language.Clafer.IG.Constraints (Constraint(..), Cardinality(..), ClaferInfo(..), ConstraintInfo(..), isLowerCardinalityConstraint, isUpperCardinalityConstraint, lookupConstraint, parseConstraints) where
import Data.List
import Data.Maybe
import Data.Ord
import Language.Clafer
import Language.Clafer.Front.AbsClafer (Span(..))
import Language.Clafer.Intermediate.Intclafer
import qualified Language.Clafer.Intermediate.Intclafer as I
data Constraint =
ExactCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
LowerCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
UpperCardinalityConstraint {range::Span, claferInfo::ClaferInfo} |
UserConstraint {range::Span, constraintInfo::ConstraintInfo}
deriving (Show, Eq)
data Cardinality = Cardinality {lower::Integer, upper::Maybe Integer} deriving Eq
instance Show Cardinality where
show (Cardinality 0 Nothing) = "*"
show (Cardinality 1 Nothing) = "+"
show (Cardinality lower Nothing) = show lower ++ "..*"
show (Cardinality 0 (Just 1)) = "?"
show (Cardinality lower (Just upper))
| lower == upper = show lower
| otherwise = show lower ++ ".." ++ show upper
data ClaferInfo = ClaferInfo {uniqueId::String, cardinality::Cardinality} deriving Eq
instance Show ClaferInfo where
show (ClaferInfo uniqueId cardinality) = uniqueId ++ " " ++ show cardinality
data ConstraintInfo = ConstraintInfo {pId::String, pos::Span, syntax::String} deriving Eq
instance Show ConstraintInfo where
show ConstraintInfo{pos = Span (Pos l c) _, syntax} = syntax ++ " (line " ++ show l ++ ", column " ++ show c ++ ")"
isLowerCardinalityConstraint :: Constraint -> Bool
isLowerCardinalityConstraint LowerCardinalityConstraint{} = True
isLowerCardinalityConstraint _ = False
isUpperCardinalityConstraint :: Constraint -> Bool
isUpperCardinalityConstraint UpperCardinalityConstraint{} = True
isUpperCardinalityConstraint _ = False
to :: Span -> Pos
to (Span _ t) = t
{-from :: Span -> Pos
from (Span f _) = f -}
lookupConstraint :: Span -> [Constraint] -> Constraint
lookupConstraint constraint' constraints =
case [x | x <- constraints, constraint' == range x] of
[] -> error $ show constraint' ++ " not equal to known constraints " ++ show constraints
cs -> minimumBy (comparing $ to . range) cs
parseConstraints :: String -> IModule -> [(Span, IrTrace)] -> [Constraint]
parseConstraints claferModel imodule mapping =
mapMaybe (uncurry convert) mapping
where
clafers = _mDecls imodule >>= subclafers
pexps = (mapMaybe constraint $ _mDecls imodule ++ concatMap _elements clafers) >>= subexpressions
convert s IrPExp{pUid} =
Just $ UserConstraint s $ ConstraintInfo pUid (_inPos $ findPExp pUid) $ extract $ _inPos $ findPExp pUid
convert s LowerCard{pUid, isGroup = False} =
Just $ LowerCardinalityConstraint s $ claferInfo pUid
convert s UpperCard{pUid, isGroup = False} =
Just $ UpperCardinalityConstraint s $ claferInfo pUid
convert s ExactCard{pUid, isGroup = False} =
Just $ ExactCardinalityConstraint s $ claferInfo pUid
convert _ _ = Nothing
findPExp pUid = fromMaybe (error $ "Unknown constraint " ++ pUid) $ find ((== pUid) . _pid) pexps
findClafer pUid = fromMaybe (error $ "Unknown clafer " ++ pUid) $ find ((== pUid) . _uid) clafers
text = lines claferModel
extract (Span (Pos l1 c1) (Pos l2 c2))
| l1 == l2 = drop (fromInteger $ c1 - 1) $ take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l1 - 1)
| otherwise = unlines $ f1 : fs ++ [fn]
where
f1 = drop (fromInteger $ c1 - 1) $ text !! (fromInteger $ l1 - 1)
fs = map (text !!) [(fromInteger $ l1) .. (fromInteger $ l2 - 2)]
fn = take (fromInteger $ c2 - 1) $ text !! (fromInteger $ l2 - 1)
convertCard (l, -1) = Cardinality l Nothing
convertCard (l, h) = Cardinality l $ Just h
claferInfo pUid =
ClaferInfo (_ident claf) $ convertCard $ fromJust $ _card claf
where
claf = findClafer pUid
subclafers :: IElement -> [IClafer]
subclafers (IEClafer claf) = claf : (_elements claf >>= subclafers)
subclafers _ = []
constraint :: IElement -> Maybe PExp
constraint (IEConstraint _ pexp') = Just pexp'
constraint _ = Nothing
subexpressions :: PExp -> [PExp]
subexpressions p@PExp{I._exp = exp'} =
p : subexpressions' exp'
where
subexpressions' IDeclPExp{_oDecls, _bpexp} =
concatMap (subexpressions . _body) _oDecls ++ subexpressions _bpexp
subexpressions' IFunExp{_exps} = concatMap subexpressions _exps
subexpressions' _ = []
| gsdlab/claferIG | src/Language/Clafer/IG/Constraints.hs | mit | 5,792 | 0 | 14 | 1,132 | 1,579 | 835 | 744 | 84 | 6 |
{-# LANGUAGE Safe #-}
module Data.UTC.Class.Epoch
( Epoch(..)
) where
-- | The instant in time also known as __the epoch__: 1970-01-01T00:00:00Z
class Epoch t where
epoch :: t
| lpeterse/haskell-utc | Data/UTC/Class/Epoch.hs | mit | 184 | 0 | 6 | 37 | 33 | 21 | 12 | 5 | 0 |
import Control.Monad
import Data.Char
import Data.Function
import Data.List
import Data.Maybe
import Text.Printf
main = do
tests <- readLn
forM_ [1..tests] $ \caseNum -> do
str <- getLine
let ans = concatMap insertPause . groupBy pauseNeeded $ numified where
numified = map numify str
pauseNeeded = (==) `on` head
insertPause = unwords
printf "Case #%d: %s\n" (caseNum::Int) ans
numify c = replicate count digit where
digit = case findIndex (c `elem`) dict of
Just n -> intToDigit n
Nothing -> error "Invalid character"
count = case elemIndex c =<< find (c `elem`) dict of
Just n -> n + 1
Nothing -> error "Invalid character"
dict = [" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"]
| marknsikora/codejam | 351101/C.hs | mit | 767 | 0 | 16 | 183 | 279 | 149 | 130 | 23 | 3 |
-- This file is covered by an MIT license. See 'LICENSE' for details.
-- Author: Bertram Felgenhauer
{-# LANGUAGE OverloadedStrings #-}
module Confluence.Direct.Ground (
confluent
) where
import Confluence.Types
import Framework.Types
import Framework.Explain
import Util.Pretty
import qualified Util.Relation as R
import qualified Data.Rewriting.Rules as Rules
import qualified Data.Rewriting.Rule as Rule
import qualified Data.Rewriting.Term as Term
import Text.PrettyPrint.ANSI.Leijen
import Control.Monad.RWS hiding ((<>))
import Control.Monad
import qualified Data.Set as S
import qualified Data.Map as M
import Data.List
import Debug.Trace
confluent :: Problem String String -> Explain Answer
confluent trs = section "Confluence for Ground TRSs" $
if Rules.isGround trs then confluent' trs else do
tell "Not a ground TRS."
return Maybe
confluent' :: (Ord f, PPretty f) => Problem f v -> Explain Answer
confluent' trs = do
let trs' = map (mapRule Term.withArity) trs
trs2 = tseitin trs'
trs3 = ffc trs2
-- trs3 is the forward closure of the curried TRS, restricted to
-- the sides of that curried TRS
joins = joinc trs3
sides = S.fromList [x | (l, r) <- R.toList trs3, x <- [l, r]]
stabilizables = stabilizable trs3
{-
section "Tseitin transformation" $
tell $ vList trs2
section "Forward closure" $
tell $ vList $ R.toList trs3
section "Joinability closure" $
tell $ vList $ R.toList joins
-}
case filter (not . cconds trs3 joins stabilizables) (S.toList sides) of
s:_ -> do
tell $ "C-Conditions not satisfied for" <+> ppretty s <> "."
return No
[] -> do
tell "C-Conditions satisfied."
let ndjs = ndj trs3 joins stabilizables
case filter (\(s, _) -> (s, s) `R.member` ndjs) (R.toList trs3) of
(s, _):_ -> do
tell $ "Side not deeply joinable with itself:" <+> ppretty s
return No
[] -> do
tell $ "All sides deeply joinable with themselves."
return Yes
mapRule :: (Term.Term f v -> Term.Term f' v') ->
Rule.Rule f v -> Rule.Rule f' v'
mapRule f (Rule.Rule l r) = Rule.Rule (f l) (f r)
data Con f = F f Int | C Int deriving (Eq, Ord, Show)
data Side f = Con (Con f) | App (Con f) (Con f) deriving (Eq, Ord, Show)
data Tops f = Con' (Con f) | App' (Side f) (Side f) deriving (Eq, Ord, Show)
isCon :: Side f -> Bool
isCon Con{} = True
isCon App{} = False
isApp :: Side f -> Bool
isApp Con{} = False
isApp App{} = True
type M f = RWS () [(Side f, Side f)] Int
-- Currying and Tseitin transform.
tseitin :: Problem (f, Int) v -> [(Side f, Side f)]
tseitin trs = snd (evalRWS (mapM go trs) () 0) where
term :: Term.Term (f, Int) v -> M f (Con f)
term = Term.fold var fun
var _ = error "Not a ground TRS"
fun (f, a) ts = do
ts' <- sequence ts
foldM app (F f a) ts'
app a b = do
n <- get
put $! n+1
tell [(Con (C n), App a b), (App a b, Con (C n))]
return $ C n
go :: Rule.Rule (f, Int) v -> M f ()
go rule = do
l <- term (Rule.lhs rule)
r <- term (Rule.rhs rule)
tell [(Con l, Con r)]
-- -->* closure.
ffc :: Ord f => [(Side f, Side f)] -> R.Rel (Side f)
ffc trs =
let sides = S.fromList $ trs >>= \(l, r) -> subterms l ++ subterms r
subterms (Con c) = [Con c]
subterms (App l r) = [App l r, Con l, Con r]
add rel (l, r) | (l, r) `R.member` rel = rel
add rel (l, r) =
let rel' = R.insert (l, r) rel
todo = S.map (\x -> (l, x)) (R.succ rel r) `S.union`
S.map (\x -> (x, r)) (R.pred rel l) `S.union`
S.fromList congr
Con fl = l
Con fr = r
congr = [(l', r') |
isCon l && isCon r,
(l', r') <- left ++ right,
l' `S.member` sides && r' `S.member` sides]
left = [(App fl gl, App fr gr) |
(Con gl, Con gr) <- R.toList $ R.restrict isCon rel']
right = [(App gl fl, App gr fr) |
(Con gl, Con gr) <- R.toList $ R.restrict isCon rel']
in foldl add rel' (S.toList todo)
in foldl add (R.fromList [(a, a) | a <- S.toList sides]) trs
-- joinability closure
joinc :: (Ord f, PPretty f) => R.Rel (Side f) -> R.Rel (Side f)
joinc trs =
let sides = S.fromList [x | (l, r) <- R.toList trs, x <- [l, r]]
add rel (l, r) | (l, r) `R.member` rel = rel
add rel (l, r) =
let rel' = R.insert (l, r) rel
todo = S.map (\x -> (l, x)) (R.pred trs r) `S.union`
S.map (\x -> (x, r)) (R.pred trs l) `S.union`
S.fromList congr
Con fl = l
Con fr = r
congr = [(l', r') |
isCon l && isCon r,
(l', r') <- left ++ right,
l' `S.member` sides && r' `S.member` sides]
left = [(App fl gl, App fr gr) |
(Con gl, Con gr) <- R.toList $ R.restrict isCon rel']
right = [(App gl fl, App gr fr) |
(Con gl, Con gr) <- R.toList $ R.restrict isCon rel']
in -- (\res -> traceShow (ppretty (l, r) <$> vList (S.toList todo)) res) $
foldl add rel' (S.toList todo)
in -- (\res -> traceShow ("joinc" <$> vList (S.toList sides)) res) $
foldl add R.empty [(a, a) | a <- S.toList sides]
-- (top-)stabilizable terms
stabilizable :: Ord f => R.Rel (Side f) -> S.Set (Side f)
stabilizable trs =
let sides = S.fromList [x | (l, r) <- R.toList trs, x <- [l, r]]
rcons = R.restrict isCon trs
stable = S.fromList
[x | x <- S.toList sides, all isApp (S.toList $ R.succ trs x)]
stabilizable0 = S.fromList
[App l' r' |
App l r <- S.toList stable,
Con l' <- S.toList $ R.pred trs (Con l),
Con r' <- S.toList $ R.pred trs (Con r),
App l' r' `S.member` sides]
add new old | S.null new = old
add new old =
let next = old `S.union` S.fromList
[App l r |
App l r <- S.toList sides,
not $ S.null $ S.intersection old $
R.succ trs (Con l) `S.union` R.succ trs (Con r)]
in add (next `S.difference` old) next
in add stabilizable0 S.empty
-- top rewrite steps
topsteps :: Ord f =>
R.Rel (Side f) -> S.Set (Side f) -> Side f -> ([Tops f], [Tops f], [Tops f])
topsteps trs stabilizables s =
let step2 (Con f) = [Con' f]
step2 (App l r) = liftM2 App'
(S.toList $ R.succ trs (Con l))
(S.toList $ R.succ trs (Con r))
tops = S.toList $ S.fromList $ S.toList (R.succ trs s) >>= step2
left = [App' l r | App' l r <- tops, l `S.member` stabilizables]
right = [App' l r | App' l r <- tops, r `S.member` stabilizables]
in (tops, left, right)
joinable :: (Ord f, PPretty f) =>
R.Rel (Side f) -> R.Rel (Side f) -> Tops f -> Tops f -> Bool
joinable trs joins s t =
-- (\res -> traceShow ("joinable" <+> ppretty s <+> ppretty t <+> text (show res) <$> ppretty s' <$> ppretty t' <$> ppretty s'' <$> ppretty t'') res) $
any (`R.member` joins) (liftM2 (,) s' t') ||
any (\((sl, sr), (tl, tr)) -> (sl, tl) `R.member` joins &&
(sr, tr) `R.member` joins) (liftM2 (,) s'' t'')
where
succ' = S.toList . R.succ trs
s' = case s of
Con' c -> [Con c]
App' l r -> [App l' r' | Con l' <- succ' l, Con r' <- succ' r]
t' = case t of
Con' c -> [Con c]
App' l r -> [App l' r' | Con l' <- succ' l, Con r' <- succ' r]
s'' = case s of
Con' c -> [(Con l', Con r') | App l' r' <- succ' (Con c)]
App' l r -> [(l, r)] ++ [(Con l', Con r') | App l' r' <- s' >>= succ']
t'' = case t of
Con' c -> [(Con l', Con r') | App l' r' <- succ' (Con c)]
App' l r -> [(l, r)] ++ [(Con l', Con r') | App l' r' <- t' >>= succ']
reachable :: Ord f => R.Rel (Side f) -> Tops f -> Tops f -> Bool
reachable trs s t =
any (`R.member` trs) (liftM2 (,) s' t') ||
any (\((sl, sr), (tl, tr)) -> (sl, tl) `R.member` trs &&
(sr, tr) `R.member` trs) (liftM2 (,) s'' t'')
where
succ' = S.toList . R.succ trs
pred' = S.toList . R.pred trs
s' = case s of
Con' c -> [Con c]
App' l r -> [App l' r' | Con l' <- succ' l, Con r' <- succ' r]
t' = case t of
Con' c -> [Con c]
App' l r -> [App l' r' | Con l' <- pred' l, Con r' <- pred' r]
s'' = case s of
Con' c -> [(Con l', Con r') | App l' r' <- succ' (Con c)]
App' l r -> [(l, r)]
t'' = case t of
Con' c -> [(Con l', Con r') | App l' r' <- pred' (Con c)]
App' l r -> [(l, r)]
-- Definition 18
cconds :: (Ord f, PPretty f) =>
R.Rel (Side f) -> R.Rel (Side f) -> S.Set (Side f) -> Side f -> Bool
cconds trs joins stabilizables s =
let (tops, left, right) = topsteps trs stabilizables s
leftp = (`S.member` S.fromList left)
rightp = (`S.member` S.fromList right)
succ' = S.toList . R.succ trs
in -- 1. term in Topsteps(s) are pairwise joinable
all (uncurry $ joinable trs joins)
[(a, b) | a : bs <- tails tops, b <- bs] &&
-- 2. l1 @ r1, l2 @ r2 in Left(s) (Right(s)) -> l1, l2 (r1, r2) joinable
all (`R.member` joins)
[(a, b) | (App' _ a):bs <- tails left, (App' _ b) <- bs] &&
all (`R.member` joins)
[(a, b) | (App' a _):bs <- tails left, (App' b _) <- bs] &&
-- 3. Left(Right) /= {} ==> for all Tops, exists reachable Lef(Right)
(null left ||
and [or [reachable trs t t' | t' <- left] | t <- tops]) &&
(null right ||
and [or [reachable trs t t' | t' <- right] | t <- tops]) &&
-- 4.
(null left ||
and [or [leftp (App' l' r) | l' <- succ' l] | App' l r <- right]) &&
(null right ||
and [or [rightp (App' l r') | r' <- succ' r] | App' l r <- left])
-- Definition 24
djconds :: (Ord f, PPretty f) => R.Rel (Side f) -> R.Rel (Side f) ->
S.Set (Side f) -> Side f -> Side f -> Bool
djconds trs joins stabilizables s t =
let (topss, lefts, rights) = topsteps trs stabilizables s
(topst, leftt, rightt) = topsteps trs stabilizables t
in -- 1. Topsteps(s) and Topsteps(t) are joinable
all (uncurry $ joinable trs joins) [(a, b) | a <- topss, b <- topst] &&
-- 2.
(null lefts == null leftt) && (null rights == null rightt) &&
-- 3.
all (`R.member` joins)
[(a, b) | (App' _ a) <- lefts, (App' _ b) <- leftt] &&
-- 4.
all (`R.member` joins)
[(a, b) | (App' a _) <- rights, (App' b _) <- rightt]
-- "not deeply joinable"
ndj :: (Ord f, PPretty f) =>
R.Rel (Side f) -> R.Rel (Side f) -> S.Set (Side f) -> R.Rel (Side f)
ndj trs joins stabilizables =
let sides = S.toList $ S.fromList [x | (l, r) <- R.toList trs, x <- [l, r]]
ndj0 = R.fromList [(s, s') | l@(s:_) <- tails sides, s' <- l,
not $ djconds trs joins stabilizables s s']
add new old | R.null new = old
add new old =
let next = old `R.union` new
next' = R.fromList [
(s, t) | s <- sides, t <- sides,
let (_, lefts, rights) = topsteps trs stabilizables s,
let (_, leftt, rightt) = topsteps trs stabilizables t,
any (`R.member` next)
[(l, l') | App' l _ <- lefts, App' l' _ <- leftt] ||
any (`R.member` next)
[(r, r') | App' _ r <- rights, App' _ r' <- rightt]]
in add (next' `R.difference` next) next'
in add ndj0 R.empty
instance PPretty f => PPretty (Con f) where
ppretty (F f a) = ppretty f <> "/" <> text (show a)
ppretty (C i) = "c_" <> text (show i)
instance PPretty f => PPretty (Side f) where
ppretty (Con f) = ppretty f
ppretty (App f g) = "(" <> ppretty f <+> "@" <+> ppretty g <> ")"
instance PPretty f => PPretty (Tops f) where
ppretty (Con' f) = ppretty f
ppretty (App' f g) = "(" <> ppretty f <+> "@" <+> ppretty g <> ")"
| haskell-rewriting/confluence-tool | src/Confluence/Direct/Ground.hs | mit | 12,522 | 0 | 21 | 4,307 | 5,710 | 2,929 | 2,781 | 250 | 5 |
{-# LANGUAGE NoImplicitPrelude #-}
module Rx.Observable.Scheduler where
import Prelude.Compat
import Rx.Disposable (newBooleanDisposable, setDisposable, toDisposable)
import Rx.Scheduler (Scheduler, schedule)
import Rx.Observable.Types
scheduleOn
:: Scheduler s
-> Observable s0 a
-> Observable s a
scheduleOn scheduler source = Observable $ \observer -> do
currentDisp <- newBooleanDisposable
subDisp <- subscribe source
(\v -> do
disp <- schedule scheduler (onNext observer v)
setDisposable currentDisp disp)
(onError observer)
(onCompleted observer)
return $ toDisposable currentDisp `mappend`
subDisp
| roman/Haskell-Reactive-Extensions | rx-core/src/Rx/Observable/Scheduler.hs | mit | 715 | 0 | 18 | 181 | 180 | 94 | 86 | 20 | 1 |
{-# LANGUAGE ExistentialQuantification, DeriveDataTypeable
, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, CPP #-}
module Transient.MapReduce
(
Distributable(..),distribute, getText,
getUrl, getFile,textUrl, textFile,
mapKeyB, mapKeyU, reduce,eval,
PartRef)
where
#ifdef ghcjs_HOST_OS
import Transient.Base
import Transient.Move hiding (pack)
import Transient.Logged
-- dummy Transient.MapReduce module,
reduce _ _ = local stop :: Loggable a => Cloud a
mapKeyB _ _= undefined
mapKeyU _ _= undefined
distribute _ = undefined
getText _ _ = undefined
textFile _ = undefined
getUrl _ _ = undefined
textUrl _ = undefined
getFile _ _ = undefined
eval _= local stop
data DDS= DDS
class Distributable
data PartRef a=PartRef a
#else
import Transient.Base
import Transient.Internals((!>))
import Transient.Move hiding (pack)
import Transient.Logged
import Transient.Indeterminism
import Control.Applicative
import System.Random
import Control.Monad.IO.Class
import System.IO
import Control.Monad
import Data.Monoid
import Data.Maybe
import Data.Typeable
import Data.List hiding (delete, foldl')
import Control.Exception
import Control.Concurrent
--import Data.Time.Clock
import Network.HTTP
import Data.TCache
import Data.TCache.Defs
import Data.ByteString.Lazy.Char8 (pack,unpack)
import Control.Monad.STM
import qualified Data.Map.Strict as M
import Control.Arrow (second)
import qualified Data.Vector.Unboxed as DVU
import qualified Data.Vector as DV
import Data.Hashable
import System.IO.Unsafe
import qualified Data.Foldable as F
import qualified Data.Text as Text
data DDS a= Loggable a => DDS (Cloud (PartRef a))
data PartRef a= Ref Node Path Save deriving (Typeable, Read, Show)
data Partition a= Part Node Path Save a deriving (Typeable,Read,Show)
type Save= Bool
instance Indexable (Partition a) where
key (Part _ string b _)= keyp string b
keyp s True= "PartP@"++s :: String
keyp s False="PartT@"++s
instance Loggable a => IResource (Partition a) where
keyResource= key
readResourceByKey k= r
where
typePart :: IO (Maybe a) -> a
typePart = undefined
r = if k !! 4 /= 'P' then return Nothing else
defaultReadByKey (defPath (typePart r) ++ k) >>= return . fmap ( read . unpack)
writeResource (s@(Part _ _ save _))=
unless (not save) $ defaultWrite (defPath s ++ key s) (pack $ show s)
eval :: DDS a -> Cloud (PartRef a)
eval (DDS mx) = mx
type Path=String
instance F.Foldable DVU.Vector where
{-# INLINE foldr #-}
foldr = foldr
{-# INLINE foldl #-}
foldl = foldl
{-# INLINE foldr1 #-}
foldr1 = foldr1
{-# INLINE foldl1 #-}
foldl1 = foldl1
--foldlIt' :: V.Unbox a => (b -> a -> b) -> b -> V.Vector a -> b
--foldlIt' f z0 xs= V.foldr f' id xs z0
-- where f' x k z = k $! f z x
--
--foldlIt1 :: V.Unbox a => (a -> a -> a) -> V.Vector a -> a
--foldlIt1 f xs = fromMaybe (error "foldl1: empty structure")
-- (V.foldl mf Nothing xs)
-- where
-- mf m y = Just (case m of
-- Nothing -> y
-- Just x -> f x y)
class (F.Foldable c, Typeable c, Typeable a, Monoid (c a), Loggable (c a)) => Distributable c a where
singleton :: a -> c a
splitAt :: Int -> c a -> (c a, c a)
fromList :: [a] -> c a
instance (Loggable a) => Distributable DV.Vector a where
singleton = DV.singleton
splitAt= DV.splitAt
fromList = DV.fromList
instance (Loggable a,DVU.Unbox a) => Distributable DVU.Vector a where
singleton= DVU.singleton
splitAt= DVU.splitAt
fromList= DVU.fromList
-- | perform a map and partition the result with different keys using boxed vectors
-- The final result will be used by reduce.
mapKeyB :: (Loggable a, Loggable b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DV.Vector a)
-> DDS (M.Map k(DV.Vector b))
mapKeyB= mapKey
-- | perform a map and partition the result with different keys using unboxed vectors
-- The final result will be used by reduce.
mapKeyU :: (Loggable a, DVU.Unbox a, Loggable b, DVU.Unbox b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DVU.Vector a)
-> DDS (M.Map k(DVU.Vector b))
mapKeyU= mapKey
-- | perform a map and partition the result with different keys.
-- The final result will be used by reduce.
mapKey :: (Distributable vector a,Distributable vector b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (vector a)
-> DDS (M.Map k (vector b))
mapKey f (DDS mx)= DDS $ loggedc $ do
refs <- mx
process refs
where
-- process :: Partition a -> Cloud [Partition b]
process (ref@(Ref node path sav))= runAt node $ local $ do
xs <- getPartitionData ref -- !> ("CMAP", ref,node)
(generateRef $ map1 f xs)
-- map1 :: (Ord k, F.Foldable vector) => (a -> (k,b)) -> vector a -> M.Map k(vector b)
map1 f v= F.foldl' f1 M.empty v
where
f1 map x=
let (k,r) = f x
in M.insertWith (<>) k (Transient.MapReduce.singleton r) map
--instance Show a => Show (MVar a) where
-- show mvx= "MVar " ++ show (unsafePerformIO $ readMVar mvx)
--
--instance Read a => Read (MVar a) where
-- readsPrec n ('M':'V':'a':'r':' ':s)=
-- let [(x,s')]= readsPrec n s
-- in [(unsafePerformIO $ newMVar x,s')]
data ReduceChunk a= EndReduce | Reduce a deriving (Typeable, Read, Show)
reduce :: (Hashable k,Ord k, Distributable vector a, Loggable k,Loggable a)
=> (a -> a -> a) -> DDS (M.Map k (vector a)) ->Cloud (M.Map k a)
reduce red (dds@(DDS mx))= loggedc $ do
box <- lliftIO $ return . Text.pack =<< replicateM 10 (randomRIO ('a','z'))
nodes <- local getNodes
let lengthNodes = length nodes
shuffler nodes = do
ref@(Ref node path sav) <- mx
-- return () !> ref
runAt node $ foldAndSend nodes ref
stop
-- groupByDestiny :: (Hashable k, Distributable vector a) => M.Map k (vector a) -> M.Map Int [(k ,vector a)]
groupByDestiny map = M.foldlWithKey' f M.empty map
where
-- f :: M.Map Int [(k ,vector a)] -> k -> vector a -> M.Map Int [(k ,vector a)]
f map k vs= M.insertWith (<>) (hash1 k) [(k,vs)] map
hash1 k= abs $ hash k `rem` length nodes
-- foldAndSend :: (Hashable k, Distributable vector a)=> (Int,[(k,vector a)]) -> Cloud ()
foldAndSend nodes ref= do
pairs <- onAll $ getPartitionData1 ref
<|> return (error $ "DDS computed out of his node:"++ show ref)
let mpairs = groupByDestiny pairs
length <- local . return $ M.size mpairs
nsent <- onAll $ liftIO $ newMVar 0
(i,folded) <- local $ parallelize foldthem (M.assocs mpairs)
n <- lliftIO $ modifyMVar nsent $ \r -> return (r+1, r+1)
runAt (nodes !! i) $ local $ putMailbox box $ Reduce folded
when (n == length) $ sendEnd nodes
where
count n proc proc2= do
nsent <- onAll $ liftIO $ newMVar 0
proc
n' <- lliftIO $ modifyMVar nsent $ \r -> return (r+1, r+1)
when (n'==n) proc2
foldthem (i,kvs)= async . return
$ (i,map (\(k,vs) -> (k,foldl1 red vs)) kvs)
sendEnd nodes = onNodes nodes . local $ putMailbox box (EndReduce `asTypeOf` paramOf dds)
-- !> ("send ENDREDUCE",mynode)
onNodes nodes f= foldr (<|>) empty $ map (\n -> runAt n f) nodes
sumNodes nodes f= foldr (<>) mempty $ map (\n -> runAt n f) nodes
reducer nodes= sumNodes nodes reduce1 -- a reduce1 process in each node, get the results and mappend them
-- reduce :: (Ord k) => Cloud (M.Map k v)
reduce1 = local $ do
reduceResults <- liftIO $ newMVar M.empty
numberSent <- liftIO $ newMVar 0
minput <- getMailbox box -- get the chunk once it arrives to the mailbox
case minput of
EndReduce -> do
n <- liftIO $ modifyMVar numberSent $ \r -> return (r+1, r+1)
if n == lengthNodes -- !> ("END REDUCE RECEIVED",n, lengthNodes,mynode)
then do
cleanMailbox box (EndReduce `asTypeOf` paramOf dds)
r <- liftIO $ readMVar reduceResults
return r -- !> ("reduceresult",r)
else stop
Reduce kvs -> do
let addIt (k,inp) = do
let input= inp `asTypeOf` atype dds
liftIO $ modifyMVar_ reduceResults
$ \map -> do
let maccum = M.lookup k map
return $ M.insert k (case maccum of
Just accum -> red input accum
Nothing -> input) map
mapM addIt (kvs `asTypeOf` paramOf' dds) -- !> ("Received Reduce",kvs)
stop
reducer nodes <|> shuffler nodes
where
atype ::DDS(M.Map k (vector a)) -> a
atype = undefined -- type level
paramOf :: DDS (M.Map k (vector a)) -> ReduceChunk [( k, a)]
paramOf = undefined -- type level
paramOf' :: DDS (M.Map k (vector a)) -> [( k, a)]
paramOf' = undefined -- type level
--parallelize :: Loggable b => (a -> Cloud b) -> [a] -> Cloud b
parallelize f xs = foldr (<|>) empty $ map f xs
mparallelize f xs = loggedc $ foldr (<>) mempty $ map f xs
getPartitionData :: Loggable a => PartRef a -> TransIO a
getPartitionData (Ref node path save) = Transient $ do
mp <- (liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return $ Just xs
getPartitionData1 :: Loggable a => PartRef a -> TransIO a
getPartitionData1 (Ref node path save) = Transient $ do
mp <- liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save
case mp of
Just (Part _ _ _ xs) -> return $ Just xs
Nothing -> return Nothing
getPartitionData2 :: Loggable a => PartRef a -> IO a
getPartitionData2 (Ref node path save) = do
mp <- ( atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return xs
-- en caso de fallo de Node, se lanza un clustered en busca del path
-- si solo uno lo tiene, se copia a otro
-- se pone ese nodo de referencia en Part
runAtP :: Loggable a => Node -> (Path -> IO a) -> Path -> Cloud a
runAtP node f uuid= do
r <- streamFrom node $ onAll . liftIO $ (SLast <$> f uuid) `catch` sendAnyError
case r of
SLast r -> return r
SError e -> do
nodes <- mclustered $ search uuid
when(length nodes < 1) $ asyncDuplicate node uuid
runAtP ( head nodes) f uuid
search uuid= error $ "chunk failover not yet defined. Lookin for: "++ uuid
asyncDuplicate node uuid= do
forkTo node
nodes <- onAll getNodes
let node'= head $ nodes \\ [node]
content <- onAll . liftIO $ readFile uuid
runAt node' $ local $ liftIO $ writeFile uuid content
sendAnyError :: SomeException -> IO (StreamData a)
sendAnyError e= return $ SError e
-- | distribute a vector of values among many nodes.
-- If the vector is static and sharable, better use the get* primitives
-- since each node will load the data independently.
distribute :: (Loggable a, Distributable vector a ) => vector a -> DDS (vector a)
distribute = DDS . distribute'
distribute' xs= loggedc $ do
nodes <- local getNodes -- !> "DISTRIBUTE"
let lnodes = length nodes
let size= case F.length xs `div` (length nodes) of 0 ->1 ; n -> n
xss= split size lnodes 1 xs -- !> size
r <- distribute'' xss nodes
return r
where
split n s s' xs | s==s' = [xs]
split n s s' xs=
let (h,t)= Transient.MapReduce.splitAt n xs
in h : split n s (s'+1) t
distribute'' :: (Loggable a, Distributable vector a)
=> [vector a] -> [Node] -> Cloud (PartRef (vector a))
distribute'' xss nodes =
parallelize move $ zip nodes xss -- !> show xss
where
move (node, xs)= runAt node $ local $ do
par <- generateRef xs
return par
-- !> ("move", node,xs)
-- | input data from a text that must be static and shared by all the nodes.
-- The function parameter partition the text in words
getText :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getText part str= DDS $ loggedc $ do
nodes' <- local getNodes -- !> "DISTRIBUTE"
let nodes = filter (not . isWebNode) nodes'
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1]
where
isWebNode node= "webnode" `elem` (map fst $ nodeServices node)
process lnodes (node,i)= do
runAt node $ local $ do
let xs = part str
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
-- | get the worlds of an URL
textUrl :: String -> DDS (DV.Vector Text.Text)
textUrl= getUrl (map Text.pack . words)
-- | generate a DDS from the content of a URL.
-- The first parameter is a function that divide the text in words
getUrl :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getUrl partitioner url= DDS $ do
nodes <- local getNodes -- !> "DISTRIBUTE"
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss
where
process lnodes (node,i)= runAt node $ local $ do
r <- liftIO . simpleHTTP $ getRequest url
body <- liftIO $ getResponseBody r
let xs = partitioner body
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $ take size $ drop (i * size) xs
generateRef xss
-- | get the words of a file
textFile :: String -> DDS (DV.Vector Text.Text)
textFile= getFile (map Text.pack . words)
-- | generate a DDS from a file. All the nodes must access the file with the same path
-- the first parameter is the parser that generates elements from the content
getFile :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getFile partitioner file= DDS $ do
nodes <- local getNodes -- !> "DISTRIBUTE"
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss
where
process lnodes (node, i)= runAt node $ local $ do
content <- liftIO $ readFile file
let xs = partitioner content
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss=Transient.MapReduce.fromList $ take size $ drop (i * size) xs -- !> size
generateRef xss
generateRef :: Loggable a => a -> TransIO (PartRef a)
generateRef x= do
node <- getMyNode
liftIO $ do
temp <- getTempName
let reg= Part node temp False x
atomically $ newDBRef reg
-- syncCache
(return $ getRef reg) -- !> ("generateRef",reg,node)
getRef (Part n t s x)= Ref n t s
getTempName :: IO String
getTempName= ("DDS" ++) <$> replicateM 5 (randomRIO ('a','z'))
-------------- Distributed Datasource Streams ---------
-- | produce a stream of DDS's that can be map-reduced. Similar to spark streams.
-- each interval of time,a new DDS is produced.(to be tested)
streamDDS
:: (Loggable a, Distributable vector a) =>
Integer -> IO (StreamData a) -> DDS (vector a)
streamDDS time io= DDS $ do
xs <- local . groupByTime time $ do
r <- parallel io
case r of
SDone -> empty
SLast x -> return x
SMore x -> return x
SError e -> error $ show e
distribute' $ Transient.MapReduce.fromList xs
#endif
| geraldus/transient-universe | src/Transient/MapReduce.hs | mit | 16,955 | 0 | 6 | 5,459 | 207 | 116 | 91 | -1 | -1 |
module Language.TaPL.TypedArith.Types (typeOf, Ty) where
import Language.TaPL.TypedArith.Syntax (Term(..))
data Ty = TyBool
| TyNat
deriving (Show, Read, Eq)
typeOf :: Term -> Maybe Ty
typeOf TmZero = Just TyNat
typeOf (TmSucc t) | typeOf t == Just TyNat = Just TyNat
typeOf (TmPred t) | typeOf t == Just TyNat = Just TyNat
typeOf (TmIsZero t) | typeOf t == Just TyNat = Just TyBool
typeOf TmTrue = Just TyBool
typeOf TmFalse = Just TyBool
typeOf (TmIf t1 t2 t3) | typeOf t1 == Just TyBool && typeOf t2 == typeOf t3 = typeOf t2
typeOf _ = Nothing
| zeckalpha/TaPL | src/Language/TaPL/TypedArith/Types.hs | mit | 577 | 0 | 11 | 129 | 260 | 125 | 135 | 14 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
module Development.CSSCSS.RedundancyCalcTest (tests) where
import TestHelper
import Test.HUnit
import Development.CSSCSS.Rulesets
import Development.CSSCSS.RedundancyCalc
main = $(defaultMainGenerator)
tests = $(testGroupGenerator)
case_findMatches = do
findMatches [
".foo"@/["display"@:"none", "position"@:"relative"],
".bar"@/["position"@:"relative", "display"@:"none"],
".baz"@/["position"@:"relative"]
]
@?= [
([".bar", ".foo"], ["position"@:"relative", "display"@:"none"]),
([".bar", ".baz", ".foo"], ["position"@:"relative"])
]
case_returnEmptyLists = do
findMatches [
".foo"@/["display"@:"none", "position"@:"relative"],
".bar"@/["display"@:"block"],
".baz"@/["position"@:"absolute"]
] @?= []
| zmoazeni/csscss-haskell | test/Development/CSSCSS/RedundancyCalcTest.hs | mit | 823 | 0 | 12 | 114 | 243 | 142 | 101 | 23 | 1 |
{-# LANGUAGE DataKinds #-}
-- |
-- Interpreters tests
--
-- Checks you /can/ combine interpreters nicely
module Interpreters where
import Control.Biegunka
import qualified Data.Monoid as M
import qualified Data.Semigroup as S
interpreter_0 :: Interpreter
interpreter_0 = confirm M.<> run
interpreter_1 :: Interpreter
interpreter_1 = confirm S.<> run
| biegunka/biegunka | test/typecheck/should_compile/OK9.hs | mit | 364 | 0 | 5 | 62 | 62 | 41 | 21 | 9 | 1 |
{-# language FlexibleInstances #-}
{-# language MultiParamTypeClasses #-}
{-# language ScopedTypeVariables #-}
module Polynomial.Test where
import qualified Prelude
import Prelude hiding ( Num (..), Integer, null, negate, fromInteger)
import Polynomial.Class
import Polynomial.Common
import Polynomial.ToDoc
import Control.Applicative
import Autolib.ToDoc
import Autolib.Reader
import Autolib.TES.Identifier
import Test.Hspec
import Test.Hspec.SmallCheck
import Test.SmallCheck.Series
test d = spec d
$ ring_spec (undefined :: Poly Integer Identifier)
leading_spec (_ :: Poly r v) = describe "leading" $ do
it "valid" $ property $ \ p ->
case splitLeading (p :: Poly r v) of
Nothing -> null p
Just ((c,m), q) -> valid q
it "sum" $ property $ \ p ->
case splitLeading (p :: Poly r v) of
Nothing -> null p
Just ((c,m), q) -> monomial m c + q == p
valid_spec (_ :: Poly r v) = describe "valid" $ do
it "poly" $ property $ \ p -> valid (p :: Poly r v)
it "terms/poly" $ property $ \ p ->
(p :: Poly r v) == poly (terms p)
it "fromInteger" $ property $ \ i -> valid (fromInteger i :: Poly r v)
it "negate" $ property $ \ p -> valid (negate p :: Poly r v)
it "plus" $ property $ \ p q -> valid (p + q :: Poly r v)
it "times" $ property $ \ p q -> valid (p * q :: Poly r v)
instance Monad m => Serial m Identifier where
series = ( \ p -> mk 0 $ "s" ++ show (p::Int) ) <$> series
instance ( Serial m v) => Serial m (Factor v) where
series = ( \ v (Positive e) -> factor v e ) <$> series <*> series
instance ( Ord v, Serial m v) => Serial m (Mono v) where
series = mono <$> series
instance (Ord v, Ring r, Serial m r, Serial m v)
=> Serial m (Poly r v) where
series = poly <$> series
| marcellussiegburg/autotool | collection/src/Polynomial/Test.hs | gpl-2.0 | 1,766 | 0 | 15 | 417 | 765 | 396 | 369 | 44 | 3 |
{- |
Module : $EmptyHeader$
Description : <optional short description entry>
Copyright : (c) <Authors or Affiliations>
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <email>
Stability : unstable | experimental | provisional | stable | frozen
Portability : portable | non-portable (<reason>)
<optional description>
-}
-- examples for probabilistic modal logic. To run these examples,
-- try both provable and sat(isfiable) from the (imported) module
-- Generic on the formulas defined here.
-- quickstart: [ghci|hugs] examples.gml.hs
-- then try ``provable phi1''
import Generic
-- pdiam q phi is the PML formula L_p phi
pdiam :: Rational -> L P -> L P; pdiam k x = box (P k) x
-- shorthands for propositional atoms
p0 :: L P; p0 = Atom 0
p1 :: L P; p1 = Atom 1
p2 :: L P; p2 = Atom 2
p3 :: L P; p3 = Atom 3
phi1 :: L P; phi1 = ((pdiam 0.5 ((pdiam 1 (p0 /\ (neg p1)) ) )) /\
(pdiam 0.5 (pdiam 1 (p3 /\ p2)))) --> ((pdiam 1 (pdiam 1 (p0 \/ p3))))
phi2 :: L P; phi2 = pdiam 0.5 (p0 \/ p3)
phi3 :: L P; phi3 = (pdiam 0.5 phi2) \/ (pdiam 0.5 (neg phi2))
phi4 :: L P; phi4 = (pdiam 0.5 p0) \/ (pdiam 0.5 (neg p0))
| nevrenato/Hets_Fork | GMP/versioning/coloss-0.0.4/examples.pml.hs | gpl-2.0 | 1,176 | 0 | 16 | 279 | 333 | 179 | 154 | 11 | 1 |
factorial a | a <=1 = 1
| otherwise = a * factorial (a-1)
main = print $ factorial_bis 4
| algebrato/Exercise | Esercizio2.hs | gpl-2.0 | 99 | 0 | 9 | 30 | 54 | 25 | 29 | 3 | 1 |
module Experimentation.P03 (p03_test) where
import Test.HUnit
import Data.Maybe
import Data.List
elementAt_rec :: Int -> [a] -> Maybe a
elementAt_rec b all@(a:as)
| b == 0 = Just a
| b > length all = Nothing
| otherwise = elementAt_rec (b - 1) as
elementAt_nat :: Int -> [a] -> Maybe a
elementAt_nat b a
| b > length a = Nothing
| otherwise = Just (a !! b)
-- Tests
test_elementAt_rec = TestCase $ do
assertEqual "for (test_elementAt_rec 9 [1..10])" (Just 10) (elementAt_rec 9 [1..10])
assertEqual "for (test_elementAt_rec 9 [0..10])" (Just 9) (elementAt_rec 9 [0..10])
test_elementAt_nat = TestCase $ do
assertEqual "for (test_elementAt_nat 9 [1..10])" (Just 10) (elementAt_nat 9 [1..10])
assertEqual "for (test_elementAt_nat 9 [0..10])" (Just 9) (elementAt_nat 9 [0..10])
p03_test = do
runTestTT p03_tests
p03_tests = TestList [
TestLabel "test_elementAt_rec" test_elementAt_rec,
TestLabel "test_elementAt_nat" test_elementAt_nat
]
| adarqui/99problems-hs | Experimentation/P03.hs | gpl-3.0 | 958 | 0 | 11 | 160 | 346 | 172 | 174 | 24 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Text as T
import NLP.Grabber
import NLP.Article.Analyze
import Database.Persist.MySQL
import NLP.Grabber.Wordlist
import NLP.Database.Article
import NLP.Types.Monad
import NLP.Types
dbCfg :: ConnectInfo
dbCfg = ConnectInfo "localhost" 3306 "nlp" "nlp" "nlp" [] "" Nothing
main :: IO ()
main =
withMySQLPool dbCfg 150 $ \pool ->
flip runNLP (NLPEnv dbCfg pool) $ do
runDB $ runMigration migrateAll
_ <- grabNews
--_ <- handleAllArticles
--h <- liftIO $ openFile "words" ReadMode
-- parseHandle h
-- _ <- forkNLP getAndInsertWords
return ()
| azapps/nlp.hs | src/NLP.hs | gpl-3.0 | 681 | 0 | 11 | 153 | 157 | 88 | 69 | 19 | 1 |
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE RecordWildCards #-}
-- ----------------------------------------------------- --
-- --| Hearth - Haskell Interpreter for Haiku Forth |--- --
-- ----------------------------------------------------- --
import qualified "GLFW-b" Graphics.UI.GLFW as GLFW
import Graphics.Rendering.OpenGL.Raw
import Control.Monad
import Control.Applicative
import Data.Maybe
import Foreign
import Foreign.C.String
import Foreign.C.Types
import Data.Time.Clock.POSIX
import System.Exit
import System.IO
import System.Environment
import Hearth
data GLIDs = GLIDs
{ progId :: !GLuint
, vertexArrayId :: !GLuint
, vertexBufferId :: !GLuint
}
main :: IO ()
main = do
-- parse arguments
args <- getArgs
code <- readArgs args
let tran = readArgsTran args
let verb = readArgsVerb args
let size = readArgsSize args
-- print usage and return if error parsing input
when (code == "") $ do {
print "Usage: HearthMain [-t] [-v] [-s size] [[filename] | [-c code]]";
exitFailure;
}
-- parse code into valid haiku forth expression
-- level the expression, so that 4 values are always returned
expr <- return $ level $ parseHaiku code
-- create GLSL code from the haiku forth expression
-- generate code w/o temporary variables, if '-t' option given
glsl <- if not tran
then return $ translateHaiku expr
else return $ translateHaiku' expr
-- print out GLSL code, if '-v' / verbosity option set
when (verb) $ do {
putStrLn glsl
}
-- get time when program first starts
time <- realToFrac <$> getPOSIXTime
-- initialize, enter main loop, then finish when application is closed
win <- initialize size
glids <- initializeGL glsl
inputLoop win glids time
freeResources glids
GLFW.terminate
return ()
-- Utility function to return Haiku Forth code, given command line arguments
readArgs :: [String] -> IO String
readArgs ("-t":xs) = readArgs xs -- skip -t translation argument
readArgs ("-v":xs) = readArgs xs -- skip -v verbosity argument
readArgs ("-s":s:xs) = readArgs xs -- skip -s size argument
readArgs [] = readFile "haiku.txt" -- read from default file, if no arguments given
readArgs [x] = readFile x -- read from given filename, if one argument given
readArgs ("-c":c:_) = return $ c -- read code directly from input, if -c option given
readArgs _ = return "" -- otherwise, return error string
-- Utility function to read -t, or translation, command line option
readArgsTran :: [String] -> Bool
readArgsTran = any ((==) "-t")
-- Utility function to read -v, or verbosity, command line option
readArgsVerb :: [String] -> Bool
readArgsVerb = any ((==) "-v")
-- Utility function to read -s, or size, command line option, default size is 256 x 256
readArgsSize :: [String] -> Int
readArgsSize [] = 256
readArgsSize ("-s":s:_) = read s :: Int
readArgsSize (x:xs) = readArgsSize xs
-- adapted from: http://funloop.org/post/2014-03-15-opengl-from-haskell.html
-- initialize window
initialize :: Int -> IO GLFW.Window
initialize size = do
ok <- GLFW.init
when (not ok) $ do
_ <- fail "Failed to initialize GLFW"
exitFailure
mapM_ GLFW.windowHint
[ GLFW.WindowHint'Samples 4 -- 4x antialiasing
, GLFW.WindowHint'ContextVersionMajor 3 -- OpenGL 3.3
, GLFW.WindowHint'ContextVersionMinor 3
-- we don't want the old OpenGL
, GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
]
win <- GLFW.createWindow size size "Hearth" Nothing Nothing
when (isNothing win) $ do
_ <- fail "Failed to create OpenGL window"
GLFW.terminate
exitFailure
let win' = fromJust win
GLFW.makeContextCurrent win
GLFW.setStickyKeysInputMode win' GLFW.StickyKeysInputMode'Enabled
return win'
-- setup OpenGL objects, shaders
initializeGL :: String -> IO GLIDs
initializeGL glsl = do
-- specify RGBA bitmask used to clear color buffers
glClearColor 0 0 0 0
progId <- loadProgram vertexShader' glsl
vaId <- newVAO
bufId <- fillNewBuffer vertexBufferData
return $ GLIDs
{ progId = progId
, vertexArrayId = vaId
, vertexBufferId = bufId
}
-- free all buffer and array objects
freeResources :: GLIDs -> IO ()
freeResources GLIDs{..} = do
with vertexBufferId $ glDeleteBuffers 1
with vertexArrayId $ glDeleteVertexArrays 1
-- return a new VAO object
newVAO :: IO GLuint
newVAO = do
vaId <- withNewPtr (glGenVertexArrays 1)
glBindVertexArray vaId
return vaId
-- transform a linked list of floats into a pointer to an array of ints
fillNewBuffer :: [GLfloat] -> IO GLuint
fillNewBuffer xs = do
bufId <- withNewPtr (glGenBuffers 1)
glBindBuffer gl_ARRAY_BUFFER bufId
withArrayLen xs func -- give given vertices to OpenGL
return bufId
where
func len ptr = glBufferData
gl_ARRAY_BUFFER
(fromIntegral (len * sizeOf (undefined :: GLfloat)))
(ptr :: Ptr GLfloat)
gl_STATIC_DRAW
-- given a buffer ID, and pointer to a buffer location, bind them
bindBufferToAttrib :: GLuint -> GLuint -> IO ()
bindBufferToAttrib bufId attribLoc = do
glEnableVertexAttribArray attribLoc
glBindBuffer gl_ARRAY_BUFFER bufId
glVertexAttribPointer
attribLoc -- attribute location in the shader
3 -- 3 components per vertex
gl_FLOAT -- coord type
(fromBool False) -- normalize?
0 -- stride
nullPtr -- vertex buffer offset
-- load a new program, with the given shaders
loadProgram :: String -> String -> IO GLuint
loadProgram vertShader fragShader = do
shaderIds <- mapM (uncurry loadShader)
[ (gl_VERTEX_SHADER, vertShader)
, (gl_FRAGMENT_SHADER, fragShader)
]
progId <- glCreateProgram
putStrLn "Linking program"
mapM_ (glAttachShader progId) shaderIds
glLinkProgram progId
_ <- checkStatus
gl_LINK_STATUS glGetProgramiv glGetProgramInfoLog progId
mapM_ glDeleteShader shaderIds
return progId
-- load and compile the shader source code string
loadShader :: GLenum -> String -> IO GLuint
loadShader shaderTypeFlag code = do
shaderId <- glCreateShader shaderTypeFlag
withCString code $ \codePtr ->
with codePtr $ \codePtrPtr ->
glShaderSource shaderId 1 codePtrPtr nullPtr
putStrLn "Compiling shader..."
glCompileShader shaderId
_ <- checkStatus
gl_COMPILE_STATUS glGetShaderiv glGetShaderInfoLog shaderId
return shaderId
-- check current status
checkStatus :: (Integral a1, Storable a1)
=> GLenum
-> (t -> GLenum -> Ptr a1 -> IO a)
-> (t -> a1 -> Ptr a3 -> Ptr Foreign.C.Types.CChar -> IO a2)
-> t
-> IO Bool
checkStatus statusFlag glGetFn glInfoLogFn componentId = do
let
fetch info = withNewPtr (glGetFn componentId info)
status <- liftM toBool $ fetch statusFlag
logLength <- fetch gl_INFO_LOG_LENGTH
when (logLength > 0) $
allocaArray0 (fromIntegral logLength) $ \msgPtr -> do
_ <- glInfoLogFn componentId logLength nullPtr msgPtr
msg <- peekCString msgPtr
(if status then putStrLn else fail) msg
return status
fragmentShader' :: String
fragmentShader' = unlines
[ "#version 330 core"
, "varying vec2 tpos;"
, "uniform float time_val;"
, "float PI = 3.1415926535897931;"
, "out vec3 color;"
, "void main()"
, "{"
, "color = vec3(sin((tpos.x * 10.0) + time_val) * 0.1, 0.0, " ++
"1 - sqrt (abs(cos(tpos.x * 10.0) * cos(time_val) * 0.1 - tpos.y + 0.5)));"
, "}"
]
vertexShader' :: String
vertexShader' = unlines
[ "#version 330 core"
, "layout(location = 0) in vec3 vPosition_modelspace;"
, "varying highp vec2 tpos;"
, "void main()"
, "{"
, "tpos.x = ((vPosition_modelspace.x) + 1.0) / 2.0;"
, "tpos.y = ((vPosition_modelspace.y) + 1.0) / 2.0;"
, "gl_Position.xyz = vPosition_modelspace;"
, "gl_Position.w = 1.0;"
, "}"
]
vertexBufferData :: [GLfloat]
vertexBufferData =
-- x, y, z
[ -1, -1, 0
, -1, 1, 0
, 1, -1, 0
, 1, -1, 0
, -1, 1, 0
, 1, 1, 0
]
inputLoop :: GLFW.Window -> GLIDs -> Double -> IO ()
inputLoop win glids time = do
drawStuff glids time
GLFW.swapBuffers win
GLFW.pollEvents
keyState <- GLFW.getKey win GLFW.Key'Escape
closeWindow <- GLFW.windowShouldClose win
when (keyState /= GLFW.KeyState'Pressed && closeWindow == False) $
inputLoop win glids time
drawStuff :: GLIDs -> Double -> IO ()
drawStuff GLIDs{..} time = do
glClear gl_COLOR_BUFFER_BIT
glClear gl_DEPTH_BUFFER_BIT
glUseProgram progId
bindBufferToAttrib vertexBufferId 0
glDrawArrays gl_TRIANGLES 0 6 -- for attrib array 0, draw 6 vertices
glDisableVertexAttribArray 0 -- disable attrib array 0
-- from: http://stackoverflow.com/questions/11726563/how-can-i-convert-a-haskell-string-into-a-ptr-ptr-glchar
uniformLoc <- withCString "time_val" $ \c_string -> glGetUniformLocation progId $ castPtr c_string
Just time' <- GLFW.getTime -- getPOSIXTime
glUniform1f uniformLoc $ (realToFrac (time'))
withNewPtr :: Storable b => (Ptr b -> IO a) -> IO b
withNewPtr f = alloca (\p -> f p >> peek p)
| vcte/CS241_Hearth | HearthMain.hs | gpl-3.0 | 9,398 | 141 | 15 | 2,250 | 2,288 | 1,141 | 1,147 | 220 | 2 |
fmap :: (a -> b) -> (Maybe a -> Maybe b) | hmemcpy/milewski-ctfp-pdf | src/content/1.7/code/haskell/snippet04.hs | gpl-3.0 | 40 | 0 | 8 | 10 | 30 | 15 | 15 | 1 | 0 |
import Data.List (sort)
test = [[2],[3,4],[6,5,7],[4,1,8,3]]
nextRow :: [Integer] -> [Integer] -> [Integer]
nextRow a [] = a
nextRow a b = [(x + y) | x <- a, y <- b]
minimumTotal :: [[Integer]] -> Integer
minimumTotal [] = 0
minimumTotal (x:xs) = (head.sort)$ foldl nextRow x xs
| ccqpein/Arithmetic-Exercises | Triangle/Triangle.hs | apache-2.0 | 297 | 0 | 7 | 67 | 184 | 105 | 79 | 8 | 1 |
permutations' :: (Enum a, Num a) => a -> a -> a
permutations' a b = let aa = a-b+1 in
(fromRational (product [aa..a]))/ (fromRational (product [1..b]))
climbS :: (Fractional a, Enum a, Num a, Integral a) => a -> a
climbS nn = sum [(permutations' n (n + y))| n <- [1..(div nn 2)], let y = (nn - n * 2)]
| ccqpein/Arithmetic-Exercises | Climbing-Stairs/CS.hs | apache-2.0 | 305 | 0 | 13 | 66 | 203 | 105 | 98 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{- | This module defines session objects that act as entry points to spark.
There are two ways to interact with Spark: using an explicit state object,
or using the default state object (interactive session).
While the interactive session is the most convenient, it should not be
used for more than quick experimentations. Any complex code should use
the SparkSession and SparkState objects.
-}
module Spark.Core.Context(
SparkSessionConf(..),
SparkSession,
SparkState,
SparkInteractiveException,
FromSQL,
defaultConf,
executeCommand1,
executeCommand1',
computationStats,
createSparkSessionDef,
closeSparkSessionDef,
currentSessionDef,
computationStatsDef,
exec1Def,
exec1Def',
execStateDef
) where
import Data.Text(pack)
import Spark.Core.Internal.BrainStructures
import Spark.Core.Internal.ContextStructures
import Spark.Core.Internal.ContextIOInternal
import Spark.Core.Internal.ContextInteractive
import Spark.Core.Internal.RowGenericsFrom(FromSQL)
-- | The default configuration if the Karps server is being run locally.
defaultConf :: SparkSessionConf
defaultConf =
SparkSessionConf {
confEndPoint = pack "http://127.0.0.1",
confPort = 8081,
confPollingIntervalMillis = 500,
confRequestedSessionName = "",
confCompiler = CompilerConf {
ccUseNodePruning = False -- Disable by default.
}
}
| tjhunter/karps | haskell/src/Spark/Core/Context.hs | apache-2.0 | 1,440 | 0 | 8 | 225 | 169 | 113 | 56 | 34 | 1 |
{-|
Module : VecMath
Description : 3D vectors, normals and points
Copyright : (c) Jonathan Merritt, 2015
License : Apache License 2.0
Maintainer : [email protected]
Stability : experimental
Vector mathematics and transformations.
-}
module VecMath (
-- * Classes
Cartesian3Tuple(
xcomp3
, ycomp3
, zcomp3
, cartesian3Tuple
, toVector3
, toNormal3
, toPoint3
)
-- * Basic 3D vector math types
, Vector3
, Normal3
, Point3
-- * Point / Vector constructor functions
, v3
, p3
, n3
-- * Rectangle (2D)
, Rectangle
, rectangle
, rectangleContains
, rectangleUnion
-- * Vector3 arithmetic
, (.*)
, (./)
-- * Vector3 operations
, lengthSquared
, vectorLength
, normalize
, dot
, cross
, (⋅)
, (⨯)
-- * Point3 operations
, offsetPoint
, offsetPointAlongVector
-- * UV coordinates
, UVCoord(UVCoord)
-- * Transformations between spaces
, XForm
, xformInv
, xformCompose
, xformId
, translate
, scale
, rotate
, Transform(xform)
, inSpace
, inSpace'
-- * Utilities
, degrees
, radians
, clamp
, normAngle1
) where
import Control.Exception (assert)
----------------------------------------------------------------------------------------------------
-- BASIC 3D VECTOR OPERATIONS
-- | 3D vector.
data Vector3 = Vector3 {-# UNPACK #-} !Float !Float !Float deriving (Show)
-- | 3D normal.
data Normal3 = Normal3 {-# UNPACK #-} !Float !Float !Float deriving (Show)
-- | 3D point.
data Point3 = Point3 {-# UNPACK #-} !Float !Float !Float deriving (Show)
-- | Provides a uniform way to access elements of a 3D vector, normal or point.
class Cartesian3Tuple a where
xcomp3 :: a -> Float
ycomp3 :: a -> Float
zcomp3 :: a -> Float
cartesian3Tuple :: a -> (Float, Float, Float)
cartesian3Tuple q = (xcomp3 q, ycomp3 q, zcomp3 q)
toVector3 :: a -> Vector3
toVector3 q = v3 (xcomp3 q) (ycomp3 q) (zcomp3 q)
toNormal3 :: a -> Normal3
toNormal3 q = n3 (xcomp3 q) (ycomp3 q) (zcomp3 q)
toPoint3 :: a -> Point3
toPoint3 q = p3 (xcomp3 q) (ycomp3 q) (zcomp3 q)
instance Cartesian3Tuple Vector3 where
xcomp3 v = let (Vector3 x _ _) = v in x
ycomp3 v = let (Vector3 _ y _) = v in y
zcomp3 v = let (Vector3 _ _ z) = v in z
instance Cartesian3Tuple Normal3 where
xcomp3 n = let (Normal3 x _ _) = n in x
ycomp3 n = let (Normal3 _ y _) = n in y
zcomp3 n = let (Normal3 _ _ z) = n in z
instance Cartesian3Tuple Point3 where
xcomp3 p = let (Point3 x _ _) = p in x
ycomp3 p = let (Point3 _ y _) = p in y
zcomp3 p = let (Point3 _ _ z) = p in z
-- | Vector3 pretends to have a Num instance.
--
-- Insert grumbles about Haskell numeric typeclasses.
instance Num Vector3 where
(+) (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = Vector3 (x1 + x2) (y1 + y2) (z1 + z2)
(-) (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = Vector3 (x1 - x2) (y1 - y2) (z1 - z2)
negate (Vector3 x y z) = Vector3 (-x) (-y) (-z)
(*) = error "Multiplication is NOT defined for Vector3"
abs = error "abs is NOT defined for Vector3"
signum = error "signum is NOT defined for Vector3"
fromInteger = error "fromInteger is NOT defined for Vector3"
-- | Constructs a vector.
v3 :: Float -> Float -> Float -> Vector3
v3 x y z = Vector3 x y z
-- | Constructs a point.
p3 :: Float -> Float -> Float -> Point3
p3 x y z = Point3 x y z
-- | Constructs a normal (guaranteed to be unit length by construction).
n3 :: Float -> Float -> Float -> Normal3
n3 x y z =
let l = sqrt ((x * x) + (y * y) + (z * z))
in assert (l >= 0.0) (Normal3 (x / l) (y / l) (z / l))
-- | Returns the squared length of a vector.
lengthSquared :: Vector3 -> Float
lengthSquared (Vector3 x y z) = (x * x) + (y * y) + (z * z)
-- | Returns the length of a vector.
vectorLength :: Vector3 -> Float
vectorLength = sqrt . lengthSquared
-- | Multiplies a vector by a scalar.
(.*) :: Vector3 -> Float -> Vector3
(.*) (Vector3 x y z) c = v3 (x * c) (y * c) (z * c)
-- | Divides a vector by a scalar.
(./) :: Vector3 -> Float -> Vector3
(./) (Vector3 x y z) c = v3 (x / c) (y / c) (z / c)
-- | Normalizes a vector, creating a normal.
normalize :: Vector3 -> Vector3
normalize (Vector3 x y z) = toVector3 $ n3 x y z
-- | Vector dot product.
dot :: Vector3 -> Vector3 -> Float
dot (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) = (x1 * x2) + (y1 * y2) + (z1 * z2)
-- | Vector dot product (symbolic alias).
(⋅) :: Vector3 -> Vector3 -> Float
(⋅) = dot
-- | Vector cross product.
cross :: Vector3 -> Vector3 -> Vector3
cross (Vector3 x1 y1 z1) (Vector3 x2 y2 z2) =
let x = (y1 * z2) - (y2 * z1)
y = (x2 * z1) - (x1 * z2)
z = (x1 * y2) - (x2 * y1)
in Vector3 x y z
-- | Vector cross product (symbolic alias).
(⨯) :: Vector3 -> Vector3 -> Vector3
(⨯) = cross
-- | Offsets a point by a given vector.
offsetPoint :: Vector3 -> Point3 -> Point3
offsetPoint (Vector3 vx vy vz) (Point3 px py pz) = Point3 (px + vx) (py + vy) (pz + vz)
-- | Offsets a point by a given factor along a direction vector.
offsetPointAlongVector :: Vector3 -> Float -> Point3 -> Point3
offsetPointAlongVector v d p = toPoint3 ((toVector3 p) + (v .* d))
----------------------------------------------------------------------------------------------------
-- 2D RECTANGLE
data Rectangle a = Rectangle
!a -- ^ x
!a -- ^ y
!a -- ^ width
!a -- ^ height
-- | Creates a rectangle.
--
-- The width and height of the rectangle are normalized so that they are always positive.
rectangle :: (Num a, Ord a)
=> a -- ^ x coordinate
-> a -- ^ y coordinate
-> a -- ^ width
-> a -- ^ height
-> Rectangle a
rectangle x y w h
| w < 0 = rectangle (x-w) y (-w) h
| h < 0 = rectangle x (y-h) w (-h)
| otherwise = Rectangle x y w h
-- | Checks if a rectangle contains a point.
rectangleContains :: (Ord a)
=> Rectangle a
-> a -- ^ x coordinate
-> a -- ^ y coordinate
-> Bool
rectangleContains (Rectangle x y w h) px py =
(px >= x) && (px < w) && (py >= y) && (py < h)
-- | Finds a rectangle which completely bounds two existing rectangles.
rectangleUnion :: (Num a, Ord a)
=> Rectangle a
-> Rectangle a
-> Rectangle a
rectangleUnion (Rectangle x1 y1 w1 h1) (Rectangle x2 y2 w2 h2) =
let x = min x1 x2
y = max y1 y2
xmax = max (x1+w1) (x2+w2)
ymax = max (y1+h1) (y2+h2)
w = xmax - x
h = ymax - y
in Rectangle x y w h
----------------------------------------------------------------------------------------------------
-- UV COORDINATES
-- | UV parametric coordinates.
data UVCoord = UVCoord {-# UNPACK #-} !Float !Float deriving (Show)
----------------------------------------------------------------------------------------------------
-- TRANSFORMATIONS BETWEEN COORDINATE SPACES
-- | Transformation between coordinate spaces.
data XForm = XForm
AMatrix -- ^ transformation from -> to
AMatrix -- ^ inverse transformation to -> from
deriving (Show)
-- | Invert a transformation.
xformInv :: XForm -> XForm
xformInv (XForm x x') = XForm x' x
-- | Compose transformations.
xformCompose :: XForm -- ^ transformation A
-> XForm -- ^ transformation B
-> XForm -- ^ transformation that is equal to applying A and then B
xformCompose (XForm x1 x1') (XForm x2 x2') = XForm (x2 * x1) (x1' * x2')
-- | Monoid instance for XForm.
instance Monoid XForm where
mempty = xformId
mappend = xformCompose
-- | Identity affine transformation.
xformId :: XForm
xformId =
let m = AMatrix 1 0 0 0 0 1 0 0 0 0 1 0
in XForm m m
-- | Translation.
translate :: Float -> Float -> Float -> XForm
translate tx ty tz =
let
m = AMatrix 1 0 0 tx 0 1 0 ty 0 0 1 tz
m' = AMatrix 1 0 0 (-tx) 0 1 0 (-ty) 0 0 1 (-tz)
in XForm m m'
-- | Scale.
scale :: Float -> Float -> Float -> XForm
scale sx sy sz =
let
m = AMatrix sx 0 0 0 0 sy 0 0 0 0 sz 0
m' = AMatrix (1.0 / sx) 0 0 0 0 (1.0 / sy) 0 0 0 0 (1.0/sz) 0
in XForm m m'
-- | Axis-angle rotation.
--
-- The angle is expressed in degrees.
rotate :: Float -> Vector3 -> XForm
rotate degAngle v =
let
angle = degAngle * pi / 180.0
Normal3 ax ay az = toNormal3 v
s = sin angle
c = cos angle
m11 = ax * ax + (1.0 - ax * ax) * c
m12 = ax * ay * (1.0 - c) - az * s
m13 = ax * az * (1.0 - c) + ay * s
m21 = ax * ay * (1.0 - c) + az * s
m22 = ay * ay + (1.0 - ay * ay) * c
m23 = ay * az * (1.0 - c) - ax * s
m31 = ax * az * (1.0 - c) - ay * s
m32 = ay * az * (1.0 - c) + ax * s
m33 = az * az + (1.0 - az * az) * c
m = AMatrix m11 m12 m13 0 m21 m22 m23 0 m31 m32 m33 0
m' = AMatrix m11 m21 m31 0 m12 m22 m32 0 m13 m23 m33 0
in XForm m m'
-- | Transform a vector.
xformVector3 :: XForm -> Vector3 -> Vector3
xformVector3 (XForm m _) (Vector3 x y z) =
let HVector x' y' z' _ = affineMul m (HVector x y z 0)
in Vector3 x' y' z'
-- | Transform a point.
xformPoint3 :: XForm -> Point3 -> Point3
xformPoint3 (XForm m _) (Point3 x y z) =
let HVector x' y' z' _ = affineMul m (HVector x y z 1)
in Point3 x' y' z'
-- | Transform a normal.
xformNormal3 :: XForm -> Normal3 -> Normal3
xformNormal3 (XForm _ m') (Normal3 x y z) =
let HVector x' y' z' _ = affineTransposeMul m' (HVector x y z 0)
in n3 x' y' z'
-- | Transforms an object of type 'a' between coordinate spaces.
class Transform a where
xform :: XForm -> a -> a
instance Transform Vector3 where xform = xformVector3
instance Transform Point3 where xform = xformPoint3
instance Transform Normal3 where xform = xformNormal3
instance (Transform a) => Transform (Maybe a) where
xform x = maybe Nothing (Just . xform x)
-- | Performs a function in a given space and then transforms back.
--
-- Transforms a value using the given transformation, then computes a function, and finally
-- transforms the result back using the inverse of the transformation.
inSpace :: (Transform a, Transform b)
=> XForm
-> (a -> b)
-> a
-> b
inSpace x f =
let fwd = xform x
bwd = (xform . xformInv) x
in bwd . f . fwd
-- | Performs a function in a given space, but does NOT transform the result back.
inSpace' :: (Transform a)
=> XForm
-> (a -> b)
-> a
-> b
inSpace' x f =
let fwd = xform x
in f . fwd
----------------------------------------------------------------------------------------------------
-- HOMOGENEOUS COORDINATE VECTORS AND AFFINE MATRICES
-- | Vector or point in homogeneous coordinates.
data HVector = HVector {-# UNPACK #-} !Float !Float !Float !Float
-- | Affine transformation matrix.
--
-- This is a 4x4 homogeneous transformation matrix, but we explicitly assume that the bottom row
-- just always contains the values [0,0,0,1]. (Saves writing them out.)
-- This can represent all possible affine transformations, but NOT projective transformations.
data AMatrix = AMatrix {-# UNPACK #-} !Float !Float !Float !Float
!Float !Float !Float !Float
!Float !Float !Float !Float
deriving (Show)
instance Num AMatrix where
(*) a b =
let
AMatrix a11 a12 a13 a14 a21 a22 a23 a24 a31 a32 a33 a34 = a
AMatrix b11 b12 b13 b14 b21 b22 b23 b24 b31 b32 b33 b34 = b
x11 = (a11 * b11) + (a12 * b21) + (a13 * b31)
x12 = (a11 * b12) + (a12 * b22) + (a13 * b32)
x13 = (a11 * b13) + (a12 * b23) + (a13 * b33)
x14 = (a11 * b14) + (a12 * b24) + (a13 * b34) + a14
x21 = (a21 * b11) + (a22 * b21) + (a23 * b31)
x22 = (a21 * b12) + (a22 * b22) + (a23 * b32)
x23 = (a21 * b13) + (a22 * b23) + (a23 * b33)
x24 = (a21 * b14) + (a22 * b24) + (a23 * b34) + a24
x31 = (a31 * b11) + (a32 * b21) + (a33 * b31)
x32 = (a31 * b12) + (a32 * b22) + (a33 * b32)
x33 = (a31 * b13) + (a32 * b23) + (a33 * b33)
x34 = (a31 * b14) + (a32 * b24) + (a33 * b34) + a34
in
AMatrix x11 x12 x13 x14 x21 x22 x23 x24 x31 x32 x33 x34
(+) = error "(+) is not defined for AMatrix"
(-) = error "(-) is not defined for AMatrix"
abs = error "abs is not defined for AMatrix"
signum = error "signum is not defined for AMatrix"
fromInteger = error "fromInteger is not defined for AMatrix"
negate = error "negate is not defined for AMatrix"
-- | Multiplies an affine matrix by a homogeneous vector.
affineMul :: AMatrix -> HVector -> HVector
affineMul m v =
let
AMatrix m11 m12 m13 m14 m21 m22 m23 m24 m31 m32 m33 m34 = m
HVector x y z w = v
x' = (m11 * x) + (m12 * y) + (m13 * z) + (m14 * w)
y' = (m21 * x) + (m22 * y) + (m23 * z) + (m24 * w)
z' = (m31 * x) + (m32 * y) + (m33 * z) + (m34 * w)
in HVector x' y' z' w
-- | Multiplies the transpose of an affine matrix by a homogeneous vector.
--
-- This operation ONLY uses the rotational component of the matrix, and assumes the
-- translation component is zero. (It is used in transforming normals, so we can
-- safely disregard the translations.)
affineTransposeMul :: AMatrix -> HVector -> HVector
affineTransposeMul m v =
let
AMatrix m11 m21 m31 _ m12 m22 m32 _ m13 m23 m33 _ = m
HVector x y z w = v
x' = (m11 * x) + (m12 * y) + (m13 * z)
y' = (m21 * x) + (m22 * y) + (m23 * z)
z' = (m31 * x) + (m32 * y) + (m33 * z)
in HVector x' y' z' w
----------------------------------------------------------------------------------------------------
-- UTILITIES
-- | Converts radians to degrees.
degrees :: Float -> Float
degrees r = 180.0 * r / pi
-- | Converts degrees to radians.
radians :: Float -> Float
radians d = pi * d / 180.0
-- | Clamps a floating-point value to a given range.
clamp :: Float -- ^ minimum allowed value
-> Float -- ^ maximum allowed value
-> Float -- ^ input value
-> Float -- ^ output value after having been clamped
clamp minx maxx x
| x < minx = minx
| x > maxx = maxx
| otherwise = x
-- | Normalizes an angle to the range [0, 2*pi).
--
-- NOTE: normalizing angles is very tricky; double-check you have the right logic.
normAngle1 :: Float -> Float
normAngle1 x | x < 0 = normAngle1 (x + 2*pi)
| x >= (2*pi) = normAngle1 (x - 2*pi)
| otherwise = x
| lancelet/approxier | src/lib/VecMath.hs | apache-2.0 | 14,540 | 0 | 14 | 4,039 | 4,847 | 2,574 | 2,273 | 353 | 1 |
-- Copyright 2021 Google LLC
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE CPP #-}
module Main where
import Control.Monad (unless)
import System.IO (hSetBuffering, BufferMode(NoBuffering), stdout)
import Text.Read (readMaybe)
#ifdef SOLUTION
import Solution (Hand, Score, score)
#else
import Codelab (Hand, Score, score)
#endif
main :: IO ()
main = hSetBuffering stdout NoBuffering >> printHelp >> play
play :: IO ()
play = playTurn [] []
-- We play up to 3.
gameOver :: Score -> Bool
gameOver (s1, s2) = s1 >= 3 || s2 >= 3
-- Below is the impure IO code that lets us read hands from the standard
-- input and play the game!
-- Beware: Haskell 102 spoilers!
readHand :: String -> IO Hand
readHand prompt = do
putStr prompt -- prints the prompt
handText <- getLine -- reads one line of input
case readMaybe handText of -- tries to convert it to Hand
Just h -> return h -- success: our result is h
Nothing -> badMove prompt handText -- failure: we try again
playTurn :: [Hand] -> [Hand] -> IO ()
playTurn p1 p2 = do
h1 <- readHand "p1: "
h2 <- readHand "p2: "
let p1' = h1 : p1
p2' = h2 : p2
newScore = score p1' p2'
print newScore
unless (gameOver newScore) $ playTurn p1' p2'
-- Helpers, again using Haskell 102 spoilers!
printHelp :: IO ()
printHelp = printHeader >> printMoves
printHeader :: IO ()
printHeader = do
putStrLn "Welcome to Rock-Paper-Scissors!"
putStrLn "-------------------------------"
printMoves :: IO ()
printMoves = do
putStr "Each move is one of "
putStrLn (show [minBound :: Hand ..])
badMove :: String -> String -> IO Hand
badMove prompt move = do
putStr "Bad move: "
putStrLn move
printMoves
readHand prompt
| google/haskell-trainings | haskell_101/codelab/06_rps/src/Main.hs | apache-2.0 | 2,295 | 0 | 10 | 514 | 484 | 253 | 231 | 44 | 2 |
import Data.List
import Text.Printf
ans ([0,0]:_) = []
ans x =
let d = take 5 x
r = drop 5 x
a = maximumBy (\(a,b) (c,d)-> compare b d) $ zip ['A','B'..] $ map (\[x,y] -> x + y) d
in
a:(ans r)
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
o = ans i
mapM_ (\(a,b) -> printf "%c %d\n" a b) o
| a143753/AOJ | 0195.hs | apache-2.0 | 361 | 0 | 14 | 111 | 243 | 127 | 116 | 13 | 1 |
module Chord where
import Interval (Interval (..), addInterval)
import Note
-- |A chord is defined by it's root note and all it's
-- intervals, relative to the root note.
data Chord = Chord Note [Interval]
deriving (Eq, Read, Show)
-- |Converts a chord to a list of notes that constitute the
-- chord.
toNotes :: Chord -> [Note]
toNotes (Chord root intervals) =
map (root `addInterval`) intervals | blacktaxi/inversion | src/Chord.hs | bsd-3-clause | 407 | 0 | 7 | 77 | 94 | 57 | 37 | 8 | 1 |
module Data.Text.Lazy.Encoding.AsLt
( module Data.Text.Lazy.Encoding.AsLt
) where
-- generated by https://github.com/rvion/ride/tree/master/jetpack-gen
import qualified Data.Text.Lazy.Encoding as I
-- lt_decodeLatin1 :: ByteString -> Text
lt_decodeLatin1 = I.decodeLatin1
-- lt_decodeUtf16BE :: ByteString -> Text
lt_decodeUtf16BE = I.decodeUtf16BE
-- lt_decodeUtf16BEWith :: OnDecodeError -> ByteString -> Text
lt_decodeUtf16BEWith = I.decodeUtf16BEWith
-- lt_decodeUtf16LE :: ByteString -> Text
lt_decodeUtf16LE = I.decodeUtf16LE
-- lt_decodeUtf16LEWith :: OnDecodeError -> ByteString -> Text
lt_decodeUtf16LEWith = I.decodeUtf16LEWith
-- lt_decodeUtf32BE :: ByteString -> Text
lt_decodeUtf32BE = I.decodeUtf32BE
-- lt_decodeUtf32BEWith :: OnDecodeError -> ByteString -> Text
lt_decodeUtf32BEWith = I.decodeUtf32BEWith
-- lt_decodeUtf32LE :: ByteString -> Text
lt_decodeUtf32LE = I.decodeUtf32LE
-- lt_decodeUtf32LEWith :: OnDecodeError -> ByteString -> Text
lt_decodeUtf32LEWith = I.decodeUtf32LEWith
-- lt_decodeUtf8 :: ByteString -> Text
lt_decodeUtf8 = I.decodeUtf8
-- lt_decodeUtf8' :: ByteString -> Either UnicodeException Text
lt_decodeUtf8' = I.decodeUtf8'
-- lt_decodeUtf8With :: OnDecodeError -> ByteString -> Text
lt_decodeUtf8With = I.decodeUtf8With
-- lt_encodeUtf16BE :: Text -> ByteString
lt_encodeUtf16BE = I.encodeUtf16BE
-- lt_encodeUtf16LE :: Text -> ByteString
lt_encodeUtf16LE = I.encodeUtf16LE
-- lt_encodeUtf32BE :: Text -> ByteString
lt_encodeUtf32BE = I.encodeUtf32BE
-- lt_encodeUtf32LE :: Text -> ByteString
lt_encodeUtf32LE = I.encodeUtf32LE
-- lt_encodeUtf8 :: Text -> ByteString
lt_encodeUtf8 = I.encodeUtf8
-- lt_encodeUtf8Builder :: Text -> Builder
lt_encodeUtf8Builder = I.encodeUtf8Builder
-- lt_encodeUtf8BuilderEscaped :: BoundedPrim Word8 -> Text -> Builder
lt_encodeUtf8BuilderEscaped = I.encodeUtf8BuilderEscaped
| rvion/ride | jetpack/src/Data/Text/Lazy/Encoding/AsLt.hs | bsd-3-clause | 1,879 | 0 | 5 | 227 | 183 | 119 | 64 | 22 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module Snooze.Core (
httpGo
, httpGo'
) where
import Data.ByteString.Lazy as BSL
import Network.HTTP.Client
import P
import System.IO
-- Eventually we will want/need to have sensible retries/timeouts here
httpGo :: Manager -> Request -> IO (Response BSL.ByteString)
httpGo mgr req =
httpLbs req {
#if MIN_VERSION_http_client(0,5,0)
#else
checkStatus = _checkStatusIgnore,
#endif
-- Never follow redirects - should always be done by the consumer explicitly if appropriate
redirectCount = 0
} mgr
where
-- A stupid default of http-client is to throw exceptions for non-200
_checkStatusIgnore _ _ _ = Nothing
httpGo' :: Request -> IO (Response BSL.ByteString)
httpGo' req =
newManager defaultManagerSettings >>= flip httpGo req
| ambiata/snooze | src/Snooze/Core.hs | bsd-3-clause | 942 | 0 | 10 | 211 | 147 | 84 | 63 | 21 | 1 |
-- DataKinds is needed for deriveAll0 calls on GHC 8
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module DataFamilies.Types (module DataFamilies.Types) where
import Prelude ()
import Prelude.Compat
import Generics.Deriving.TH (deriveAll0)
import Types (ApproxEq(..))
data family Nullary a
data instance Nullary Int = C1 | C2 | C3 deriving (Eq, Show)
data instance Nullary Char = C4 deriving (Eq, Show)
data family SomeType a b c
data instance SomeType c () a = Nullary
| Unary Int
| Product String (Maybe Char) a
| Record { testOne :: Double
, testTwo :: Maybe Bool
, testThree :: Maybe a
}
| List [a]
deriving (Eq, Show)
data family Approx a
newtype instance Approx a = Approx { fromApprox :: a }
deriving (Show, ApproxEq, Num)
instance (ApproxEq a) => Eq (Approx a) where
Approx a == Approx b = a =~ b
data family GADT a
data instance GADT a where
GADT :: { gadt :: String } -> GADT String
deriving instance Eq (GADT a)
deriving instance Show (GADT a)
-- We use generic-deriving to be able to derive Generic instances for
-- data families on GHC 7.4.
$(deriveAll0 'C1)
$(deriveAll0 'C4)
$(deriveAll0 'Approx)
$(deriveAll0 'Nullary)
| sol/aeson | tests/DataFamilies/Types.hs | bsd-3-clause | 1,629 | 0 | 9 | 502 | 394 | 225 | 169 | 39 | 0 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1998
This module contains definitions for the IdInfo for things that
have a standard form, namely:
- data constructors
- record selectors
- method and superclass selectors
- primitive operations
-}
{-# LANGUAGE CPP #-}
module MkId (
mkDictFunId, mkDictFunTy, mkDictSelId, mkDictSelRhs,
mkPrimOpId, mkFCallId,
wrapNewTypeBody, unwrapNewTypeBody,
wrapFamInstBody, unwrapFamInstScrut,
wrapTypeUnbranchedFamInstBody, unwrapTypeUnbranchedFamInstScrut,
DataConBoxer(..), mkDataConRep, mkDataConWorkId,
-- And some particular Ids; see below for why they are wired in
wiredInIds, ghcPrimIds,
unsafeCoerceName, unsafeCoerceId, realWorldPrimId,
voidPrimId, voidArgId,
nullAddrId, seqId, lazyId, lazyIdKey, runRWId,
coercionTokenId, magicDictId, coerceId,
proxyHashId, noinlineId, noinlineIdName,
-- Re-export error Ids
module PrelRules
) where
#include "HsVersions.h"
import GhcPrelude
import Rules
import TysPrim
import TysWiredIn
import PrelRules
import Type
import FamInstEnv
import Coercion
import TcType
import MkCore
import CoreUtils ( exprType, mkCast )
import CoreUnfold
import Literal
import TyCon
import CoAxiom
import Class
import NameSet
import Name
import PrimOp
import ForeignCall
import DataCon
import Id
import IdInfo
import Demand
import CoreSyn
import Unique
import UniqSupply
import PrelNames
import BasicTypes hiding ( SuccessFlag(..) )
import Util
import Pair
import DynFlags
import Outputable
import FastString
import ListSetOps
import qualified GHC.LanguageExtensions as LangExt
import Data.Maybe ( maybeToList )
{-
************************************************************************
* *
\subsection{Wired in Ids}
* *
************************************************************************
Note [Wired-in Ids]
~~~~~~~~~~~~~~~~~~~
There are several reasons why an Id might appear in the wiredInIds:
(1) The ghcPrimIds are wired in because they can't be defined in
Haskell at all, although the can be defined in Core. They have
compulsory unfoldings, so they are always inlined and they have
no definition site. Their home module is GHC.Prim, so they
also have a description in primops.txt.pp, where they are called
'pseudoops'.
(2) The 'error' function, eRROR_ID, is wired in because we don't yet have
a way to express in an interface file that the result type variable
is 'open'; that is can be unified with an unboxed type
[The interface file format now carry such information, but there's
no way yet of expressing at the definition site for these
error-reporting functions that they have an 'open'
result type. -- sof 1/99]
(3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because
the desugarer generates code that mentions them directly, and
(b) for the same reason as eRROR_ID
(4) lazyId is wired in because the wired-in version overrides the
strictness of the version defined in GHC.Base
(5) noinlineId is wired in because when we serialize to interfaces
we may insert noinline statements.
In cases (2-4), the function has a definition in a library module, and
can be called; but the wired-in version means that the details are
never read from that module's interface file; instead, the full definition
is right here.
-}
wiredInIds :: [Id]
wiredInIds
= [lazyId, dollarId, oneShotId, runRWId, noinlineId]
++ errorIds -- Defined in MkCore
++ ghcPrimIds
-- These Ids are exported from GHC.Prim
ghcPrimIds :: [Id]
ghcPrimIds
= [ -- These can't be defined in Haskell, but they have
-- perfectly reasonable unfoldings in Core
realWorldPrimId,
voidPrimId,
unsafeCoerceId,
nullAddrId,
seqId,
magicDictId,
coerceId,
proxyHashId
]
{-
************************************************************************
* *
\subsection{Data constructors}
* *
************************************************************************
The wrapper for a constructor is an ordinary top-level binding that evaluates
any strict args, unboxes any args that are going to be flattened, and calls
the worker.
We're going to build a constructor that looks like:
data (Data a, C b) => T a b = T1 !a !Int b
T1 = /\ a b ->
\d1::Data a, d2::C b ->
\p q r -> case p of { p ->
case q of { q ->
Con T1 [a,b] [p,q,r]}}
Notice that
* d2 is thrown away --- a context in a data decl is used to make sure
one *could* construct dictionaries at the site the constructor
is used, but the dictionary isn't actually used.
* We have to check that we can construct Data dictionaries for
the types a and Int. Once we've done that we can throw d1 away too.
* We use (case p of q -> ...) to evaluate p, rather than "seq" because
all that matters is that the arguments are evaluated. "seq" is
very careful to preserve evaluation order, which we don't need
to be here.
You might think that we could simply give constructors some strictness
info, like PrimOps, and let CoreToStg do the let-to-case transformation.
But we don't do that because in the case of primops and functions strictness
is a *property* not a *requirement*. In the case of constructors we need to
do something active to evaluate the argument.
Making an explicit case expression allows the simplifier to eliminate
it in the (common) case where the constructor arg is already evaluated.
Note [Wrappers for data instance tycons]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the case of data instances, the wrapper also applies the coercion turning
the representation type into the family instance type to cast the result of
the wrapper. For example, consider the declarations
data family Map k :: * -> *
data instance Map (a, b) v = MapPair (Map a (Pair b v))
The tycon to which the datacon MapPair belongs gets a unique internal
name of the form :R123Map, and we call it the representation tycon.
In contrast, Map is the family tycon (accessible via
tyConFamInst_maybe). A coercion allows you to move between
representation and family type. It is accessible from :R123Map via
tyConFamilyCoercion_maybe and has kind
Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v}
The wrapper and worker of MapPair get the types
-- Wrapper
$WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
$WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v)
-- Worker
MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
This coercion is conditionally applied by wrapFamInstBody.
It's a bit more complicated if the data instance is a GADT as well!
data instance T [a] where
T1 :: forall b. b -> T [Maybe b]
Hence we translate to
-- Wrapper
$WT1 :: forall b. b -> T [Maybe b]
$WT1 b v = T1 (Maybe b) b (Maybe b) v
`cast` sym (Co7T (Maybe b))
-- Worker
T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c
-- Coercion from family type to representation type
Co7T a :: T [a] ~ :R7T a
Note [Newtype datacons]
~~~~~~~~~~~~~~~~~~~~~~~
The "data constructor" for a newtype should always be vanilla. At one
point this wasn't true, because the newtype arising from
class C a => D a
looked like
newtype T:D a = D:D (C a)
so the data constructor for T:C had a single argument, namely the
predicate (C a). But now we treat that as an ordinary argument, not
part of the theta-type, so all is well.
************************************************************************
* *
\subsection{Dictionary selectors}
* *
************************************************************************
Selecting a field for a dictionary. If there is just one field, then
there's nothing to do.
Dictionary selectors may get nested forall-types. Thus:
class Foo a where
op :: forall b. Ord b => a -> b -> b
Then the top-level type for op is
op :: forall a. Foo a =>
forall b. Ord b =>
a -> b -> b
-}
mkDictSelId :: Name -- Name of one of the *value* selectors
-- (dictionary superclass or method)
-> Class -> Id
mkDictSelId name clas
= mkGlobalId (ClassOpId clas) name sel_ty info
where
tycon = classTyCon clas
sel_names = map idName (classAllSelIds clas)
new_tycon = isNewTyCon tycon
[data_con] = tyConDataCons tycon
tyvars = dataConUserTyVarBinders data_con
n_ty_args = length tyvars
arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses
val_index = assoc "MkId.mkDictSelId" (sel_names `zip` [0..]) name
sel_ty = mkForAllTys tyvars $
mkFunTy (mkClassPred clas (mkTyVarTys (binderVars tyvars))) $
getNth arg_tys val_index
base_info = noCafIdInfo
`setArityInfo` 1
`setStrictnessInfo` strict_sig
`setLevityInfoWithType` sel_ty
info | new_tycon
= base_info `setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` mkInlineUnfoldingWithArity 1
(mkDictSelRhs clas val_index)
-- See Note [Single-method classes] in TcInstDcls
-- for why alwaysInlinePragma
| otherwise
= base_info `setRuleInfo` mkRuleInfo [rule]
-- Add a magic BuiltinRule, but no unfolding
-- so that the rule is always available to fire.
-- See Note [ClassOp/DFun selection] in TcInstDcls
-- This is the built-in rule that goes
-- op (dfT d1 d2) ---> opT d1 d2
rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS`
occNameFS (getOccName name)
, ru_fn = name
, ru_nargs = n_ty_args + 1
, ru_try = dictSelRule val_index n_ty_args }
-- The strictness signature is of the form U(AAAVAAAA) -> T
-- where the V depends on which item we are selecting
-- It's worth giving one, so that absence info etc is generated
-- even if the selector isn't inlined
strict_sig = mkClosedStrictSig [arg_dmd] topRes
arg_dmd | new_tycon = evalDmd
| otherwise = mkManyUsedDmd $
mkProdDmd [ if name == sel_name then evalDmd else absDmd
| sel_name <- sel_names ]
mkDictSelRhs :: Class
-> Int -- 0-indexed selector among (superclasses ++ methods)
-> CoreExpr
mkDictSelRhs clas val_index
= mkLams tyvars (Lam dict_id rhs_body)
where
tycon = classTyCon clas
new_tycon = isNewTyCon tycon
[data_con] = tyConDataCons tycon
tyvars = dataConUnivTyVars data_con
arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses
the_arg_id = getNth arg_ids val_index
pred = mkClassPred clas (mkTyVarTys tyvars)
dict_id = mkTemplateLocal 1 pred
arg_ids = mkTemplateLocalsNum 2 arg_tys
rhs_body | new_tycon = unwrapNewTypeBody tycon (mkTyVarTys tyvars) (Var dict_id)
| otherwise = Case (Var dict_id) dict_id (idType the_arg_id)
[(DataAlt data_con, arg_ids, varToCoreExpr the_arg_id)]
-- varToCoreExpr needed for equality superclass selectors
-- sel a b d = case x of { MkC _ (g:a~b) _ -> CO g }
dictSelRule :: Int -> Arity -> RuleFun
-- Tries to persuade the argument to look like a constructor
-- application, using exprIsConApp_maybe, and then selects
-- from it
-- sel_i t1..tk (D t1..tk op1 ... opm) = opi
--
dictSelRule val_index n_ty_args _ id_unf _ args
| (dict_arg : _) <- drop n_ty_args args
, Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg
= Just (getNth con_args val_index)
| otherwise
= Nothing
{-
************************************************************************
* *
Data constructors
* *
************************************************************************
-}
mkDataConWorkId :: Name -> DataCon -> Id
mkDataConWorkId wkr_name data_con
| isNewTyCon tycon
= mkGlobalId (DataConWrapId data_con) wkr_name nt_wrap_ty nt_work_info
| otherwise
= mkGlobalId (DataConWorkId data_con) wkr_name alg_wkr_ty wkr_info
where
tycon = dataConTyCon data_con
----------- Workers for data types --------------
alg_wkr_ty = dataConRepType data_con
wkr_arity = dataConRepArity data_con
wkr_info = noCafIdInfo
`setArityInfo` wkr_arity
`setStrictnessInfo` wkr_sig
`setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated,
-- even if arity = 0
`setLevityInfoWithType` alg_wkr_ty
-- NB: unboxed tuples have workers, so we can't use
-- setNeverLevPoly
wkr_sig = mkClosedStrictSig (replicate wkr_arity topDmd) (dataConCPR data_con)
-- Note [Data-con worker strictness]
-- Notice that we do *not* say the worker Id is strict
-- even if the data constructor is declared strict
-- e.g. data T = MkT !(Int,Int)
-- Why? Because the *wrapper* $WMkT is strict (and its unfolding has
-- case expressions that do the evals) but the *worker* MkT itself is
-- not. If we pretend it is strict then when we see
-- case x of y -> MkT y
-- the simplifier thinks that y is "sure to be evaluated" (because
-- the worker MkT is strict) and drops the case. No, the workerId
-- MkT is not strict.
--
-- However, the worker does have StrictnessMarks. When the simplifier
-- sees a pattern
-- case e of MkT x -> ...
-- it uses the dataConRepStrictness of MkT to mark x as evaluated;
-- but that's fine... dataConRepStrictness comes from the data con
-- not from the worker Id.
----------- Workers for newtypes --------------
(nt_tvs, _, nt_arg_tys, _) = dataConSig data_con
res_ty_args = mkTyVarTys nt_tvs
nt_wrap_ty = dataConUserType data_con
nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo
`setArityInfo` 1 -- Arity 1
`setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` newtype_unf
`setLevityInfoWithType` nt_wrap_ty
id_arg1 = mkTemplateLocal 1 (head nt_arg_tys)
newtype_unf = ASSERT2( isVanillaDataCon data_con &&
isSingleton nt_arg_tys, ppr data_con )
-- Note [Newtype datacons]
mkCompulsoryUnfolding $
mkLams nt_tvs $ Lam id_arg1 $
wrapNewTypeBody tycon res_ty_args (Var id_arg1)
dataConCPR :: DataCon -> DmdResult
dataConCPR con
| isDataTyCon tycon -- Real data types only; that is,
-- not unboxed tuples or newtypes
, null (dataConExTyVars con) -- No existentials
, wkr_arity > 0
, wkr_arity <= mAX_CPR_SIZE
= if is_prod then vanillaCprProdRes (dataConRepArity con)
else cprSumRes (dataConTag con)
| otherwise
= topRes
where
is_prod = isProductTyCon tycon
tycon = dataConTyCon con
wkr_arity = dataConRepArity con
mAX_CPR_SIZE :: Arity
mAX_CPR_SIZE = 10
-- We do not treat very big tuples as CPR-ish:
-- a) for a start we get into trouble because there aren't
-- "enough" unboxed tuple types (a tiresome restriction,
-- but hard to fix),
-- b) more importantly, big unboxed tuples get returned mainly
-- on the stack, and are often then allocated in the heap
-- by the caller. So doing CPR for them may in fact make
-- things worse.
{-
-------------------------------------------------
-- Data constructor representation
--
-- This is where we decide how to wrap/unwrap the
-- constructor fields
--
--------------------------------------------------
-}
type Unboxer = Var -> UniqSM ([Var], CoreExpr -> CoreExpr)
-- Unbox: bind rep vars by decomposing src var
data Boxer = UnitBox | Boxer (TCvSubst -> UniqSM ([Var], CoreExpr))
-- Box: build src arg using these rep vars
-- | Data Constructor Boxer
newtype DataConBoxer = DCB ([Type] -> [Var] -> UniqSM ([Var], [CoreBind]))
-- Bind these src-level vars, returning the
-- rep-level vars to bind in the pattern
{-
Note [Inline partially-applied constructor wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow the wrapper to inline when partially applied to avoid
boxing values unnecessarily. For example, consider
data Foo a = Foo !Int a
instance Traversable Foo where
traverse f (Foo i a) = Foo i <$> f a
This desugars to
traverse f foo = case foo of
Foo i# a -> let i = I# i#
in map ($WFoo i) (f a)
If the wrapper `$WFoo` is not inlined, we get a fruitless reboxing of `i`.
But if we inline the wrapper, we get
map (\a. case i of I# i# a -> Foo i# a) (f a)
and now case-of-known-constructor eliminates the redundant allocation.
-}
mkDataConRep :: DynFlags
-> FamInstEnvs
-> Name
-> Maybe [HsImplBang]
-- See Note [Bangs on imported data constructors]
-> DataCon
-> UniqSM DataConRep
mkDataConRep dflags fam_envs wrap_name mb_bangs data_con
| not wrapper_reqd
= return NoDataConRep
| otherwise
= do { wrap_args <- mapM newLocal wrap_arg_tys
; wrap_body <- mk_rep_app (wrap_args `zip` dropList eq_spec unboxers)
initial_wrap_app
; let wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty wrap_info
wrap_info = noCafIdInfo
`setArityInfo` wrap_arity
-- It's important to specify the arity, so that partial
-- applications are treated as values
`setInlinePragInfo` wrap_prag
`setUnfoldingInfo` wrap_unf
`setStrictnessInfo` wrap_sig
-- We need to get the CAF info right here because TidyPgm
-- does not tidy the IdInfo of implicit bindings (like the wrapper)
-- so it not make sure that the CAF info is sane
`setNeverLevPoly` wrap_ty
wrap_sig = mkClosedStrictSig wrap_arg_dmds (dataConCPR data_con)
wrap_arg_dmds =
replicate (length theta) topDmd ++ map mk_dmd arg_ibangs
-- Don't forget the dictionary arguments when building
-- the strictness signature (#14290).
mk_dmd str | isBanged str = evalDmd
| otherwise = topDmd
wrap_prag = alwaysInlinePragma `setInlinePragmaActivation`
ActiveAfter NoSourceText 2
-- See Note [Activation for data constructor wrappers]
-- The wrapper will usually be inlined (see wrap_unf), so its
-- strictness and CPR info is usually irrelevant. But this is
-- not always the case; GHC may choose not to inline it. In
-- particular, the wrapper constructor is not inlined inside
-- an INLINE rhs or when it is not applied to any arguments.
-- See Note [Inline partially-applied constructor wrappers]
-- Passing Nothing here allows the wrapper to inline when
-- unsaturated.
wrap_unf = mkInlineUnfolding wrap_rhs
wrap_rhs = mkLams wrap_tvs $
mkLams wrap_args $
wrapFamInstBody tycon res_ty_args $
wrap_body
; return (DCR { dcr_wrap_id = wrap_id
, dcr_boxer = mk_boxer boxers
, dcr_arg_tys = rep_tys
, dcr_stricts = rep_strs
, dcr_bangs = arg_ibangs }) }
where
(univ_tvs, ex_tvs, eq_spec, theta, orig_arg_tys, _orig_res_ty)
= dataConFullSig data_con
wrap_tvs = dataConUserTyVars data_con
res_ty_args = substTyVars (mkTvSubstPrs (map eqSpecPair eq_spec)) univ_tvs
tycon = dataConTyCon data_con -- The representation TyCon (not family)
wrap_ty = dataConUserType data_con
ev_tys = eqSpecPreds eq_spec ++ theta
all_arg_tys = ev_tys ++ orig_arg_tys
ev_ibangs = map (const HsLazy) ev_tys
orig_bangs = dataConSrcBangs data_con
wrap_arg_tys = theta ++ orig_arg_tys
wrap_arity = length wrap_arg_tys
-- The wrap_args are the arguments *other than* the eq_spec
-- Because we are going to apply the eq_spec args manually in the
-- wrapper
arg_ibangs =
case mb_bangs of
Nothing -> zipWith (dataConSrcToImplBang dflags fam_envs)
orig_arg_tys orig_bangs
Just bangs -> bangs
(rep_tys_w_strs, wrappers)
= unzip (zipWith dataConArgRep all_arg_tys (ev_ibangs ++ arg_ibangs))
(unboxers, boxers) = unzip wrappers
(rep_tys, rep_strs) = unzip (concat rep_tys_w_strs)
wrapper_reqd =
(not (isNewTyCon tycon)
-- (Most) newtypes have only a worker, with the exception
-- of some newtypes written with GADT syntax. See below.
&& (any isBanged (ev_ibangs ++ arg_ibangs)
-- Some forcing/unboxing (includes eq_spec)
|| isFamInstTyCon tycon -- Cast result
|| (not $ null eq_spec))) -- GADT
|| dataConUserTyVarsArePermuted data_con
-- If the data type was written with GADT syntax and
-- orders the type variables differently from what the
-- worker expects, it needs a data con wrapper to reorder
-- the type variables.
-- See Note [Data con wrappers and GADT syntax].
initial_wrap_app = Var (dataConWorkId data_con)
`mkTyApps` res_ty_args
`mkVarApps` ex_tvs
`mkCoApps` map (mkReflCo Nominal . eqSpecType) eq_spec
mk_boxer :: [Boxer] -> DataConBoxer
mk_boxer boxers = DCB (\ ty_args src_vars ->
do { let (ex_vars, term_vars) = splitAtList ex_tvs src_vars
subst1 = zipTvSubst univ_tvs ty_args
subst2 = extendTvSubstList subst1 ex_tvs
(mkTyVarTys ex_vars)
; (rep_ids, binds) <- go subst2 boxers term_vars
; return (ex_vars ++ rep_ids, binds) } )
go _ [] src_vars = ASSERT2( null src_vars, ppr data_con ) return ([], [])
go subst (UnitBox : boxers) (src_var : src_vars)
= do { (rep_ids2, binds) <- go subst boxers src_vars
; return (src_var : rep_ids2, binds) }
go subst (Boxer boxer : boxers) (src_var : src_vars)
= do { (rep_ids1, arg) <- boxer subst
; (rep_ids2, binds) <- go subst boxers src_vars
; return (rep_ids1 ++ rep_ids2, NonRec src_var arg : binds) }
go _ (_:_) [] = pprPanic "mk_boxer" (ppr data_con)
mk_rep_app :: [(Id,Unboxer)] -> CoreExpr -> UniqSM CoreExpr
mk_rep_app [] con_app
= return con_app
mk_rep_app ((wrap_arg, unboxer) : prs) con_app
= do { (rep_ids, unbox_fn) <- unboxer wrap_arg
; expr <- mk_rep_app prs (mkVarApps con_app rep_ids)
; return (unbox_fn expr) }
{- Note [Activation for data constructor wrappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Activation on a data constructor wrapper allows it to inline in
Phase 2 and later (1, 0). But not in the InitialPhase. That gives
rewrite rules a chance to fire (in the InitialPhase) if they mention
a data constructor on the left
RULE "foo" f (K a b) = ...
Since the LHS of rules are simplified with InitialPhase, we won't
inline the wrapper on the LHS either.
People have asked for this before, but now that even the InitialPhase
does some inlining, it has become important.
Note [Bangs on imported data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We pass Maybe [HsImplBang] to mkDataConRep to make use of HsImplBangs
from imported modules.
- Nothing <=> use HsSrcBangs
- Just bangs <=> use HsImplBangs
For imported types we can't work it all out from the HsSrcBangs,
because we want to be very sure to follow what the original module
(where the data type was declared) decided, and that depends on what
flags were enabled when it was compiled. So we record the decisions in
the interface file.
The HsImplBangs passed are in 1-1 correspondence with the
dataConOrigArgTys of the DataCon.
Note [Data con wrappers and unlifted types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data T = MkT !Int#
We certainly do not want to make a wrapper
$WMkT x = case x of y { DEFAULT -> MkT y }
For a start, it's still to generate a no-op. But worse, since wrappers
are currently injected at TidyCore, we don't even optimise it away!
So the stupid case expression stays there. This actually happened for
the Integer data type (see Trac #1600 comment:66)!
Note [Data con wrappers and GADT syntax]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider these two very similar data types:
data T1 a b = MkT1 b
data T2 a b where
MkT2 :: forall b a. b -> T2 a b
Despite their similar appearance, T2 will have a data con wrapper but T1 will
not. What sets them apart? The types of their constructors, which are:
MkT1 :: forall a b. b -> T1 a b
MkT2 :: forall b a. b -> T2 a b
MkT2's use of GADT syntax allows it to permute the order in which `a` and `b`
would normally appear. See Note [DataCon user type variable binders] in DataCon
for further discussion on this topic.
The worker data cons for T1 and T2, however, both have types such that `a` is
expected to come before `b` as arguments. Because MkT2 permutes this order, it
needs a data con wrapper to swizzle around the type variables to be in the
order the worker expects.
A somewhat surprising consequence of this is that *newtypes* can have data con
wrappers! After all, a newtype can also be written with GADT syntax:
newtype T3 a b where
MkT3 :: forall b a. b -> T3 a b
Again, this needs a wrapper data con to reorder the type variables. It does
mean that this newtype constructor requires another level of indirection when
being called, but the inliner should make swift work of that.
-}
-------------------------
newLocal :: Type -> UniqSM Var
newLocal ty = do { uniq <- getUniqueM
; return (mkSysLocalOrCoVar (fsLit "dt") uniq ty) }
-- | Unpack/Strictness decisions from source module
dataConSrcToImplBang
:: DynFlags
-> FamInstEnvs
-> Type
-> HsSrcBang
-> HsImplBang
dataConSrcToImplBang dflags fam_envs arg_ty
(HsSrcBang ann unpk NoSrcStrict)
| xopt LangExt.StrictData dflags -- StrictData => strict field
= dataConSrcToImplBang dflags fam_envs arg_ty
(HsSrcBang ann unpk SrcStrict)
| otherwise -- no StrictData => lazy field
= HsLazy
dataConSrcToImplBang _ _ _ (HsSrcBang _ _ SrcLazy)
= HsLazy
dataConSrcToImplBang dflags fam_envs arg_ty
(HsSrcBang _ unpk_prag SrcStrict)
| isUnliftedType arg_ty
= HsLazy -- For !Int#, say, use HsLazy
-- See Note [Data con wrappers and unlifted types]
| not (gopt Opt_OmitInterfacePragmas dflags) -- Don't unpack if -fomit-iface-pragmas
-- Don't unpack if we aren't optimising; rather arbitrarily,
-- we use -fomit-iface-pragmas as the indication
, let mb_co = topNormaliseType_maybe fam_envs arg_ty
-- Unwrap type families and newtypes
arg_ty' = case mb_co of { Just (_,ty) -> ty; Nothing -> arg_ty }
, isUnpackableType dflags fam_envs arg_ty'
, (rep_tys, _) <- dataConArgUnpack arg_ty'
, case unpk_prag of
NoSrcUnpack ->
gopt Opt_UnboxStrictFields dflags
|| (gopt Opt_UnboxSmallStrictFields dflags
&& rep_tys `lengthAtMost` 1) -- See Note [Unpack one-wide fields]
srcUnpack -> isSrcUnpacked srcUnpack
= case mb_co of
Nothing -> HsUnpack Nothing
Just (co,_) -> HsUnpack (Just co)
| otherwise -- Record the strict-but-no-unpack decision
= HsStrict
-- | Wrappers/Workers and representation following Unpack/Strictness
-- decisions
dataConArgRep
:: Type
-> HsImplBang
-> ([(Type,StrictnessMark)] -- Rep types
,(Unboxer,Boxer))
dataConArgRep arg_ty HsLazy
= ([(arg_ty, NotMarkedStrict)], (unitUnboxer, unitBoxer))
dataConArgRep arg_ty HsStrict
= ([(arg_ty, MarkedStrict)], (seqUnboxer, unitBoxer))
dataConArgRep arg_ty (HsUnpack Nothing)
| (rep_tys, wrappers) <- dataConArgUnpack arg_ty
= (rep_tys, wrappers)
dataConArgRep _ (HsUnpack (Just co))
| let co_rep_ty = pSnd (coercionKind co)
, (rep_tys, wrappers) <- dataConArgUnpack co_rep_ty
= (rep_tys, wrapCo co co_rep_ty wrappers)
-------------------------
wrapCo :: Coercion -> Type -> (Unboxer, Boxer) -> (Unboxer, Boxer)
wrapCo co rep_ty (unbox_rep, box_rep) -- co :: arg_ty ~ rep_ty
= (unboxer, boxer)
where
unboxer arg_id = do { rep_id <- newLocal rep_ty
; (rep_ids, rep_fn) <- unbox_rep rep_id
; let co_bind = NonRec rep_id (Var arg_id `Cast` co)
; return (rep_ids, Let co_bind . rep_fn) }
boxer = Boxer $ \ subst ->
do { (rep_ids, rep_expr)
<- case box_rep of
UnitBox -> do { rep_id <- newLocal (TcType.substTy subst rep_ty)
; return ([rep_id], Var rep_id) }
Boxer boxer -> boxer subst
; let sco = substCoUnchecked subst co
; return (rep_ids, rep_expr `Cast` mkSymCo sco) }
------------------------
seqUnboxer :: Unboxer
seqUnboxer v = return ([v], \e -> Case (Var v) v (exprType e) [(DEFAULT, [], e)])
unitUnboxer :: Unboxer
unitUnboxer v = return ([v], \e -> e)
unitBoxer :: Boxer
unitBoxer = UnitBox
-------------------------
dataConArgUnpack
:: Type
-> ( [(Type, StrictnessMark)] -- Rep types
, (Unboxer, Boxer) )
dataConArgUnpack arg_ty
| Just (tc, tc_args) <- splitTyConApp_maybe arg_ty
, Just con <- tyConSingleAlgDataCon_maybe tc
-- NB: check for an *algebraic* data type
-- A recursive newtype might mean that
-- 'arg_ty' is a newtype
, let rep_tys = dataConInstArgTys con tc_args
= ASSERT( isVanillaDataCon con )
( rep_tys `zip` dataConRepStrictness con
,( \ arg_id ->
do { rep_ids <- mapM newLocal rep_tys
; let unbox_fn body
= Case (Var arg_id) arg_id (exprType body)
[(DataAlt con, rep_ids, body)]
; return (rep_ids, unbox_fn) }
, Boxer $ \ subst ->
do { rep_ids <- mapM (newLocal . TcType.substTyUnchecked subst) rep_tys
; return (rep_ids, Var (dataConWorkId con)
`mkTyApps` (substTysUnchecked subst tc_args)
`mkVarApps` rep_ids ) } ) )
| otherwise
= pprPanic "dataConArgUnpack" (ppr arg_ty)
-- An interface file specified Unpacked, but we couldn't unpack it
isUnpackableType :: DynFlags -> FamInstEnvs -> Type -> Bool
-- True if we can unpack the UNPACK the argument type
-- See Note [Recursive unboxing]
-- We look "deeply" inside rather than relying on the DataCons
-- we encounter on the way, because otherwise we might well
-- end up relying on ourselves!
isUnpackableType dflags fam_envs ty
| Just (tc, _) <- splitTyConApp_maybe ty
, Just con <- tyConSingleAlgDataCon_maybe tc
, isVanillaDataCon con
= ok_con_args (unitNameSet (getName tc)) con
| otherwise
= False
where
ok_arg tcs (ty, bang) = not (attempt_unpack bang) || ok_ty tcs norm_ty
where
norm_ty = topNormaliseType fam_envs ty
ok_ty tcs ty
| Just (tc, _) <- splitTyConApp_maybe ty
, let tc_name = getName tc
= not (tc_name `elemNameSet` tcs)
&& case tyConSingleAlgDataCon_maybe tc of
Just con | isVanillaDataCon con
-> ok_con_args (tcs `extendNameSet` getName tc) con
_ -> True
| otherwise
= True
ok_con_args tcs con
= all (ok_arg tcs) (dataConOrigArgTys con `zip` dataConSrcBangs con)
-- NB: dataConSrcBangs gives the *user* request;
-- We'd get a black hole if we used dataConImplBangs
attempt_unpack (HsSrcBang _ SrcUnpack NoSrcStrict)
= xopt LangExt.StrictData dflags
attempt_unpack (HsSrcBang _ SrcUnpack SrcStrict)
= True
attempt_unpack (HsSrcBang _ NoSrcUnpack SrcStrict)
= True -- Be conservative
attempt_unpack (HsSrcBang _ NoSrcUnpack NoSrcStrict)
= xopt LangExt.StrictData dflags -- Be conservative
attempt_unpack _ = False
{-
Note [Unpack one-wide fields]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The flag UnboxSmallStrictFields ensures that any field that can
(safely) be unboxed to a word-sized unboxed field, should be so unboxed.
For example:
data A = A Int#
newtype B = B A
data C = C !B
data D = D !C
data E = E !()
data F = F !D
data G = G !F !F
All of these should have an Int# as their representation, except
G which should have two Int#s.
However
data T = T !(S Int)
data S = S !a
Here we can represent T with an Int#.
Note [Recursive unboxing]
~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data R = MkR {-# UNPACK #-} !S Int
data S = MkS {-# UNPACK #-} !Int
The representation arguments of MkR are the *representation* arguments
of S (plus Int); the rep args of MkS are Int#. This is all fine.
But be careful not to try to unbox this!
data T = MkT {-# UNPACK #-} !T Int
Because then we'd get an infinite number of arguments.
Here is a more complicated case:
data S = MkS {-# UNPACK #-} !T Int
data T = MkT {-# UNPACK #-} !S Int
Each of S and T must decide independently whether to unpack
and they had better not both say yes. So they must both say no.
Also behave conservatively when there is no UNPACK pragma
data T = MkS !T Int
with -funbox-strict-fields or -funbox-small-strict-fields
we need to behave as if there was an UNPACK pragma there.
But it's the *argument* type that matters. This is fine:
data S = MkS S !Int
because Int is non-recursive.
************************************************************************
* *
Wrapping and unwrapping newtypes and type families
* *
************************************************************************
-}
wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
-- The wrapper for the data constructor for a newtype looks like this:
-- newtype T a = MkT (a,Int)
-- MkT :: forall a. (a,Int) -> T a
-- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a)
-- where CoT is the coercion TyCon associated with the newtype
--
-- The call (wrapNewTypeBody T [a] e) returns the
-- body of the wrapper, namely
-- e `cast` (CoT [a])
--
-- If a coercion constructor is provided in the newtype, then we use
-- it, otherwise the wrap/unwrap are both no-ops
--
-- If the we are dealing with a newtype *instance*, we have a second coercion
-- identifying the family instance with the constructor of the newtype
-- instance. This coercion is applied in any case (ie, composed with the
-- coercion constructor of the newtype or applied by itself).
wrapNewTypeBody tycon args result_expr
= ASSERT( isNewTyCon tycon )
wrapFamInstBody tycon args $
mkCast result_expr (mkSymCo co)
where
co = mkUnbranchedAxInstCo Representational (newTyConCo tycon) args []
-- When unwrapping, we do *not* apply any family coercion, because this will
-- be done via a CoPat by the type checker. We have to do it this way as
-- computing the right type arguments for the coercion requires more than just
-- a spliting operation (cf, TcPat.tcConPat).
unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
unwrapNewTypeBody tycon args result_expr
= ASSERT( isNewTyCon tycon )
mkCast result_expr (mkUnbranchedAxInstCo Representational (newTyConCo tycon) args [])
-- If the type constructor is a representation type of a data instance, wrap
-- the expression into a cast adjusting the expression type, which is an
-- instance of the representation type, to the corresponding instance of the
-- family instance type.
-- See Note [Wrappers for data instance tycons]
wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
wrapFamInstBody tycon args body
| Just co_con <- tyConFamilyCoercion_maybe tycon
= mkCast body (mkSymCo (mkUnbranchedAxInstCo Representational co_con args []))
| otherwise
= body
-- Same as `wrapFamInstBody`, but for type family instances, which are
-- represented by a `CoAxiom`, and not a `TyCon`
wrapTypeFamInstBody :: CoAxiom br -> Int -> [Type] -> [Coercion]
-> CoreExpr -> CoreExpr
wrapTypeFamInstBody axiom ind args cos body
= mkCast body (mkSymCo (mkAxInstCo Representational axiom ind args cos))
wrapTypeUnbranchedFamInstBody :: CoAxiom Unbranched -> [Type] -> [Coercion]
-> CoreExpr -> CoreExpr
wrapTypeUnbranchedFamInstBody axiom
= wrapTypeFamInstBody axiom 0
unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
unwrapFamInstScrut tycon args scrut
| Just co_con <- tyConFamilyCoercion_maybe tycon
= mkCast scrut (mkUnbranchedAxInstCo Representational co_con args []) -- data instances only
| otherwise
= scrut
unwrapTypeFamInstScrut :: CoAxiom br -> Int -> [Type] -> [Coercion]
-> CoreExpr -> CoreExpr
unwrapTypeFamInstScrut axiom ind args cos scrut
= mkCast scrut (mkAxInstCo Representational axiom ind args cos)
unwrapTypeUnbranchedFamInstScrut :: CoAxiom Unbranched -> [Type] -> [Coercion]
-> CoreExpr -> CoreExpr
unwrapTypeUnbranchedFamInstScrut axiom
= unwrapTypeFamInstScrut axiom 0
{-
************************************************************************
* *
\subsection{Primitive operations}
* *
************************************************************************
-}
mkPrimOpId :: PrimOp -> Id
mkPrimOpId prim_op
= id
where
(tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op
ty = mkSpecForAllTys tyvars (mkFunTys arg_tys res_ty)
name = mkWiredInName gHC_PRIM (primOpOcc prim_op)
(mkPrimOpIdUnique (primOpTag prim_op))
(AnId id) UserSyntax
id = mkGlobalId (PrimOpId prim_op) name ty info
info = noCafIdInfo
`setRuleInfo` mkRuleInfo (maybeToList $ primOpRules name prim_op)
`setArityInfo` arity
`setStrictnessInfo` strict_sig
`setInlinePragInfo` neverInlinePragma
`setLevityInfoWithType` res_ty
-- We give PrimOps a NOINLINE pragma so that we don't
-- get silly warnings from Desugar.dsRule (the inline_shadows_rule
-- test) about a RULE conflicting with a possible inlining
-- cf Trac #7287
-- For each ccall we manufacture a separate CCallOpId, giving it
-- a fresh unique, a type that is correct for this particular ccall,
-- and a CCall structure that gives the correct details about calling
-- convention etc.
--
-- The *name* of this Id is a local name whose OccName gives the full
-- details of the ccall, type and all. This means that the interface
-- file reader can reconstruct a suitable Id
mkFCallId :: DynFlags -> Unique -> ForeignCall -> Type -> Id
mkFCallId dflags uniq fcall ty
= ASSERT( noFreeVarsOfType ty )
-- A CCallOpId should have no free type variables;
-- when doing substitutions won't substitute over it
mkGlobalId (FCallId fcall) name ty info
where
occ_str = showSDoc dflags (braces (ppr fcall <+> ppr ty))
-- The "occurrence name" of a ccall is the full info about the
-- ccall; it is encoded, but may have embedded spaces etc!
name = mkFCallName uniq occ_str
info = noCafIdInfo
`setArityInfo` arity
`setStrictnessInfo` strict_sig
`setLevityInfoWithType` ty
(bndrs, _) = tcSplitPiTys ty
arity = count isAnonTyBinder bndrs
strict_sig = mkClosedStrictSig (replicate arity topDmd) topRes
-- the call does not claim to be strict in its arguments, since they
-- may be lifted (foreign import prim) and the called code doesn't
-- necessarily force them. See Trac #11076.
{-
************************************************************************
* *
\subsection{DictFuns and default methods}
* *
************************************************************************
Note [Dict funs and default methods]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dict funs and default methods are *not* ImplicitIds. Their definition
involves user-written code, so we can't figure out their strictness etc
based on fixed info, as we can for constructors and record selectors (say).
NB: See also Note [Exported LocalIds] in Id
-}
mkDictFunId :: Name -- Name to use for the dict fun;
-> [TyVar]
-> ThetaType
-> Class
-> [Type]
-> Id
-- Implements the DFun Superclass Invariant (see TcInstDcls)
-- See Note [Dict funs and default methods]
mkDictFunId dfun_name tvs theta clas tys
= mkExportedLocalId (DFunId is_nt)
dfun_name
dfun_ty
where
is_nt = isNewTyCon (classTyCon clas)
dfun_ty = mkDictFunTy tvs theta clas tys
mkDictFunTy :: [TyVar] -> ThetaType -> Class -> [Type] -> Type
mkDictFunTy tvs theta clas tys
= mkSpecSigmaTy tvs theta (mkClassPred clas tys)
{-
************************************************************************
* *
\subsection{Un-definable}
* *
************************************************************************
These Ids can't be defined in Haskell. They could be defined in
unfoldings in the wired-in GHC.Prim interface file, but we'd have to
ensure that they were definitely, definitely inlined, because there is
no curried identifier for them. That's what mkCompulsoryUnfolding
does. If we had a way to get a compulsory unfolding from an interface
file, we could do that, but we don't right now.
unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that
just gets expanded into a type coercion wherever it occurs. Hence we
add it as a built-in Id with an unfolding here.
The type variables we use here are "open" type variables: this means
they can unify with both unlifted and lifted types. Hence we provide
another gun with which to shoot yourself in the foot.
-}
lazyIdName, unsafeCoerceName, nullAddrName, seqName,
realWorldName, voidPrimIdName, coercionTokenName,
magicDictName, coerceName, proxyName, dollarName, oneShotName,
runRWName, noinlineIdName :: Name
unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId
nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId
seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId
realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId
voidPrimIdName = mkWiredInIdName gHC_PRIM (fsLit "void#") voidPrimIdKey voidPrimId
lazyIdName = mkWiredInIdName gHC_MAGIC (fsLit "lazy") lazyIdKey lazyId
coercionTokenName = mkWiredInIdName gHC_PRIM (fsLit "coercionToken#") coercionTokenIdKey coercionTokenId
magicDictName = mkWiredInIdName gHC_PRIM (fsLit "magicDict") magicDictKey magicDictId
coerceName = mkWiredInIdName gHC_PRIM (fsLit "coerce") coerceKey coerceId
proxyName = mkWiredInIdName gHC_PRIM (fsLit "proxy#") proxyHashKey proxyHashId
dollarName = mkWiredInIdName gHC_BASE (fsLit "$") dollarIdKey dollarId
oneShotName = mkWiredInIdName gHC_MAGIC (fsLit "oneShot") oneShotKey oneShotId
runRWName = mkWiredInIdName gHC_MAGIC (fsLit "runRW#") runRWKey runRWId
noinlineIdName = mkWiredInIdName gHC_MAGIC (fsLit "noinline") noinlineIdKey noinlineId
dollarId :: Id -- Note [dollarId magic]
dollarId = pcMiscPrelId dollarName ty
(noCafIdInfo `setUnfoldingInfo` unf)
where
fun_ty = mkFunTy alphaTy openBetaTy
ty = mkSpecForAllTys [runtimeRep2TyVar, alphaTyVar, openBetaTyVar] $
mkFunTy fun_ty fun_ty
unf = mkInlineUnfoldingWithArity 2 rhs
[f,x] = mkTemplateLocals [fun_ty, alphaTy]
rhs = mkLams [runtimeRep2TyVar, alphaTyVar, openBetaTyVar, f, x] $
App (Var f) (Var x)
------------------------------------------------
proxyHashId :: Id
proxyHashId
= pcMiscPrelId proxyName ty
(noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings]
`setNeverLevPoly` ty )
where
-- proxy# :: forall k (a:k). Proxy# k a
bndrs = mkTemplateKiTyVars [liftedTypeKind] (\ks -> ks)
[k,t] = mkTyVarTys bndrs
ty = mkSpecForAllTys bndrs (mkProxyPrimTy k t)
------------------------------------------------
unsafeCoerceId :: Id
unsafeCoerceId
= pcMiscPrelId unsafeCoerceName ty info
where
info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` mkCompulsoryUnfolding rhs
-- unsafeCoerce# :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep)
-- (a :: TYPE r1) (b :: TYPE r2).
-- a -> b
bndrs = mkTemplateKiTyVars [runtimeRepTy, runtimeRepTy]
(\ks -> map tYPE ks)
[_, _, a, b] = mkTyVarTys bndrs
ty = mkSpecForAllTys bndrs (mkFunTy a b)
[x] = mkTemplateLocals [a]
rhs = mkLams (bndrs ++ [x]) $
Cast (Var x) (mkUnsafeCo Representational a b)
------------------------------------------------
nullAddrId :: Id
-- nullAddr# :: Addr#
-- The reason it is here is because we don't provide
-- a way to write this literal in Haskell.
nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info
where
info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` mkCompulsoryUnfolding (Lit nullAddrLit)
`setNeverLevPoly` addrPrimTy
------------------------------------------------
seqId :: Id -- See Note [seqId magic]
seqId = pcMiscPrelId seqName ty info
where
info = noCafIdInfo `setInlinePragInfo` inline_prag
`setUnfoldingInfo` mkCompulsoryUnfolding rhs
`setNeverLevPoly` ty
inline_prag
= alwaysInlinePragma `setInlinePragmaActivation` ActiveAfter
NoSourceText 0
-- Make 'seq' not inline-always, so that simpleOptExpr
-- (see CoreSubst.simple_app) won't inline 'seq' on the
-- LHS of rules. That way we can have rules for 'seq';
-- see Note [seqId magic]
ty = mkSpecForAllTys [alphaTyVar,betaTyVar]
(mkFunTy alphaTy (mkFunTy betaTy betaTy))
[x,y] = mkTemplateLocals [alphaTy, betaTy]
rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x betaTy [(DEFAULT, [], Var y)])
------------------------------------------------
lazyId :: Id -- See Note [lazyId magic]
lazyId = pcMiscPrelId lazyIdName ty info
where
info = noCafIdInfo `setNeverLevPoly` ty
ty = mkSpecForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
noinlineId :: Id -- See Note [noinlineId magic]
noinlineId = pcMiscPrelId noinlineIdName ty info
where
info = noCafIdInfo `setNeverLevPoly` ty
ty = mkSpecForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy)
oneShotId :: Id -- See Note [The oneShot function]
oneShotId = pcMiscPrelId oneShotName ty info
where
info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` mkCompulsoryUnfolding rhs
ty = mkSpecForAllTys [ runtimeRep1TyVar, runtimeRep2TyVar
, openAlphaTyVar, openBetaTyVar ]
(mkFunTy fun_ty fun_ty)
fun_ty = mkFunTy openAlphaTy openBetaTy
[body, x] = mkTemplateLocals [fun_ty, openAlphaTy]
x' = setOneShotLambda x
rhs = mkLams [ runtimeRep1TyVar, runtimeRep2TyVar
, openAlphaTyVar, openBetaTyVar
, body, x'] $
Var body `App` Var x
runRWId :: Id -- See Note [runRW magic] in this module
runRWId = pcMiscPrelId runRWName ty info
where
info = noCafIdInfo `setInlinePragInfo` neverInlinePragma
`setStrictnessInfo` strict_sig
`setArityInfo` 1
strict_sig = mkClosedStrictSig [strictApply1Dmd] topRes
-- Important to express its strictness,
-- since it is not inlined until CorePrep
-- Also see Note [runRW arg] in CorePrep
-- State# RealWorld
stateRW = mkTyConApp statePrimTyCon [realWorldTy]
-- o
ret_ty = openAlphaTy
-- State# RealWorld -> o
arg_ty = stateRW `mkFunTy` ret_ty
-- (State# RealWorld -> o) -> o
ty = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] $
arg_ty `mkFunTy` ret_ty
--------------------------------------------------------------------------------
magicDictId :: Id -- See Note [magicDictId magic]
magicDictId = pcMiscPrelId magicDictName ty info
where
info = noCafIdInfo `setInlinePragInfo` neverInlinePragma
`setNeverLevPoly` ty
ty = mkSpecForAllTys [alphaTyVar] alphaTy
--------------------------------------------------------------------------------
coerceId :: Id
coerceId = pcMiscPrelId coerceName ty info
where
info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma
`setUnfoldingInfo` mkCompulsoryUnfolding rhs
`setNeverLevPoly` ty
eqRTy = mkTyConApp coercibleTyCon [ liftedTypeKind
, alphaTy, betaTy ]
eqRPrimTy = mkTyConApp eqReprPrimTyCon [ liftedTypeKind
, liftedTypeKind
, alphaTy, betaTy ]
ty = mkSpecForAllTys [alphaTyVar, betaTyVar] $
mkFunTys [eqRTy, alphaTy] betaTy
[eqR,x,eq] = mkTemplateLocals [eqRTy, alphaTy, eqRPrimTy]
rhs = mkLams [alphaTyVar, betaTyVar, eqR, x] $
mkWildCase (Var eqR) eqRTy betaTy $
[(DataAlt coercibleDataCon, [eq], Cast (Var x) (mkCoVarCo eq))]
{-
Note [dollarId magic]
~~~~~~~~~~~~~~~~~~~~~
The only reason that ($) is wired in is so that its type can be
forall (a:*, b:Open). (a->b) -> a -> b
That is, the return type can be unboxed. E.g. this is OK
foo $ True where foo :: Bool -> Int#
because ($) doesn't inspect or move the result of the call to foo.
See Trac #8739.
There is a special typing rule for ($) in TcExpr, so the type of ($)
isn't looked at there, BUT Lint subsequently (and rightly) complains
if sees ($) applied to Int# (say), unless we give it a wired-in type
as we do here.
Note [Unsafe coerce magic]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We define a *primitive*
GHC.Prim.unsafeCoerce#
and then in the base library we define the ordinary function
Unsafe.Coerce.unsafeCoerce :: forall (a:*) (b:*). a -> b
unsafeCoerce x = unsafeCoerce# x
Notice that unsafeCoerce has a civilized (albeit still dangerous)
polymorphic type, whose type args have kind *. So you can't use it on
unboxed values (unsafeCoerce 3#).
In contrast unsafeCoerce# is even more dangerous because you *can* use
it on unboxed things, (unsafeCoerce# 3#) :: Int. Its type is
forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) (a: TYPE r1) (b: TYPE r2). a -> b
Note [seqId magic]
~~~~~~~~~~~~~~~~~~
'GHC.Prim.seq' is special in several ways.
a) In source Haskell its second arg can have an unboxed type
x `seq` (v +# w)
But see Note [Typing rule for seq] in TcExpr, which
explains why we give seq itself an ordinary type
seq :: forall a b. a -> b -> b
and treat it as a language construct from a typing point of view.
b) Its fixity is set in LoadIface.ghcPrimIface
c) It has quite a bit of desugaring magic.
See DsUtils.hs Note [Desugaring seq (1)] and (2) and (3)
d) There is some special rule handing: Note [User-defined RULES for seq]
Note [User-defined RULES for seq]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Roman found situations where he had
case (f n) of _ -> e
where he knew that f (which was strict in n) would terminate if n did.
Notice that the result of (f n) is discarded. So it makes sense to
transform to
case n of _ -> e
Rather than attempt some general analysis to support this, I've added
enough support that you can do this using a rewrite rule:
RULE "f/seq" forall n. seq (f n) = seq n
You write that rule. When GHC sees a case expression that discards
its result, it mentally transforms it to a call to 'seq' and looks for
a RULE. (This is done in Simplify.trySeqRules.) As usual, the
correctness of the rule is up to you.
VERY IMPORTANT: to make this work, we give the RULE an arity of 1, not 2.
If we wrote
RULE "f/seq" forall n e. seq (f n) e = seq n e
with rule arity 2, then two bad things would happen:
- The magical desugaring done in Note [seqId magic] item (c)
for saturated application of 'seq' would turn the LHS into
a case expression!
- The code in Simplify.rebuildCase would need to actually supply
the value argument, which turns out to be awkward.
Note [lazyId magic]
~~~~~~~~~~~~~~~~~~~
lazy :: forall a?. a? -> a? (i.e. works for unboxed types too)
'lazy' is used to make sure that a sub-expression, and its free variables,
are truly used call-by-need, with no code motion. Key examples:
* pseq: pseq a b = a `seq` lazy b
We want to make sure that the free vars of 'b' are not evaluated
before 'a', even though the expression is plainly strict in 'b'.
* catch: catch a b = catch# (lazy a) b
Again, it's clear that 'a' will be evaluated strictly (and indeed
applied to a state token) but we want to make sure that any exceptions
arising from the evaluation of 'a' are caught by the catch (see
Trac #11555).
Implementing 'lazy' is a bit tricky:
* It must not have a strictness signature: by being a built-in Id,
all the info about lazyId comes from here, not from GHC.Base.hi.
This is important, because the strictness analyser will spot it as
strict!
* It must not have an unfolding: it gets "inlined" by a HACK in
CorePrep. It's very important to do this inlining *after* unfoldings
are exposed in the interface file. Otherwise, the unfolding for
(say) pseq in the interface file will not mention 'lazy', so if we
inline 'pseq' we'll totally miss the very thing that 'lazy' was
there for in the first place. See Trac #3259 for a real world
example.
* Suppose CorePrep sees (catch# (lazy e) b). At all costs we must
avoid using call by value here:
case e of r -> catch# r b
Avoiding that is the whole point of 'lazy'. So in CorePrep (which
generate the 'case' expression for a call-by-value call) we must
spot the 'lazy' on the arg (in CorePrep.cpeApp), and build a 'let'
instead.
* lazyId is defined in GHC.Base, so we don't *have* to inline it. If it
appears un-applied, we'll end up just calling it.
Note [noinlineId magic]
~~~~~~~~~~~~~~~~~~~~~~~
noinline :: forall a. a -> a
'noinline' is used to make sure that a function f is never inlined,
e.g., as in 'noinline f x'. Ordinarily, the identity function with NOINLINE
could be used to achieve this effect; however, this has the unfortunate
result of leaving a (useless) call to noinline at runtime. So we have
a little bit of magic to optimize away 'noinline' after we are done
running the simplifier.
'noinline' needs to be wired-in because it gets inserted automatically
when we serialize an expression to the interface format, and we DON'T
want use its fingerprints.
Note [runRW magic]
~~~~~~~~~~~~~~~~~~
Some definitions, for instance @runST@, must have careful control over float out
of the bindings in their body. Consider this use of @runST@,
f x = runST ( \ s -> let (a, s') = newArray# 100 [] s
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s'' )
If we inline @runST@, we'll get:
f x = let (a, s') = newArray# 100 [] realWorld#{-NB-}
(_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
And now if we allow the @newArray#@ binding to float out to become a CAF,
we end up with a result that is totally and utterly wrong:
f = let (a, s') = newArray# 100 [] realWorld#{-NB-} -- YIKES!!!
in \ x ->
let (_, s'') = fill_in_array_or_something a x s'
in freezeArray# a s''
All calls to @f@ will share a {\em single} array! Clearly this is nonsense and
must be prevented.
This is what @runRW#@ gives us: by being inlined extremely late in the
optimization (right before lowering to STG, in CorePrep), we can ensure that
no further floating will occur. This allows us to safely inline things like
@runST@, which are otherwise needlessly expensive (see #10678 and #5916).
While the definition of @GHC.Magic.runRW#@, we override its type in @MkId@
to be open-kinded,
runRW# :: forall (r1 :: RuntimeRep). (o :: TYPE r)
=> (State# RealWorld -> (# State# RealWorld, o #))
-> (# State# RealWorld, o #)
Note [The oneShot function]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the context of making left-folds fuse somewhat okish (see ticket #7994
and Note [Left folds via right fold]) it was determined that it would be useful
if library authors could explicitly tell the compiler that a certain lambda is
called at most once. The oneShot function allows that.
'oneShot' is open kinded, i.e. the type variables can refer to unlifted
types as well (Trac #10744); e.g.
oneShot (\x:Int# -> x +# 1#)
Like most magic functions it has a compulsary unfolding, so there is no need
for a real definition somewhere. We have one in GHC.Magic for the convenience
of putting the documentation there.
It uses `setOneShotLambda` on the lambda's binder. That is the whole magic:
A typical call looks like
oneShot (\y. e)
after unfolding the definition `oneShot = \f \x[oneshot]. f x` we get
(\f \x[oneshot]. f x) (\y. e)
--> \x[oneshot]. ((\y.e) x)
--> \x[oneshot] e[x/y]
which is what we want.
It is only effective if the one-shot info survives as long as possible; in
particular it must make it into the interface in unfoldings. See Note [Preserve
OneShotInfo] in CoreTidy.
Also see https://ghc.haskell.org/trac/ghc/wiki/OneShot.
Note [magicDictId magic]
~~~~~~~~~~~~~~~~~~~~~~~~~
The identifier `magicDict` is just a place-holder, which is used to
implement a primitive that we cannot define in Haskell but we can write
in Core. It is declared with a place-holder type:
magicDict :: forall a. a
The intention is that the identifier will be used in a very specific way,
to create dictionaries for classes with a single method. Consider a class
like this:
class C a where
f :: T a
We are going to use `magicDict`, in conjunction with a built-in Prelude
rule, to cast values of type `T a` into dictionaries for `C a`. To do
this, we define a function like this in the library:
data WrapC a b = WrapC (C a => Proxy a -> b)
withT :: (C a => Proxy a -> b)
-> T a -> Proxy a -> b
withT f x y = magicDict (WrapC f) x y
The purpose of `WrapC` is to avoid having `f` instantiated.
Also, it avoids impredicativity, because `magicDict`'s type
cannot be instantiated with a forall. The field of `WrapC` contains
a `Proxy` parameter which is used to link the type of the constraint,
`C a`, with the type of the `Wrap` value being made.
Next, we add a built-in Prelude rule (see prelude/PrelRules.hs),
which will replace the RHS of this definition with the appropriate
definition in Core. The rewrite rule works as follows:
magicDict @t (wrap @a @b f) x y
---->
f (x `cast` co a) y
The `co` coercion is the newtype-coercion extracted from the type-class.
The type class is obtain by looking at the type of wrap.
-------------------------------------------------------------
@realWorld#@ used to be a magic literal, \tr{void#}. If things get
nasty as-is, change it back to a literal (@Literal@).
voidArgId is a Local Id used simply as an argument in functions
where we just want an arg to avoid having a thunk of unlifted type.
E.g.
x = \ void :: Void# -> (# p, q #)
This comes up in strictness analysis
Note [evaldUnfoldings]
~~~~~~~~~~~~~~~~~~~~~~
The evaldUnfolding makes it look that some primitive value is
evaluated, which in turn makes Simplify.interestingArg return True,
which in turn makes INLINE things applied to said value likely to be
inlined.
-}
realWorldPrimId :: Id -- :: State# RealWorld
realWorldPrimId = pcMiscPrelId realWorldName realWorldStatePrimTy
(noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings]
`setOneShotInfo` stateHackOneShot
`setNeverLevPoly` realWorldStatePrimTy)
voidPrimId :: Id -- Global constant :: Void#
voidPrimId = pcMiscPrelId voidPrimIdName voidPrimTy
(noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings]
`setNeverLevPoly` voidPrimTy)
voidArgId :: Id -- Local lambda-bound :: Void#
voidArgId = mkSysLocal (fsLit "void") voidArgIdKey voidPrimTy
coercionTokenId :: Id -- :: () ~ ()
coercionTokenId -- Used to replace Coercion terms when we go to STG
= pcMiscPrelId coercionTokenName
(mkTyConApp eqPrimTyCon [liftedTypeKind, liftedTypeKind, unitTy, unitTy])
noCafIdInfo
pcMiscPrelId :: Name -> Type -> IdInfo -> Id
pcMiscPrelId name ty info
= mkVanillaGlobalWithInfo name ty info
-- We lie and say the thing is imported; otherwise, we get into
-- a mess with dependency analysis; e.g., core2stg may heave in
-- random calls to GHCbase.unpackPS__. If GHCbase is the module
-- being compiled, then it's just a matter of luck if the definition
-- will be in "the right place" to be in scope.
| ezyang/ghc | compiler/basicTypes/MkId.hs | bsd-3-clause | 64,452 | 0 | 21 | 17,694 | 7,339 | 4,019 | 3,320 | 614 | 6 |
module Mandelbrot.ColoringSpec (main, spec) where
import Test.Hspec
import Test.QuickCheck
import Mandelbrot.Coloring
import Data.Word
main :: IO ()
main = hspec spec
spec :: Spec
spec = parallel $ do
describe "diverseColoring" $ do
it "should produce a zero value for zero input" $
diverseColoring 0 `shouldBe` (0, 0, 0)
it "should produce values that are *8, *16, and *32" $ property
(\x -> diverseColoring x `shouldBe` (fromInteger $ toInteger x * 8 `mod` (maxDepth :: Integer),
fromInteger $ toInteger x * 16 `mod` maxDepth,
fromInteger $ toInteger x * 32 `mod` maxDepth))
it "should wrap all numbers to the range [0, 256)" $ property
(inRange . diverseColoring)
describe "greenColoring" $ do
it "should always have zero for red and blue channels" $ property
(and . ([redZero, blueZero] <*>) . (:[]) . greenColoring)
it "should always have green be the mod of the input with the max depth" $ property
(\x -> (greenValue . greenColoring) x `shouldBe` x `mod` maxDepth)
it "should wrap all numbers to the range [0, 256)" $ property
(inRange . greenColoring)
describe "grayColoring" $ do
it "should always have equal values for the three channels" $ property
(equalChannels . grayColoring)
it "should always have green be the mod of the input with the max depth" $ property
(\x -> (greenValue . greenColoring) x `shouldBe` x `mod` maxDepth)
it "should wrap all numbers to the range [0, 256)" $ property
(inRange . grayColoring)
inRange :: Integral a => (a, a, a) -> Bool
inRange (r, g, b) = zeroToMax r && zeroToMax g && zeroToMax b
zeroToMax :: Integral a => a -> Bool
zeroToMax num = intNum >= 0 && intNum < maxDepth
where intNum = toInteger num
redZero :: (Word8, Word8, Word8) -> Bool
redZero (r, _, _) = r == 0
blueZero :: (Word8, Word8, Word8) -> Bool
blueZero (_, _, b) = b == 0
equalChannels :: (Word8, Word8, Word8) -> Bool
equalChannels (r, g, b) = r == g && g == b
greenValue :: Integral a => (Word8, Word8, Word8) -> a
greenValue (_, g, _) = fromIntegral g
| matt-keibler/mandelbrot | test/Mandelbrot/ColoringSpec.hs | bsd-3-clause | 2,164 | 0 | 20 | 541 | 705 | 375 | 330 | 45 | 1 |
import Math.Operad
import Data.List
a = corolla 1 [1,2]
b = corolla 2 [1,2]
la1 = shuffleCompose 1 [1,2,3] a a
la2 = shuffleCompose 1 [1,3,2] a a
la3 = shuffleCompose 2 [1,2,3] a a
lb1 = shuffleCompose 1 [1,2,3] b b
lb2 = shuffleCompose 1 [1,3,2] b b
lb3 = shuffleCompose 2 [1,2,3] b b
lc1 = shuffleCompose 1 [1,2,3] b a
lc2 = shuffleCompose 1 [1,3,2] b a
lc3 = shuffleCompose 2 [1,2,3] b a
ld1 = shuffleCompose 1 [1,2,3] a b
ld2 = shuffleCompose 1 [1,3,2] a b
ld3 = shuffleCompose 2 [1,2,3] a b
oa1 = oet la1 :: OperadElement Integer Rational RPathPerm
oa2 = oet la2 :: OperadElement Integer Rational RPathPerm
oa3 = oet la3 :: OperadElement Integer Rational RPathPerm
ob1 = oet lb1 :: OperadElement Integer Rational RPathPerm
ob2 = oet lb2 :: OperadElement Integer Rational RPathPerm
ob3 = oet lb3 :: OperadElement Integer Rational RPathPerm
oc1 = oet lc1 :: OperadElement Integer Rational RPathPerm
oc2 = oet lc2 :: OperadElement Integer Rational RPathPerm
oc3 = oet lc3 :: OperadElement Integer Rational RPathPerm
od1 = oet ld1 :: OperadElement Integer Rational RPathPerm
od2 = oet ld2 :: OperadElement Integer Rational RPathPerm
od3 = oet ld3 :: OperadElement Integer Rational RPathPerm
ra = oa1 - oa2 - oa3
rb = ob1 - ob2 - ob3
r1 = oc1 - oc2 - oc3
r2 = od1 - od2 - od3
r3 = oc1 - od1
r4 = oc2 - od2
r5 = oc3 - od3
gens = [ra,rb,r1,r2,r3,r4]
gb0 = gens
gbn0 = stepInitialOperadicBuchberger 4 [] gb0
gb1 = nub $ gb0 ++ gbn0
gbn1 = stepInitialOperadicBuchberger 4 gb0 gbn0
gb2 = nub $ gb1 ++ gbn1
gbn2 = stepInitialOperadicBuchberger 4 gb1 gbn1
main = putStrLn . unlines . map pp $ gbn1 | Dronte/Operads | examples/example.hs | bsd-3-clause | 1,642 | 0 | 7 | 348 | 726 | 392 | 334 | 43 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiWayIf #-}
module Client.VID where
import Control.Lens ((.=), ix, (^.), zoom, use, preuse, (-=), (&), (.~), (-~), (+~))
import Control.Monad (void, liftM, when, unless)
import Data.Char (toLower)
import Data.Maybe (isJust, isNothing, fromJust)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Vector as V
import Game.CVarT
import QuakeRef
import Client.MenuFrameworkS
import Client.ClientStateT
import Client.ClientStaticT
import Client.RefExportT
import Client.VidModeT
import Client.MenuItem
import Client.MenuCommonS
import Render.Renderer
import Sys.KBD
import Types
import QuakeState
import CVarVariables
import QCommon.XCommandT
import Render.VideoMode
import qualified Constants
import qualified Client.Console as Console
import qualified Client.KeyConstants as KeyConstants
import {-# SOURCE #-} qualified Client.Menu as Menu
import {-# SOURCE #-} qualified Game.Cmd as Cmd
import {-# SOURCE #-} qualified QCommon.Com as Com
import qualified QCommon.CVar as CVar
import {-# SOURCE #-} qualified Render.QRenderer as QRenderer
import qualified Sound.S as S
import qualified Sys.IN as IN
resolutions :: V.Vector B.ByteString
resolutions =
V.fromList [ "[320 240 ]"
, "[400 300 ]"
, "[512 384 ]"
, "[640 480 ]"
, "[800 600 ]"
, "[960 720 ]"
, "[1024 768 ]"
, "[1152 864 ]"
, "[1280 1024]"
, "[1600 1200]"
, "[2048 1536]"
, "user mode"
]
yesNoNames :: V.Vector B.ByteString
yesNoNames = V.fromList ["no", "yes"]
init :: Quake ()
init = do
-- Create the video variables so we know how to start the graphics drivers
void $ CVar.get "vid_ref" QRenderer.getPreferredName Constants.cvarArchive
void $ CVar.get "vid_xpos" "3" Constants.cvarArchive
void $ CVar.get "vid_ypos" "22" Constants.cvarArchive
void $ CVar.get "vid_width" "640" Constants.cvarArchive
void $ CVar.get "vid_height" "480" Constants.cvarArchive
void $ CVar.get "vid_fullscreen" "0" Constants.cvarArchive
void $ CVar.get "vid_gamma" "1" Constants.cvarArchive
vidGlobals.vgVidModes.ix 11.vmWidth .= 640
vidGlobals.vgVidModes.ix 11.vmHeight .= 480
-- Add some console commands that we want to handle
Cmd.addCommand "vid_restart" (Just restartF)
-- Disable the 3Dfx splash screen
-- putenv("FX_GLIDE_NO_SPLASH=0");
-- Start the graphics mode and load refresh DLL
checkChanges
{-
============
VID_Restart_f
Console command to re-start the video mode and refresh DLL. We do this
simply by setting the modified flag for the vid_ref variable, which will
cause the entire video mode and refresh DLL to be reset on the next frame.
============
-}
restartF :: XCommandT
restartF =
XCommandT "VID.restartF" (do
vidWidthValue <- liftM (truncate . (^.cvValue)) vidWidthCVar
vidHeightValue <- liftM (truncate . (^.cvValue)) vidHeightCVar
zoom (vidGlobals.vgVidModes.ix 11) $ do
vmWidth .= vidWidthValue
vmHeight .= vidHeightValue
vidRef <- vidRefCVar
CVar.update vidRef { _cvModified = True }
)
{-
============
VID_CheckChanges
This function gets called once just before drawing each frame, and it's sole purpose in life
is to check to see if any of the video mode parameters have changed, and if they have to
update the rendering DLL and/or video mode to match.
============
-}
checkChanges :: Quake ()
checkChanges = do
vd <- use $ globals.gVidDef
globals.gVidDef .= vd { _vdWidth = (vd^.vdNewWidth), _vdHeight = (vd^.vdNewHeight) }
vidRef <- vidRefCVar
when (vidRef^.cvModified) $
S.stopAllSounds
changeRefresh (vidRef^.cvModified)
where changeRefresh :: Bool -> Quake ()
changeRefresh False = return ()
-- refresh has changed
changeRefresh True = do
vidRef <- vidRefCVar
vidFullScreen <- vidFullScreenCVar
CVar.update vidRef { _cvModified = False }
CVar.update vidFullScreen { _cvModified = True }
globals.gCl.csRefreshPrepped .= False
globals.gCls.csDisableScreen .= 1 -- True
loaded <- loadRefresh (vidRef^.cvString) True
unless loaded $ do
let renderer = if (vidRef^.cvString) == QRenderer.getPreferredName
-- try the default renderer as fallback after preferred
then QRenderer.getDefaultName
-- try the preferred renderer as first fallback
else QRenderer.getPreferredName
renderer' <- if (vidRef^.cvString) == QRenderer.getDefaultName
then do
Com.printf "Refresh failed\n"
Just glMode <- CVar.get "gl_mode" "0" 0
if (glMode^.cvValue) /= 0
then do
Com.printf "Trying mode 0\n"
CVar.setValueF "gl_mode" 0
loaded' <- loadRefresh (vidRef^.cvString) False
unless loaded' $
Com.comError Constants.errFatal ("Couldn't fall back to " `B.append` (vidRef^.cvString) `B.append` " refresh!")
else
Com.comError Constants.errFatal ("Couldn't fall back to " `B.append` (vidRef^.cvString) `B.append` " refresh!")
return (vidRef^.cvString)
else return renderer
void $ CVar.set "vid_ref" renderer'
-- drop the console if we fail to load a refresh
keyDest <- use $ globals.gCls.csKeyDest
when (keyDest /= Constants.keyConsole) $
(Console.toggleConsoleF)^.xcCmd -- IMPROVE: catch exception?
globals.gCls.csDisableScreen .= 0 -- False
loadRefresh :: B.ByteString -> Bool -> Quake Bool
loadRefresh name fast = do
refLibActive <- use $ vidGlobals.vgRefLibActive
when refLibActive $ do
Just renderer <- use $ globals.gRenderer
renderer^.rRefExport.reGetKeyboardHandler.kbdClose
IN.shutdown
renderer^.rRefExport.reShutDown
freeRefLib
Com.printf $ "------- Loading " `B.append` name `B.append` " -------\n"
let found = V.elem name QRenderer.getDriverNames
if not found
then do
Com.printf $ "LoadLibrary(\"" `B.append` name `B.append` "\") failed\n"
return False
else do
Com.printf $ "LoadLibrary(\"" `B.append` name `B.append` "\")\n"
let r = QRenderer.getDriver name fast
globals.gRenderer .= r
when (isNothing r) $
Com.comError Constants.errFatal (name `B.append` " can't load but registered")
let Just renderer = r
when ((renderer^.rRefExport.reApiVersion) /= Constants.apiVersion) $ do
freeRefLib
Com.comError Constants.errFatal (name `B.append` " has incompatible api_version")
IN.realINInit
xpos <- liftM (truncate . (^.cvValue)) vidXPosCVar
ypos <- liftM (truncate . (^.cvValue)) vidYPosCVar
ok <- (renderer^.rRefExport.reInit) xpos ypos
if not ok
then do
renderer^.rRefExport.reShutDown
freeRefLib
return False
else do
-- init KBD
renderer^.rRefExport.reGetKeyboardHandler.kbdInit
Com.printf "------------------------------------\n"
vidGlobals.vgRefLibActive .= True
return True
freeRefLib :: Quake ()
freeRefLib = do
r <- use $ globals.gRenderer
when (isJust r) $ do
let Just renderer = r
renderer^.rRefExport.reGetKeyboardHandler.kbdClose
IN.shutdown
globals.gRenderer .= Nothing
vidGlobals.vgRefLibActive .= False
printf :: Int -> B.ByteString -> Quake ()
printf printLevel str =
if printLevel == Constants.printAll
then
Com.printf str
else
Com.dprintf str
menuInit :: Quake ()
menuInit = do
initRefs
setNonExistingCVar "gl_driver" QRenderer.getPreferredName 0
setNonExistingCVar "gl_picmip" "0" 0
setNonExistingCVar "gl_mode" "3" 0
setNonExistingCVar "gl_ext_palettedtexture" "1" Constants.cvarArchive
setNonExistingCVar "gl_swapinterval" "0" Constants.cvarArchive
liftM (truncate . (^.cvValue)) glModeCVar >>= \n ->
modifyRef modeListRef (\v -> v & mlCurValue .~ n)
liftM (^.cvValue) vidFullScreenCVar >>= \fullscreenValue ->
if fullscreenValue /= 0
then do
res <- use $ vidGlobals.vgFSResolutions
menuItem <- readRef modeListRef
let curValue = if (menuItem^.mlCurValue) >= V.length res - 1
then 0
else menuItem^.mlCurValue
modifyRef modeListRef (\v -> v & mlCurValue .~ curValue
& mlItemNames .~ res
)
Just fsModes <- use $ vidGlobals.vgFSModes
vidGlobals.vgModeX .= (fsModes V.! curValue)^.vmWidth
else do
menuItem <- readRef modeListRef
let curValue = if (menuItem^.mlCurValue) >= V.length resolutions - 1
then 0
else menuItem^.mlCurValue
modifyRef modeListRef (\v -> v & mlCurValue .~ curValue
& mlItemNames .~ resolutions
)
Just width <- preuse $ vidGlobals.vgVidModes.ix curValue.vmWidth
vidGlobals.vgModeX .= width
setNonExistingCVar "viewsize" "100" Constants.cvarArchive
liftM (^.cvValue) viewSizeCVar >>= \v -> do
let intv = truncate (v / 10) :: Int
modifyRef screenSizeSliderRef (\v -> v & msCurValue .~ fromIntegral intv)
use (vidGlobals.vgDrivers) >>= \drivers -> do
str <- liftM (^.cvString) vidRefCVar
case V.findIndex (== str) drivers of
Nothing -> return ()
Just idx -> modifyRef refListRef (\v -> v & mlCurValue .~ idx)
use (globals.gVidDef.vdWidth) >>= \width -> do
let widthF = fromIntegral width :: Float
modifyRef openGLMenuRef (\v -> v & mfX .~ truncate (widthF * 0.5)
& mfNItems .~ 0
)
use (vidGlobals.vgRefs) >>= \refs -> do
modifyRef refListRef (\v -> v & mlGeneric.mcType .~ Constants.mtypeSpinControl
& mlGeneric.mcName .~ Just "driver"
& mlGeneric.mcX .~ 0
& mlGeneric.mcY .~ 0
& mlGeneric.mcCallback .~ Just (vidGlobals.vgCurrentMenu .= Just openGLMenuRef)
& mlItemNames .~ refs
)
modifyRef modeListRef (\v -> v & mlGeneric.mcType .~ Constants.mtypeSpinControl
& mlGeneric.mcName .~ Just "video mode"
& mlGeneric.mcX .~ 0
& mlGeneric.mcY .~ 10
)
modifyRef screenSizeSliderRef (\v -> v & msGeneric.mcType .~ Constants.mtypeSlider
& msGeneric.mcX .~ 0
& msGeneric.mcY .~ 20
& msGeneric.mcName .~ Just "screen size"
& msMinValue .~ 3
& msMaxValue .~ 12
& msGeneric.mcCallback .~ Just screenSizeCallback
)
liftM (^.cvValue) vidGammaCVar >>= \gammaValue ->
modifyRef brightnessSliderRef (\v -> v & msGeneric.mcType .~ Constants.mtypeSlider
& msGeneric.mcX .~ 0
& msGeneric.mcY .~ 30
& msGeneric.mcName .~ Just "brightness"
& msMinValue .~ 5
& msMaxValue .~ 13
& msCurValue .~ (1.3 - gammaValue + 0.5) * 10
& msGeneric.mcCallback .~ Just brightnessCallback
)
liftM (truncate . (^.cvValue)) vidFullScreenCVar >>= \fullscreenValue ->
modifyRef fsBoxRef (\v -> v & mlGeneric.mcType .~ Constants.mtypeSpinControl
& mlGeneric.mcX .~ 0
& mlGeneric.mcY .~ 40
& mlGeneric.mcName .~ Just "fullscreen"
& mlItemNames .~ yesNoNames
& mlCurValue .~ fullscreenValue
& mlGeneric.mcCallback .~ Just fsBoxCallback
)
liftM (^.cvValue) glPicMipCVar >>= \picmipValue ->
modifyRef tqSliderRef (\v -> v & msGeneric.mcType .~ Constants.mtypeSlider
& msGeneric.mcX .~ 0
& msGeneric.mcY .~ 60
& msGeneric.mcName .~ Just "texture quality"
& msMinValue .~ 0
& msMaxValue .~ 3
& msCurValue .~ 3 - picmipValue
)
liftM (truncate . (^.cvValue)) glExtPalettedTextureCVar >>= \palettedTextureValue ->
modifyRef palettedTextureBoxRef (\v -> v & mlGeneric.mcType .~ Constants.mtypeSpinControl
& mlGeneric.mcX .~ 0
& mlGeneric.mcY .~ 70
& mlGeneric.mcName .~ Just "8-bit textures"
& mlItemNames .~ yesNoNames
& mlCurValue .~ palettedTextureValue
)
liftM (truncate . (^.cvValue)) glSwapIntervalCVar >>= \swapIntervalValue ->
modifyRef vSyncBoxRef (\v -> v & mlGeneric.mcType .~ Constants.mtypeSpinControl
& mlGeneric.mcX .~ 0
& mlGeneric.mcY .~ 80
& mlGeneric.mcName .~ Just "sync every frame"
& mlItemNames .~ yesNoNames
& mlCurValue .~ swapIntervalValue
)
modifyRef defaultsActionRef (\v -> v & maGeneric.mcType .~ Constants.mtypeAction
& maGeneric.mcName .~ Just "reset to default"
& maGeneric.mcX .~ 0
& maGeneric.mcY .~ 100
& maGeneric.mcCallback .~ Just menuInit
)
modifyRef applyActionRef (\v -> v & maGeneric.mcType .~ Constants.mtypeAction
& maGeneric.mcName .~ Just "apply"
& maGeneric.mcX .~ 0
& maGeneric.mcY .~ 110
& maGeneric.mcCallback .~ Just applyChanges
)
Menu.menuAddItem openGLMenuRef (MenuListRef refListRef)
Menu.menuAddItem openGLMenuRef (MenuListRef modeListRef)
Menu.menuAddItem openGLMenuRef (MenuSliderRef screenSizeSliderRef)
Menu.menuAddItem openGLMenuRef (MenuSliderRef brightnessSliderRef)
Menu.menuAddItem openGLMenuRef (MenuListRef fsBoxRef)
Menu.menuAddItem openGLMenuRef (MenuSliderRef tqSliderRef)
Menu.menuAddItem openGLMenuRef (MenuListRef palettedTextureBoxRef)
Menu.menuAddItem openGLMenuRef (MenuListRef vSyncBoxRef)
Menu.menuAddItem openGLMenuRef (MenuActionRef defaultsActionRef)
Menu.menuAddItem openGLMenuRef (MenuActionRef applyActionRef)
Menu.menuCenter openGLMenuRef
modifyRef openGLMenuRef (\v -> v & mfX -~ 8)
where setNonExistingCVar :: B.ByteString -> B.ByteString -> Int -> Quake ()
setNonExistingCVar name value flags =
CVar.findVar name >>= \v ->
when (isNothing v) $
void $ CVar.get name value flags
screenSizeCallback :: Quake ()
screenSizeCallback = do
menuItem <- readRef screenSizeSliderRef
CVar.setValueF "viewsize" ((menuItem^.msCurValue) * 10)
brightnessCallback :: Quake ()
brightnessCallback = do
str <- liftM ((BC.map toLower) . (^.cvString)) vidRefCVar
when (str == "soft" || str == "softx") $ do
menuItem <- readRef brightnessSliderRef
CVar.setValueF "vid_gamma" ((0.8 - ((menuItem^.msCurValue) / 10 - 0.5)) + 0.5)
fsBoxCallback :: Quake ()
fsBoxCallback = do
io (putStrLn "VID.vgFSBox callback") >> undefined -- TODO
applyChanges :: Quake ()
applyChanges = do
brightnessSlider <- readRef brightnessSliderRef
tqSlider <- readRef tqSliderRef
fsBox <- readRef fsBoxRef
vSyncBox <- readRef vSyncBoxRef
palettedTextureBox <- readRef palettedTextureBoxRef
modeList <- readRef modeListRef
refList <- readRef refListRef
-- invert sense so greater = brighter, and scale to a range of 0.5 to 1.3
--
-- the original was modified, because on CRTs it was too dark.
-- the slider range is [5; 13]
-- gamma: [1.1; 0.7]
let gamma = 0.4 - ((brightnessSlider^.msCurValue) / 20.0 - 0.25) + 0.7
-- modulate: [1.0; 2.6]
modulate = (brightnessSlider^.msCurValue) * 0.2
CVar.setValueF "vid_gamma" gamma
CVar.setValueF "gl_modulate" modulate
CVar.setValueF "gl_picmip" (3 - (tqSlider^.msCurValue))
CVar.setValueI "vid_fullscreen" (fsBox^.mlCurValue)
CVar.setValueI "gl_swapinterval" (vSyncBox^.mlCurValue)
-- set always true because of vid_ref or mode changes
glSwapIntervalCVar >>= \cvar -> CVar.update cvar { _cvModified = True }
CVar.setValueI "gl_ext_palettedtexture" (palettedTextureBox^.mlCurValue)
CVar.setValueI "gl_mode" (modeList^.mlCurValue)
drivers <- use $ vidGlobals.vgDrivers
CVar.set "vid_ref" (drivers V.! (refList^.mlCurValue))
CVar.set "gl_driver" (drivers V.! (refList^.mlCurValue))
glDriverModified <- liftM (^.cvModified) glDriverCVar
when glDriverModified $ do
vidRefCVar >>= \cvar -> CVar.update cvar { _cvModified = True }
Menu.forceMenuOff
initRefs :: Quake ()
initRefs = do
let drivers = QRenderer.getDriverNames
vidGlobals.vgDrivers .= drivers
vidGlobals.vgRefs .= V.map constructRef drivers
where constructRef :: B.ByteString -> B.ByteString
constructRef driver =
let a = "[OpenGL " `B.append` driver
b = if B.length a < 16 then a `B.append` BC.replicate (16 - B.length a) ' ' else a
c = b `B.append` "]"
in c
getModeInfo :: Int -> Quake (Maybe (Int, Int))
getModeInfo mode = do
use (vidGlobals.vgFSModes) >>= \v ->
when (isNothing v) initModeList
fullscreenValue <- liftM (^.cvValue) vidFullScreenCVar
modes <- if fullscreenValue /= 0
then liftM fromJust (use $ vidGlobals.vgFSModes)
else use $ vidGlobals.vgVidModes
if mode < 0 || mode > V.length modes
then return Nothing
else do
let m = modes V.! mode
return $ Just (m^.vmWidth, m^.vmHeight)
initModeList :: Quake ()
initModeList = do
Just renderer <- use $ globals.gRenderer
modes <- renderer^.rRefExport.reGetModeList
let (fsResolutions, fsModes) = V.unzip $ V.imap parseMode modes
vidGlobals.vgFSModes .= Just fsModes
vidGlobals.vgFSResolutions .= fsResolutions
where parseMode :: Int -> VideoMode -> (B.ByteString, VidModeT)
parseMode idx mode =
let width = getVideoModeWidth mode
height = getVideoModeHeight mode
widthS = BC.pack (show width)
heightS = BC.pack (show height)
res = "[" `B.append` widthS `B.append` " " `B.append` heightS
len = B.length res
res' = (if len < 10 then res `B.append` BC.replicate (10 - len) ' ' else res) `B.append` "]"
m = "Mode " `B.append` BC.pack (show idx) `B.append` widthS `B.append` "x" `B.append` heightS
in (res', VidModeT m width height idx)
newWindow :: Int -> Int -> Quake ()
newWindow width height =
zoom (globals.gVidDef) $ do
vdNewWidth .= width
vdNewHeight .= height
shutdown :: Quake ()
shutdown = do
refLibActive <- use $ vidGlobals.vgRefLibActive
when refLibActive $ do
Just renderer <- use $ globals.gRenderer
renderer^.rRefExport.reGetKeyboardHandler.kbdClose
IN.shutdown
renderer^.rRefExport.reShutDown
freeRefLib
menuDraw :: XCommandT
menuDraw =
XCommandT "VID.menuDraw" (do
vidGlobals.vgCurrentMenu .= Just openGLMenuRef
-- draw the banner
Just renderer <- use $ globals.gRenderer
vidDef' <- use $ globals.gVidDef
Just (width, _) <- (renderer^.rRefExport.reDrawGetPicSize) "m_banner_video"
(renderer^.rRefExport.reDrawPic) ((vidDef'^.vdWidth) `div` 2 - width `div` 2) ((vidDef'^.vdHeight) `div` 2 - 110) "m_banner_video"
-- move cursor to a reasonable starting position
Menu.menuAdjustCursor openGLMenuRef 1
-- draw the menu
Menu.menuDraw openGLMenuRef
)
menuKey :: KeyFuncT
menuKey =
KeyFuncT "VID.menuKey" (\key -> do
Just menuRef <- use $ vidGlobals.vgCurrentMenu
let sound = Just "misc/menu1.wav"
if | key == KeyConstants.kEscape -> do
Menu.popMenu
return Nothing
| key == KeyConstants.kUpArrow -> do
modifyRef menuRef (\v -> v & mfCursor -~ 1)
Menu.menuAdjustCursor menuRef (-1)
return sound
| key == KeyConstants.kDownArrow -> do
modifyRef menuRef (\v -> v & mfCursor +~ 1)
Menu.menuAdjustCursor menuRef 1
return sound
| key == KeyConstants.kLeftArrow -> do
Menu.menuSlideItem menuRef (-1)
return sound
| key == KeyConstants.kRightArrow -> do
Menu.menuSlideItem menuRef 1
return sound
| key == KeyConstants.kEnter -> do
Menu.menuSelectItem menuRef
return sound
| otherwise ->
return sound
)
| ksaveljev/hake-2 | src/Client/VID.hs | bsd-3-clause | 24,058 | 0 | 29 | 8,996 | 5,666 | 2,841 | 2,825 | -1 | -1 |
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
--------------------------------------------------------------------
-- |
-- Executable : mbox-partition
-- Copyright : (c) Nicolas Pouillard 2008, 2009, 2011
-- License : BSD3
--
-- Maintainer: Nicolas Pouillard <[email protected]>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
import Control.Applicative
import Control.Lens hiding (inside,outside)
import Codec.Mbox (Mbox(..),Direction(..),parseMboxFile,mboxMsgBody,showMboxMessage)
import Email (Email(..),emailFields,readEmail)
import Text.ParserCombinators.Parsec.Rfc2822 (Field(MessageID))
import Data.Maybe (listToMaybe, fromMaybe)
import Data.Set (fromList, member)
import qualified Data.ByteString.Lazy.Char8 as C
import System.Environment (getArgs)
import System.Console.GetOpt
import System.IO (Handle, IOMode(AppendMode), stderr, openFile, hPutStr, hFlush, hClose)
progressStr :: String -> IO ()
progressStr s = hPutStr stderr ('\r':s) >> hFlush stderr
progress_ :: [IO a] -> IO ()
progress_ = (>> progressStr "Finished\n") . sequence_ . zipWith (>>) (map (progressStr . show) [(1::Int)..])
-- should be in ByteString
hPutStrLnC :: Handle -> C.ByteString -> IO ()
hPutStrLnC h s = C.hPut h s >> C.hPut h (C.pack "\n")
data Settings = Settings { _help :: Bool
, _msgids :: String
, _inside :: String
, _outside :: String
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
partitionMbox :: Settings -> [String] -> IO ()
partitionMbox opts mboxfiles = do
msgids' <- (fromList . C.lines) <$> C.readFile (opts^.msgids)
let predicate = fromMaybe False . fmap (`member` msgids') . emailMsgId . readEmail . view mboxMsgBody
hinside <- openFile (opts^.inside) AppendMode
houtside <- openFile (opts^.outside) AppendMode
let onFile fp =
progress_ . map (\m -> hPutStrLnC (if predicate m then hinside else houtside) (showMboxMessage m))
. mboxMessages
=<< parseMboxFile Forward fp
mapM_ onFile mboxfiles
mapM_ hClose [hinside, houtside]
emailMsgId :: Email -> Maybe C.ByteString
emailMsgId m = listToMaybe [ removeAngles $ C.pack i | MessageID i <- m^.emailFields ]
removeAngles :: C.ByteString -> C.ByteString
removeAngles = C.takeWhile (/='>') . C.dropWhile (=='<')
defaultSettings :: Settings
defaultSettings = Settings { _help = False
, _msgids = ""
, _inside = ""
, _outside = "" }
usage :: String -> a
usage msg = error (msg ++ "\n" ++ usageInfo header options)
where header = "Usage: mbox-partition [OPTION...] <mbox-file>*"
options :: [OptDescr Flag]
options =
[ Option "m" ["msgids"] (ReqArg (set msgids) "FILE") "A file with message-IDs"
, Option "i" ["inside"] (ReqArg (set inside) "FILE") "Will receive messages referenced by the 'msgids' file"
, Option "o" ["outside"] (ReqArg (set outside) "FILE") "Will receive messages *NOT* referenced by the 'msgids' file"
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
case (nonopts, errs) of
_ | opts^.help -> usage ""
(_, _:_) -> usage (concat errs)
([], _) -> usage "Too few arguments (mbox-file missing)"
(mboxfiles, _) -> partitionMbox opts mboxfiles
| np/mbox-tools | mbox-partition.hs | bsd-3-clause | 3,571 | 0 | 19 | 762 | 1,092 | 593 | 499 | 64 | 4 |
module Two (two) where
import Data.List
import Data.List.Split
import Control.Monad
up :: Integer -> Integer
up n
| n > 3 = n - 3
| otherwise = n
down :: Integer -> Integer
down n
| n < 7 = n + 3
| otherwise = n
right :: Integer -> Integer
right n
| n `mod` 3 == 0 = n
| otherwise = n + 1
left :: Integer -> Integer
left n
| (n + 2) `mod` 3 == 0 = n
| otherwise = n - 1
move :: Char -> Integer -> Integer
move 'U' = up
move 'D' = down
move 'R' = right
move 'L' = left
move _ = undefined
walk :: [String] -> Integer -> [Integer]
walk [] _ = []
walk (l:ls) s = e : walk ls e
where e = foldl' (flip move) s l
-- this is kind of a weird way to structure part b
-- but it's better than defining every transform piecewise for every freaking one
newtype Coord = Coord (Integer, Integer)
instance Show Coord where
show (Coord (0, 2)) = "1"
show (Coord (-1, 1)) = "2"
show (Coord (0, 1)) = "3"
show (Coord (1, 1)) = "4"
show (Coord (-2, 0)) = "5"
show (Coord (-1, 0)) = "6"
show (Coord (0, 0)) = "7"
show (Coord (1, 0)) = "8"
show (Coord (2, 0)) = "9"
show (Coord (-1, -1)) = "A"
show (Coord (0, -1)) = "B"
show (Coord (1, -1)) = "C"
show (Coord (0, -2)) = "D"
dist :: Coord -> Integer
dist (Coord (x, y)) = abs x + abs y
move' :: Char -> Coord -> Coord
move' c (Coord (x, y)) = if dist x'y' > 2 then Coord (x, y) else x'y'
where x'y' = case c of
'U' -> Coord (x, y + 1)
'D' -> Coord (x, y - 1)
'R' -> Coord (x + 1, y)
'L' -> Coord (x - 1, y)
walk' :: [String] -> Coord -> [Coord]
walk' [] _ = []
walk' (l:ls) s = e : walk' ls e
where e = foldl' (flip move') s l
two = do
input <- init <$> (splitOn "\n") <$> readFile "data/two.txt"
--let input = ["ULL", "RRDDD", "LURDL", "UUUUD"]
let result1 = walk input 5
putStrLn $ "part A: " ++ show result1
let result2 = walk' input (Coord (-2, 0))
putStrLn $ "part B: " ++ show result2
| alicemaz/advent2016 | Two.hs | bsd-3-clause | 2,050 | 0 | 14 | 644 | 1,000 | 524 | 476 | 64 | 5 |
{-# LANGUAGE Rank2Types, ScopedTypeVariables, LambdaCase #-}
module Data.Boombox.ByteString where
import qualified Data.ByteString as B
import qualified Data.ByteString.Internal as B
import Foreign.ForeignPtr
import Foreign.Ptr
import Foreign.Storable
import Control.Monad
import Control.Monad.Trans.Class
import Data.Boombox.Player
import Data.Boombox.Boombox
import Data.Boombox.Tape
import Data.Functor.Identity
import System.IO.Unsafe
awaitStorable :: forall w m a. (MonadPlus m, Storable a) => PlayerT w B.ByteString m a
awaitStorable = do
B.PS fptr ofs len <- await
let ofs' = ofs + sizeOf (undefined :: a)
lift $ guard $ ofs' <= len
leftover $ B.PS fptr ofs' len
return $! unsafePerformIO $ withForeignPtr fptr $ peek . castPtr
awaitByteString :: Int -> PlayerT w B.ByteString m B.ByteString
awaitByteString n = do
bs <- await
let (b, bs') = B.splitAt n bs
leftover bs'
return b
lines :: Recorder w Identity IO (Maybe B.ByteString) (Maybe B.ByteString)
lines = Tape (go []) where
go ls = await >>= \case
Just c -> do
let (l, r) = B.break (==10) c
if B.null r
then go (l : ls)
else return (Just $ B.concat $ reverse $ l : ls, pure
$ Tape $ leftover (Just (B.tail r)) >> go [])
Nothing -> return $ case ls of
[] -> (Nothing, pure $ Tape $ go [])
_ -> (Just (B.concat (reverse ls)), pure $ Tape $ go [])
| fumieval/boombox | src/Data/Boombox/ByteString.hs | bsd-3-clause | 1,392 | 0 | 23 | 298 | 558 | 290 | 268 | 39 | 4 |
module Ntha.Core.Ast where
import Ntha.Type.Type
import Data.List (intercalate)
import Data.Maybe (fromMaybe)
import qualified Data.Map as M
import qualified Text.PrettyPrint as PP
type EName = String -- variable name
type EPath = String
type EField = String
type EIndent = Int
type TypeVariable = Type -- just for documentation
data Expr = EVar EName
| EAccessor Expr EField
| ENum Int
| EStr String
| EChar Char
| EBool Bool
| EList [Expr]
| ETuple [Expr]
| ERecord (M.Map EField Expr)
| EUnit
| ELambda [Named] (Maybe Type) [Expr]
| EApp Expr Expr
| EIf Expr [Expr] [Expr]
| EPatternMatching Expr [Case]
| ELetBinding Pattern Expr [Expr]
| EDestructLetBinding Pattern [Pattern] [Expr]
| EDataDecl EName Type [TypeVariable] [TypeConstructor]
| ETypeSig EName Type -- explicit type annotation
| EImport EPath
| EProgram [Expr]
deriving (Eq, Ord)
isImport :: Expr -> Bool
isImport expr = case expr of
EImport _ -> True
_ -> False
-- for do block desuger to bind
data Bind = Bind EName Expr
| Return Expr
| Single Expr
-- for cond desuger to if
data Clause = Clause Expr Expr
| Else Expr
data TypeConstructor = TypeConstructor EName [Type]
deriving (Eq, Ord)
data Named = Named EName (Maybe Type)
deriving (Eq, Ord)
data Pattern = WildcardPattern
| IdPattern EName
| NumPattern Int
| BoolPattern Bool
| CharPattern Char
| TuplePattern [Pattern]
| TConPattern EName [Pattern]
deriving (Eq, Ord)
data Case = Case Pattern [Expr]
deriving (Eq, Ord)
-- temp structure for parser
data EVConArg = EVCAVar EName
| EVCAOper EName [EName]
| EVCAList EVConArg
| EVCATuple [EVConArg]
deriving (Show, Eq, Ord)
data EVConstructor = EVConstructor EName [EVConArg]
deriving (Show, Eq, Ord)
substName :: M.Map EName EName -> Expr -> Expr
substName subrule (EVar name) = EVar $ fromMaybe name $ M.lookup name subrule
substName subrule (EAccessor expr field) = EAccessor (substName subrule expr) field
substName subrule (EList exprs) = EList $ map (substName subrule) exprs
substName subrule (ETuple exprs) = ETuple $ map (substName subrule) exprs
substName subrule (ERecord pairs) = ERecord $ M.map (substName subrule) pairs
substName subrule (ELambda nameds t exprs) = ELambda newNames t newExprs
where
newNames = map (\(Named name t') -> Named (fromMaybe name $ M.lookup name subrule) t') nameds
newExprs = map (substName subrule) exprs
substName subrule (EApp fn arg) = EApp (substName subrule fn) (substName subrule arg)
substName subrule (EIf cond thenInstrs elseInstrs) = EIf newCond newThenInstrs newElseInstrs
where
newCond = substName subrule cond
newThenInstrs = map (substName subrule) thenInstrs
newElseInstrs = map (substName subrule) elseInstrs
substName subrule (EPatternMatching expr cases) = EPatternMatching newExpr newCases
where
newCases = map (\(Case pat exprs) -> Case pat (map (substName subrule) exprs)) cases
newExpr = substName subrule expr
substName subrule (ELetBinding pat expr exprs) = ELetBinding pat (substName subrule expr) $ map (substName subrule) exprs
substName _ e = e
tab :: EIndent -> String
tab i = intercalate "" $ take i $ repeat "\t"
stringOfNamed :: Named -> String
stringOfNamed (Named name t) = name ++ case t of
Just t' -> ":" ++ show t'
Nothing -> ""
stringofNameds :: [Named] -> String
stringofNameds = unwords . (map stringOfNamed)
stringOfExpr :: Expr -> String
stringOfExpr e = case e of
EApp fn arg -> "<" ++ show fn ++ ">(" ++ show arg ++ ")"
ELambda params annoT body -> "λ" ++ stringofNameds params ++ b
where b = (case annoT of
Just annoT' -> " : " ++ show annoT'
Nothing -> "")
++ " = \n" ++ intercalate "" (map (\instr -> "\t" ++ show instr ++ "\n") body)
EIf cond thenInstrs elseInstrs -> "if " ++ show cond ++ " then \n" ++ th ++ "else \n" ++ el
where stringOfInstrs instrs = intercalate "" $ map (\instr -> "\t" ++ show instr ++ "\n") instrs
th = stringOfInstrs thenInstrs
el = stringOfInstrs elseInstrs
EProgram instrs -> intercalate "" $ map (\instr -> show instr ++ "\n") instrs
_ -> reprOfExpr 0 e
stringOfCase :: EIndent -> Case -> String
stringOfCase i (Case pat outcomes) = "\n" ++ tab i ++ show pat ++ " ⇒ " ++ show outcomes
stringOfCases :: EIndent -> [Case] -> String
stringOfCases i cases = intercalate "" (map (stringOfCase i) cases)
reprOfExpr :: EIndent -> Expr -> String
reprOfExpr i e = case e of
EVar n -> tab i ++ n
EAccessor e' f -> tab i ++ reprOfExpr 0 e' ++ "." ++ f
ENum v -> tab i ++ show v
EStr v -> tab i ++ v
EChar v -> tab i ++ [v]
EBool v -> tab i ++ show v
EUnit -> tab i ++ "()"
EList es -> tab i ++ show es
ETuple es -> "(" ++ intercalate "," (map (reprOfExpr 0) es) ++ ")"
ERecord pairs -> "{" ++ intercalate "," (M.elems $ M.mapWithKey (\f v -> f ++ ": " ++ reprOfExpr 0 v) pairs) ++ "}"
EApp _ _ -> tab i ++ show e
ELambda params annoT body -> tab i ++ "λ" ++ stringofNameds params ++ b
where b = (case annoT of
Just annoT' -> " : " ++ show annoT'
Nothing -> "")
++ " = \n" ++ intercalate "" (map (\instr -> "\t" ++ reprOfExpr (i + 1) instr ++ "\n") body)
EIf cond thenInstrs elseInstrs -> tab i ++ "if " ++ show cond ++ " then \n" ++ th ++ tab i ++ "else \n" ++ el
where stringOfInstrs instrs = intercalate "" $ map (\instr -> "\t" ++ reprOfExpr (i + 1) instr ++ "\n") instrs
th = stringOfInstrs thenInstrs
el = stringOfInstrs elseInstrs
EPatternMatching input cases -> tab i ++ "match " ++ show input ++ stringOfCases i cases
EDataDecl name _ tvars tcons -> tab i ++ "data " ++ name ++ " " ++ unwords (map show tvars) ++ " = " ++ cs
where scons = (map (\(TypeConstructor name' types) ->
name' ++ case types of
[] -> ""
_ -> " " ++ unwords (map show types)) tcons)
cs = intercalate " | " scons
EDestructLetBinding main args instrs -> tab i ++ "let " ++ show main ++ " " ++ unwords (map show args) ++ " = \n" ++ is
where is = intercalate "" (map (\instr -> reprOfExpr (i + 1) instr ++ "\n") instrs)
ELetBinding main def body -> tab i ++ "let " ++ show main ++ " " ++ show def ++ " in " ++ intercalate "\n" (map show body)
ETypeSig name t -> tab i ++ "(" ++ name ++ " : " ++ show t ++ ")"
EImport path -> "import " ++ path
EProgram instrs -> intercalate "" $ map (\instr -> reprOfExpr i instr ++ "\n") instrs
instance Show Expr where
showsPrec _ x = shows $ PP.text $ stringOfExpr x
instance Show Pattern where
show WildcardPattern = "_"
show (NumPattern val) = "pint→" ++ show val
show (BoolPattern val) = "pbool→" ++ show val
show (CharPattern val) = "pchar→" ++ show val
show (IdPattern name) = "'" ++ name ++ "'"
show (TuplePattern pattens) = "(" ++ intercalate "," (map show pattens) ++ ")"
show (TConPattern name pattens) = name ++ " " ++ show pattens
| zjhmale/Ntha | src/Ntha/Core/Ast.hs | bsd-3-clause | 7,522 | 0 | 21 | 2,177 | 2,731 | 1,378 | 1,353 | 152 | 22 |
module Main where
import Log
import LogAnalysis
import Language.Haskell.Interpreter
demort :: String -> String -> IO ()
demort cmd ('(':stresult) = demort cmd (init stresult)
demort cmd stresult = putStrLn (cmd ++ " = " ++ stresult)
demor :: String -> String -> IO ()
demor cmd sresult = demort cmd (drop 6 sresult)
imports = ["Prelude","Log","LogAnalysis"]
demoLogm :: String -> IO ()
demoLogm cmd = do
result <- runInterpreter $ setImports imports >> interpret cmd (as :: LogMessage)
demor cmd (show result)
demoLogs :: String -> IO ()
demoLogs cmd = do
result <- runInterpreter $ setImports imports >> interpret cmd (as :: [LogMessage])
demor cmd (show result)
demoTree :: String -> IO ()
demoTree cmd = do
result <- runInterpreter $ setImports imports >> interpret cmd (as :: MessageTree)
demor cmd (show result)
demoStrs :: String -> IO ()
demoStrs cmd = do
result <- runInterpreter $ setImports imports >> interpret cmd (as :: [String])
demor cmd (show result)
main :: IO ()
main = do
putStrLn "CIS194 Homework 2"
putStrLn "\nExercise 1"
demoLogm "parseMessage \"E 2 562 help help\" "
demoLogm "parseMessage \"I 29 la la la\" "
demoLogm "parseMessage \"This is not in the right format\" "
putStrLn "\nExercise 2"
demoTree "insert (parseMessage \"I 29 la la la\") Leaf "
demoTree "insert (parseMessage \"unkown message\") Leaf "
demoTree "insert (parseMessage \"I 1 one\") (insert (parseMessage \"I 2 two\") Leaf) "
demoTree "insert (parseMessage \"I 2 two\") (insert (parseMessage \"I 1 one\") Leaf) "
putStrLn "\nExercise 3"
demoTree "build [ (parseMessage \"I 1 one\"), (parseMessage \"I 2 two\") ] "
demoTree "build [ (parseMessage \"I 2 two\"), (parseMessage \"I 1 one\") ] "
putStrLn "\nExercise 4"
demoLogs "inOrder $ build [ (parseMessage \"I 1 one\"), (parseMessage \"I 2 two\") ] "
demoLogs "inOrder $ build [ (parseMessage \"I 2 two\"), (parseMessage \"I 1 one\") ] "
putStrLn "\nExercise 5"
demoStrs "whatWentWrong [ (parseMessage \"I 1 one\"), (parseMessage \"I 2 two\") ] "
| tessmero/CIS194-HW02 | app/Main.hs | bsd-3-clause | 2,255 | 0 | 11 | 587 | 530 | 247 | 283 | 46 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Main where
import System.FilePath
import System.Console.CmdArgs
import GitRunner
import G4Release
data CmdOptions = AboutIrt {
}
| G4Release { gitRepo :: String
, ignoreGitModifications :: Bool
, g4options :: [G4ReleaseOption]
, g4Tree :: String
}
| G4AblaRelease { gitRepo :: String
, ignoreGitModifications :: Bool
, g4options :: [G4ReleaseOption]
, g4Tree :: String
}
deriving (Show, Eq, Data, Typeable)
data SourceConfig = SourceConfig { rootDir :: FilePath }
data SourceTransform = FileTransform { transformFileName :: FilePath
, transformFileContents :: [String]
}
| TreeTransform { transformTreeDirectory :: FilePath
}
deriving (Show, Eq)
g4release :: CmdOptions
g4release = G4Release { gitRepo = def &= help "INCL++ Git repository path"
, ignoreGitModifications = False &= help "Ignore modifications in the Git tree"
, g4Tree = def &= help "Geant4 checkout (main level)"
, g4options = [] &= help "(AllowAssert, NoG4Types, NoLicense, NoRevisionInfo)"
} &= help "Release INCL++ to Geant4"
g4ablarelease :: CmdOptions
g4ablarelease = G4AblaRelease { gitRepo = def &= help "INCL++ Git repository path (containing the ablaxx directory)"
, ignoreGitModifications = False &= help "Ignore modifications in the Git tree"
, g4Tree = def &= help "Geant4 checkout (main level)"
, g4options = [] &= help "(AllowAssert, NoG4Types, NoLicense, NoRevisionInfo)"
} &= help "Release ABLAXX to Geant4"
info :: CmdOptions
info = AboutIrt {} &= help "Help"
mode :: Mode (CmdArgs CmdOptions)
mode = cmdArgsMode $ modes [info,g4release,g4ablarelease] &= help "Make an INCL release" &= program "irt" &= summary "irt v0.5"
abortG4Release :: IO ()
abortG4Release = do
putStrLn "Error! Git tree must not contain uncommitted changes!"
performG4Release :: GitRepo -> FilePath -> [G4ReleaseOption] -> IO ()
performG4Release repo targetDir g4opts = do
let inclDir = gitRepoPath repo
codename = "inclxx"
g4inclxxUtilsModule <- mkModuleDefinition inclDir "utils" codename "utils" []
g4inclxxPhysicsModule <- mkModuleDefinition inclDir "incl_physics" codename "physics" [g4inclxxUtilsModule]
g4inclxxInterfaceModule <- mkModuleDefinition inclDir "interface" codename "interface" [g4inclxxUtilsModule, g4inclxxPhysicsModule]
let g4modules = [g4inclxxUtilsModule, g4inclxxPhysicsModule, g4inclxxInterfaceModule]
releaseG4 repo targetDir g4modules g4opts
performG4AblaRelease :: GitRepo -> FilePath -> [G4ReleaseOption] -> IO ()
performG4AblaRelease repo targetDir g4opts = do
let ablaDir = (gitRepoPath repo) </> "ablaxx"
codename = "abla"
g4AblaModule <- mkModuleDefinition ablaDir "" codename "abla" []
releaseG4Abla repo targetDir g4AblaModule g4opts
runIrtCommand :: CmdOptions -> IO ()
runIrtCommand (G4Release gitpath ignoregitmodif g4opts g4sourcepath) = do
let inclRepository = GitRepo gitpath
targetDir = g4sourcepath </> "source/processes/hadronic/models/inclxx/"
inclDirtyTree <- gitIsDirtyTree inclRepository
inclRev <- buildGitRevisionString inclRepository
putStrLn $ "INCL++ repository path is: " ++ gitpath
putStrLn $ "INCL++ revision is: " ++ inclRev
putStrLn $ "Geant4 path is: " ++ g4sourcepath
putStrLn $ "G4 release options: " ++ (show g4opts)
if inclDirtyTree && (not ignoregitmodif)
then abortG4Release
else performG4Release inclRepository targetDir g4opts
runIrtCommand (G4AblaRelease gitpath ignoregitmodif g4opts g4sourcepath) = do
let inclRepository = GitRepo gitpath
targetDir = g4sourcepath </> "source/processes/hadronic/models/abla/"
inclDirtyTree <- gitIsDirtyTree inclRepository
inclRev <- buildGitRevisionString inclRepository
putStrLn $ "INCL++ repository path is: " ++ gitpath
putStrLn $ "INCL++ revision is: " ++ inclRev
putStrLn $ "Geant4 path is: " ++ g4sourcepath
putStrLn $ "G4 release options: " ++ (show g4opts)
if inclDirtyTree && (not ignoregitmodif)
then abortG4Release
else performG4AblaRelease inclRepository targetDir g4opts
runIrtCommand AboutIrt = do
putStrLn "About irt"
main :: IO ()
main = do
conf <- cmdArgsRun mode
runIrtCommand conf
| kaitanie/irt | src/irt.hs | bsd-3-clause | 4,749 | 1 | 12 | 1,275 | 1,000 | 513 | 487 | 86 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE Trustworthy #-}
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE TypeInType #-}
#endif
#include "lens-common.h"
-------------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Lens
-- Copyright : (C) 2012-16 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : Rank2Types
--
-- A @'Lens' s t a b@ is a purely functional reference.
--
-- While a 'Control.Lens.Traversal.Traversal' could be used for
-- 'Control.Lens.Getter.Getting' like a valid 'Control.Lens.Fold.Fold', it
-- wasn't a valid 'Control.Lens.Getter.Getter' as a
-- 'Control.Lens.Getter.Getter' can't require an 'Applicative' constraint.
--
-- 'Functor', however, is a constraint on both.
--
-- @
-- type 'Lens' s t a b = forall f. 'Functor' f => (a -> f b) -> s -> f t
-- @
--
-- Every 'Lens' is a valid 'Control.Lens.Setter.Setter'.
--
-- Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a
-- 'Control.Lens.Fold.Fold' that doesn't use the 'Applicative' or
-- 'Contravariant'.
--
-- Every 'Lens' is a valid 'Control.Lens.Traversal.Traversal' that only uses
-- the 'Functor' part of the 'Applicative' it is supplied.
--
-- Every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a valid
-- 'Control.Lens.Getter.Getter'.
--
-- Since every 'Lens' can be used for 'Control.Lens.Getter.Getting' like a
-- valid 'Control.Lens.Getter.Getter' it follows that it must view exactly one element in the
-- structure.
--
-- The 'Lens' laws follow from this property and the desire for it to act like
-- a 'Data.Traversable.Traversable' when used as a
-- 'Control.Lens.Traversal.Traversal'.
--
-- In the examples below, 'getter' and 'setter' are supplied as example getters
-- and setters, and are not actual functions supplied by this package.
-------------------------------------------------------------------------------
module Control.Lens.Lens
(
-- * Lenses
Lens, Lens'
, IndexedLens, IndexedLens'
-- ** Concrete Lenses
, ALens, ALens'
, AnIndexedLens, AnIndexedLens'
-- * Combinators
, lens, ilens, iplens, withLens
, (%%~), (%%=)
, (%%@~), (%%@=)
, (<%@~), (<%@=)
, (<<%@~), (<<%@=)
-- ** General Purpose Combinators
, (&), (<&>), (??)
, (&~)
-- * Lateral Composition
, choosing
, chosen
, alongside
, inside
-- * Setting Functionally with Passthrough
, (<%~), (<+~), (<-~), (<*~), (<//~)
, (<^~), (<^^~), (<**~)
, (<||~), (<&&~), (<<>~)
, (<<%~), (<<.~), (<<?~), (<<+~), (<<-~), (<<*~)
, (<<//~), (<<^~), (<<^^~), (<<**~)
, (<<||~), (<<&&~), (<<<>~)
-- * Setting State with Passthrough
, (<%=), (<+=), (<-=), (<*=), (<//=)
, (<^=), (<^^=), (<**=)
, (<||=), (<&&=), (<<>=)
, (<<%=), (<<.=), (<<?=), (<<+=), (<<-=), (<<*=)
, (<<//=), (<<^=), (<<^^=), (<<**=)
, (<<||=), (<<&&=), (<<<>=)
, (<<~)
-- * Cloning Lenses
, cloneLens
, cloneIndexPreservingLens
, cloneIndexedLens
-- * Arrow operators
, overA
-- * ALens Combinators
, storing
, (^#)
, ( #~ ), ( #%~ ), ( #%%~ ), (<#~), (<#%~)
, ( #= ), ( #%= ), ( #%%= ), (<#=), (<#%=)
-- * Common Lenses
, devoid
, united
, head1, last1
-- * Context
, Context(..)
, Context'
, locus
-- * Lens fusion
, fusing
) where
import Prelude ()
import Control.Arrow
import Control.Comonad
import Control.Lens.Internal.Context
import Control.Lens.Internal.Prelude
import Control.Lens.Internal.Getter
import Control.Lens.Internal.Indexed
import Control.Lens.Type
import Control.Monad.State as State
import Data.Functor.Apply
import Data.Functor.Reverse
import Data.Functor.Yoneda
import Data.Semigroup.Traversable
#if __GLASGOW_HASKELL__ >= 800
import GHC.Exts (TYPE)
#endif
#ifdef HLINT
{-# ANN module "HLint: ignore Use ***" #-}
#endif
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Control.Monad.State
-- >>> import Data.Char (chr)
-- >>> import Data.List.NonEmpty (NonEmpty ((:|)))
-- >>> import Data.Monoid (Sum (..))
-- >>> import Data.Tree (Tree (Node))
-- >>> import Debug.SimpleReflect.Expr
-- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g,h)
-- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f
-- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g
-- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h
-- >>> let getter :: Expr -> Expr; getter = fun "getter"
-- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter"
infixl 8 ^#
infixr 4 %%@~, <%@~, <<%@~, %%~, <+~, <*~, <-~, <//~, <^~, <^^~, <**~, <&&~, <||~, <<>~, <%~, <<%~, <<.~, <<?~, <#~, #~, #%~, <#%~, #%%~
, <<+~, <<-~, <<*~, <<//~, <<^~, <<^^~, <<**~, <<||~, <<&&~, <<<>~
infix 4 %%@=, <%@=, <<%@=, %%=, <+=, <*=, <-=, <//=, <^=, <^^=, <**=, <&&=, <||=, <<>=, <%=, <<%=, <<.=, <<?=, <#=, #=, #%=, <#%=, #%%=
, <<+=, <<-=, <<*=, <<//=, <<^=, <<^^=, <<**=, <<||=, <<&&=, <<<>=
infixr 2 <<~
infixl 1 ??, &~
-------------------------------------------------------------------------------
-- Lenses
-------------------------------------------------------------------------------
-- | When you see this as an argument to a function, it expects a 'Lens'.
--
-- This type can also be used when you need to store a 'Lens' in a container,
-- since it is rank-1. You can turn them back into a 'Lens' with 'cloneLens',
-- or use it directly with combinators like 'storing' and ('^#').
type ALens s t a b = LensLike (Pretext (->) a b) s t a b
-- | @
-- type 'ALens'' = 'Simple' 'ALens'
-- @
type ALens' s a = ALens s s a a
-- | When you see this as an argument to a function, it expects an 'IndexedLens'
type AnIndexedLens i s t a b = Optical (Indexed i) (->) (Pretext (Indexed i) a b) s t a b
-- | @
-- type 'AnIndexedLens'' = 'Simple' ('AnIndexedLens' i)
-- @
type AnIndexedLens' i s a = AnIndexedLens i s s a a
--------------------------
-- Constructing Lenses
--------------------------
-- | Build a 'Lens' from a getter and a setter.
--
-- @
-- 'lens' :: 'Functor' f => (s -> a) -> (s -> b -> t) -> (a -> f b) -> s -> f t
-- @
--
-- >>> s ^. lens getter setter
-- getter s
--
-- >>> s & lens getter setter .~ b
-- setter s b
--
-- >>> s & lens getter setter %~ f
-- setter s (f (getter s))
--
-- @
-- 'lens' :: (s -> a) -> (s -> a -> s) -> 'Lens'' s a
-- @
lens :: (s -> a) -> (s -> b -> t) -> Lens s t a b
lens sa sbt afb s = sbt s <$> afb (sa s)
{-# INLINE lens #-}
-- | Obtain a getter and a setter from a lens, reversing 'lens'.
#if __GLASGOW_HASKELL__ >= 800
withLens :: forall s t a b rep (r :: TYPE rep).
ALens s t a b -> ((s -> a) -> (s -> b -> t) -> r) -> r
#else
withLens :: ALens s t a b -> ((s -> a) -> (s -> b -> t) -> r) -> r
#endif
withLens l f = f (^# l) (flip (storing l))
{-# INLINE withLens #-}
-- | Build an index-preserving 'Lens' from a 'Control.Lens.Getter.Getter' and a
-- 'Control.Lens.Setter.Setter'.
iplens :: (s -> a) -> (s -> b -> t) -> IndexPreservingLens s t a b
iplens sa sbt pafb = cotabulate $ \ws -> sbt (extract ws) <$> cosieve pafb (sa <$> ws)
{-# INLINE iplens #-}
-- | Build an 'IndexedLens' from a 'Control.Lens.Getter.Getter' and
-- a 'Control.Lens.Setter.Setter'.
ilens :: (s -> (i, a)) -> (s -> b -> t) -> IndexedLens i s t a b
ilens sia sbt iafb s = sbt s <$> uncurry (indexed iafb) (sia s)
{-# INLINE ilens #-}
-- | This can be used to chain lens operations using @op=@ syntax
-- rather than @op~@ syntax for simple non-type-changing cases.
--
-- >>> (10,20) & _1 .~ 30 & _2 .~ 40
-- (30,40)
--
-- >>> (10,20) &~ do _1 .= 30; _2 .= 40
-- (30,40)
--
-- This does not support type-changing assignment, /e.g./
--
-- >>> (10,20) & _1 .~ "hello"
-- ("hello",20)
(&~) :: s -> State s a -> s
s &~ l = execState l s
{-# INLINE (&~) #-}
-- | ('%%~') can be used in one of two scenarios:
--
-- When applied to a 'Lens', it can edit the target of the 'Lens' in a
-- structure, extracting a functorial result.
--
-- When applied to a 'Traversal', it can edit the
-- targets of the traversals, extracting an applicative summary of its
-- actions.
--
-- >>> [66,97,116,109,97,110] & each %%~ \a -> ("na", chr a)
-- ("nananananana","Batman")
--
-- For all that the definition of this combinator is just:
--
-- @
-- ('%%~') ≡ 'id'
-- @
--
-- It may be beneficial to think about it as if it had these even more
-- restricted types, however:
--
-- @
-- ('%%~') :: 'Functor' f => 'Control.Lens.Iso.Iso' s t a b -> (a -> f b) -> s -> f t
-- ('%%~') :: 'Functor' f => 'Lens' s t a b -> (a -> f b) -> s -> f t
-- ('%%~') :: 'Applicative' f => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> f b) -> s -> f t
-- @
--
-- When applied to a 'Traversal', it can edit the
-- targets of the traversals, extracting a supplemental monoidal summary
-- of its actions, by choosing @f = ((,) m)@
--
-- @
-- ('%%~') :: 'Control.Lens.Iso.Iso' s t a b -> (a -> (r, b)) -> s -> (r, t)
-- ('%%~') :: 'Lens' s t a b -> (a -> (r, b)) -> s -> (r, t)
-- ('%%~') :: 'Monoid' m => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> (m, b)) -> s -> (m, t)
-- @
(%%~) :: LensLike f s t a b -> (a -> f b) -> s -> f t
(%%~) = id
{-# INLINE (%%~) #-}
-- | Modify the target of a 'Lens' in the current state returning some extra
-- information of type @r@ or modify all targets of a
-- 'Control.Lens.Traversal.Traversal' in the current state, extracting extra
-- information of type @r@ and return a monoidal summary of the changes.
--
-- >>> runState (_1 %%= \x -> (f x, g x)) (a,b)
-- (f a,(g a,b))
--
-- @
-- ('%%=') ≡ ('state' '.')
-- @
--
-- It may be useful to think of ('%%='), instead, as having either of the
-- following more restricted type signatures:
--
-- @
-- ('%%=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso' s s a b -> (a -> (r, b)) -> m r
-- ('%%=') :: 'MonadState' s m => 'Lens' s s a b -> (a -> (r, b)) -> m r
-- ('%%=') :: ('MonadState' s m, 'Monoid' r) => 'Control.Lens.Traversal.Traversal' s s a b -> (a -> (r, b)) -> m r
-- @
(%%=) :: MonadState s m => Over p ((,) r) s s a b -> p a (r, b) -> m r
#if MIN_VERSION_mtl(2,1,1)
l %%= f = State.state (l f)
#else
l %%= f = do
(r, s) <- State.gets (l f)
State.put s
return r
#endif
{-# INLINE (%%=) #-}
-------------------------------------------------------------------------------
-- General Purpose Combinators
-------------------------------------------------------------------------------
-- | This is convenient to 'flip' argument order of composite functions defined as:
--
-- @
-- fab ?? a = fmap ($ a) fab
-- @
--
-- For the 'Functor' instance @f = ((->) r)@ you can reason about this function as if the definition was @('??') ≡ 'flip'@:
--
-- >>> (h ?? x) a
-- h a x
--
-- >>> execState ?? [] $ modify (1:)
-- [1]
--
-- >>> over _2 ?? ("hello","world") $ length
-- ("hello",5)
--
-- >>> over ?? length ?? ("hello","world") $ _2
-- ("hello",5)
(??) :: Functor f => f (a -> b) -> a -> f b
fab ?? a = fmap ($ a) fab
{-# INLINE (??) #-}
-------------------------------------------------------------------------------
-- Common Lenses
-------------------------------------------------------------------------------
-- | Lift a 'Lens' so it can run under a function (or other corepresentable profunctor).
--
-- @
-- 'inside' :: 'Lens' s t a b -> 'Lens' (e -> s) (e -> t) (e -> a) (e -> b)
-- @
--
--
-- >>> (\x -> (x-1,x+1)) ^. inside _1 $ 5
-- 4
--
-- >>> runState (modify (1:) >> modify (2:)) ^. (inside _2) $ []
-- [2,1]
inside :: Corepresentable p => ALens s t a b -> Lens (p e s) (p e t) (p e a) (p e b)
inside l f es = o <$> f i where
i = cotabulate $ \ e -> ipos $ l sell (cosieve es e)
o ea = cotabulate $ \ e -> ipeek (cosieve ea e) $ l sell (cosieve es e)
{-# INLINE inside #-}
{-
-- | Lift a 'Lens' so it can run under a function (or any other corepresentable functor).
insideF :: F.Representable f => ALens s t a b -> Lens (f s) (f t) (f a) (f b)
insideF l f es = o <$> f i where
i = F.tabulate $ \e -> ipos $ l sell (F.index es e)
o ea = F.tabulate $ \ e -> ipeek (F.index ea e) $ l sell (F.index es e)
{-# INLINE inside #-}
-}
-- | Merge two lenses, getters, setters, folds or traversals.
--
-- @
-- 'chosen' ≡ 'choosing' 'id' 'id'
-- @
--
-- @
-- 'choosing' :: 'Control.Lens.Getter.Getter' s a -> 'Control.Lens.Getter.Getter' s' a -> 'Control.Lens.Getter.Getter' ('Either' s s') a
-- 'choosing' :: 'Control.Lens.Fold.Fold' s a -> 'Control.Lens.Fold.Fold' s' a -> 'Control.Lens.Fold.Fold' ('Either' s s') a
-- 'choosing' :: 'Lens'' s a -> 'Lens'' s' a -> 'Lens'' ('Either' s s') a
-- 'choosing' :: 'Control.Lens.Traversal.Traversal'' s a -> 'Control.Lens.Traversal.Traversal'' s' a -> 'Control.Lens.Traversal.Traversal'' ('Either' s s') a
-- 'choosing' :: 'Control.Lens.Setter.Setter'' s a -> 'Control.Lens.Setter.Setter'' s' a -> 'Control.Lens.Setter.Setter'' ('Either' s s') a
-- @
choosing :: Functor f
=> LensLike f s t a b
-> LensLike f s' t' a b
-> LensLike f (Either s s') (Either t t') a b
choosing l _ f (Left a) = Left <$> l f a
choosing _ r f (Right a') = Right <$> r f a'
{-# INLINE choosing #-}
-- | This is a 'Lens' that updates either side of an 'Either', where both sides have the same type.
--
-- @
-- 'chosen' ≡ 'choosing' 'id' 'id'
-- @
--
-- >>> Left a^.chosen
-- a
--
-- >>> Right a^.chosen
-- a
--
-- >>> Right "hello"^.chosen
-- "hello"
--
-- >>> Right a & chosen *~ b
-- Right (a * b)
--
-- @
-- 'chosen' :: 'Lens' ('Either' a a) ('Either' b b) a b
-- 'chosen' f ('Left' a) = 'Left' '<$>' f a
-- 'chosen' f ('Right' a) = 'Right' '<$>' f a
-- @
chosen :: IndexPreservingLens (Either a a) (Either b b) a b
chosen pafb = cotabulate $ \weaa -> cosieve (either id id `lmap` pafb) weaa <&> \b -> case extract weaa of
Left _ -> Left b
Right _ -> Right b
{-# INLINE chosen #-}
-- | 'alongside' makes a 'Lens' from two other lenses or a 'Getter' from two other getters
-- by executing them on their respective halves of a product.
--
-- >>> (Left a, Right b)^.alongside chosen chosen
-- (a,b)
--
-- >>> (Left a, Right b) & alongside chosen chosen .~ (c,d)
-- (Left c,Right d)
--
-- @
-- 'alongside' :: 'Lens' s t a b -> 'Lens' s' t' a' b' -> 'Lens' (s,s') (t,t') (a,a') (b,b')
-- 'alongside' :: 'Getter' s a -> 'Getter' s' a' -> 'Getter' (s,s') (a,a')
-- @
alongside :: LensLike (AlongsideLeft f b') s t a b
-> LensLike (AlongsideRight f t) s' t' a' b'
-> LensLike f (s, s') (t, t') (a, a') (b, b')
alongside l1 l2 f (a1, a2)
= getAlongsideRight $ l2 ?? a2 $ \b2 -> AlongsideRight
$ getAlongsideLeft $ l1 ?? a1 $ \b1 -> AlongsideLeft
$ f (b1,b2)
{-# INLINE alongside #-}
-- | This 'Lens' lets you 'view' the current 'pos' of any indexed
-- store comonad and 'seek' to a new position. This reduces the API
-- for working these instances to a single 'Lens'.
--
-- @
-- 'ipos' w ≡ w 'Control.Lens.Getter.^.' 'locus'
-- 'iseek' s w ≡ w '&' 'locus' 'Control.Lens.Setter..~' s
-- 'iseeks' f w ≡ w '&' 'locus' 'Control.Lens.Setter.%~' f
-- @
--
-- @
-- 'locus' :: 'Lens'' ('Context'' a s) a
-- 'locus' :: 'Conjoined' p => 'Lens'' ('Pretext'' p a s) a
-- 'locus' :: 'Conjoined' p => 'Lens'' ('PretextT'' p g a s) a
-- @
locus :: IndexedComonadStore p => Lens (p a c s) (p b c s) a b
locus f w = (`iseek` w) <$> f (ipos w)
{-# INLINE locus #-}
-------------------------------------------------------------------------------
-- Cloning Lenses
-------------------------------------------------------------------------------
-- | Cloning a 'Lens' is one way to make sure you aren't given
-- something weaker, such as a 'Control.Lens.Traversal.Traversal' and can be
-- used as a way to pass around lenses that have to be monomorphic in @f@.
--
-- Note: This only accepts a proper 'Lens'.
--
-- >>> let example l x = set (cloneLens l) (x^.cloneLens l + 1) x in example _2 ("hello",1,"you")
-- ("hello",2,"you")
cloneLens :: ALens s t a b -> Lens s t a b
cloneLens l afb s = runPretext (l sell s) afb
{-# INLINE cloneLens #-}
-- | Clone a 'Lens' as an 'IndexedPreservingLens' that just passes through whatever
-- index is on any 'IndexedLens', 'IndexedFold', 'IndexedGetter' or 'IndexedTraversal' it is composed with.
cloneIndexPreservingLens :: ALens s t a b -> IndexPreservingLens s t a b
cloneIndexPreservingLens l pafb = cotabulate $ \ws -> runPretext (l sell (extract ws)) $ \a -> cosieve pafb (a <$ ws)
{-# INLINE cloneIndexPreservingLens #-}
-- | Clone an 'IndexedLens' as an 'IndexedLens' with the same index.
cloneIndexedLens :: AnIndexedLens i s t a b -> IndexedLens i s t a b
cloneIndexedLens l f s = runPretext (l sell s) (Indexed (indexed f))
{-# INLINE cloneIndexedLens #-}
-------------------------------------------------------------------------------
-- Setting and Remembering
-------------------------------------------------------------------------------
-- | Modify the target of a 'Lens' and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.%~') is more flexible.
--
-- @
-- ('<%~') :: 'Lens' s t a b -> (a -> b) -> s -> (b, t)
-- ('<%~') :: 'Control.Lens.Iso.Iso' s t a b -> (a -> b) -> s -> (b, t)
-- ('<%~') :: 'Monoid' b => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> b) -> s -> (b, t)
-- @
(<%~) :: LensLike ((,) b) s t a b -> (a -> b) -> s -> (b, t)
l <%~ f = l $ (\t -> (t, t)) . f
{-# INLINE (<%~) #-}
-- | Increment the target of a numerically valued 'Lens' and return the result.
--
-- When you do not need the result of the addition, ('Control.Lens.Setter.+~') is more flexible.
--
-- @
-- ('<+~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<+~') :: 'Num' a => 'Control.Lens.Iso.Iso'' s a -> a -> s -> (a, s)
-- @
(<+~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)
l <+~ a = l <%~ (+ a)
{-# INLINE (<+~) #-}
-- | Decrement the target of a numerically valued 'Lens' and return the result.
--
-- When you do not need the result of the subtraction, ('Control.Lens.Setter.-~') is more flexible.
--
-- @
-- ('<-~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<-~') :: 'Num' a => 'Control.Lens.Iso.Iso'' s a -> a -> s -> (a, s)
-- @
(<-~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)
l <-~ a = l <%~ subtract a
{-# INLINE (<-~) #-}
-- | Multiply the target of a numerically valued 'Lens' and return the result.
--
-- When you do not need the result of the multiplication, ('Control.Lens.Setter.*~') is more
-- flexible.
--
-- @
-- ('<*~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<*~') :: 'Num' a => 'Control.Lens.Iso.Iso'' s a -> a -> s -> (a, s)
-- @
(<*~) :: Num a => LensLike ((,)a) s t a a -> a -> s -> (a, t)
l <*~ a = l <%~ (* a)
{-# INLINE (<*~) #-}
-- | Divide the target of a fractionally valued 'Lens' and return the result.
--
-- When you do not need the result of the division, ('Control.Lens.Setter.//~') is more flexible.
--
-- @
-- ('<//~') :: 'Fractional' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<//~') :: 'Fractional' a => 'Control.Lens.Iso.Iso'' s a -> a -> s -> (a, s)
-- @
(<//~) :: Fractional a => LensLike ((,)a) s t a a -> a -> s -> (a, t)
l <//~ a = l <%~ (/ a)
{-# INLINE (<//~) #-}
-- | Raise the target of a numerically valued 'Lens' to a non-negative
-- 'Integral' power and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^~') is more flexible.
--
-- @
-- ('<^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)
-- ('<^~') :: ('Num' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> s -> (a, s)
-- @
(<^~) :: (Num a, Integral e) => LensLike ((,)a) s t a a -> e -> s -> (a, t)
l <^~ e = l <%~ (^ e)
{-# INLINE (<^~) #-}
-- | Raise the target of a fractionally valued 'Lens' to an 'Integral' power
-- and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^^~') is more flexible.
--
-- @
-- ('<^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)
-- ('<^^~') :: ('Fractional' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> s -> (a, s)
-- @
(<^^~) :: (Fractional a, Integral e) => LensLike ((,)a) s t a a -> e -> s -> (a, t)
l <^^~ e = l <%~ (^^ e)
{-# INLINE (<^^~) #-}
-- | Raise the target of a floating-point valued 'Lens' to an arbitrary power
-- and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.**~') is more flexible.
--
-- @
-- ('<**~') :: 'Floating' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<**~') :: 'Floating' a => 'Control.Lens.Iso.Iso'' s a -> a -> s -> (a, s)
-- @
(<**~) :: Floating a => LensLike ((,)a) s t a a -> a -> s -> (a, t)
l <**~ a = l <%~ (** a)
{-# INLINE (<**~) #-}
-- | Logically '||' a Boolean valued 'Lens' and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.||~') is more flexible.
--
-- @
-- ('<||~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- ('<||~') :: 'Control.Lens.Iso.Iso'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- @
(<||~) :: LensLike ((,)Bool) s t Bool Bool -> Bool -> s -> (Bool, t)
l <||~ b = l <%~ (|| b)
{-# INLINE (<||~) #-}
-- | Logically '&&' a Boolean valued 'Lens' and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.&&~') is more flexible.
--
-- @
-- ('<&&~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- ('<&&~') :: 'Control.Lens.Iso.Iso'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- @
(<&&~) :: LensLike ((,)Bool) s t Bool Bool -> Bool -> s -> (Bool, t)
l <&&~ b = l <%~ (&& b)
{-# INLINE (<&&~) #-}
-- | Modify the target of a 'Lens', but return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.%~') is more flexible.
--
-- @
-- ('<<%~') :: 'Lens' s t a b -> (a -> b) -> s -> (a, t)
-- ('<<%~') :: 'Control.Lens.Iso.Iso' s t a b -> (a -> b) -> s -> (a, t)
-- ('<<%~') :: 'Monoid' a => 'Control.Lens.Traversal.Traversal' s t a b -> (a -> b) -> s -> (a, t)
-- @
(<<%~) :: LensLike ((,)a) s t a b -> (a -> b) -> s -> (a, t)
(<<%~) l = l . lmap (\a -> (a, a)) . second'
{-# INLINE (<<%~) #-}
-- | Replace the target of a 'Lens', but return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter..~') is more flexible.
--
-- @
-- ('<<.~') :: 'Lens' s t a b -> b -> s -> (a, t)
-- ('<<.~') :: 'Control.Lens.Iso.Iso' s t a b -> b -> s -> (a, t)
-- ('<<.~') :: 'Monoid' a => 'Control.Lens.Traversal.Traversal' s t a b -> b -> s -> (a, t)
-- @
(<<.~) :: LensLike ((,)a) s t a b -> b -> s -> (a, t)
l <<.~ b = l $ \a -> (a, b)
{-# INLINE (<<.~) #-}
-- | Replace the target of a 'Lens' with a 'Just' value, but return the old value.
--
-- If you do not need the old value ('Control.Lens.Setter.?~') is more flexible.
--
-- >>> import Data.Map as Map
-- >>> _2.at "hello" <<?~ "world" $ (42,Map.fromList [("goodnight","gracie")])
-- (Nothing,(42,fromList [("goodnight","gracie"),("hello","world")]))
--
-- @
-- ('<<?~') :: 'Iso' s t a ('Maybe' b) -> b -> s -> (a, t)
-- ('<<?~') :: 'Lens' s t a ('Maybe' b) -> b -> s -> (a, t)
-- ('<<?~') :: 'Traversal' s t a ('Maybe' b) -> b -> s -> (a, t)
-- @
(<<?~) :: LensLike ((,)a) s t a (Maybe b) -> b -> s -> (a, t)
l <<?~ b = l <<.~ Just b
{-# INLINE (<<?~) #-}
-- | Increment the target of a numerically valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.+~') is more flexible.
--
-- >>> (a,b) & _1 <<+~ c
-- (a,(a + c,b))
--
-- >>> (a,b) & _2 <<+~ c
-- (b,(a,b + c))
--
-- @
-- ('<<+~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<<+~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)
-- @
(<<+~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)
l <<+~ b = l $ \a -> (a, a + b)
{-# INLINE (<<+~) #-}
-- | Decrement the target of a numerically valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.-~') is more flexible.
--
-- >>> (a,b) & _1 <<-~ c
-- (a,(a - c,b))
--
-- >>> (a,b) & _2 <<-~ c
-- (b,(a,b - c))
--
-- @
-- ('<<-~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<<-~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)
-- @
(<<-~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)
l <<-~ b = l $ \a -> (a, a - b)
{-# INLINE (<<-~) #-}
-- | Multiply the target of a numerically valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.-~') is more flexible.
--
-- >>> (a,b) & _1 <<*~ c
-- (a,(a * c,b))
--
-- >>> (a,b) & _2 <<*~ c
-- (b,(a,b * c))
--
-- @
-- ('<<*~') :: 'Num' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<<*~') :: 'Num' a => 'Iso'' s a -> a -> s -> (a, s)
-- @
(<<*~) :: Num a => LensLike' ((,) a) s a -> a -> s -> (a, s)
l <<*~ b = l $ \a -> (a, a * b)
{-# INLINE (<<*~) #-}
-- | Divide the target of a numerically valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.//~') is more flexible.
--
-- >>> (a,b) & _1 <<//~ c
-- (a,(a / c,b))
--
-- >>> ("Hawaii",10) & _2 <<//~ 2
-- (10.0,("Hawaii",5.0))
--
-- @
-- ('<<//~') :: Fractional a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<<//~') :: Fractional a => 'Iso'' s a -> a -> s -> (a, s)
-- @
(<<//~) :: Fractional a => LensLike' ((,) a) s a -> a -> s -> (a, s)
l <<//~ b = l $ \a -> (a, a / b)
{-# INLINE (<<//~) #-}
-- | Raise the target of a numerically valued 'Lens' to a non-negative power and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.^~') is more flexible.
--
-- @
-- ('<<^~') :: ('Num' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)
-- ('<<^~') :: ('Num' a, 'Integral' e) => 'Iso'' s a -> e -> s -> (a, s)
-- @
(<<^~) :: (Num a, Integral e) => LensLike' ((,) a) s a -> e -> s -> (a, s)
l <<^~ e = l $ \a -> (a, a ^ e)
{-# INLINE (<<^~) #-}
-- | Raise the target of a fractionally valued 'Lens' to an integral power and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.^^~') is more flexible.
--
-- @
-- ('<<^^~') :: ('Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> s -> (a, s)
-- ('<<^^~') :: ('Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> S -> (a, s)
-- @
(<<^^~) :: (Fractional a, Integral e) => LensLike' ((,) a) s a -> e -> s -> (a, s)
l <<^^~ e = l $ \a -> (a, a ^^ e)
{-# INLINE (<<^^~) #-}
-- | Raise the target of a floating-point valued 'Lens' to an arbitrary power and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.**~') is more flexible.
--
-- >>> (a,b) & _1 <<**~ c
-- (a,(a**c,b))
--
-- >>> (a,b) & _2 <<**~ c
-- (b,(a,b**c))
--
-- @
-- ('<<**~') :: 'Floating' a => 'Lens'' s a -> a -> s -> (a, s)
-- ('<<**~') :: 'Floating' a => 'Iso'' s a -> a -> s -> (a, s)
-- @
(<<**~) :: Floating a => LensLike' ((,) a) s a -> a -> s -> (a, s)
l <<**~ e = l $ \a -> (a, a ** e)
{-# INLINE (<<**~) #-}
-- | Logically '||' the target of a 'Bool'-valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.||~') is more flexible.
--
-- >>> (False,6) & _1 <<||~ True
-- (False,(True,6))
--
-- >>> ("hello",True) & _2 <<||~ False
-- (True,("hello",True))
--
-- @
-- ('<<||~') :: 'Lens'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- ('<<||~') :: 'Iso'' s 'Bool' -> 'Bool' -> s -> ('Bool', s)
-- @
(<<||~) :: LensLike' ((,) Bool) s Bool -> Bool -> s -> (Bool, s)
l <<||~ b = l $ \a -> (a, b || a)
{-# INLINE (<<||~) #-}
-- | Logically '&&' the target of a 'Bool'-valued 'Lens' and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.&&~') is more flexible.
--
-- >>> (False,6) & _1 <<&&~ True
-- (False,(False,6))
--
-- >>> ("hello",True) & _2 <<&&~ False
-- (True,("hello",False))
--
-- @
-- ('<<&&~') :: 'Lens'' s Bool -> Bool -> s -> (Bool, s)
-- ('<<&&~') :: 'Iso'' s Bool -> Bool -> s -> (Bool, s)
-- @
(<<&&~) :: LensLike' ((,) Bool) s Bool -> Bool -> s -> (Bool, s)
l <<&&~ b = l $ \a -> (a, b && a)
{-# INLINE (<<&&~) #-}
-- | Modify the target of a monoidally valued 'Lens' by using ('<>') a new value and return the old value.
--
-- When you do not need the old value, ('Control.Lens.Setter.<>~') is more flexible.
--
-- >>> (Sum a,b) & _1 <<<>~ Sum c
-- (Sum {getSum = a},(Sum {getSum = a + c},b))
--
-- >>> _2 <<<>~ ", 007" $ ("James", "Bond")
-- ("Bond",("James","Bond, 007"))
--
-- @
-- ('<<<>~') :: 'Semigroup' r => 'Lens'' s r -> r -> s -> (r, s)
-- ('<<<>~') :: 'Semigroup' r => 'Iso'' s r -> r -> s -> (r, s)
-- @
(<<<>~) :: Semigroup r => LensLike' ((,) r) s r -> r -> s -> (r, s)
l <<<>~ b = l $ \a -> (a, a <> b)
{-# INLINE (<<<>~) #-}
-------------------------------------------------------------------------------
-- Setting and Remembering State
-------------------------------------------------------------------------------
-- | Modify the target of a 'Lens' into your 'Monad''s state by a user supplied
-- function and return the result.
--
-- When applied to a 'Control.Lens.Traversal.Traversal', it this will return a monoidal summary of all of the intermediate
-- results.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.
--
-- @
-- ('<%=') :: 'MonadState' s m => 'Lens'' s a -> (a -> a) -> m a
-- ('<%=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s a -> (a -> a) -> m a
-- ('<%=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> a) -> m a
-- @
(<%=) :: MonadState s m => LensLike ((,)b) s s a b -> (a -> b) -> m b
l <%= f = l %%= (\b -> (b, b)) . f
{-# INLINE (<%=) #-}
-- | Add to the target of a numerically valued 'Lens' into your 'Monad''s state
-- and return the result.
--
-- When you do not need the result of the addition, ('Control.Lens.Setter.+=') is more
-- flexible.
--
-- @
-- ('<+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<+=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- @
(<+=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a
l <+= a = l <%= (+ a)
{-# INLINE (<+=) #-}
-- | Subtract from the target of a numerically valued 'Lens' into your 'Monad''s
-- state and return the result.
--
-- When you do not need the result of the subtraction, ('Control.Lens.Setter.-=') is more
-- flexible.
--
-- @
-- ('<-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<-=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- @
(<-=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a
l <-= a = l <%= subtract a
{-# INLINE (<-=) #-}
-- | Multiply the target of a numerically valued 'Lens' into your 'Monad''s
-- state and return the result.
--
-- When you do not need the result of the multiplication, ('Control.Lens.Setter.*=') is more
-- flexible.
--
-- @
-- ('<*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<*=') :: ('MonadState' s m, 'Num' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- @
(<*=) :: (MonadState s m, Num a) => LensLike' ((,)a) s a -> a -> m a
l <*= a = l <%= (* a)
{-# INLINE (<*=) #-}
-- | Divide the target of a fractionally valued 'Lens' into your 'Monad''s state
-- and return the result.
--
-- When you do not need the result of the division, ('Control.Lens.Setter.//=') is more flexible.
--
-- @
-- ('<//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a -> a -> m a
-- ('<//=') :: ('MonadState' s m, 'Fractional' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- @
(<//=) :: (MonadState s m, Fractional a) => LensLike' ((,)a) s a -> a -> m a
l <//= a = l <%= (/ a)
{-# INLINE (<//=) #-}
-- | Raise the target of a numerically valued 'Lens' into your 'Monad''s state
-- to a non-negative 'Integral' power and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^=') is more flexible.
--
-- @
-- ('<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a -> e -> m a
-- ('<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> m a
-- @
(<^=) :: (MonadState s m, Num a, Integral e) => LensLike' ((,)a) s a -> e -> m a
l <^= e = l <%= (^ e)
{-# INLINE (<^=) #-}
-- | Raise the target of a fractionally valued 'Lens' into your 'Monad''s state
-- to an 'Integral' power and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^^=') is more flexible.
--
-- @
-- ('<^^=') :: ('MonadState' s m, 'Fractional' b, 'Integral' e) => 'Lens'' s a -> e -> m a
-- ('<^^=') :: ('MonadState' s m, 'Fractional' b, 'Integral' e) => 'Control.Lens.Iso.Iso'' s a -> e -> m a
-- @
(<^^=) :: (MonadState s m, Fractional a, Integral e) => LensLike' ((,)a) s a -> e -> m a
l <^^= e = l <%= (^^ e)
{-# INLINE (<^^=) #-}
-- | Raise the target of a floating-point valued 'Lens' into your 'Monad''s
-- state to an arbitrary power and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.
--
-- @
-- ('<**=') :: ('MonadState' s m, 'Floating' a) => 'Lens'' s a -> a -> m a
-- ('<**=') :: ('MonadState' s m, 'Floating' a) => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- @
(<**=) :: (MonadState s m, Floating a) => LensLike' ((,)a) s a -> a -> m a
l <**= a = l <%= (** a)
{-# INLINE (<**=) #-}
-- | Logically '||' a Boolean valued 'Lens' into your 'Monad''s state and return
-- the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.||=') is more flexible.
--
-- @
-- ('<||=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'
-- ('<||=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s 'Bool' -> 'Bool' -> m 'Bool'
-- @
(<||=) :: MonadState s m => LensLike' ((,)Bool) s Bool -> Bool -> m Bool
l <||= b = l <%= (|| b)
{-# INLINE (<||=) #-}
-- | Logically '&&' a Boolean valued 'Lens' into your 'Monad''s state and return
-- the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.&&=') is more flexible.
--
-- @
-- ('<&&=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'
-- ('<&&=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s 'Bool' -> 'Bool' -> m 'Bool'
-- @
(<&&=) :: MonadState s m => LensLike' ((,)Bool) s Bool -> Bool -> m Bool
l <&&= b = l <%= (&& b)
{-# INLINE (<&&=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by a user supplied
-- function and return the /old/ value that was replaced.
--
-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values
-- present.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.%=') is more flexible.
--
-- @
-- ('<<%=') :: 'MonadState' s m => 'Lens'' s a -> (a -> a) -> m a
-- ('<<%=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s a -> (a -> a) -> m a
-- ('<<%=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> (a -> a) -> m a
-- @
--
-- @('<<%=') :: 'MonadState' s m => 'LensLike' ((,)a) s s a b -> (a -> b) -> m a@
(<<%=) :: (Strong p, MonadState s m) => Over p ((,)a) s s a b -> p a b -> m a
l <<%= f = l %%= lmap (\a -> (a,a)) (second' f)
{-# INLINE (<<%=) #-}
-- | Replace the target of a 'Lens' into your 'Monad''s state with a user supplied
-- value and return the /old/ value that was replaced.
--
-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values
-- present.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter..=') is more flexible.
--
-- @
-- ('<<.=') :: 'MonadState' s m => 'Lens'' s a -> a -> m a
-- ('<<.=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso'' s a -> a -> m a
-- ('<<.=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal'' s a -> a -> m a
-- @
(<<.=) :: MonadState s m => LensLike ((,)a) s s a b -> b -> m a
l <<.= b = l %%= \a -> (a,b)
{-# INLINE (<<.=) #-}
-- | Replace the target of a 'Lens' into your 'Monad''s state with 'Just' a user supplied
-- value and return the /old/ value that was replaced.
--
-- When applied to a 'Control.Lens.Traversal.Traversal', this will return a monoidal summary of all of the old values
-- present.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.?=') is more flexible.
--
-- @
-- ('<<?=') :: 'MonadState' s m => 'Lens' s t a (Maybe b) -> b -> m a
-- ('<<?=') :: 'MonadState' s m => 'Control.Lens.Iso.Iso' s t a (Maybe b) -> b -> m a
-- ('<<?=') :: ('MonadState' s m, 'Monoid' a) => 'Control.Lens.Traversal.Traversal' s t a (Maybe b) -> b -> m a
-- @
(<<?=) :: MonadState s m => LensLike ((,)a) s s a (Maybe b) -> b -> m a
l <<?= b = l <<.= Just b
{-# INLINE (<<?=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by adding a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.+=') is more flexible.
--
-- @
-- ('<<+=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<<+=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a
-- @
(<<+=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a
l <<+= n = l %%= \a -> (a, a + n)
{-# INLINE (<<+=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by subtracting a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.-=') is more flexible.
--
-- @
-- ('<<-=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<<-=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a
-- @
(<<-=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a
l <<-= n = l %%= \a -> (a, a - n)
{-# INLINE (<<-=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by multipling a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.*=') is more flexible.
--
-- @
-- ('<<*=') :: ('MonadState' s m, 'Num' a) => 'Lens'' s a -> a -> m a
-- ('<<*=') :: ('MonadState' s m, 'Num' a) => 'Iso'' s a -> a -> m a
-- @
(<<*=) :: (MonadState s m, Num a) => LensLike' ((,) a) s a -> a -> m a
l <<*= n = l %%= \a -> (a, a * n)
{-# INLINE (<<*=) #-}
-- | Modify the target of a 'Lens' into your 'Monad'\s state by dividing by a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.//=') is more flexible.
--
-- @
-- ('<<//=') :: ('MonadState' s m, 'Fractional' a) => 'Lens'' s a -> a -> m a
-- ('<<//=') :: ('MonadState' s m, 'Fractional' a) => 'Iso'' s a -> a -> m a
-- @
(<<//=) :: (MonadState s m, Fractional a) => LensLike' ((,) a) s a -> a -> m a
l <<//= n = l %%= \a -> (a, a / n)
{-# INLINE (<<//=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by a non-negative power
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^=') is more flexible.
--
-- @
-- ('<<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Lens'' s a -> e -> m a
-- ('<<^=') :: ('MonadState' s m, 'Num' a, 'Integral' e) => 'Iso'' s a -> a -> m a
-- @
(<<^=) :: (MonadState s m, Num a, Integral e) => LensLike' ((,) a) s a -> e -> m a
l <<^= n = l %%= \a -> (a, a ^ n)
{-# INLINE (<<^=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by an integral power
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.^^=') is more flexible.
--
-- @
-- ('<<^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Lens'' s a -> e -> m a
-- ('<<^^=') :: ('MonadState' s m, 'Fractional' a, 'Integral' e) => 'Iso'' s a -> e -> m a
-- @
(<<^^=) :: (MonadState s m, Fractional a, Integral e) => LensLike' ((,) a) s a -> e -> m a
l <<^^= n = l %%= \a -> (a, a ^^ n)
{-# INLINE (<<^^=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by raising it by an arbitrary power
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.**=') is more flexible.
--
-- @
-- ('<<**=') :: ('MonadState' s m, 'Floating' a) => 'Lens'' s a -> a -> m a
-- ('<<**=') :: ('MonadState' s m, 'Floating' a) => 'Iso'' s a -> a -> m a
-- @
(<<**=) :: (MonadState s m, Floating a) => LensLike' ((,) a) s a -> a -> m a
l <<**= n = l %%= \a -> (a, a ** n)
{-# INLINE (<<**=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by taking its logical '||' with a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.||=') is more flexible.
--
-- @
-- ('<<||=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'
-- ('<<||=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m 'Bool'
-- @
(<<||=) :: MonadState s m => LensLike' ((,) Bool) s Bool -> Bool -> m Bool
l <<||= b = l %%= \a -> (a, a || b)
{-# INLINE (<<||=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by taking its logical '&&' with a value
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.&&=') is more flexible.
--
-- @
-- ('<<&&=') :: 'MonadState' s m => 'Lens'' s 'Bool' -> 'Bool' -> m 'Bool'
-- ('<<&&=') :: 'MonadState' s m => 'Iso'' s 'Bool' -> 'Bool' -> m 'Bool'
-- @
(<<&&=) :: MonadState s m => LensLike' ((,) Bool) s Bool -> Bool -> m Bool
l <<&&= b = l %%= \a -> (a, a && b)
{-# INLINE (<<&&=) #-}
-- | Modify the target of a 'Lens' into your 'Monad''s state by using ('<>')
-- and return the /old/ value that was replaced.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.<>=') is more flexible.
--
-- @
-- ('<<<>=') :: ('MonadState' s m, 'Semigroup' r) => 'Lens'' s r -> r -> m r
-- ('<<<>=') :: ('MonadState' s m, 'Semigroup' r) => 'Iso'' s r -> r -> m r
-- @
(<<<>=) :: (MonadState s m, Semigroup r) => LensLike' ((,) r) s r -> r -> m r
l <<<>= b = l %%= \a -> (a, a <> b)
{-# INLINE (<<<>=) #-}
-- | Run a monadic action, and set the target of 'Lens' to its result.
--
-- @
-- ('<<~') :: 'MonadState' s m => 'Control.Lens.Iso.Iso' s s a b -> m b -> m b
-- ('<<~') :: 'MonadState' s m => 'Lens' s s a b -> m b -> m b
-- @
--
-- NB: This is limited to taking an actual 'Lens' than admitting a 'Control.Lens.Traversal.Traversal' because
-- there are potential loss of state issues otherwise.
(<<~) :: MonadState s m => ALens s s a b -> m b -> m b
l <<~ mb = do
b <- mb
modify $ \s -> ipeek b (l sell s)
return b
{-# INLINE (<<~) #-}
-- | ('<>') a 'Semigroup' value onto the end of the target of a 'Lens' and
-- return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.<>~') is more flexible.
(<<>~) :: Semigroup m => LensLike ((,)m) s t m m -> m -> s -> (m, t)
l <<>~ m = l <%~ (<> m)
{-# INLINE (<<>~) #-}
-- | ('<>') a 'Semigroup' value onto the end of the target of a 'Lens' into
-- your 'Monad''s state and return the result.
--
-- When you do not need the result of the operation, ('Control.Lens.Setter.<>=') is more flexible.
(<<>=) :: (MonadState s m, Semigroup r) => LensLike' ((,)r) s r -> r -> m r
l <<>= r = l <%= (<> r)
{-# INLINE (<<>=) #-}
------------------------------------------------------------------------------
-- Arrow operators
------------------------------------------------------------------------------
-- | 'Control.Lens.Setter.over' for Arrows.
--
-- Unlike 'Control.Lens.Setter.over', 'overA' can't accept a simple
-- 'Control.Lens.Setter.Setter', but requires a full lens, or close
-- enough.
--
-- >>> overA _1 ((+1) *** (+2)) ((1,2),6)
-- ((2,4),6)
--
-- @
-- overA :: Arrow ar => Lens s t a b -> ar a b -> ar s t
-- @
overA :: Arrow ar => LensLike (Context a b) s t a b -> ar a b -> ar s t
overA l p = arr (\s -> let (Context f a) = l sell s in (f, a))
>>> second p
>>> arr (uncurry id)
------------------------------------------------------------------------------
-- Indexed
------------------------------------------------------------------------------
-- | Adjust the target of an 'IndexedLens' returning the intermediate result, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary
-- along with the answer.
--
-- @
-- l '<%~' f ≡ l '<%@~' 'const' f
-- @
--
-- When you do not need access to the index then ('<%~') is more liberal in what it can accept.
--
-- If you do not need the intermediate result, you can use ('Control.Lens.Setter.%@~') or even ('Control.Lens.Setter.%~').
--
-- @
-- ('<%@~') :: 'IndexedLens' i s t a b -> (i -> a -> b) -> s -> (b, t)
-- ('<%@~') :: 'Monoid' b => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> (b, t)
-- @
(<%@~) :: Over (Indexed i) ((,) b) s t a b -> (i -> a -> b) -> s -> (b, t)
l <%@~ f = l (Indexed $ \i a -> let b = f i a in (b, b))
{-# INLINE (<%@~) #-}
-- | Adjust the target of an 'IndexedLens' returning the old value, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary
-- of the old values along with the answer.
--
-- @
-- ('<<%@~') :: 'IndexedLens' i s t a b -> (i -> a -> b) -> s -> (a, t)
-- ('<<%@~') :: 'Monoid' a => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> b) -> s -> (a, t)
-- @
(<<%@~) :: Over (Indexed i) ((,) a) s t a b -> (i -> a -> b) -> s -> (a, t)
l <<%@~ f = l $ Indexed $ \i a -> second' (f i) (a,a)
{-# INLINE (<<%@~) #-}
-- | Adjust the target of an 'IndexedLens' returning a supplementary result, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' and return a monoidal summary
-- of the supplementary results and the answer.
--
-- @
-- ('%%@~') ≡ 'Control.Lens.Indexed.withIndex'
-- @
--
-- @
-- ('%%@~') :: 'Functor' f => 'IndexedLens' i s t a b -> (i -> a -> f b) -> s -> f t
-- ('%%@~') :: 'Applicative' f => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> f b) -> s -> f t
-- @
--
-- In particular, it is often useful to think of this function as having one of these even more
-- restricted type signatures:
--
-- @
-- ('%%@~') :: 'IndexedLens' i s t a b -> (i -> a -> (r, b)) -> s -> (r, t)
-- ('%%@~') :: 'Monoid' r => 'Control.Lens.Traversal.IndexedTraversal' i s t a b -> (i -> a -> (r, b)) -> s -> (r, t)
-- @
(%%@~) :: Over (Indexed i) f s t a b -> (i -> a -> f b) -> s -> f t
(%%@~) l = l .# Indexed
{-# INLINE (%%@~) #-}
-- | Adjust the target of an 'IndexedLens' returning a supplementary result, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and
-- return a monoidal summary of the supplementary results.
--
-- @
-- l '%%@=' f ≡ 'state' (l '%%@~' f)
-- @
--
-- @
-- ('%%@=') :: 'MonadState' s m => 'IndexedLens' i s s a b -> (i -> a -> (r, b)) -> s -> m r
-- ('%%@=') :: ('MonadState' s m, 'Monoid' r) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> (r, b)) -> s -> m r
-- @
(%%@=) :: MonadState s m => Over (Indexed i) ((,) r) s s a b -> (i -> a -> (r, b)) -> m r
#if MIN_VERSION_mtl(2,1,0)
l %%@= f = State.state (l %%@~ f)
#else
l %%@= f = do
(r, s) <- State.gets (l %%@~ f)
State.put s
return r
#endif
{-# INLINE (%%@=) #-}
-- | Adjust the target of an 'IndexedLens' returning the intermediate result, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and
-- return a monoidal summary of the intermediate results.
--
-- @
-- ('<%@=') :: 'MonadState' s m => 'IndexedLens' i s s a b -> (i -> a -> b) -> m b
-- ('<%@=') :: ('MonadState' s m, 'Monoid' b) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> b) -> m b
-- @
(<%@=) :: MonadState s m => Over (Indexed i) ((,) b) s s a b -> (i -> a -> b) -> m b
l <%@= f = l %%@= \ i a -> let b = f i a in (b, b)
{-# INLINE (<%@=) #-}
-- | Adjust the target of an 'IndexedLens' returning the old value, or
-- adjust all of the targets of an 'Control.Lens.Traversal.IndexedTraversal' within the current state, and
-- return a monoidal summary of the old values.
--
-- @
-- ('<<%@=') :: 'MonadState' s m => 'IndexedLens' i s s a b -> (i -> a -> b) -> m a
-- ('<<%@=') :: ('MonadState' s m, 'Monoid' b) => 'Control.Lens.Traversal.IndexedTraversal' i s s a b -> (i -> a -> b) -> m a
-- @
(<<%@=) :: MonadState s m => Over (Indexed i) ((,) a) s s a b -> (i -> a -> b) -> m a
#if MIN_VERSION_mtl(2,1,0)
l <<%@= f = State.state (l (Indexed $ \ i a -> (a, f i a)))
#else
l <<%@= f = do
(r, s) <- State.gets (l (Indexed $ \ i a -> (a, f i a)))
State.put s
return r
#endif
{-# INLINE (<<%@=) #-}
------------------------------------------------------------------------------
-- ALens Combinators
------------------------------------------------------------------------------
-- | A version of ('Control.Lens.Getter.^.') that works on 'ALens'.
--
-- >>> ("hello","world")^#_2
-- "world"
(^#) :: s -> ALens s t a b -> a
s ^# l = ipos (l sell s)
{-# INLINE (^#) #-}
-- | A version of 'Control.Lens.Setter.set' that works on 'ALens'.
--
-- >>> storing _2 "world" ("hello","there")
-- ("hello","world")
storing :: ALens s t a b -> b -> s -> t
storing l b s = ipeek b (l sell s)
{-# INLINE storing #-}
-- | A version of ('Control.Lens.Setter..~') that works on 'ALens'.
--
-- >>> ("hello","there") & _2 #~ "world"
-- ("hello","world")
( #~ ) :: ALens s t a b -> b -> s -> t
( #~ ) l b s = ipeek b (l sell s)
{-# INLINE ( #~ ) #-}
-- | A version of ('Control.Lens.Setter.%~') that works on 'ALens'.
--
-- >>> ("hello","world") & _2 #%~ length
-- ("hello",5)
( #%~ ) :: ALens s t a b -> (a -> b) -> s -> t
( #%~ ) l f s = ipeeks f (l sell s)
{-# INLINE ( #%~ ) #-}
-- | A version of ('%%~') that works on 'ALens'.
--
-- >>> ("hello","world") & _2 #%%~ \x -> (length x, x ++ "!")
-- (5,("hello","world!"))
( #%%~ ) :: Functor f => ALens s t a b -> (a -> f b) -> s -> f t
( #%%~ ) l f s = runPretext (l sell s) f
{-# INLINE ( #%%~ ) #-}
-- | A version of ('Control.Lens.Setter..=') that works on 'ALens'.
( #= ) :: MonadState s m => ALens s s a b -> b -> m ()
l #= f = modify (l #~ f)
{-# INLINE ( #= ) #-}
-- | A version of ('Control.Lens.Setter.%=') that works on 'ALens'.
( #%= ) :: MonadState s m => ALens s s a b -> (a -> b) -> m ()
l #%= f = modify (l #%~ f)
{-# INLINE ( #%= ) #-}
-- | A version of ('<%~') that works on 'ALens'.
--
-- >>> ("hello","world") & _2 <#%~ length
-- (5,("hello",5))
(<#%~) :: ALens s t a b -> (a -> b) -> s -> (b, t)
l <#%~ f = \s -> runPretext (l sell s) $ \a -> let b = f a in (b, b)
{-# INLINE (<#%~) #-}
-- | A version of ('<%=') that works on 'ALens'.
(<#%=) :: MonadState s m => ALens s s a b -> (a -> b) -> m b
l <#%= f = l #%%= \a -> let b = f a in (b, b)
{-# INLINE (<#%=) #-}
-- | A version of ('%%=') that works on 'ALens'.
( #%%= ) :: MonadState s m => ALens s s a b -> (a -> (r, b)) -> m r
#if MIN_VERSION_mtl(2,1,1)
l #%%= f = State.state $ \s -> runPretext (l sell s) f
#else
l #%%= f = do
p <- State.gets (l sell)
let (r, t) = runPretext p f
State.put t
return r
#endif
{-# INLINE ( #%%= ) #-}
-- | A version of ('Control.Lens.Setter.<.~') that works on 'ALens'.
--
-- >>> ("hello","there") & _2 <#~ "world"
-- ("world",("hello","world"))
(<#~) :: ALens s t a b -> b -> s -> (b, t)
l <#~ b = \s -> (b, storing l b s)
{-# INLINE (<#~) #-}
-- | A version of ('Control.Lens.Setter.<.=') that works on 'ALens'.
(<#=) :: MonadState s m => ALens s s a b -> b -> m b
l <#= b = do
l #= b
return b
{-# INLINE (<#=) #-}
-- | There is a field for every type in the 'Void'. Very zen.
--
-- >>> [] & mapped.devoid +~ 1
-- []
--
-- >>> Nothing & mapped.devoid %~ abs
-- Nothing
--
-- @
-- 'devoid' :: 'Lens'' 'Void' a
-- @
devoid :: Over p f Void Void a b
devoid _ = absurd
{-# INLINE devoid #-}
-- | We can always retrieve a @()@ from any type.
--
-- >>> "hello"^.united
-- ()
--
-- >>> "hello" & united .~ ()
-- "hello"
united :: Lens' a ()
united f v = f () <&> \ () -> v
{-# INLINE united #-}
data First1 f a = First1 (f a) a
instance (Functor f) => Functor (First1 f) where
fmap f (First1 fa a) = First1 (f <$> fa) (f a)
{-# INLINE fmap #-}
instance (Functor f) => Apply (First1 f) where
First1 ff f <.> First1 _ x = First1 (($ x) <$> ff) (f x)
{-# INLINE (<.>) #-}
getFirst1 :: First1 f a -> f a
getFirst1 (First1 fa _) = fa
{-# INLINE getFirst1 #-}
-- | A 'Lens' focusing on the first element of a 'Traversable1' container.
--
-- >>> 2 :| [3, 4] & head1 +~ 10
-- 12 :| [3,4]
--
-- >>> Identity True ^. head1
-- True
head1 :: (Traversable1 t) => Lens' (t a) a
head1 f = getFirst1 . traverse1 (\a -> First1 (f a) a)
{-# INLINE head1 #-}
-- | A 'Lens' focusing on the last element of a 'Traversable1' container.
--
-- >>> 2 :| [3, 4] & last1 +~ 10
-- 2 :| [3,14]
--
-- >>> Node 'a' [Node 'b' [], Node 'c' []] ^. last1
-- 'c'
last1 :: (Traversable1 t) => Lens' (t a) a
last1 f = fmap getReverse . head1 f . Reverse
{-# INLINE last1 #-}
-- | Fuse a composition of lenses using 'Yoneda' to provide 'fmap' fusion.
--
-- In general, given a pair of lenses 'foo' and 'bar'
--
-- @
-- fusing (foo.bar) = foo.bar
-- @
--
-- however, @foo@ and @bar@ are either going to 'fmap' internally or they are trivial.
--
-- 'fusing' exploits the 'Yoneda' lemma to merge these separate uses into a single 'fmap'.
--
-- This is particularly effective when the choice of functor 'f' is unknown at compile
-- time or when the 'Lens' @foo.bar@ in the above description is recursive or complex
-- enough to prevent inlining.
--
-- @
-- 'fusing' :: 'Lens' s t a b -> 'Lens' s t a b
-- @
fusing :: Functor f => LensLike (Yoneda f) s t a b -> LensLike f s t a b
fusing t = \f -> lowerYoneda . t (liftYoneda . f)
{-# INLINE fusing #-}
| ddssff/lens | src/Control/Lens/Lens.hs | bsd-3-clause | 54,288 | 0 | 15 | 11,711 | 9,056 | 5,405 | 3,651 | 386 | 2 |
module Paths_haskelldb_template (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version {versionBranch = [0,1,0,0], versionTags = []}
bindir, libdir, datadir, libexecdir :: FilePath
bindir = "/usr/local/bin"
libdir = "/usr/local/lib/haskelldb-template-0.1.0.0/ghc-7.6.2"
datadir = "/usr/local/share/haskelldb-template-0.1.0.0"
libexecdir = "/usr/local/libexec"
getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath
getBinDir = catchIO (getEnv "haskelldb_template_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "haskelldb_template_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "haskelldb_template_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "haskelldb_template_libexecdir") (\_ -> return libexecdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| zearen-wover/haskelldb-template | dist/build/autogen/Paths_haskelldb_template.hs | bsd-3-clause | 1,172 | 0 | 10 | 164 | 329 | 188 | 141 | 25 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Aeson.ZipperSpec (spec) where
import Test.Hspec
import Data.Aeson (decode, Value(..))
import Data.Aeson.Zipper
import qualified Data.Vector as V
spec :: Spec
spec = do
describe "motion" $ do
it "up of top" $ getValue (tloc >>= up) `shouldBe` Null
it "bar" $ getValue bar `shouldBe` Bool True
it "first entry of foo" $ getValue (bar >>= sibling "foo" >>= firstEntry)
`shouldBe` Number 1
it "second entry of foo" $ getValue (bar >>= sibling "foo" >>= entry 1)
`shouldBe` Number 2
it "one but last entry of foo" $
getValue (bar >>= sibling "foo" >>= lastEntry >>= previous)
`shouldBe` Number 3
it "move back and forth in foo" $
getValue (foo >>= firstEntry >>= forward 3 >>= jump (-2))
`shouldBe` Number 2
describe "edits" $ do
it "change value" $
getValue (foo >>= entry 0 >>= replace (Number 3) >>= up) `shouldBe`
Array (V.fromList [Number 3,Number 2,Number 3,Number 4])
it "add sibling" $ getValue (bar >>= addSibling "baz" (String "hi"))
`shouldBe` String "hi"
it "add preceding entry" $
getValue (foo >>= entry 1 >>= addBefore (Number 4) >>= up)
`shouldBe`
Array (V.fromList [Number 1,Number 4,Number 2,Number 3,Number 4])
it "add following entry" $
getValue (foo >>= entry 1 >>= addAfter (Number 5) >>= up)
`shouldBe`
Array (V.fromList [Number 1,Number 2,Number 5,Number 3,Number 4])
where
tloc = decode "{\"root\": {\"foo\": [1,2,3,4], \"bar\": true}}" >>= anchor
bar = tloc >>= child "root" >>= child "bar"
foo = tloc >>= child "root" >>= child "foo"
| llhotka/tiphys | test/Data/Aeson/ZipperSpec.hs | bsd-3-clause | 1,787 | 0 | 18 | 528 | 637 | 314 | 323 | 38 | 1 |
module Skype.LogExport (
exportChats
) where
import Skype.Entry
import Data.Set as DS
import Data.List as DL
import Data.ByteString.Char8 as DB8
import Data.ByteString as S
import Data.Time
import Control.Monad
import Control.Monad.IfElse
import Control.Exception
import System.Directory
import System.FilePath
import System.IO
import System.Locale
import Control.Arrow
import Debug.Trace
newtype SortedSkypeEntry = SortedSkypeEntry { entries :: [SkypeEntry] }
type FolderName = ByteString
newtype ExportChat = ExportChat { export :: ( FolderName, (Int, SortedSkypeEntry) ) }
getFolderName = fst . export
getEntries = entries . snd . snd . export
getUsernameSize = fst . snd . export
sortEntries :: [SkypeEntry] -> (Int,SortedSkypeEntry)
sortEntries = second (SortedSkypeEntry . DS.toList) . DL.foldl go (0,DS.empty)
where
go (current,uniq) entry = (
max (DB8.length $ senderId entry) current,
DS.insert entry uniq
)
exportChat :: String -> SkypeChat -> ExportChat
exportChat srcUser chat = ExportChat (folderName, (maxLen, sortedEntries))
where
(maxLen,sortedEntries) = sortEntries . messages $ chat
firstEntry = DL.head . entries $ sortedEntries
srcUser' = DB8.pack srcUser
uL = userL chat
uR = userR chat
folderName | srcUser' == uL = uR
| srcUser' == uR = uL
| otherwise = srcUser'
separator = DB8.pack " : "
space = DB8.head $ DB8.pack " "
exportChats :: String -> String -> [SkypeChat] -> IO ()
exportChats folder username = mapM_ ( go . exportChat username )
where
go chat = do
mkdirs $ splitDirectories folder'
bracket (openFile file' WriteMode)
hClose
(\handle -> hSetBinaryMode handle True >> doExport handle)
where
mkdirs [dir] = mkDir dir
mkdirs (dir:new:dirs) = do
mkDir dir
mkdirs $ (dir </> new) : dirs
mkDir dir =
whenM ( liftM not $ doesDirectoryExist dir )
( createDirectory dir )
folder' = folder </> username </> DB8.unpack folderName
file' = folder' </> firstEntryDateStr <.> "log"
firstEntry = DL.head . getEntries $ chat
firstEntryDateStr = formatTime defaultTimeLocale "%Y-%m-%d %H-%M-%S" . timeStamp $ firstEntry
folderName = getFolderName chat
usernameSize = getUsernameSize chat
pad l str | len' == l = str
| otherwise = DB8.concat [str, DB8.replicate ( l - len') space]
where
len' = DB8.length str
doExport handle =
mapM_ (writeEntry handle) $ getEntries chat
writeEntry handle chatEntry | DB8.length content == 0 = return ()
| otherwise = do
let username = pad usernameSize $ senderId chatEntry
let timestamp = formatTime defaultTimeLocale " %d-%m-%Y %H:%M:%S" .
timeStamp $ chatEntry
-- ugly formatting goes here
S.hPutStr handle username
S.hPutStr handle separator
S.hPutStr handle $ DB8.pack timestamp
S.hPutStr handle separator
S.hPutStrLn handle content
where
content = message chatEntry
| jdevelop/skypelogr | Skype/LogExport.hs | bsd-3-clause | 3,917 | 4 | 18 | 1,602 | 942 | 493 | 449 | 76 | 2 |
-- | This module provides the /Empty/ processor.
-- Checks wether the strict components of a problem are empty.
module Tct.Trs.Processor.Empty
( emptyDeclaration
, empty
) where
import qualified Tct.Core.Data as T
import qualified Tct.Core.Processor.Empty as E
import Tct.Trs.Data
import qualified Tct.Trs.Data.Problem as Prob
empty :: TrsStrategy
empty = E.empty Prob.isTrivial
emptyDeclaration :: T.Declaration ('[] T.:-> TrsStrategy)
emptyDeclaration = T.declare "empty" [desc] () empty
where desc = "Checks if the the strict components is empty."
| ComputationWithBoundedResources/tct-trs | src/Tct/Trs/Processor/Empty.hs | bsd-3-clause | 590 | 0 | 9 | 114 | 121 | 76 | 45 | -1 | -1 |
--
--
--
-----------------
-- Exercise 9.14.
-----------------
--
--
--
module E'9'14 where
import E'9'12 ( rev )
import Test.QuickCheck
prop_ReverseRev :: [Integer] -> Bool
prop_ReverseRev list
= reverse list == rev list
-- GHCi> quickCheck prop_ReverseRev
-- Note: Works for QuickCheck testing, but can't be used 'directly' for proving.
| pascal-knodel/haskell-craft | _/links/E'9'14.hs | mit | 357 | 0 | 6 | 69 | 58 | 37 | 21 | 6 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Abstract syntax of temporal basic specifications
Copyright : (c) Klaus Hartke, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
pretty poor abstract syntax of temporal Basic_spec, Formula, Symb_items and
Symb_map_items.
-}
module Temporal.AS_BASIC_Temporal
(
FORMULA (..)
, BASIC_SPEC (..) -- Basic Spec
, SYMB_ITEMS (..) -- List of symbols
, SYMB (..) -- Symbols
, SYMB_MAP_ITEMS (..) -- Symbol map
) where
import Common.DocUtils
import Common.Doc
import Common.Id
import Data.Data
data BASIC_SPEC = Basic_spec
deriving (Show, Typeable, Data)
instance GetRange BASIC_SPEC
instance Pretty BASIC_SPEC where
pretty = text . show
data FORMULA = Formula
deriving (Show, Eq, Ord, Typeable, Data)
instance GetRange FORMULA
instance Pretty FORMULA where
pretty = text . show
data SYMB_ITEMS = Symb_items
deriving (Show, Eq, Typeable, Data)
data SYMB = Symb_id
deriving (Show, Eq, Typeable, Data)
data SYMB_MAP_ITEMS = Symb_map_items
deriving (Show, Eq, Typeable, Data)
| keithodulaigh/Hets | Temporal/AS_BASIC_Temporal.hs | gpl-2.0 | 1,324 | 0 | 6 | 355 | 247 | 142 | 105 | 28 | 0 |
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving, Rank2Types,
FlexibleInstances, ExistentialQuantification,
DeriveDataTypeable #-}
-- | The BlazeMarkup core, consisting of functions that offer the power to
-- generate custom markup elements. It also offers user-centric functions,
-- which are exposed through 'Text.Blaze'.
--
-- While this module is exported, usage of it is not recommended, unless you
-- know what you are doing. This module might undergo changes at any time.
--
module Text.Blaze.Internal
(
-- * Important types.
ChoiceString (..)
, StaticString (..)
, MarkupM (..)
, Markup
, Tag
, Attribute
, AttributeValue
-- * Creating custom tags and attributes.
, customParent
, customLeaf
, attribute
, dataAttribute
, customAttribute
-- * Converting values to Markup.
, text
, preEscapedText
, lazyText
, preEscapedLazyText
, string
, preEscapedString
, unsafeByteString
, unsafeLazyByteString
-- * Comments
, textComment
, lazyTextComment
, stringComment
, unsafeByteStringComment
, unsafeLazyByteStringComment
-- * Converting values to tags.
, textTag
, stringTag
-- * Converting values to attribute values.
, textValue
, preEscapedTextValue
, lazyTextValue
, preEscapedLazyTextValue
, stringValue
, preEscapedStringValue
, unsafeByteStringValue
, unsafeLazyByteStringValue
-- * Setting attributes
, Attributable
, (!)
, (!?)
-- * Modifying Markup elements
, contents
, external
-- * Querying Markup elements
, null
) where
import Prelude hiding (null)
import Control.Applicative (Applicative (..))
import Data.Monoid (Monoid, mappend, mempty, mconcat)
import Unsafe.Coerce (unsafeCoerce)
import qualified Data.List as List
import Data.ByteString.Char8 (ByteString)
import Data.Text (Text)
import Data.Typeable (Typeable)
import GHC.Exts (IsString (..))
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as LT
-- | A static string that supports efficient output to all possible backends.
--
data StaticString = StaticString
{ getString :: String -> String -- ^ Appending haskell string
, getUtf8ByteString :: B.ByteString -- ^ UTF-8 encoded bytestring
, getText :: Text -- ^ Text value
}
-- 'StaticString's should only be converted from string literals, as far as I
-- can see.
--
instance IsString StaticString where
fromString s = let t = T.pack s
in StaticString (s ++) (T.encodeUtf8 t) t
-- | A string denoting input from different string representations.
--
data ChoiceString
-- | Static data
= Static {-# UNPACK #-} !StaticString
-- | A Haskell String
| String String
-- | A Text value
| Text Text
-- | An encoded bytestring
| ByteString B.ByteString
-- | A pre-escaped string
| PreEscaped ChoiceString
-- | External data in style/script tags, should be checked for validity
| External ChoiceString
-- | Concatenation
| AppendChoiceString ChoiceString ChoiceString
-- | Empty string
| EmptyChoiceString
instance Monoid ChoiceString where
mempty = EmptyChoiceString
{-# INLINE mempty #-}
mappend = AppendChoiceString
{-# INLINE mappend #-}
instance IsString ChoiceString where
fromString = String
{-# INLINE fromString #-}
-- | The core Markup datatype.
--
data MarkupM a
-- | Tag, open tag, end tag, content
= forall b. Parent StaticString StaticString StaticString (MarkupM b)
-- | Custom parent
| forall b. CustomParent ChoiceString (MarkupM b)
-- | Tag, open tag, end tag
| Leaf StaticString StaticString StaticString
-- | Custom leaf
| CustomLeaf ChoiceString Bool
-- | HTML content
| Content ChoiceString
-- | HTML comment. Note: you should wrap the 'ChoiceString' in a
-- 'PreEscaped'.
| Comment ChoiceString
-- | Concatenation of two HTML pieces
| forall b c. Append (MarkupM b) (MarkupM c)
-- | Add an attribute to the inner HTML. Raw key, key, value, HTML to
-- receive the attribute.
| AddAttribute StaticString StaticString ChoiceString (MarkupM a)
-- | Add a custom attribute to the inner HTML.
| AddCustomAttribute ChoiceString ChoiceString (MarkupM a)
-- | Empty HTML.
| Empty
deriving (Typeable)
-- | Simplification of the 'MarkupM' datatype.
--
type Markup = MarkupM ()
instance Monoid a => Monoid (MarkupM a) where
mempty = Empty
{-# INLINE mempty #-}
mappend x y = Append x y
{-# INLINE mappend #-}
mconcat = foldr Append Empty
{-# INLINE mconcat #-}
instance Functor MarkupM where
-- Safe because it does not contain a value anyway
fmap _ = unsafeCoerce
instance Applicative MarkupM where
pure _ = Empty
{-# INLINE pure #-}
(<*>) = Append
{-# INLINE (<*>) #-}
(*>) = Append
{-# INLINE (*>) #-}
(<*) = Append
{-# INLINE (<*) #-}
instance Monad MarkupM where
return _ = Empty
{-# INLINE return #-}
(>>) = Append
{-# INLINE (>>) #-}
h1 >>= f = h1 >> f
(error "Text.Blaze.Internal.MarkupM: invalid use of monadic bind")
{-# INLINE (>>=) #-}
instance IsString (MarkupM a) where
fromString = Content . fromString
{-# INLINE fromString #-}
-- | Type for an HTML tag. This can be seen as an internal string type used by
-- BlazeMarkup.
--
newtype Tag = Tag { unTag :: StaticString }
deriving (IsString)
-- | Type for an attribute.
--
newtype Attribute = Attribute (forall a. MarkupM a -> MarkupM a)
instance Monoid Attribute where
mempty = Attribute id
Attribute f `mappend` Attribute g = Attribute (g . f)
-- | The type for the value part of an attribute.
--
newtype AttributeValue = AttributeValue { unAttributeValue :: ChoiceString }
deriving (IsString, Monoid)
-- | Create a custom parent element
customParent :: Tag -- ^ Element tag
-> Markup -- ^ Content
-> Markup -- ^ Resulting markup
customParent tag = CustomParent (Static $ unTag tag)
-- | Create a custom leaf element
customLeaf :: Tag -- ^ Element tag
-> Bool -- ^ Close the leaf?
-> Markup -- ^ Resulting markup
customLeaf tag = CustomLeaf (Static $ unTag tag)
-- | Create an HTML attribute that can be applied to an HTML element later using
-- the '!' operator.
--
attribute :: Tag -- ^ Raw key
-> Tag -- ^ Shared key string for the HTML attribute.
-> AttributeValue -- ^ Value for the HTML attribute.
-> Attribute -- ^ Resulting HTML attribute.
attribute rawKey key value = Attribute $
AddAttribute (unTag rawKey) (unTag key) (unAttributeValue value)
{-# INLINE attribute #-}
-- | From HTML 5 onwards, the user is able to specify custom data attributes.
--
-- An example:
--
-- > <p data-foo="bar">Hello.</p>
--
-- We support this in BlazeMarkup using this funcion. The above fragment could
-- be described using BlazeMarkup with:
--
-- > p ! dataAttribute "foo" "bar" $ "Hello."
--
dataAttribute :: Tag -- ^ Name of the attribute.
-> AttributeValue -- ^ Value for the attribute.
-> Attribute -- ^ Resulting HTML attribute.
dataAttribute tag value = Attribute $ AddCustomAttribute
(Static "data-" `mappend` Static (unTag tag))
(unAttributeValue value)
{-# INLINE dataAttribute #-}
-- | Create a custom attribute. This is not specified in the HTML spec, but some
-- JavaScript libraries rely on it.
--
-- An example:
--
-- > <select dojoType="select">foo</select>
--
-- Can be produced using:
--
-- > select ! customAttribute "dojoType" "select" $ "foo"
--
customAttribute :: Tag -- ^ Name of the attribute
-> AttributeValue -- ^ Value for the attribute
-> Attribute -- ^ Resulting HTML attribtue
customAttribute tag value = Attribute $ AddCustomAttribute
(Static $ unTag tag)
(unAttributeValue value)
{-# INLINE customAttribute #-}
-- | Render text. Functions like these can be used to supply content in HTML.
--
text :: Text -- ^ Text to render.
-> Markup -- ^ Resulting HTML fragment.
text = Content . Text
{-# INLINE text #-}
-- | Render text without escaping.
--
preEscapedText :: Text -- ^ Text to insert
-> Markup -- ^ Resulting HTML fragment
preEscapedText = Content . PreEscaped . Text
{-# INLINE preEscapedText #-}
-- | A variant of 'text' for lazy 'LT.Text'.
--
lazyText :: LT.Text -- ^ Text to insert
-> Markup -- ^ Resulting HTML fragment
lazyText = mconcat . map text . LT.toChunks
{-# INLINE lazyText #-}
-- | A variant of 'preEscapedText' for lazy 'LT.Text'
--
preEscapedLazyText :: LT.Text -- ^ Text to insert
-> Markup -- ^ Resulting HTML fragment
preEscapedLazyText = mconcat . map preEscapedText . LT.toChunks
-- | Create an HTML snippet from a 'String'.
--
string :: String -- ^ String to insert.
-> Markup -- ^ Resulting HTML fragment.
string = Content . String
{-# INLINE string #-}
-- | Create an HTML snippet from a 'String' without escaping
--
preEscapedString :: String -- ^ String to insert.
-> Markup -- ^ Resulting HTML fragment.
preEscapedString = Content . PreEscaped . String
{-# INLINE preEscapedString #-}
-- | Insert a 'ByteString'. This is an unsafe operation:
--
-- * The 'ByteString' could have the wrong encoding.
--
-- * The 'ByteString' might contain illegal HTML characters (no escaping is
-- done).
--
unsafeByteString :: ByteString -- ^ Value to insert.
-> Markup -- ^ Resulting HTML fragment.
unsafeByteString = Content . ByteString
{-# INLINE unsafeByteString #-}
-- | Insert a lazy 'BL.ByteString'. See 'unsafeByteString' for reasons why this
-- is an unsafe operation.
--
unsafeLazyByteString :: BL.ByteString -- ^ Value to insert
-> Markup -- ^ Resulting HTML fragment
unsafeLazyByteString = mconcat . map unsafeByteString . BL.toChunks
{-# INLINE unsafeLazyByteString #-}
-- | Create a comment from a 'Text' value.
-- The text should not contain @"--"@.
-- This is not checked by the library.
textComment :: Text -> Markup
textComment = Comment . PreEscaped . Text
-- | Create a comment from a 'LT.Text' value.
-- The text should not contain @"--"@.
-- This is not checked by the library.
lazyTextComment :: LT.Text -> Markup
lazyTextComment = Comment . mconcat . map (PreEscaped . Text) . LT.toChunks
-- | Create a comment from a 'String' value.
-- The text should not contain @"--"@.
-- This is not checked by the library.
stringComment :: String -> Markup
stringComment = Comment . PreEscaped . String
-- | Create a comment from a 'ByteString' value.
-- The text should not contain @"--"@.
-- This is not checked by the library.
unsafeByteStringComment :: ByteString -> Markup
unsafeByteStringComment = Comment . PreEscaped . ByteString
-- | Create a comment from a 'BL.ByteString' value.
-- The text should not contain @"--"@.
-- This is not checked by the library.
unsafeLazyByteStringComment :: BL.ByteString -> Markup
unsafeLazyByteStringComment =
Comment . mconcat . map (PreEscaped . ByteString) . BL.toChunks
-- | Create a 'Tag' from some 'Text'.
--
textTag :: Text -- ^ Text to create a tag from
-> Tag -- ^ Resulting tag
textTag t = Tag $ StaticString (T.unpack t ++) (T.encodeUtf8 t) t
-- | Create a 'Tag' from a 'String'.
--
stringTag :: String -- ^ String to create a tag from
-> Tag -- ^ Resulting tag
stringTag = Tag . fromString
-- | Render an attribute value from 'Text'.
--
textValue :: Text -- ^ The actual value.
-> AttributeValue -- ^ Resulting attribute value.
textValue = AttributeValue . Text
{-# INLINE textValue #-}
-- | Render an attribute value from 'Text' without escaping.
--
preEscapedTextValue :: Text -- ^ The actual value
-> AttributeValue -- ^ Resulting attribute value
preEscapedTextValue = AttributeValue . PreEscaped . Text
{-# INLINE preEscapedTextValue #-}
-- | A variant of 'textValue' for lazy 'LT.Text'
--
lazyTextValue :: LT.Text -- ^ The actual value
-> AttributeValue -- ^ Resulting attribute value
lazyTextValue = mconcat . map textValue . LT.toChunks
{-# INLINE lazyTextValue #-}
-- | A variant of 'preEscapedTextValue' for lazy 'LT.Text'
--
preEscapedLazyTextValue :: LT.Text -- ^ The actual value
-> AttributeValue -- ^ Resulting attribute value
preEscapedLazyTextValue = mconcat . map preEscapedTextValue . LT.toChunks
{-# INLINE preEscapedLazyTextValue #-}
-- | Create an attribute value from a 'String'.
--
stringValue :: String -> AttributeValue
stringValue = AttributeValue . String
{-# INLINE stringValue #-}
-- | Create an attribute value from a 'String' without escaping.
--
preEscapedStringValue :: String -> AttributeValue
preEscapedStringValue = AttributeValue . PreEscaped . String
{-# INLINE preEscapedStringValue #-}
-- | Create an attribute value from a 'ByteString'. See 'unsafeByteString'
-- for reasons why this might not be a good idea.
--
unsafeByteStringValue :: ByteString -- ^ ByteString value
-> AttributeValue -- ^ Resulting attribute value
unsafeByteStringValue = AttributeValue . ByteString
{-# INLINE unsafeByteStringValue #-}
-- | Create an attribute value from a lazy 'BL.ByteString'. See
-- 'unsafeByteString' for reasons why this might not be a good idea.
--
unsafeLazyByteStringValue :: BL.ByteString -- ^ ByteString value
-> AttributeValue -- ^ Resulting attribute value
unsafeLazyByteStringValue = mconcat . map unsafeByteStringValue . BL.toChunks
{-# INLINE unsafeLazyByteStringValue #-}
-- | Used for applying attributes. You should not define your own instances of
-- this class.
class Attributable h where
-- | Apply an attribute to an element.
--
-- Example:
--
-- > img ! src "foo.png"
--
-- Result:
--
-- > <img src="foo.png" />
--
-- This can be used on nested elements as well.
--
-- Example:
--
-- > p ! style "float: right" $ "Hello!"
--
-- Result:
--
-- > <p style="float: right">Hello!</p>
--
(!) :: h -> Attribute -> h
instance Attributable (MarkupM a) where
h ! (Attribute f) = f h
{-# INLINE (!) #-}
instance Attributable (MarkupM a -> MarkupM b) where
h ! f = (! f) . h
{-# INLINE (!) #-}
-- | Shorthand for setting an attribute depending on a conditional.
--
-- Example:
--
-- > p !? (isBig, A.class "big") $ "Hello"
--
-- Gives the same result as:
--
-- > (if isBig then p ! A.class "big" else p) "Hello"
--
(!?) :: Attributable h => h -> (Bool, Attribute) -> h
(!?) h (c, a) = if c then h ! a else h
-- | Mark HTML as external data. External data can be:
--
-- * CSS data in a @<style>@ tag;
--
-- * Script data in a @<script>@ tag.
--
-- This function is applied automatically when using the @style@ or @script@
-- combinators.
--
external :: MarkupM a -> MarkupM a
external (Content x) = Content $ External x
external (Append x y) = Append (external x) (external y)
external (Parent x y z i) = Parent x y z $ external i
external (CustomParent x i) = CustomParent x $ external i
external (AddAttribute x y z i) = AddAttribute x y z $ external i
external (AddCustomAttribute x y i) = AddCustomAttribute x y $ external i
external x = x
{-# INLINE external #-}
-- | Take only the text content of an HTML tree.
--
-- > contents $ do
-- > p ! $ "Hello "
-- > p ! $ "Word!"
--
-- Result:
--
-- > Hello World!
--
contents :: MarkupM a -> MarkupM b
contents (Parent _ _ _ c) = contents c
contents (CustomParent _ c) = contents c
contents (Content c) = Content c
contents (Append c1 c2) = Append (contents c1) (contents c2)
contents (AddAttribute _ _ _ c) = contents c
contents (AddCustomAttribute _ _ c) = contents c
contents _ = Empty
-- | Check if a 'Markup' value is completely empty (renders to the empty
-- string).
null :: MarkupM a -> Bool
null markup = case markup of
Parent _ _ _ _ -> False
CustomParent _ _ -> False
Leaf _ _ _ -> False
CustomLeaf _ _ -> False
Content c -> emptyChoiceString c
Comment c -> emptyChoiceString c
Append c1 c2 -> null c1 && null c2
AddAttribute _ _ _ c -> null c
AddCustomAttribute _ _ c -> null c
Empty -> True
where
emptyChoiceString cs = case cs of
Static ss -> emptyStaticString ss
String s -> List.null s
Text t -> T.null t
ByteString bs -> B.null bs
PreEscaped c -> emptyChoiceString c
External c -> emptyChoiceString c
AppendChoiceString c1 c2 -> emptyChoiceString c1 && emptyChoiceString c2
EmptyChoiceString -> True
emptyStaticString = B.null . getUtf8ByteString
| FranklinChen/blaze-markup | src/Text/Blaze/Internal.hs | bsd-3-clause | 17,403 | 0 | 11 | 4,409 | 2,795 | 1,621 | 1,174 | 290 | 17 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Network/Wai/Handler/Warp/Buffer.hs" #-}
{-# LANGUAGE BangPatterns, OverloadedStrings #-}
module Network.Wai.Handler.Warp.Buffer (
bufferSize
, allocateBuffer
, freeBuffer
, mallocBS
, newBufferPool
, withBufferPool
, toBuilderBuffer
, copy
, bufferIO
) where
import qualified Data.ByteString as BS
import Data.ByteString.Internal (ByteString(..), memcpy)
import Data.ByteString.Unsafe (unsafeTake, unsafeDrop)
import Data.IORef (newIORef, readIORef, writeIORef)
import qualified Data.Streaming.ByteString.Builder.Buffer as B (Buffer (..))
import Foreign.ForeignPtr
import Foreign.Marshal.Alloc (mallocBytes, free, finalizerFree)
import Foreign.Ptr (castPtr, plusPtr)
import Network.Wai.Handler.Warp.Types
----------------------------------------------------------------
-- | The default size of the write buffer: 16384 (2^14 = 1024 * 16).
-- This is the maximum size of TLS record.
-- This is also the maximum size of HTTP/2 frame payload
-- (excluding frame header).
bufferSize :: BufSize
bufferSize = 16384
-- | Allocating a buffer with malloc().
allocateBuffer :: Int -> IO Buffer
allocateBuffer = mallocBytes
-- | Releasing a buffer with free().
freeBuffer :: Buffer -> IO ()
freeBuffer = free
----------------------------------------------------------------
largeBufferSize :: Int
largeBufferSize = 16384
minBufferSize :: Int
minBufferSize = 2048
newBufferPool :: IO BufferPool
newBufferPool = newIORef BS.empty
mallocBS :: Int -> IO ByteString
mallocBS size = do
ptr <- allocateBuffer size
fptr <- newForeignPtr finalizerFree ptr
return $! PS fptr 0 size
{-# INLINE mallocBS #-}
usefulBuffer :: ByteString -> Bool
usefulBuffer buffer = BS.length buffer >= minBufferSize
{-# INLINE usefulBuffer #-}
getBuffer :: BufferPool -> IO ByteString
getBuffer pool = do
buffer <- readIORef pool
if usefulBuffer buffer then return buffer else mallocBS largeBufferSize
{-# INLINE getBuffer #-}
putBuffer :: BufferPool -> ByteString -> IO ()
putBuffer pool buffer = writeIORef pool buffer
{-# INLINE putBuffer #-}
withForeignBuffer :: ByteString -> ((Buffer, BufSize) -> IO Int) -> IO Int
withForeignBuffer (PS ps s l) f = withForeignPtr ps $ \p -> f (castPtr p `plusPtr` s, l)
{-# INLINE withForeignBuffer #-}
withBufferPool :: BufferPool -> ((Buffer, BufSize) -> IO Int) -> IO ByteString
withBufferPool pool f = do
buffer <- getBuffer pool
consumed <- withForeignBuffer buffer f
putBuffer pool $! unsafeDrop consumed buffer
return $! unsafeTake consumed buffer
{-# INLINE withBufferPool #-}
----------------------------------------------------------------
--
-- Utilities
--
toBuilderBuffer :: Buffer -> BufSize -> IO B.Buffer
toBuilderBuffer ptr size = do
fptr <- newForeignPtr_ ptr
return $ B.Buffer fptr ptr ptr (ptr `plusPtr` size)
-- | Copying the bytestring to the buffer.
-- This function returns the point where the next copy should start.
copy :: Buffer -> ByteString -> IO Buffer
copy !ptr (PS fp o l) = withForeignPtr fp $ \p -> do
memcpy ptr (p `plusPtr` o) (fromIntegral l)
return $! ptr `plusPtr` l
{-# INLINE copy #-}
bufferIO :: Buffer -> Int -> (ByteString -> IO ()) -> IO ()
bufferIO ptr siz io = do
fptr <- newForeignPtr_ ptr
io $ PS fptr 0 siz
| phischu/fragnix | tests/packages/scotty/Network.Wai.Handler.Warp.Buffer.hs | bsd-3-clause | 3,307 | 0 | 11 | 566 | 825 | 447 | 378 | 74 | 2 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, OverloadedStrings, MultiWayIf #-}
module Main where
import Control.Applicative
import Control.Arrow
import Control.Concurrent (MVar, newMVar, takeMVar, putMVar, threadDelay)
import Control.Monad (guard)
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.State.Strict (StateT, get, modify, runStateT)
import Data.Char (isDigit)
import Data.List (isPrefixOf)
import Data.Monoid ((<>))
import qualified Data.Text as T
import IHaskell.IPython.Kernel
import IHaskell.IPython.EasyKernel (installProfile, easyKernel, KernelConfig(..))
import System.Environment (getArgs)
import System.FilePath ((</>))
import Text.Parsec (Parsec, ParseError, alphaNum, char, letter, oneOf, optionMaybe,
runParser, (<?>))
import qualified Text.Parsec.Token as P
import qualified Paths_ipython_kernel as Paths
---------------------------------------------------------
-- Hutton's Razor, plus time delays, plus a global state
---------------------------------------------------------
--
-- | This language is Hutton's Razor with two added operations that are needed to demonstrate the
-- kernel features: a global state, accessed and modified using Count, and a sleep operation.
data Razor = I Integer
| Plus Razor Razor
| SleepThen Double Razor
| Count
deriving (Read, Show, Eq)
-- ------- Parser -------
razorDef :: Monad m => P.GenLanguageDef String a m
razorDef = P.LanguageDef
{ P.commentStart = "(*"
, P.commentEnd = "*)"
, P.commentLine = "//"
, P.nestedComments = True
, P.identStart = letter <|> char '_'
, P.identLetter = alphaNum <|> char '_'
, P.opStart = oneOf "+"
, P.opLetter = oneOf "+"
, P.reservedNames = ["sleep", "then", "end", "count"]
, P.reservedOpNames = []
, P.caseSensitive = True
}
lexer :: Monad m => P.GenTokenParser String a m
lexer = P.makeTokenParser razorDef
parens :: Parsec String a b -> Parsec String a b
parens = P.parens lexer
reserved :: String -> Parsec String a ()
reserved = P.reserved lexer
integer :: Parsec String a Integer
integer = P.integer lexer
float :: Parsec String a Double
float = P.float lexer
operator :: Parsec String a String
operator = P.operator lexer
keyword :: String -> Parsec String a ()
keyword kwd = reserved kwd <?> "the keyword \"" ++ kwd ++ "\""
literal :: Parsec String a Razor
literal = I <$> integer
sleepThen :: Parsec String a Razor
sleepThen = do
keyword "sleep"
delay <- float <?> "seconds"
keyword "then"
body <- expr
keyword "end" <?> ""
return $ SleepThen delay body
count :: Parsec String a Razor
count = keyword "count" >> return Count
expr :: Parsec String a Razor
expr = do
one <- parens expr <|> literal <|> sleepThen <|> count
rest <- optionMaybe
(do
op <- operator
guard (op == "+")
expr)
case rest of
Nothing -> return one
Just other -> return $ Plus one other
parse :: String -> Either ParseError Razor
parse = runParser expr () "(input)"
-- -------------------- Language operations -------------------- | Completion
langCompletion :: T.Text -> T.Text -> Int -> Maybe ([T.Text], T.Text, T.Text)
langCompletion _code line col =
let (before, _) = T.splitAt col line
in fmap (\word -> (map T.pack . matchesFor $ T.unpack word, word, word))
(lastMaybe (T.words before))
where
lastMaybe :: [a] -> Maybe a
lastMaybe [] = Nothing
lastMaybe [x] = Just x
lastMaybe (_:xs) = lastMaybe xs
matchesFor :: String -> [String]
matchesFor input = filter (isPrefixOf input) available
available = ["sleep", "then", "end", "count"] ++ map show [(-1000 :: Int) .. 1000]
-- | Documentation lookup
langInfo :: T.Text -> Maybe (T.Text, T.Text, T.Text)
langInfo obj =
if | any (T.isPrefixOf obj) ["sleep", "then", "end"] -> Just (obj, sleepDocs, sleepType)
| T.isPrefixOf obj "count" -> Just (obj, countDocs, countType)
| obj == "+" -> Just (obj, plusDocs, plusType)
| T.all isDigit obj -> Just (obj, intDocs obj, intType)
| [x, y] <- T.splitOn "." obj
, T.all isDigit x
, T.all isDigit y -> Just (obj, floatDocs obj, floatType)
| otherwise -> Nothing
where
sleepDocs = "sleep DURATION then VALUE end: sleep DURATION seconds, then eval VALUE"
sleepType = "sleep FLOAT then INT end"
plusDocs = "Perform addition"
plusType = "INT + INT"
intDocs i = "The integer " <> i
intType = "INT"
floatDocs f = "The floating point value " <> f
floatType = "FLOAT"
countDocs = "Increment and return the current counter"
countType = "INT"
-- | Messages sent to the frontend during evaluation will be lists of trace elements
data IntermediateEvalRes = Got Razor Integer
| Waiting Double
deriving Show
-- | Cons for lists of trace elements - in this case, "sleeping" messages should replace old ones to
-- create a countdown effect.
consRes :: IntermediateEvalRes -> [IntermediateEvalRes] -> [IntermediateEvalRes]
consRes r@(Waiting _) (Waiting _:s) = r : s
consRes r s = r : s
-- | Execute an expression.
execRazor :: MVar Integer -- ^ The global counter state
-> Razor -- ^ The term to execute
-> IO () -- ^ Callback to clear output so far
-> ([IntermediateEvalRes] -> IO ()) -- ^ Callback for intermediate results
-> StateT ([IntermediateEvalRes], T.Text) IO Integer
execRazor _ x@(I i) _ _ =
modify (second (<> T.pack (show x))) >> return i
execRazor val tm@(Plus x y) clear send =
do
modify (second (<> T.pack (show tm)))
x' <- execRazor val x clear send
modify (first $ consRes (Got x x'))
sendState
y' <- execRazor val y clear send
modify (first $ consRes (Got y y'))
sendState
let res = x' + y'
modify (first $ consRes (Got tm res))
sendState
return res
where
sendState = liftIO clear >> fst <$> get >>= liftIO . send
execRazor val (SleepThen delay body) clear send
| delay <= 0.0 = execRazor val body clear send
| delay > 0.1 = do
modify (first $ consRes (Waiting delay))
sendState
liftIO $ threadDelay 100000
execRazor val (SleepThen (delay - 0.1) body) clear send
| otherwise = do
modify (first $ consRes (Waiting 0))
sendState
liftIO $ threadDelay (floor (delay * 1000000))
execRazor val body clear send
where
sendState = liftIO clear >> fst <$> get >>= liftIO . send
execRazor val Count clear send = do
i <- liftIO $ takeMVar val
modify (first $ consRes (Got Count i))
sendState
liftIO $ putMVar val (i + 1)
return i
where
sendState = liftIO clear >> fst <$> get >>= liftIO . send
-- | Generate a language configuration for some initial state
mkConfig :: MVar Integer -- ^ The internal state of the execution
-> KernelConfig IO [IntermediateEvalRes] (Either ParseError Integer)
mkConfig var = KernelConfig
{ languageName = "expanded_huttons_razor"
, languageVersion = [0, 1, 0]
, profileSource = Just . (</> "calc_profile.tar") <$> Paths.getDataDir
, displayResult = displayRes
, displayOutput = displayOut
, completion = langCompletion
, inspectInfo = langInfo
, run = parseAndRun
, debug = False
}
where
displayRes (Left err) =
[ DisplayData MimeHtml . T.pack $ "<em>" ++ show err ++ "</em>"
, DisplayData PlainText . T.pack $ show err
]
displayRes (Right x) =
return . DisplayData MimeHtml . T.pack $
"Answer: <strong>" ++ show x ++ "</strong>"
displayOut out =
let outLines = reverse (map (T.pack . show) out)
in return (DisplayData PlainText (T.unlines outLines))
parseAndRun code clear send =
case parse (T.unpack code) of
Left err -> return (Left err, Err, "")
Right tm -> do
(res, (_, pager)) <- runStateT (execRazor var tm clear send) ([], "")
return (Right res, Ok, T.unpack pager)
main :: IO ()
main = do
args <- getArgs
val <- newMVar 1
case args of
["kernel", profileFile] ->
easyKernel profileFile (mkConfig val)
["setup"] -> do
putStrLn "Installing profile..."
installProfile (mkConfig val)
_ -> do
putStrLn "Usage:"
putStrLn "simple-calc-example setup -- set up the profile"
putStrLn
"simple-calc-example kernel FILE -- run a kernel with FILE for communication with the frontend"
| FranklinChen/IHaskell | ipython-kernel/examples/Calc.hs | mit | 8,560 | 0 | 16 | 2,106 | 2,701 | 1,401 | 1,300 | 198 | 6 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Completion
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Collection of functions for completion and matching.
module Yi.Completion
( completeInList, completeInList'
, completeInListCustomShow
, commonPrefix
, prefixMatch, infixMatch
, subsequenceMatch
, containsMatch', containsMatch, containsMatchCaseInsensitive
, mkIsPrefixOf
)
where
import Control.Applicative ((<$>))
import Data.Function (on)
import Data.List (find, nub)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import qualified Data.Text as T (Text, breakOn, isPrefixOf, length, null, tails, toCaseFold)
import Yi.Editor (EditorM, printMsg, printMsgs)
import Yi.String (commonTPrefix', showT)
import Yi.Utils (commonPrefix)
-------------------------------------------
-- General completion
-- | Like usual 'T.isPrefixOf' but user can specify case sensitivity.
-- See 'T.toCaseFold' for exotic unicode gotchas.
mkIsPrefixOf :: Bool -- ^ Is case-sensitive?
-> T.Text
-> T.Text
-> Bool
mkIsPrefixOf True = T.isPrefixOf
mkIsPrefixOf False = T.isPrefixOf `on` T.toCaseFold
-- | Prefix matching function, for use with 'completeInList'
prefixMatch :: T.Text -> T.Text -> Maybe T.Text
prefixMatch prefix s = if prefix `T.isPrefixOf` s then Just s else Nothing
-- | Infix matching function, for use with 'completeInList'
infixMatch :: T.Text -> T.Text -> Maybe T.Text
infixMatch needle haystack = case T.breakOn needle haystack of
(_, t) -> if T.null t then Nothing else Just t
-- | Example: "abc" matches "a1b2c"
subsequenceMatch :: String -> String -> Bool
subsequenceMatch needle haystack = go needle haystack
where go (n:ns) (h:hs) | n == h = go ns hs
go (n:ns) (h:hs) | n /= h = go (n:ns) hs
go [] _ = True
go _ [] = False
go _ _ = False
-- | TODO: this is a terrible function, isn't this just
-- case-insensitive infix? – Fūzetsu
containsMatch' :: Bool -> T.Text -> T.Text -> Maybe T.Text
containsMatch' caseSensitive pattern str =
const str <$> find (pattern `tstPrefix`) (T.tails str)
where
tstPrefix = mkIsPrefixOf caseSensitive
containsMatch :: T.Text -> T.Text -> Maybe T.Text
containsMatch = containsMatch' True
containsMatchCaseInsensitive :: T.Text -> T.Text -> Maybe T.Text
containsMatchCaseInsensitive = containsMatch' False
-- | Complete a string given a user input string, a matching function
-- and a list of possibilites. Matching function should return the
-- part of the string that matches the user string.
completeInList :: T.Text -- ^ Input to match on
-> (T.Text -> Maybe T.Text) -- ^ matcher function
-> [T.Text] -- ^ items to match against
-> EditorM T.Text
completeInList = completeInListCustomShow id
-- | Same as 'completeInList', but maps @showFunction@ on possible
-- matches when printing
completeInListCustomShow :: (T.Text -> T.Text) -- ^ Show function
-> T.Text -- ^ Input to match on
-> (T.Text -> Maybe T.Text) -- ^ matcher function
-> [T.Text] -- ^ items to match against
-> EditorM T.Text
completeInListCustomShow showFunction s match possibilities
| null filtered = printMsg "No match" >> return s
| prefix /= s = return prefix
| isSingleton filtered = printMsg "Sole completion" >> return s
| prefix `elem` filtered =
printMsg ("Complete, but not unique: " <> showT filtered) >> return s
| otherwise = printMsgs (map showFunction filtered)
>> return (bestMatch filtered s)
where
prefix = commonTPrefix' filtered
filtered = filterMatches match possibilities
completeInList' :: T.Text
-> (T.Text -> Maybe T.Text)
-> [T.Text]
-> EditorM T.Text
completeInList' s match l = case filtered of
[] -> printMsg "No match" >> return s
[x] | s == x -> printMsg "Sole completion" >> return s
| otherwise -> return x
_ -> printMsgs filtered >> return (bestMatch filtered s)
where
filtered = filterMatches match l
-- | This function attempts to provide a better tab completion result in
-- cases where more than one file matches our prefix. Consider directory with
-- following files: @["Main.hs", "Main.hi", "Main.o", "Test.py", "Foo.hs"]@.
--
-- After inserting @Mai@ into the minibuffer and attempting to complete, the
-- possible matches will be filtered in 'completeInList'' to
-- @["Main.hs", "Main.hi", "Main.o"]@ however because of multiple matches,
-- the buffer will not be updated to say @Main.@ but will instead stay at @Mai@.
--
-- This is extremely tedious when trying to complete filenames in directories
-- with many files so here we try to catch common prefixes of filtered files and
-- if the result is longer than what we have, we use it instead.
bestMatch :: [T.Text] -> T.Text -> T.Text
bestMatch fs s = let p = commonTPrefix' fs
in if T.length p > T.length s then p else s
filterMatches :: Eq a => (b -> Maybe a) -> [b] -> [a]
filterMatches match = nub . catMaybes . fmap match
-- Not really necessary but a bit faster than @(length l) == 1@
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
| TOSPIO/yi | src/library/Yi/Completion.hs | gpl-2.0 | 5,587 | 0 | 11 | 1,375 | 1,245 | 665 | 580 | 83 | 5 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="el-GR">
<title>JSON View</title>
<maps>
<homeID>jsonview</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/jsonview/src/main/javahelp/help_el_GR/helpset_el_GR.hs | apache-2.0 | 959 | 77 | 66 | 156 | 407 | 206 | 201 | -1 | -1 |
module Options.CodeGen where
import Types
codegenOptions :: [Flag]
codegenOptions =
[ flag { flagName = "-fasm"
, flagDescription =
"Use the :ref:`native code generator <native-code-gen>`"
, flagType = DynamicFlag
, flagReverse = "-fllvm"
}
, flag { flagName = "-fllvm"
, flagDescription =
"Compile using the :ref:`LLVM code generator <llvm-code-gen>`"
, flagType = DynamicFlag
, flagReverse = "-fasm"
}
, flag { flagName = "-fno-code"
, flagDescription = "Omit code generation"
, flagType = DynamicFlag
}
, flag { flagName = "-fwrite-interface"
, flagDescription = "Always write interface files"
, flagType = DynamicFlag
}
, flag { flagName = "-fbyte-code"
, flagDescription = "Generate byte-code"
, flagType = DynamicFlag
}
, flag { flagName = "-fobject-code"
, flagDescription = "Generate object code"
, flagType = DynamicFlag
}
]
| siddhanathan/ghc | utils/mkUserGuidePart/Options/CodeGen.hs | bsd-3-clause | 1,052 | 0 | 7 | 346 | 172 | 112 | 60 | 26 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.Monitors.CpuFreq
-- Copyright : (c) Juraj Hercek
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Juraj Hercek <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- A cpu frequency monitor for Xmobar
--
-----------------------------------------------------------------------------
module Plugins.Monitors.CpuFreq where
import Plugins.Monitors.Common
import Plugins.Monitors.CoreCommon
-- |
-- Cpu frequency default configuration. Default template contains only
-- one core frequency, user should specify custom template in order to
-- get more cpu frequencies.
cpuFreqConfig :: IO MConfig
cpuFreqConfig =
mkMConfig "Freq: <cpu0>" (map ((++) "cpu" . show) [0 :: Int ..])
-- |
-- Function retrieves monitor string holding the cpu frequency (or
-- frequencies)
runCpuFreq :: [String] -> Monitor String
runCpuFreq _ = do
suffix <- getConfigValue useSuffix
let path = ["/sys/devices/system/cpu/cpu", "/cpufreq/scaling_cur_freq"]
divisor = 1e6 :: Double
fmt x | x < 1 = show (round (x * 1000) :: Integer) ++
if suffix then "MHz" else ""
| otherwise = show x ++ if suffix then "GHz" else ""
failureMessage <- getConfigValue naString
checkedDataRetrieval failureMessage [path] Nothing (/divisor) fmt
| dsalisbury/xmobar | src/Plugins/Monitors/CpuFreq.hs | bsd-3-clause | 1,409 | 0 | 16 | 259 | 244 | 139 | 105 | 16 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.