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
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} module Cenary.EvmAPI.API ( OpcodeM (..) , toOpcode , stop , add , mul , sub , div , mod , gt , lt , eq , iszero , pop , mload , mstore , mstore8 , sload , sstore , jump , jumpi , codecopy , dup1 , exp , calldataload , dup2 , dup3 , dup4 , dup5 , dup6 , swap1 , swap2 , swap3 , swap4 , log0 , log1 , log2 , op_return , address , push1 , push4 , push32 , generateByteCode , inc , dec , sha3 , leq , Instruction (JUMPDEST) ) where import Data.Monoid ((<>)) import Cenary.EvmAPI.Instruction (Instruction (..)) import Cenary.EvmAPI.Program (Program (..)) import Prelude hiding (EQ, GT, LT, div, exp, mod) import Text.Printf import Cenary.EvmAPI.OpcodeM import Cenary.EvmAPI.Instruction stop, add, mul, sub, div, mod, gt, lt, eq, iszero, pop, mload, mstore, mstore8, sload, sstore, jump, jumpi, codecopy, dup1, exp, calldataload, dup2, dup3, dup4, dup5, dup6, swap1, swap2, swap3, swap4, log0, log1, log2, op_return, address, sha3 :: OpcodeM m => m () stop = op STOP add = op ADD mul = op MUL sub = op SUB div = op DIV mod = op MOD gt = op GT lt = op LT eq = op EQ iszero = op ISZERO pop = op POP mload = op MLOAD mstore = op MSTORE mstore8 = op MSTORE8 sload = op SLOAD sstore = op SSTORE jump = op JUMP jumpi = op JUMPI codecopy = op CODECOPY dup1 = op DUP1 exp = op EXP calldataload = op CALLDATALOAD dup2 = op DUP2 dup3 = op DUP3 dup4 = op DUP4 dup5 = op DUP5 dup6 = op DUP6 swap1 = op SWAP1 swap2 = op SWAP2 swap3 = op SWAP3 swap4 = op SWAP4 log0 = op LOG0 log1 = op LOG1 log2 = op LOG2 op_return = op RETURN address = op ADDRESS sha3 = op SHA3 push1 :: OpcodeM m => Integer -> m () push1 = op . PUSH1 push4 :: OpcodeM m => Integer -> m () push4 = op . PUSH4 push32 :: OpcodeM m => Integer -> m () push32 = op . PUSH32 generateByteCode :: Program -> String generateByteCode (Program instructions) = foldr (\instr bc -> bc <> to_bytecode instr) "" instructions where to_bytecode :: Instruction -> String to_bytecode instr = let (opcode, _) = toOpcode instr in (printf "%02x" (opcode :: Int)) <> (pushed_vals instr) pushed_vals :: Instruction -> String pushed_vals = \case PUSH32 val -> printf "%064x" val PUSH4 val -> printf "%08x" val PUSH1 val -> printf "%02x" val _ -> "" inc :: OpcodeM m => Integer -> m () inc val = push32 val >> add dec :: OpcodeM m => Integer -> m () dec val = push32 val >> swap1 >> sub leq :: OpcodeM m => m () leq = do push32 1 swap1 sub lt
yigitozkavci/ivy
src/Cenary/EvmAPI/API.hs
mit
3,056
0
12
1,081
1,007
576
431
128
4
module System.Logging.Facade.SinkSpec (main, spec) where import Helper import System.Logging.Facade import System.Logging.Facade.Types import System.Logging.Facade.Sink main :: IO () main = hspec spec spec :: Spec spec = do describe "withLogSink" $ do it "sets the global log sink to specified value before running specified action" $ do (logRecords, spy) <- logSinkSpy withLogSink spy (info "some log message") logRecords `shouldReturn` [LogRecord INFO Nothing "some log message"] it "restores the original log sink when done" $ do (logRecords, spy) <- logSinkSpy setLogSink spy withLogSink (\_ -> return ()) (return ()) info "some log message" logRecords `shouldReturn` [LogRecord INFO Nothing "some log message"]
sol/logging-facade
test/System/Logging/Facade/SinkSpec.hs
mit
819
0
17
202
216
112
104
20
1
{-# LANGUAGE MagicHash #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Odin.Engine.Physics ( module PE , External , OdinWorld , OdinScene , World(..) , Body(..) , emptyBody , odinBodyToWorldObj , physicalObj , worldObject , physicalObj2RndTfrms , worldObj2RndTfrms , worldObjPos , worldObjRot , applyPhysics , emptyScene , rectangleHull , canonicalizeVec , canonicalizePoint , canonicalizeConvexHull ) where import Physics.Constraint as PE import Physics.Contact as PE import Physics.Contact.ConvexHull (ConvexHull) import qualified Physics.Contact.ConvexHull as PE import Physics.Engine as PE import Physics.Engine.Main as PE import qualified Physics.Linear as PE import Physics.Linear.Convert as PE import Physics.Scenes.Scene as PE import Physics.World as PE import Physics.World.Class (External) import Physics.World.Object as PE import qualified Data.Array as A import Data.IntMap.Strict import qualified Data.IntMap.Strict as IM import Gelatin.SDL2 import GHC.Exts (Double (..)) import Linear.Affine (Point (..)) type OdinWorld = World WorldObj type OdinScene = Scene Engine physicalObj :: (Double, Double) -- ^ The velocity of the object. -> Double -- ^ The rotational velocity of the object. -> (Double, Double) -- ^ The position of the object. -> Double -- ^ The rotation of the object. -> (Double, Double) -- ^ Mass -> PhysicalObj physicalObj vel rotvel pos rotpos = PhysicalObj (pairToV2 vel) rotvel (pairToV2 pos) rotpos . toInvMass2 rectangleHull :: Double -> Double -> ConvexHull rectangleHull (D# w) (D# h) = PE.rectangleHull w h worldObject :: (Double, Double) -- ^ The velocity of the object. -> Double -- ^ The rotational velocity of the object. -> (Double, Double) -- ^ The position of the object. -> Double -- ^ The rotation of the object. -> (Double, Double) -- ^ Linear and rotation mass of the object. -> Double -- ^ Mu? -> ConvexHull -- ^ The shape of the object. -> WorldObj worldObject vel rotvel pos rotpos mass = makeWorldObj phys where phys = physicalObj vel rotvel pos rotpos mass data Body = Body { bVel :: (Double, Double) , bRotVel :: Double , bPos :: (Double, Double) , bRot :: Double , bMass :: (Double, Double) , bMu :: Double , bHull :: ConvexHull } emptyBody :: Body emptyBody = Body { bVel = (0, 0) , bRotVel = 0 , bPos = (0, 0) , bRot = 0 , bMass = (0, 0) , bMu = 0 , bHull = rectangleHull 0 0 } odinBodyToWorldObj :: Body -> WorldObj odinBodyToWorldObj Body{..} = worldObject bVel bRotVel bPos bRot bMass bMu bHull emptyScene :: OdinScene emptyScene = Scene world externals contactBehavior where world = emptyWorld externals = [] contactBehavior = ContactBehavior 0.01 0.02 physicalObj2RndTfrms :: PhysicalObj -> [RenderTransform2] physicalObj2RndTfrms PhysicalObj{..} = [v,r] where vd = toLV2 _physObjPos v = Spatial $ Translate $ realToFrac <$> vd r = Spatial $ Rotate $ realToFrac _physObjRotPos worldObj2RndTfrms :: WorldObj -> [RenderTransform2] worldObj2RndTfrms = physicalObj2RndTfrms . _worldPhysObj applyPhysics :: IntMap WorldObj -> IntMap [RenderTransform2] -> IntMap [RenderTransform2] applyPhysics objs = IM.intersectionWith (++) objTfrms where objTfrms = worldObj2RndTfrms <$> objs -------------------------------------------------------------------------------- -- Converting Shapes types to Linear types -------------------------------------------------------------------------------- canonicalizePoint :: PE.P2 -> V2 Double canonicalizePoint = unPoint . toLP2 where unPoint (P v) = v canonicalizeVec :: PE.V2 -> V2 Double canonicalizeVec = toLV2 canonicalizeConvexHull :: ConvexHull -> [V2 Double] canonicalizeConvexHull = (canonicalizePoint <$>) . A.elems . PE._hullLocalVertices worldObjPos :: WorldObj -> V2 Float worldObjPos = (realToFrac <$>) . canonicalizeVec . _physObjPos . _worldPhysObj worldObjRot :: WorldObj -> Float worldObjRot = realToFrac . _physObjRotPos . _worldPhysObj
schell/odin
odin-engine/src/Odin/Engine/Physics.hs
mit
4,877
0
11
1,558
1,007
598
409
109
1
{-# LANGUAGE TupleSections #-} -- | Convert the concrete syntax into the syntax of cubical TT. module Resolver where import Control.Applicative import Control.Monad import Control.Monad.Reader import Control.Monad.Except import Control.Monad.Identity import Data.List import Data.Map (Map,(!)) import qualified Data.Map as Map import Exp.Abs import CTT (Ter,Ident,Loc(..),mkApps,mkWheres) import qualified CTT import Connections (negFormula,andFormula,orFormula) import qualified Connections as C -- | Useful auxiliary functions -- Applicative cons (<:>) :: Applicative f => f a -> f [a] -> f [a] a <:> b = (:) <$> a <*> b -- Un-something functions unVar :: Exp -> Maybe Ident unVar (Var (AIdent (_,x))) = Just x unVar _ = Nothing unWhere :: ExpWhere -> Exp unWhere (Where e ds) = Let ds e unWhere (NoWhere e) = e -- Tail recursive form to transform a sequence of applications -- App (App (App u v) ...) w into (u, [v, …, w]) -- (cleaner than the previous version of unApps) unApps :: Exp -> [Exp] -> (Exp, [Exp]) unApps (App u v) ws = unApps u (v : ws) unApps u ws = (u, ws) -- Turns an expression of the form App (... (App id1 id2) ... idn) -- into a list of idents appsToIdents :: Exp -> Maybe [Ident] appsToIdents = mapM unVar . uncurry (:) . flip unApps [] -- Transform a sequence of applications -- (((u v1) .. vn) phi1) .. phim into (u,[v1,..,vn],[phi1,..,phim]) unAppsFormulas :: Exp -> [Formula]-> (Exp,[Exp],[Formula]) unAppsFormulas (AppFormula u phi) phis = unAppsFormulas u (phi:phis) unAppsFormulas u phis = (x,xs,phis) where (x,xs) = unApps u [] -- Flatten a tele flattenTele :: [Tele] -> [(Ident,Exp)] flattenTele tele = [ (unAIdent i,typ) | Tele id ids typ <- tele, i <- id:ids ] -- Flatten a PTele flattenPTele :: [PTele] -> Resolver [(Ident,Exp)] flattenPTele [] = return [] flattenPTele (PTele exp typ : xs) = case appsToIdents exp of Just ids -> do pt <- flattenPTele xs return $ map (,typ) ids ++ pt Nothing -> throwError "malformed ptele" ------------------------------------------------------------------------------- -- | Resolver and environment data SymKind = Variable | Constructor | PConstructor | Name deriving (Eq,Show) -- local environment for constructors data Env = Env { envModule :: String, variables :: [(Ident,SymKind)] } deriving (Eq,Show) type Resolver a = ReaderT Env (ExceptT String Identity) a emptyEnv :: Env emptyEnv = Env "" [] runResolver :: Resolver a -> Either String a runResolver x = runIdentity $ runExceptT $ runReaderT x emptyEnv updateModule :: String -> Env -> Env updateModule mod e = e{envModule = mod} insertIdent :: (Ident,SymKind) -> Env -> Env insertIdent (n,var) e | n == "_" = e | otherwise = e{variables = (n,var) : variables e} insertIdents :: [(Ident,SymKind)] -> Env -> Env insertIdents = flip $ foldr insertIdent insertName :: AIdent -> Env -> Env insertName (AIdent (_,x)) = insertIdent (x,Name) insertNames :: [AIdent] -> Env -> Env insertNames = flip $ foldr insertName insertVar :: Ident -> Env -> Env insertVar x = insertIdent (x,Variable) insertVars :: [Ident] -> Env -> Env insertVars = flip $ foldr insertVar insertAIdent :: AIdent -> Env -> Env insertAIdent (AIdent (_,x)) = insertIdent (x,Variable) insertAIdents :: [AIdent] -> Env -> Env insertAIdents = flip $ foldr insertAIdent getLoc :: (Int,Int) -> Resolver Loc getLoc l = Loc <$> asks envModule <*> pure l unAIdent :: AIdent -> Ident unAIdent (AIdent (_,x)) = x resolveName :: AIdent -> Resolver C.Name resolveName (AIdent (l,x)) = do modName <- asks envModule vars <- asks variables case lookup x vars of Just Name -> return $ C.Name x _ -> throwError $ "Cannot resolve name " ++ x ++ " at position " ++ show l ++ " in module " ++ modName resolveVar :: AIdent -> Resolver Ter resolveVar (AIdent (l,x)) = do modName <- asks envModule vars <- asks variables case lookup x vars of Just Variable -> return $ CTT.Var x Just Constructor -> return $ CTT.Con x [] Just PConstructor -> throwError $ "The path constructor " ++ x ++ " is used as a" ++ " variable at " ++ show l ++ " in " ++ modName ++ " (path constructors should have their type in" ++ " curly braces as first argument)" Just Name -> throwError $ "Name " ++ x ++ " used as a variable at position " ++ show l ++ " in module " ++ modName _ -> throwError $ "Cannot resolve variable " ++ x ++ " at position " ++ show l ++ " in module " ++ modName lam :: (Ident,Exp) -> Resolver Ter -> Resolver Ter lam (a,t) e = CTT.Lam a <$> resolveExp t <*> local (insertVar a) e lams :: [(Ident,Exp)] -> Resolver Ter -> Resolver Ter lams = flip $ foldr lam path :: AIdent -> Resolver Ter -> Resolver Ter path i e = CTT.Path (C.Name (unAIdent i)) <$> local (insertName i) e paths :: [AIdent] -> Resolver Ter -> Resolver Ter paths [] _ = throwError "Empty path abstraction" paths xs e = foldr path e xs bind :: (Ter -> Ter) -> (Ident,Exp) -> Resolver Ter -> Resolver Ter bind f (x,t) e = f <$> lam (x,t) e binds :: (Ter -> Ter) -> [(Ident,Exp)] -> Resolver Ter -> Resolver Ter binds f = flip $ foldr $ bind f resolveApps :: Exp -> [Exp] -> Resolver Ter resolveApps x xs = mkApps <$> resolveExp x <*> mapM resolveExp xs resolveExp :: Exp -> Resolver Ter resolveExp e = case e of U -> return CTT.U Var x -> resolveVar x App t s -> resolveApps x xs where (x,xs) = unApps t [s] Sigma ptele b -> do tele <- flattenPTele ptele binds CTT.Sigma tele (resolveExp b) Pi ptele b -> do tele <- flattenPTele ptele binds CTT.Pi tele (resolveExp b) Fun a b -> bind CTT.Pi ("_",a) (resolveExp b) Lam ptele t -> do tele <- flattenPTele ptele lams tele (resolveExp t) Fst t -> CTT.Fst <$> resolveExp t Snd t -> CTT.Snd <$> resolveExp t Pair t0 ts -> do e <- resolveExp t0 es <- mapM resolveExp ts return $ foldr1 CTT.Pair (e:es) Let decls e -> do (rdecls,names) <- resolveDecls decls mkWheres rdecls <$> local (insertIdents names) (resolveExp e) Path is e -> paths is (resolveExp e) Hole (HoleIdent (l,_)) -> CTT.Hole <$> getLoc l AppFormula t phi -> let (x,xs,phis) = unAppsFormulas e [] in case x of PCon n a -> CTT.PCon (unAIdent n) <$> resolveExp a <*> mapM resolveExp xs <*> mapM resolveFormula phis _ -> CTT.AppFormula <$> resolveExp t <*> resolveFormula phi IdP a u v -> CTT.IdP <$> resolveExp a <*> resolveExp u <*> resolveExp v Comp u v ts -> CTT.Comp <$> resolveExp u <*> resolveExp v <*> resolveSystem ts Fill u v ts -> CTT.Fill <$> resolveExp u <*> resolveExp v <*> resolveSystem ts Trans u v -> CTT.Comp <$> resolveExp u <*> resolveExp v <*> pure Map.empty Glue u ts -> CTT.Glue <$> resolveExp u <*> resolveSystem ts GlueElem u ts -> CTT.GlueElem <$> resolveExp u <*> resolveSystem ts _ -> do modName <- asks envModule throwError ("Could not resolve " ++ show e ++ " in module " ++ modName) resolveWhere :: ExpWhere -> Resolver Ter resolveWhere = resolveExp . unWhere resolveSystem :: System -> Resolver (C.System Ter) resolveSystem (System ts) = do ts' <- sequence [ (,) <$> resolveFace alpha <*> resolveExp u | Side alpha u <- ts ] let alphas = map fst ts' unless (nub alphas == alphas) $ throwError $ "system contains same face multiple times: " ++ C.showListSystem ts' -- Note: the symbols in alpha are in scope in u, but they mean 0 or 1 return $ Map.fromList ts' resolveFace :: [Face] -> Resolver C.Face resolveFace alpha = Map.fromList <$> sequence [ (,) <$> resolveName i <*> resolveDir d | Face i d <- alpha ] resolveDir :: Dir -> Resolver C.Dir resolveDir Dir0 = return 0 resolveDir Dir1 = return 1 resolveFormula :: Formula -> Resolver C.Formula resolveFormula (Dir d) = C.Dir <$> resolveDir d resolveFormula (Atom i) = C.Atom <$> resolveName i resolveFormula (Neg phi) = negFormula <$> resolveFormula phi resolveFormula (Conj phi _ psi) = andFormula <$> resolveFormula phi <*> resolveFormula psi resolveFormula (Disj phi psi) = orFormula <$> resolveFormula phi <*> resolveFormula psi resolveBranch :: Branch -> Resolver CTT.Branch resolveBranch (OBranch (AIdent (_,lbl)) args e) = do re <- local (insertAIdents args) $ resolveWhere e return $ CTT.OBranch lbl (map unAIdent args) re resolveBranch (PBranch (AIdent (_,lbl)) args is e) = do re <- local (insertNames is . insertAIdents args) $ resolveWhere e let names = map (C.Name . unAIdent) is return $ CTT.PBranch lbl (map unAIdent args) names re resolveTele :: [(Ident,Exp)] -> Resolver CTT.Tele resolveTele [] = return [] resolveTele ((i,d):t) = ((i,) <$> resolveExp d) <:> local (insertVar i) (resolveTele t) resolveLabel :: [(Ident,SymKind)] -> Label -> Resolver CTT.Label resolveLabel _ (OLabel n vdecl) = CTT.OLabel (unAIdent n) <$> resolveTele (flattenTele vdecl) resolveLabel cs (PLabel n vdecl is sys) = do let tele' = flattenTele vdecl ts = map fst tele' names = map (C.Name . unAIdent) is n' = unAIdent n cs' = delete (n',PConstructor) cs CTT.PLabel n' <$> resolveTele tele' <*> pure names <*> local (insertNames is . insertIdents cs' . insertVars ts) (resolveSystem sys) -- Resolve a non-mutual declaration; returns resolver for type and -- body separately resolveNonMutualDecl :: Decl -> (Ident,Resolver CTT.Ter ,Resolver CTT.Ter,[(Ident,SymKind)]) resolveNonMutualDecl d = case d of DeclDef (AIdent (_,f)) tele t body -> let tele' = flattenTele tele a = binds CTT.Pi tele' (resolveExp t) d = lams tele' (local (insertVar f) $ resolveWhere body) in (f,a,d,[(f,Variable)]) DeclData x tele sums -> resolveDeclData x tele sums null DeclHData x tele sums -> resolveDeclData x tele sums (const False) -- always pick HSum DeclSplit (AIdent (l,f)) tele t brs -> let tele' = flattenTele tele vars = map fst tele' a = binds CTT.Pi tele' (resolveExp t) d = do loc <- getLoc l ty <- local (insertVars vars) $ resolveExp t brs' <- local (insertVars (f:vars)) (mapM resolveBranch brs) lams tele' (return $ CTT.Split f loc ty brs') in (f,a,d,[(f,Variable)]) DeclUndef (AIdent (l,f)) tele t -> let tele' = flattenTele tele a = binds CTT.Pi tele' (resolveExp t) d = CTT.Undef <$> getLoc l <*> a in (f,a,d,[(f,Variable)]) -- Helper function to resolve data declarations. The predicate p is -- used to decide if we should use Sum or HSum. resolveDeclData :: AIdent -> [Tele] -> [Label] -> ([(Ident,SymKind)] -> Bool) -> (Ident, Resolver Ter, Resolver Ter, [(Ident, SymKind)]) resolveDeclData (AIdent (l,f)) tele sums p = let tele' = flattenTele tele a = binds CTT.Pi tele' (return CTT.U) cs = [ (unAIdent lbl,Constructor) | OLabel lbl _ <- sums ] pcs = [ (unAIdent lbl,PConstructor) | PLabel lbl _ _ _ <- sums ] sum = if p pcs then CTT.Sum else CTT.HSum d = lams tele' $ local (insertVar f) $ sum <$> getLoc l <*> pure f <*> mapM (resolveLabel (cs ++ pcs)) sums in (f,a,d,(f,Variable):cs ++ pcs) resolveRTele :: [Ident] -> [Resolver CTT.Ter] -> Resolver CTT.Tele resolveRTele [] _ = return [] resolveRTele (i:is) (t:ts) = do a <- t as <- local (insertVar i) (resolveRTele is ts) return ((i,a):as) -- Resolve a declaration resolveDecl :: Decl -> Resolver ([CTT.Decl],[(Ident,SymKind)]) resolveDecl d = case d of DeclMutual decls -> do let (fs,ts,bs,nss) = unzip4 $ map resolveNonMutualDecl decls ns = concat nss -- TODO: some sanity checks? Duplicates!? when (nub (map fst ns) /= concatMap (map fst) nss) $ throwError ("Duplicated constructor or ident: " ++ show nss) as <- resolveRTele fs ts -- The bodies know about all the names and constructors in the -- mutual block ds <- sequence $ map (local (insertIdents ns)) bs let ads = zipWith (\ (x,y) z -> (x,(y,z))) as ds return (ads,ns) _ -> do let (f,typ,body,ns) = resolveNonMutualDecl d a <- typ d <- body return ([(f,(a,d))],ns) resolveDecls :: [Decl] -> Resolver ([[CTT.Decl]],[(Ident,SymKind)]) resolveDecls [] = return ([],[]) resolveDecls (d:ds) = do (rtd,names) <- resolveDecl d (rds,names') <- local (insertIdents names) $ resolveDecls ds return (rtd : rds, names' ++ names) resolveModule :: Module -> Resolver ([[CTT.Decl]],[(Ident,SymKind)]) resolveModule (Module (AIdent (_,n)) _ decls) = local (updateModule n) $ resolveDecls decls resolveModules :: [Module] -> Resolver ([[CTT.Decl]],[(Ident,SymKind)]) resolveModules [] = return ([],[]) resolveModules (mod:mods) = do (rmod, names) <- resolveModule mod (rmods,names') <- local (insertIdents names) $ resolveModules mods return (rmod ++ rmods, names' ++ names)
DanGrayson/cubicaltt
Resolver.hs
mit
13,306
0
19
3,280
5,263
2,678
2,585
283
22
module Utils.Options where import System.Console.GetOpt import Utils.Common commonOptions :: [OptDescr Option] commonOptions = [ Option "q" ["quiet"] (NoArg Quiet) "Подавить вывод stdout" , Option "t" ["timeout"] (ReqArg (Timeout . read) "INT") "Время ожидания пользовательского скрипта" , Option "C" ["--no-completion"] (NoArg NoCompletion) "Не выполнять дополнение имён конфигов" , Option "h" ["help"] (NoArg Help) "Распечатать API команды" ] -- Формирует время ожидания на основе списка опций getTimeout :: [Option] -> Int getTimeout (Timeout t : os) = t getTimeout (_ : os) = getTimeout os getTimeout [] = 120 -- по умолчанию 2 минуты -- Извлекает имя владельца из списка опций getOwner :: [Option] -> Maybe Parent getOwner (Owner o : os) = Just o getOwner (_ : os) = getOwner os getOwner [] = Nothing
kahless/netm
src/Cmd/Utils/Options.hs
mit
1,079
0
10
204
251
134
117
21
1
{-# OPTIONS_GHC -O2 -Wall -fwarn-tabs -Werror #-} ------------------------------------------------------------------------------- -- | -- Module : Lorenz.Logic -- Copyright : Copyright (c) 2014 Michael R. Shannon -- License : MIT -- Maintainer : [email protected] -- Stability : unstable -- Portability : portable -- -- Handles non even driven logi ------------------------------------------------------------------------------- module Lorenz.Logic ( update , solveLorenz ) where import Lorenz.Data import Data.Number.FloatToFloat import Data.Packed.Vector as V import Data.Packed.Matrix as M import Numeric.GSL import Graphics.Rendering.OpenGL.Raw.Types(GLfloat) import Graphics.Rendering.OpenGL.GL.Tensor(Vertex3(..)) import Graphics.Rendering.OpenGL.Help -- | Perform logic operation on the App state and return a new App. update :: App -> IO App update = return . id -- | Solve the Lorenz attractor. solveLorenz :: AppFunction -> ([GLfloat], [Vertex3f]) solveLorenz (AppFunction x0 y0 z0 s r b dt tn) = (times, verts) where times = [0.0,(floatToFloat dt)..(floatToFloat tn)] :: [GLfloat] timesVector = V.fromList $ map floatToFloat times solutionMatrix = odeSolve (lorenz' s r b) [x0, y0, z0] timesVector verts = matrixToVerts solutionMatrix -- | Convert HMatrix to a list of verticies. matrixToVerts :: M.Matrix Double -> [Vertex3f] matrixToVerts mat = map converter (M.toLists mat) where converter (x:y:z:_) = Vertex3 (floatToFloat x) (floatToFloat y) (floatToFloat z) converter _ = error "wrong number of elements" -- | Lorenz attractor function. -- σ -> ρ -> β -> t -> (x, y, z) -> (dxdt, dydt, dzdt) lorenz :: Num a => a -> a -> a -> a -> (a, a, a) -> (a, a, a) lorenz s r b _ (x, y, z) = (dxdt, dydt, dzdt) where dxdt = s * (y - x) dydt = x * (r - z) - y dzdt = x * y - b * z -- | Same as the lorenz attractor function but uses lists instead of tuples and -- thus can have a runtime error. -- σ -> ρ -> β -> t -> [x, y, z] -> [dxdt, dydt, dzdt] lorenz' :: Num a => a -> a -> a -> a -> [a] -> [a] lorenz' s r b t (x:y:z:_) = [dxdt, dydt, dzdt] where (dxdt, dydt, dzdt) = lorenz s r b t (x, y, z) lorenz' _ _ _ _ _ = error "lorenz' needs a list with exactly 3 elements"
mrshannon/lorenz
src/Lorenz/Logic.hs
mit
2,413
0
11
585
639
366
273
35
2
{-# LANGUAGE DeriveDataTypeable #-} {- | Module : ./OWL2/Symbols.hs Copyright : (c) Felix Gabriel Mance License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Symbol items for Hets -} module OWL2.Symbols where import OWL2.AS import Common.IRI import Common.Id (Id) import Data.Data -- * SYMBOL ITEMS FOR HETS data ExtEntityType = AnyEntity | PrefixO | EntityType EntityType deriving (Show, Eq, Ord, Typeable, Data) data SymbItems = SymbItems ExtEntityType [IRI] deriving (Show, Eq, Typeable, Data) symbItemsName :: SymbItems -> [String] symbItemsName (SymbItems _ iris) = map showIRI iris data SymbMapItems = SymbMapItems ExtEntityType [(IRI, Maybe IRI)] deriving (Show, Eq, Typeable, Data) -- | raw symbols data RawSymb = ASymbol Entity | AnUri IRI | APrefix String deriving (Show, Eq, Ord, Typeable, Data) idToRaw :: Id -> RawSymb idToRaw = AnUri . idToIRI
spechub/Hets
OWL2/Symbols.hs
gpl-2.0
984
0
9
185
241
135
106
19
1
{- | 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 Hennessy-Milner 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.hml.hs -- then try ``provable phi1'' import Generic -- abox 'a' phi is the HML formula [a] phi abox :: Char -> (L HM) -> (L HM) abox ag phi = M (HM ag) phi -- adia is the corresponding diamond adia :: Char -> (L HM) -> (L HM) adia ag phi = neg (abox ag (neg phi)) -- shorthands for propositional atoms p0 :: L HM; p0 = Atom 0 p1 :: L HM; p1 = Atom 1 p2 :: L HM; p2 = Atom 2 p3 :: L HM; p3 = Atom 3 -- some formulas of Hennssy-Milner logic phi0 :: L HM; phi0 = p0 --> (abox 'a' p0) phi1 :: L HM; phi1 = (p0 /\ (p0 --> (abox 'a' p0))) --> (abox 'a' p0) phi2 :: L HM; phi2 = ((abox 'a' p0) \/ (abox 'b' p1)) --> (adia 'b' p0) \/ (adia 'a' p1) phi3 :: L HM; phi3 = phi2 --> (abox 'd' phi1) phi4 :: L HM; phi4 = abox 'c' (phi2 --> (abox 'd' phi1))
nevrenato/Hets_Fork
GMP/versioning/coloss-0.0.4/examples.hml.hs
gpl-2.0
1,337
0
11
314
375
201
174
14
1
{-| This module exports functionality for carrying out operations on files and directories. It uses 'System.Cmd' to carry out these operations. It is used by 'DirectoryOperations' in all it's functions. -} module SystemOperations ( deleteFile, deleteDirectory, moveDirectory, moveFile, renameDirectory, renameFile, copyDirectory, copyFile, openFile , openFileCustom ) where import System.Cmd ( rawSystem ) import Popup import Paths_FileManager import System.FilePath ( takeExtension ) import qualified GHC.IOBase as E import qualified Control.Exception as Er {-| Generic method for carrying out operations on the files and directories. -} operate :: FilePath -- ^ The path to the original file. -> FilePath -- ^ The second argument to the command. -> String -- ^ The command to be carried out. -> String -- ^ The parameters for the command. -> IO E.ExitCode -- ^ The completion status of the operation. operate orig new cmd param = rawSystem cmd [param, orig, new] {-| Move a supplied directory to a supplied location. i.e. \"mv -f dir dest\" -} moveDirectory :: FilePath -- ^ The path to the original directory. -> FilePath -- ^ The path to the destination. -> IO E.ExitCode -- ^ The completion status of the operation. moveDirectory dir dest = renameFile dir dest {-| Moves a supplied file to a supplied location. i.e. \"mv -f file dest\" -} moveFile :: FilePath -- ^ The path to the original file. -> FilePath -- ^ The path to the destination. -> IO E.ExitCode -- ^ The completion status of the operation. moveFile file dest = renameFile file dest {-| Rename a supplied file to a supplied name. i.e. \"mv -f file name\". -} renameFile :: FilePath -- ^ The path to the original file. -> FilePath -- ^ The new name for the file. -> IO E.ExitCode -- ^ The completion status of the operation. renameFile file name = operate file name "mv" "-f" {-| Renames a supplied directory to a supplied name. i.e. \"mv -f dir name\". -} renameDirectory :: FilePath -- ^ The path to the directory to be renamed. -> FilePath -- ^ The new name\/location for the directory. -> IO E.ExitCode -- ^ The completion status of the operation. renameDirectory dir name = renameFile dir name {-| Copys a supplied directory to a supplied destination. i.e. \"cp -rf dir dest\". -} copyDirectory :: FilePath -- ^ The path to the directory to be copied. -> FilePath -- ^ The destination for the directory. -> IO E.ExitCode -- ^ The completion status of the operation. copyDirectory dir dest = operate dir dest "cp" "-rf" {-| Copys a supplied file to a supplied destination. i.e. \"cp -f file dest\". -} copyFile :: FilePath -- ^ The file to be copied. -> FilePath -- ^ The destination for the file. -> IO E.ExitCode -- ^ The completion status of the operation. copyFile file dest = operate file dest "cp" "-f" {-| Deletes a supplied file. i.e. \"rm -f file\". -} deleteFile :: FilePath -- ^ The path to the file to be deleted. -> IO E.ExitCode -- ^ The competion status of the operation. deleteFile file = rawSystem "rm" ["-f", file] {-| Deletes a supplied directory. i.e. \"rm -rf dir\". -} deleteDirectory :: FilePath -- ^ The path to the directory to be deleted. -> IO E.ExitCode -- ^ The completion status of the operation. deleteDirectory dir = rawSystem "rm" ["-rf", dir] {-| Uses \"xdg-open\" to open a supplied file. -} openFile :: FilePath -- ^ The path to the file to be opened. -> IO E.ExitCode -- ^ The completion status of the operation. openFile name = ( rawSystem "xdg-open" [name] ) >>= ( \e -> case e of E.ExitSuccess -> return ( e ) _ -> openFileCustom name ) --Not opened. Open custom. {-| Finds a programs comman from a list of extensions and commands. -} findProg :: [String] -- ^ The list of extensions & commands. -> String -- ^ The desired extension. -> String -- ^ That extensions command. findProg [] _ = "" findProg (ext:cmd:xs) fExt | ext == fExt = cmd | otherwise = findProg xs fExt {-| Custom file opening. If the file to be opened doesn't have a default program associated with it, then it won't open, this queries the user for a command to be associated with the files extenstion. -} openFileCustom :: FilePath -- ^ The path to the file to be opened. -> IO E.ExitCode -- ^ The result of opening the file. openFileCustom file = do let fExt = takeExtension file wurds <- ( ( readFile =<< getDataFileName "exts.txt" ) `Er.catch` (\_ -> ( (\f -> ( rawSystem "touch" [f] ) ) =<< getDataFileName "exts.txt" ) >> return ("") ) ) >>= ( \t -> return ( words t ) ) case ( findProg wurds fExt ) of "" -> inputWindow "Custom command" ( "Please enter a command for opening " ++ fExt ++ " files: " ) >>= ( \cmd -> case cmd of "" -> return ( E.ExitFailure 4 ) cmd -> do ( \f -> writeFile f ( unwords ( wurds ++ [fExt,cmd] ) ) ) =<< getDataFileName "exts.txt" rawSystem cmd [file] ) cmd -> rawSystem cmd [file]
michaeldever/haskellfm
SystemOperations.hs
gpl-3.0
5,505
0
26
1,566
874
477
397
82
3
{-# LANGUAGE OverloadedStrings , FlexibleContexts #-} module Handlers.Browse where import Handlers.Chunks import Handlers.App import Schema import Cabal.Types import Imports import Data.Acid.Advanced (query') import qualified Data.Text as T import qualified Data.Text.Lazy as LT import Control.Monad.IO.Class (liftIO) import Control.Monad.Reader browseSearchHandle :: MonadApp m => T.Text -> MiddlewareT m browseSearchHandle x = action $ do xs <- liftIO delay get $ do json $ case xs of () -> [ ("foo" :: T.Text) ] packagesHandle :: MonadApp m => T.Text -> MiddlewareT m packagesHandle packageName app req respond = do db <- envDatabase <$> ask mPackage <- query' db . LookupPackage . PackageName $ packageName let handle = action $ get $ case mPackage of Nothing -> text ("Not found!" :: LT.Text) Just p -> json p handle app req respond allPackagesHandle :: MonadApp m => MiddlewareT m allPackagesHandle app req respond = do db <- envDatabase <$> ask vs <- query' db CurrentKnownPackageVersions let handle = action $ get $ json vs handle app req respond browseViewHandle :: MonadApp m => T.Text -> MiddlewareT m browseViewHandle x = action homeHandle -- FIXME: Populate state someherw :\
athanclark/happ-store
src/Handlers/Browse.hs
gpl-3.0
1,441
0
17
436
395
201
194
48
2
{-- | This module contains functions that expand on Hakyll's builtin pageination controls to add "Next Page" and "Previous Page" links, and add support for drafts. --} module Site.Pagination (buildPaginate, paginatePostsContext) where import qualified Data.Map as M import Data.Monoid ((<>)) import qualified Data.Set as S import qualified Data.Traversable as T import Control.Monad (join, liftM) import Hakyll hiding (getMetadata) import Site.Meta -- | Taken from the Hakyll source, because it is not exported. paginateNumPages :: Paginate -> Int paginateNumPages = M.size . paginateMap -- | Taken from the Hakyll source, because it is not exported. paginatePage :: Paginate -> PageNumber -> Maybe Identifier paginatePage pag pageNumber | pageNumber < 1 = Nothing | pageNumber > (paginateNumPages pag) = Nothing | otherwise = Just $ paginateMakeId pag pageNumber -- | Overrides the getMetadata in Hakyll to do FIXME getMetadata :: MonadMetadata m => Paginate -> PageNumber -> String -> m (Maybe String) getMetadata pag i key = liftM join $ T.sequence $ do ident <- paginatePage pag i return $ getMetadataField ident key -- Context that has title fields extracted from metadata. paginateMetadataContext :: Paginate -> PageNumber -> Context a paginateMetadataContext pag i = mconcat [ field "nextTitle" $ \_ -> fmap (maybe "" id) $ getMetadata pag (i + 1) "title" , field "previousTitle" $ \_ -> fmap (maybe "" id) $ getMetadata pag (i - 1) "title" ] paginatePostsContext :: Paginate -> PageNumber -> Context String paginatePostsContext pages i = postContext <> paginateContext pages i <> paginateMetadataContext pages i -- | Pagination that takes drafts into account, adapted from the original source. buildPaginate :: MonadMetadata m => Pattern -> m Paginate buildPaginate pattern = do ids <- filterDrafts =<< getMatches pattern let idGroups = fmap (\x -> [x]) ids -- Just one page per post. let idsSet = S.fromList ids return Paginate { paginateMap = M.fromList (zip [1 ..] idGroups) , paginateMakeId = \i -> ids !! (i-1) -- Page url is just the post url. , paginateDependency = PatternDependency pattern idsSet }
budgefeeney/amixtureofmusings
Site/Pagination.hs
gpl-3.0
2,302
0
13
519
565
295
270
37
1
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-} {- Merch.Race.Control.Background - Background task execution. Copyright 2013 Alan Manuel K. Gloria This file is part of Merchant's Race. Merchant's Race is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Merchant's Race is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Merchant's Race. If not, see <http://www.gnu.org/licenses/>. -} {- Execution of code in a background thread. The foreground thread can sample any available state that the background thread reports. -} module Merch.Race.Control.Background ( Background -- * -> * , sampleBackground -- Background s -> IO (Maybe s) , completedBackground -- Background s -> IO (Maybe s) , abortBackground -- Background s -> IO () , BackM -- * -> * -> * , runBackM -- (s' -> IO s) -> BackM s' a -> s' -> IO (Background s) ) where import Prelude hiding (catch) import Control.Concurrent import Control.Concurrent.MVar import Control.Exception import Control.Monad.State import Control.Monad.Trans newtype Background s = Background { bkState :: MVar (BackState s) } data BackState s = Running | SampleAvailable s | Finished s | RequestSample | Excepted SomeException | Aborted newtype BackM s a = BackM { bmRun :: s -> (s -> a -> IO (Event s)) -> IO (Event s) } data Event s = Put s (IO (Event s)) | EExcepted SomeException | Finish s instance Monad (BackM s) where return a = BackM $ \s k -> k s a fail e = BackM $ \_ _ -> fail e ma >>= f = BackM $ \s k -> bmRun ma s $ \s a -> bmRun (f a) s k instance MonadState s (BackM s) where get = BackM $ \s k -> k s s put s = BackM $ \_ k -> return $ Put s $ k s () instance MonadIO (BackM s) where liftIO m = BackM $ \s k -> m >>= \a -> k s a sampleBackground :: Background s -> IO (Maybe s) sampleBackground bk = do let mv = bkState bk bs <- takeMVar mv case bs of Running -> do putMVar mv RequestSample return Nothing SampleAvailable s -> do putMVar mv RequestSample return $ Just s Finished s -> do putMVar mv bs return $ Just s RequestSample -> do putMVar mv bs return Nothing Excepted e -> do putMVar mv bs throwIO e Aborted -> do putMVar mv bs fail "sampleBackground: Background task already aborted." completedBackground :: Background s -> IO (Maybe s) completedBackground bk = do let mv = bkState bk bs <- readMVar mv case bs of Finished s -> return $ Just s Excepted e -> throwIO e Aborted -> do fail "completedBackground: Background task already aborted" _ -> return Nothing abortBackground :: Background s -> IO () abortBackground bk = do let mv = bkState bk swapMVar mv Aborted return () runBackM :: (s' -> IO s) -> BackM s' a -> s' -> IO (Background s) runBackM freeze ma s' = do mv <- newMVar Running forkIO $ loop mv $ bmRun ma s' $ \s' _ -> return $ Finish s' return $ Background mv where loop mv ioe = do e <- catch ioe $ return . EExcepted bs <- takeMVar mv case e of Put s' ioe -> do case bs of Aborted -> putMVar mv Aborted Running -> putMVar mv bs >> loop mv ioe -- We assume that the freeze operation -- is not fast, so if the previous sample -- is still there, don't freeze the current -- sample, leave the foreground with stale -- data. SampleAvailable _ -> putMVar mv bs >> loop mv ioe RequestSample -> do s <- freeze s' putMVar mv $ SampleAvailable s loop mv ioe -- Finished and Excepted shouldn't have occured. _ -> putMVar mv bs EExcepted ex -> do case bs of -- If we got aborted before the -- exception triggered, ignore Aborted -> putMVar mv Aborted _ -> putMVar mv $ Excepted ex Finish s' -> do case bs of -- If we got aborted before the -- finish, ignore. Aborted -> putMVar mv Aborted _ -> do s <- freeze s' putMVar mv $ Finished s
AmkG/merchants-race
Merch/Race/Control/Background.hs
gpl-3.0
4,719
0
20
1,447
1,185
576
609
107
9
{- Let p(n) represent the number of different ways in which n coins can be separated into piles. For example, five coins can separated into piles in exactly seven different ways, so p(5)=7. OOOOO OOOO O OOO OO OOO O O OO OO O OO O O O O O O O O Find the least value of n for which p(n) is divisible by one million. -} import Control.Monad( forM_ ) import Data.Array.ST( runSTArray, newArray, readArray, writeArray ) import Data.Array( Array(..), assocs, (!) ) import Data.Int( Int64 ) k m | even m = (m `quot` 2) + 1 | otherwise = -((m `quot` 2) + 1) f k = (k*(3*k - 1)) `quot` 2 penta = f . k indexes n = [n - i | i <- takeWhile (<=n) $ fmap penta [0..]] signs = cycle [1,1,-1,-1] fff arr (s,i) = do v <- readArray arr i return (s * v) pArray :: Int -> Array Int Integer pArray n = runSTArray $ do arr <- newArray (0,n) 0 writeArray arr 0 1 forM_ [1..n] $ \i -> do vals <- mapM (fff arr) $ zip signs (indexes i) writeArray arr i $ sum vals return arr search :: [(Int, Integer)] -> [(Int, Integer)] search = take 1 . dropWhile (\(_,a) -> a `mod` 1000000 /= 0) solution :: [(Int, Integer)] solution = search . assocs $ pArray 100000 main :: IO () main = do case solution of [(x,_)] -> print x _ -> putStrLn "not found!"
zhensydow/ljcsandbox
lang/haskell/euler/completed/problem078.hs
gpl-3.0
1,297
0
16
329
540
289
251
31
2
--- | --- | tiger hash calcuation and caching stuff --- | --- Copyright : (c) Florian Richter 2011 --- License : GPL --- module TTH ( getHashForFile , initTTHCache , getCachedHash , hashFileList ) where import Data.Digest.TigerHash import Data.Digest.TigerHash.ByteString import Data.Maybe import qualified Data.ByteString.Lazy as L import qualified Data.ByteString as B import qualified Data.Map as M import qualified Data.Text as T import System.Posix.Types import System.Posix.Files import System.Directory import Control.Monad import Control.Concurrent import Control.Exception as E import Data.HashTable import Database.HDBC import Database.HDBC.Sqlite3 import Config import TTHTypes import FilelistTypes -- | init sqlite initTTHCache :: AppState -> IO () initTTHCache appState = do conn <- connectSqlite3 (configCacheFile $ appConfig appState) run conn ("CREATE TABLE IF NOT EXISTS tthcache " ++ "(path VARCHAR(1024) NOT NULL PRIMARY KEY, tth VARCHAR(80) NOT NULL, " ++ "modtime BIGINT NOT NULL);") [] commit conn putStrLn "CREATE TABLE" putMVar (appTTHCache appState) conn -- | get hash from sqlite cache getCachedHash :: AppState -> T.Text -> EpochTime -> IO (Maybe T.Text) getCachedHash appState path curModTime = do conn <- readMVar (appTTHCache appState) rows <- sqlbla conn path if null rows || (null $ head rows) then return Nothing else let row = head rows hash = fromSql $ row !! 0 modTime = fromInteger $ fromSql $ row !! 1 in if modTime == curModTime then return $! Just $ T.pack hash else return Nothing sqlbla conn path = quickQuery' conn "SELECT tth, modtime FROM tthcache WHERE path=?;" [SqlString $ T.unpack path] -- | set hash in sqlite cache setHashInCache :: AppState -> T.Text -> T.Text -> IO () setHashInCache appState path hash = do fileStatus <- getFileStatus (T.unpack path) let modTime = modificationTime fileStatus conn <- readMVar (appTTHCache appState) run conn "INSERT INTO tthcache VALUES (?, ?, ?);" [toSql path, toSql hash, SqlString $ show modTime] commit conn return () -- | calc hash for every file in fileTree, of not present hashFileList :: AppState -> IO () hashFileList appState = do IndexedFileTree tree htable <- readMVar (appFileTree appState) traverse appState [] tree where traverse :: AppState -> [T.Text] -> TreeNode -> IO () traverse appState dirs (DirNode name _ children) = mapM_ (traverse appState (name:dirs)) children traverse appState dirs (FileNode _ _ _ _ (Just hash)) = return () traverse appState dirs node@(FileNode name path _ _ Nothing) = do putStrLn ("hash: " ++ (show path)) hash <- getHashForFile path setHashInCache appState path hash modifyMVar_ (appFileTree appState) (\(IndexedFileTree tree htable) -> do insert htable hash node return $! IndexedFileTree (setHash hash (reverse (name:dirs)) tree) htable) setHash :: T.Text -> [T.Text] -> TreeNode -> TreeNode setHash hash [name] file@(FileNode fname _ _ _ _) | name == fname = file {fileNodeHash = Just hash} | otherwise = file setHash hash (name:dirs) dir@(DirNode dname _ children) | name == dname = dir {dirNodeChildren = map (setHash hash dirs) children} | otherwise = dir setHash hash rest node = node getHashForFile :: T.Text -> IO T.Text getHashForFile path = do content <- L.readFile (T.unpack path) return $! T.filter (/='=') $ T.pack $ b32TigerHash (tigerTreeHash content) -- test with runhaskell tth.hs tth file.ext --main = liftM (!!1) getArgs >>= getHashForFile >>= putStrLn -- vim: sw=4 expandtab
f1ori/hadcc
TTH.hs
gpl-3.0
3,898
0
21
990
1,119
569
550
82
5
{- | Module : $Header$ Description : Mathematical compositions. Copyright : (c) plaimi 2014 License : GPL-3 Maintainer : [email protected] -} module Plailude.Function.Compose where -- (.) :: (b -> c) -> (a -> b) -> a -> c -- (f . g) x = f (g x) (.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d -- | Compose two functions where the second function takes two values and -- delivers its result as a single value to the first function. -- -- This is equivalent to: (f .: g) x y = f (g x y). (.:) = (.).(.) (.:.) :: (d -> e) -> (a -> b -> c -> d) -> a -> b -> c -> e -- | Compose two functions where the second function takes three values and -- delivers its result as a single value to the first function. -- -- This is equivalent to: (f .:. g) x y z = f (g x y z). (.:.) = (.).(.:)
plaimi/plailude
src/Plailude/Function/Compose.hs
gpl-3.0
803
2
10
197
138
88
50
5
1
{-# LANGUAGE FlexibleContexts, NoImplicitPrelude, TemplateHaskell, RankNTypes #-} module Lamdu.Sugar.NearestHoles ( NearestHoles(..), prev, next , none , add ) where import Prelude.Compat import Control.Applicative.Utils (when) import Control.Lens (LensLike) import qualified Control.Lens as Lens import Control.Lens.Operators import Control.Lens.Tuple import Control.Monad.Trans.State (State, evalState) import qualified Control.Monad.Trans.State as State import Control.MonadA (MonadA) import qualified Lamdu.Sugar.Lens as SugarLens import qualified Lamdu.Sugar.Types as Sugar markStoredHoles :: Sugar.Expression name m a -> Sugar.Expression name m (Bool, a) markStoredHoles expr = expr <&> (,) False & SugarLens.holePayloads . Sugar.plData . _1 .~ True & SugarLens.subExprPayloads %~ removeNonStoredMarks where removeNonStoredMarks pl = case pl ^. Sugar.plActions of Nothing -> pl & Sugar.plData . _1 .~ False Just _ -> pl data NearestHoles = NearestHoles { _prev :: Maybe Sugar.EntityId , _next :: Maybe Sugar.EntityId } deriving (Eq, Show) Lens.makeLenses ''NearestHoles none :: NearestHoles none = NearestHoles Nothing Nothing add :: MonadA m => (forall a b. Lens.Traversal (f (Sugar.Expression name m a)) (f (Sugar.Expression name m b)) (Sugar.Expression name m a) (Sugar.Expression name m b)) -> f (Sugar.Expression name m (NearestHoles -> r)) -> f (Sugar.Expression name m r) add exprs s = s & exprs . Lens.mapped %~ toNearestHoles & exprs %~ markStoredHoles & passAll (exprs . SugarLens.subExprPayloads) & passAll (Lens.backwards (exprs . SugarLens.subExprPayloads)) & exprs . Lens.mapped %~ snd where toNearestHoles f prevHole nextHole = f (NearestHoles prevHole nextHole) type M = State (Maybe Sugar.EntityId) passAll :: LensLike M s t (Sugar.Payload m (Bool, Maybe Sugar.EntityId -> a)) (Sugar.Payload m (Bool, a)) -> s -> t passAll sugarPls s = s & sugarPls %%~ setEntityId & (`evalState` Nothing) setEntityId :: Sugar.Payload m (Bool, Maybe Sugar.EntityId -> a) -> M (Sugar.Payload m (Bool, a)) setEntityId pl = do oldEntityId <- State.get when isStoredHole $ State.put $ Just $ pl ^. Sugar.plEntityId pl & Sugar.plData . _2 %~ ($ oldEntityId) & return where isStoredHole = pl ^. Sugar.plData . _1
rvion/lamdu
Lamdu/Sugar/NearestHoles.hs
gpl-3.0
2,570
0
14
668
818
439
379
-1
-1
{-| Module : Game.Robo.Core.Lenses Description : Lenses for relevant records. Copyright : (c) Bradley Hardy, 2015 License : GPL3 Maintainer : [email protected] Stability : experimental Portability : non-portable This is in a separate file to enable easy re-exporting of lenses without having to go through and update export lists every time we add a new field to a record. -} {-# LANGUAGE TemplateHaskell #-} module Game.Robo.Core.Lenses where import Game.Robo.Core.Types import Lens.Micro.Platform makeLenses ''WorldState makeLenses ''BotState makeLenses ''GunState makeLenses ''RadarState makeLenses ''Bullet makeLenses ''BulletCollision
bch29/robo-monad
src/Game/Robo/Core/Lenses.hs
gpl-3.0
665
0
6
104
71
35
36
10
0
import Prelude hiding (getLine, putStr) import Data.ByteString.Char8 hiding (head) import Parse import Display main :: IO () main = getLine >>= putStr . asciize asciize :: ByteString -> ByteString asciize s = case parse s of Just x -> display x Nothing -> ":p"
phi16/ASCIIize
Main.hs
gpl-3.0
267
0
8
50
96
52
44
10
2
q :: x -> U n
hmemcpy/milewski-ctfp-pdf
src/content/2.3/code/haskell/snippet08.hs
gpl-3.0
13
0
6
5
13
6
7
1
0
import Test.HUnit import qualified SyntaxTests import qualified DistTests import qualified SemopTests main = do runTestTT SyntaxTests.syntaxTests runTestTT DistTests.distTests runTestTT SemopTests.semopTests
fredokun/piexplorer
src/AllTests.hs
gpl-3.0
226
0
8
38
47
24
23
8
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AndroidEnterprise.Products.Approve -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Approves the specified product and the relevant app permissions, if any. -- The maximum number of products that you can approve per enterprise -- customer is 1,000. To learn how to use managed Google Play to design and -- create a store layout to display approved products to your users, see -- Store Layout Design. -- -- /See:/ <https://developers.google.com/android/work/play/emm-api Google Play EMM API Reference> for @androidenterprise.products.approve@. module Network.Google.Resource.AndroidEnterprise.Products.Approve ( -- * REST Resource ProductsApproveResource -- * Creating a Request , productsApprove , ProductsApprove -- * Request Lenses , paXgafv , paUploadProtocol , paEnterpriseId , paAccessToken , paUploadType , paPayload , paProductId , paCallback ) where import Network.Google.AndroidEnterprise.Types import Network.Google.Prelude -- | A resource alias for @androidenterprise.products.approve@ method which the -- 'ProductsApprove' request conforms to. type ProductsApproveResource = "androidenterprise" :> "v1" :> "enterprises" :> Capture "enterpriseId" Text :> "products" :> Capture "productId" Text :> "approve" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ProductsApproveRequest :> Post '[JSON] () -- | Approves the specified product and the relevant app permissions, if any. -- The maximum number of products that you can approve per enterprise -- customer is 1,000. To learn how to use managed Google Play to design and -- create a store layout to display approved products to your users, see -- Store Layout Design. -- -- /See:/ 'productsApprove' smart constructor. data ProductsApprove = ProductsApprove' { _paXgafv :: !(Maybe Xgafv) , _paUploadProtocol :: !(Maybe Text) , _paEnterpriseId :: !Text , _paAccessToken :: !(Maybe Text) , _paUploadType :: !(Maybe Text) , _paPayload :: !ProductsApproveRequest , _paProductId :: !Text , _paCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProductsApprove' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'paXgafv' -- -- * 'paUploadProtocol' -- -- * 'paEnterpriseId' -- -- * 'paAccessToken' -- -- * 'paUploadType' -- -- * 'paPayload' -- -- * 'paProductId' -- -- * 'paCallback' productsApprove :: Text -- ^ 'paEnterpriseId' -> ProductsApproveRequest -- ^ 'paPayload' -> Text -- ^ 'paProductId' -> ProductsApprove productsApprove pPaEnterpriseId_ pPaPayload_ pPaProductId_ = ProductsApprove' { _paXgafv = Nothing , _paUploadProtocol = Nothing , _paEnterpriseId = pPaEnterpriseId_ , _paAccessToken = Nothing , _paUploadType = Nothing , _paPayload = pPaPayload_ , _paProductId = pPaProductId_ , _paCallback = Nothing } -- | V1 error format. paXgafv :: Lens' ProductsApprove (Maybe Xgafv) paXgafv = lens _paXgafv (\ s a -> s{_paXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). paUploadProtocol :: Lens' ProductsApprove (Maybe Text) paUploadProtocol = lens _paUploadProtocol (\ s a -> s{_paUploadProtocol = a}) -- | The ID of the enterprise. paEnterpriseId :: Lens' ProductsApprove Text paEnterpriseId = lens _paEnterpriseId (\ s a -> s{_paEnterpriseId = a}) -- | OAuth access token. paAccessToken :: Lens' ProductsApprove (Maybe Text) paAccessToken = lens _paAccessToken (\ s a -> s{_paAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). paUploadType :: Lens' ProductsApprove (Maybe Text) paUploadType = lens _paUploadType (\ s a -> s{_paUploadType = a}) -- | Multipart request metadata. paPayload :: Lens' ProductsApprove ProductsApproveRequest paPayload = lens _paPayload (\ s a -> s{_paPayload = a}) -- | The ID of the product. paProductId :: Lens' ProductsApprove Text paProductId = lens _paProductId (\ s a -> s{_paProductId = a}) -- | JSONP paCallback :: Lens' ProductsApprove (Maybe Text) paCallback = lens _paCallback (\ s a -> s{_paCallback = a}) instance GoogleRequest ProductsApprove where type Rs ProductsApprove = () type Scopes ProductsApprove = '["https://www.googleapis.com/auth/androidenterprise"] requestClient ProductsApprove'{..} = go _paEnterpriseId _paProductId _paXgafv _paUploadProtocol _paAccessToken _paUploadType _paCallback (Just AltJSON) _paPayload androidEnterpriseService where go = buildClient (Proxy :: Proxy ProductsApproveResource) mempty
brendanhay/gogol
gogol-android-enterprise/gen/Network/Google/Resource/AndroidEnterprise/Products/Approve.hs
mpl-2.0
5,994
0
21
1,481
877
512
365
128
1
module Message ( module Message ) where import Prelude hiding () import qualified Text.Printf as T (hPrintf) import qualified Data.Text as T (Text(..), pack, unpack, toLower, isPrefixOf, drop, words, tail, singleton, break) import qualified Data.Text.IO as T (putStrLn, hPutStrLn, hGetLine) import System.IO (Handle) import qualified Data.List as List (intercalate, map, concatMap) import qualified Data.Map as Map (Map(..), lookup) import Debug.Trace type Map = Map.Map type Text = T.Text data Prefix = Server { name :: Text } | User { nick :: Text, real :: Text, host :: Text } deriving (Eq) instance Show Prefix where showsPrec x (Server name) = showString (T.unpack name) showsPrec x (User nick real host) = showString (T.unpack nick) . showChar '!' . showString (T.unpack real) . showChar '@' . showString (T.unpack host) instance Read Prefix where readsPrec x pfx = case span (/='@') pfx of (name, "") -> return (Server $ T.pack name, "") (names, '@':host) -> let (nick, '!':real) = span (/='!') names in return (User (T.pack nick) (T.pack real) (T.pack host), "") data Code = RPL_Welcome | ERR_NicknameInUse deriving (Eq) instance Show Code where showsPrec x RPL_Welcome = showString "001" showsPrec x ERR_NicknameInUse = showString "433" data Command = Numeric Code | Register | Nick | Pass | Ping | Pong | Umode2 | Join | Invite | Privmsg | Notice | Undefined String deriving (Eq) instance Show Command where showsPrec x (Numeric rpl) = showsPrec x rpl showsPrec x Register = showString "USER" showsPrec x Nick = showString "NICK" showsPrec x Pass = showString "PASS" showsPrec x Ping = showString "PING" showsPrec x Pong = showString "PONG" showsPrec x Umode2 = showString "UMODE2" showsPrec x Join = showString "JOIN" showsPrec x Invite = showString "INVITE" showsPrec x Privmsg = showString "PRIVMSG" showsPrec x Notice = showString "NOTICE" showsPrec x (Undefined t) = showString t instance Read Command where readsPrec x "001" = return (Numeric RPL_Welcome, "") readsPrec x "433" = return (Numeric ERR_NicknameInUse, "") readsPrec x "USER" = return (Register, "") readsPrec x "NICK" = return (Nick, "") readsPrec x "PASS" = return (Pass, "") readsPrec x "PING" = return (Ping, "") readsPrec x "PONG" = return (Pong, "") readsPrec x "UMODE2" = return (Umode2, "") readsPrec x "JOIN" = return (Join, "") readsPrec x "INVITE" = return (Invite, "") readsPrec x "PRIVMSG" = return (Privmsg, "") readsPrec x "NOTICE" = return (Notice, "") readsPrec x s = return (Undefined s, "") data Params = Short { param :: Text, next :: Params } | Long { param :: Text } | End deriving (Eq) instance Show Params where showsPrec x (Short param next) = (showString $ T.unpack param) . case next of End -> id param -> showChar ' ' . showsPrec x next showsPrec x (Long param) = showChar ':' . (showString $ T.unpack param) showsPrec x (End) = id instance Read Params where readsPrec x "" = return (End, "") readsPrec x (':':param) = return (Long $ T.pack param, "") -- TODO: Unshittify this readsPrec x params = let (param, rest) = break (==' ') . dropWhile (==' ') $ params in return (Short (T.pack param) (read . drop 1 $ rest), "") data Message = Message { prefix :: Maybe Prefix, command :: Command, params :: Params } deriving (Eq) instance Show Message where showsPrec x msg = showPrefix . showCommand . showParams where showPrefix = case prefix msg of Nothing -> id Just prefix -> showChar ':' . showsPrec x prefix . showChar ' ' showCommand = showsPrec x (command msg) showParams = case params msg of End -> id param -> showChar ' ' . showsPrec x param instance Read Message where readsPrec x (':':line) = let (pfx, msg') = break (==' ') line msg = dropWhile (==' ') msg' (cmd, params') = break (==' ') msg params = dropWhile (==' ') params' in return (Message (Just $ read pfx) (read cmd) (read params), "") readsPrec x msg = let (cmd, params') = break (==' ') msg params = dropWhile (==' ') params' in return (Message Nothing (read cmd) (read params), "") irc_user :: (Writeable a, Writeable b) => a -> b -> Message irc_user ident realname = Message Nothing Register (Short (text ident) $ Short (T.singleton '-') $ Short (T.singleton '*') $ Long (text realname)) irc_nick :: Writeable a => a -> Message irc_nick nick = Message Nothing Nick ( Short (text nick) End ) irc_pass :: Writeable a => a -> Message irc_pass pass = Message Nothing Pass ( Short (text pass) End ) irc_umode2 :: Writeable a => a -> Message irc_umode2 mode = Message Nothing Umode2 ( Short (text mode) End ) irc_join :: Writeable a => a -> Message irc_join chan = Message Nothing Join ( Short (text chan) End ) irc_privmsg :: (Writeable a, Writeable b) => a -> b -> Message irc_privmsg chan msg = Message Nothing Privmsg ( Short (text chan) ( Long (text msg) ) ) irc_pong :: Writeable a => a -> Message irc_pong code = Message Nothing Pong ( Long (text code) ) class WriteableS a where textS :: [a] -> Text instance WriteableS Char where textS msg = T.pack msg instance WriteableS a => Writeable [a] where text = textS class Writeable a where text :: a -> Text instance Writeable Message where text msg = T.pack $ show msg instance Writeable T.Text where text msg = msg
bqv/hebi
plugin/haskell/Message.hs
mpl-2.0
7,027
0
16
2,780
2,221
1,161
1,060
136
1
-- | Put all CSS for these widgets in templates/project_feed.cassius module View.SnowdriftEvent where import Import import Model.Comment import Model.Comment.ActionPermissions import Model.Comment.Routes import Model.User import View.Comment import Widgets.Time import qualified Data.Map as M import qualified Data.Text as T renderCommentPostedEvent :: CommentId -> Comment -> Maybe UserId -> Text -> Map DiscussionId DiscussionOn -> ActionPermissionsMap -> Map CommentId [CommentClosing] -> Map CommentId [CommentRetracting] -> Map UserId User -> Map CommentId CommentClosing -> Map CommentId CommentRetracting -> Map CommentId (Entity Ticket) -> Map CommentId TicketClaiming -> Map CommentId (CommentFlagging, [FlagReason]) -> Widget renderCommentPostedEvent comment_id comment mviewer_id project_handle discussion_map action_permissions_map earlier_closures_map earlier_retracts_map user_map closure_map retract_map ticket_map claim_map flag_map = do let action_permissions = lookupErr "renderCommentPostedEvent: comment id missing from permissions map" comment_id action_permissions_map user = lookupErr "renderCommentPostedEvent: comment user missing from user map" (commentUser comment) user_map discussion = lookupErr "renderCommentPostedEvent: discussion id not found in map" (commentDiscussion comment) discussion_map (routes, feed_item_widget) = case discussion of DiscussionOnProject (Entity _ Project{..}) -> (projectCommentRoutes projectHandle, [whamlet| <div .event> On <a href=@{ProjectDiscussionR projectHandle}>#{projectName}# : ^{comment_widget} |]) DiscussionOnWikiPage (Entity _ WikiTarget{..}) -> (wikiPageCommentRoutes project_handle wikiTargetLanguage wikiTargetTarget, [whamlet| <div .event> On the <a href=@{WikiDiscussionR project_handle wikiTargetLanguage wikiTargetTarget}>#{wikiTargetTarget} wiki page: ^{comment_widget} |]) DiscussionOnUser (Entity user_id _) -> (userCommentRoutes user_id, [whamlet| <div .event> On your user discussion page: ^{comment_widget} |]) DiscussionOnBlogPost (Entity _ BlogPost{..}) -> (blogPostCommentRoutes project_handle blogPostHandle, [whamlet| <div .event> On blog post <a href=@{BlogPostDiscussionR project_handle blogPostHandle}>#{blogPostTitle} : ^{comment_widget} |]) comment_widget = commentWidget (Entity comment_id comment) mviewer_id routes action_permissions (M.findWithDefault [] comment_id earlier_closures_map) (M.findWithDefault [] comment_id earlier_retracts_map) user (M.lookup comment_id closure_map) (M.lookup comment_id retract_map) (M.lookup comment_id ticket_map) (M.lookup comment_id claim_map) (M.lookup comment_id flag_map) False mempty feed_item_widget renderCommentPendingEvent :: CommentId -> Comment -> UserMap -> Widget renderCommentPendingEvent comment_id comment user_map = do let poster = lookupErr "renderCommentPendingEvent: poster not found in user map" (commentUser comment) user_map [whamlet| <div .event> ^{renderTime $ commentCreatedTs comment} <a href=@{UserR (commentUser comment)}> #{userDisplayName (Entity (commentUser comment) poster)} posted a <a href=@{CommentDirectLinkR comment_id}> comment awaiting moderator approval: #{commentText comment} |] renderCommentRethreadedEvent :: Rethread -> UserMap -> Widget renderCommentRethreadedEvent Rethread{..} user_map = do langs <- handlerToWidget getLanguages (Just old_route, Just new_route) <- handlerToWidget $ runDB $ (,) <$> makeCommentRouteDB langs rethreadOldComment <*> makeCommentRouteDB langs rethreadNewComment let user = lookupErr "renderCommentRethreadedEvent: rethreader not found in user map" rethreadModerator user_map [whamlet| <div .event> ^{renderTime rethreadTs} <a href=@{UserR rethreadModerator}> #{userDisplayName (Entity rethreadModerator user)} rethreaded a comment from <del>@{old_route} to <a href=@{new_route}>@{new_route}# : #{rethreadReason} |] renderCommentClosedEvent :: CommentClosing -> UserMap -> Map CommentId (Entity Ticket) -> Widget renderCommentClosedEvent CommentClosing{..} user_map ticket_map = do let user = lookupErr "renderCommentClosedEvent: closing user not found in user map" commentClosingClosedBy user_map case M.lookup commentClosingComment ticket_map of Just (Entity ticket_id Ticket{..}) -> do let ticket_str = case toPersistValue ticket_id of PersistInt64 tid -> T.pack $ show tid _ -> "<malformed key>" [whamlet| <div .event> ^{renderTime commentClosingTs} <a href=@{UserR commentClosingClosedBy}> #{userDisplayName (Entity commentClosingClosedBy user)} closed ticket <a href=@{CommentDirectLinkR commentClosingComment}> <div .ticket-title>SD-#{ticket_str}: #{ticketName} |] Nothing -> [whamlet| <div .event> ^{renderTime commentClosingTs} <a href=@{UserR commentClosingClosedBy}> #{userDisplayName (Entity commentClosingClosedBy user)} closed <a href=@{CommentDirectLinkR commentClosingComment}> comment thread |] renderTicketClaimedEvent :: Either (TicketClaimingId, TicketClaiming) (TicketOldClaimingId, TicketOldClaiming) -> UserMap -> Map CommentId (Entity Ticket) -> Widget renderTicketClaimedEvent (Left (_, TicketClaiming{..})) user_map ticket_map = do let user = lookupErr "renderTicketClaimedEvent: claiming user not found in user map" ticketClaimingUser user_map Entity ticket_id Ticket{..} = lookupErr "renderTicketClaimedEvent: ticket not found in map" ticketClaimingTicket ticket_map ticket_str = case toPersistValue ticket_id of PersistInt64 tid -> T.pack $ show tid _ -> "<malformed key>" [whamlet| <div .event> ^{renderTime ticketClaimingTs} <a href=@{UserR ticketClaimingUser}> #{userDisplayName (Entity ticketClaimingUser user)} claimed ticket <a href=@{CommentDirectLinkR ticketClaimingTicket}> <div .ticket-title>SD-#{ticket_str}: #{ticketName} |] renderTicketClaimedEvent (Right (_, TicketOldClaiming{..})) user_map ticket_map = do let user = lookupErr "renderTicketClaimedEvent: claiming user not found in user map" ticketOldClaimingUser user_map Entity ticket_id Ticket{..} = lookupErr "renderTicketClaimedEvent: ticket not found in map" ticketOldClaimingTicket ticket_map ticket_str = case toPersistValue ticket_id of PersistInt64 tid -> T.pack $ show tid _ -> "<malformed key>" [whamlet| <div .event> ^{renderTime ticketOldClaimingClaimTs} <a href=@{UserR ticketOldClaimingUser}> #{userDisplayName (Entity ticketOldClaimingUser user)} claimed ticket <a href=@{CommentDirectLinkR ticketOldClaimingTicket}> <div .ticket-title>SD-#{ticket_str}: #{ticketName} |] renderTicketUnclaimedEvent :: TicketOldClaiming -> UserMap -> Map CommentId (Entity Ticket) -> Widget renderTicketUnclaimedEvent TicketOldClaiming{..} _ ticket_map = do let Entity ticket_id Ticket{..} = lookupErr "renderTicketUnclaimedEvent: ticket not found in map" ticketOldClaimingTicket ticket_map ticket_str = case toPersistValue ticket_id of PersistInt64 tid -> T.pack $ show tid _ -> "<malformed key>" [whamlet| <div .event> ^{renderTime ticketOldClaimingClaimTs} Claim released, ticket available: <a href=@{CommentDirectLinkR ticketOldClaimingTicket}> <div .ticket-title>SD-#{ticket_str}: #{ticketName} |] renderWikiPageEvent :: Text -> WikiPageId -> WikiPage -> UserMap -> Widget renderWikiPageEvent project_handle wiki_page_id wiki_page _ = do -- TODO(aaron) -- The commented stuff here (and in the whamlet commented part) -- is because there's no wikiPageUser and the -- user_map is also not needed until that is active-- -- let editor = fromMaybe -- (error "renderWikiPageEvent: wiki editor not found in user map") -- (M.lookup (wikiPageUser wiki_page) user_map) --perhaps instead of a wikiPageUser, we should just figure out how to pull --the user from the first wiki edit for the event of new pages -- TODO: pick language correctly [Entity _ wiki_target] <- runDB $ select $ from $ \wt -> do where_ $ wt ^. WikiTargetPage ==. val wiki_page_id limit 1 return wt [whamlet| <div .event> ^{renderTime $ wikiPageCreatedTs wiki_page} <!-- <a href=@{UserR (wikiPageUser wiki_page)}> #{userDisplayName (Entity (wikiPageUser wiki_page) editor)} --> made a new wiki page: # <a href=@{WikiR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target)}>#{wikiTargetTarget wiki_target} |] renderWikiEditEvent :: Text -> WikiEditId -> WikiEdit -> Map WikiPageId WikiTarget -> UserMap -> Widget renderWikiEditEvent project_handle edit_id wiki_edit wiki_target_map user_map = do let editor = lookupErr "renderWikiEditEvent: wiki editor not found in user map" (wikiEditUser wiki_edit) user_map wiki_target = lookupErr "renderWikiEditEvent: wiki page id not found in wiki target map" (wikiEditPage wiki_edit) wiki_target_map [whamlet| <div .event> ^{renderTime $ wikiEditTs wiki_edit} <a href=@{UserR (wikiEditUser wiki_edit)}> #{userDisplayName (Entity (wikiEditUser wiki_edit) editor)} edited the <a href=@{WikiR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target)}> #{wikiTargetTarget wiki_target} wiki page: # $maybe comment <- wikiEditComment wiki_edit #{comment} <br> <a href=@{WikiEditR project_handle (wikiTargetLanguage wiki_target) (wikiTargetTarget wiki_target) edit_id}> see this edit version <!-- TODO: make this link to the diff instead --> |] renderBlogPostEvent :: BlogPost -> Widget renderBlogPostEvent (BlogPost {..}) = do maybe_project <- handlerToWidget $ runYDB $ get blogPostProject [whamlet| <div .event> ^{renderTime blogPostTs} New blog post: # $maybe Project{projectHandle = project_handle} <- maybe_project <a href=@{BlogPostR project_handle blogPostHandle}> #{blogPostTitle} $nothing #{blogPostTitle} |] renderNewPledgeEvent :: SharesPledgedId -> SharesPledged -> UserMap -> Widget renderNewPledgeEvent _ SharesPledged{..} user_map = do let pledger = lookupErr "renderNewPledgeEvent: pledger not found in user map" sharesPledgedUser user_map [whamlet| <div .event> ^{renderTime sharesPledgedTs} <a href=@{UserR sharesPledgedUser}> #{userDisplayName (Entity sharesPledgedUser pledger)} made a new pledge of _{MsgShares sharesPledgedShares}! |] renderUpdatedPledgeEvent :: Int64 -> SharesPledgedId -> SharesPledged -> UserMap -> Widget renderUpdatedPledgeEvent old_shares _ SharesPledged{..} user_map = do let pledger = lookupErr "renderUpdatedPledgeEvent: pledger not found in user map" sharesPledgedUser user_map (verb, punc) = if old_shares < sharesPledgedShares then ("increased", "!") else ("decreased", ".") :: (Text, Text) [whamlet| <div .event> ^{renderTime sharesPledgedTs} <a href=@{UserR sharesPledgedUser}> #{userDisplayName (Entity sharesPledgedUser pledger)} #{verb} their pledge from _{MsgShares old_shares} to _{MsgShares sharesPledgedShares}#{punc} |] renderDeletedPledgeEvent :: UTCTime -> UserId -> Int64 -> UserMap -> Widget renderDeletedPledgeEvent ts user_id shares user_map = do let pledger = lookupErr "renderDeletedPledgeEvent: pledger not found in user map" user_id user_map [whamlet| <div .event> ^{renderTime ts} <a href=@{UserR user_id}>#{userDisplayName (Entity user_id pledger)} withdrew their #{show shares}-share pledge. |]
chreekat/snowdrift
View/SnowdriftEvent.hs
agpl-3.0
13,921
0
21
4,201
1,752
904
848
-1
-1
import Ring_7 main = do print $ Z 3 == Z 10 print $ [Z 0..Z 6] print $ map abs [Z 0..Z 6] print $ map signum [Z 0..Z 6] print $ map (\k -> 1/k) [Z 1..Z 6] print $ map (\k -> recip k) [Z 1..Z 6]
bestian/haskell-sandbox
r7_test0.hs
unlicense
244
0
11
100
159
73
86
7
1
{-# LANGUAGE BangPatterns #-} import qualified Data.ByteString.Char8 as C import Data.Array.Unboxed import Data.Maybe(fromJust) import Data.Char readint = fst . fromJust . C.readInt dig x = ord x - ord '0' div7 = (\x -> x`mod`7 == 0) . snd . C.foldr go (1, 0) where go c (!k, !r) = (k', r+(u!k) * (dig c)) where !k' = if k == 6 then 1 else succ k !u = listArray (1, 6) [1, 3, 2, -1, -3, -2] :: UArray Int Int div8 s = (\x -> x`mod`8 == 0) . readint . C.drop (len-3) $ s where !len = C.length s div4 s = (\x -> x`mod`4 == 0) . readint . C.drop (len-2) $ s where !len = C.length s div2 = even . dig . C.last div9 = (\x -> x`mod`9 == 0) . digsum digsum = C.foldl go 0 where go r c = r + dig c div6 s = div2 s && div3 s div3 = (\x -> x`mod`3 == 0) . digsum div5 = (\x -> x == 0 || x == 5) . dig . C.last gencache s = listArray (1, 9) [d1, d2, d3, d4, d5, d6, d7, d8, d9] :: UArray Int Bool where ds = digsum s d1 = True d2 = div2 s d3 = ds `mod` 3 == 0 d4 = div4 s d5 = div5 s d6 = d2 && d3 d7 = div7 s d8 = div8 s d9 = ds `mod` 9 == 0 divdig s = C.foldl go 0 s where !u = gencache s go r c | v == True = succ r | v == False = r where v = u ! (dig c) pr = foldr p1 "" where p1 x = shows x . showString "\n" main = C.getContents >>= putStr. pr . map divdig . C.lines
wangbj/haskell
pucmm025.hs
bsd-2-clause
1,420
0
11
468
799
424
375
42
2
{- | This module reexports type safe routing aproach which should be the default for all Spock applications. To learn more about the routing, read the corresponding blog post available at <http://www.spock.li/2015/04/19/type-safe_routing.html> -} module Web.Spock ( module Web.Spock.Safe ) where import Web.Spock.Safe
nmk/Spock
src/Web/Spock.hs
bsd-3-clause
327
0
5
51
22
15
7
3
0
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.Volume.AR.Rules ( rules ) where import Data.String import Data.Text (Text) import Prelude import Duckling.Dimensions.Types import Duckling.Types import Duckling.Regex.Types import Duckling.Volume.Helpers import Duckling.Numeral.Helpers (isPositive) import qualified Duckling.Volume.Types as TVolume import qualified Duckling.Numeral.Types as TNumeral volumes :: [(Text, String, TVolume.Unit)] volumes = [ ("<latent vol> ml" , "مي?لي?( ?لي?تي?ر)?" , TVolume.Millilitre) , ("<vol> hectoliters" , "(هي?كتو ?لي?تر)" , TVolume.Hectolitre) , ("<vol> liters" , "لي?تي?ر(ات)?" , TVolume.Litre) , ("<latent vol> gallon", "[جغق]الون(ين|ان|ات)?", TVolume.Gallon) ] rulesVolumes :: [Rule] rulesVolumes = map go volumes where go :: (Text, String, TVolume.Unit) -> Rule go (name, regexPattern, u) = Rule { name = name , pattern = [ regex regexPattern ] , prod = \_ -> Just . Token Volume $ unitOnly u } ruleQuarterLiter :: Rule ruleQuarterLiter = Rule { name = "quarter liter" , pattern = [ regex "ربع لي?تي?ر" ] , prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ valueOnly 0.25 } ruleHalfLiter :: Rule ruleHalfLiter = Rule { name = "half liter" , pattern = [ regex "نصف? لي?تي?ر" ] , prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ valueOnly 0.5 } ruleLiterAndQuarter :: Rule ruleLiterAndQuarter = Rule { name = "liter and quarter" , pattern = [ regex "لي?تي?ر و ?ربع" ] , prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ valueOnly 1.25 } ruleLiterAndHalf :: Rule ruleLiterAndHalf = Rule { name = "liter and half" , pattern = [ regex "لي?تي?ر و ?نصف?" ] , prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ valueOnly 1.5 } ruleTwoLiters :: Rule ruleTwoLiters = Rule { name = "two liters" , pattern = [ regex "لي?تي?ر(ان|ين)" ] , prod = \_ -> Just . Token Volume . withUnit TVolume.Litre $ valueOnly 2 } rules :: [Rule] rules = [ ruleHalfLiter , ruleQuarterLiter , ruleTwoLiters , ruleLiterAndHalf , ruleLiterAndQuarter ] ++ rulesVolumes
facebookincubator/duckling
Duckling/Volume/AR/Rules.hs
bsd-3-clause
2,612
0
12
618
625
368
257
65
1
{-# LANGUAGE BangPatterns #-} module Y2017.Day17 (answer1, answer2) where import qualified Data.Vector as V import Data.Maybe import Data.Foldable import Data.Monoid answer1, answer2 :: IO () answer1 = print $ solve1 input answer2 = let (_, _, val) = foldl' (step2 input) (0, 1, Nothing) [1 .. 50 * 10 ^ 6] in print $ fromMaybe (error "nope") val input :: Int input = 367 solve1 stepSize = let (finalX, finalV) = foldl' (step stepSize) (0, V.singleton 0) [1 .. 2017] in finalV V.! ((finalX + 1) `mod` V.length finalV) step stepSize (!x, !v) !i = let x' = (x + stepSize) `mod` V.length v + 1 (vbefore, vafter) = V.splitAt x' v v' = vbefore <> V.singleton i <> vafter in (x', v') step2 stepSize (!x, !n, val) !i = let x' = (x + stepSize) `mod` n in if x' == 0 then (1, n + 1, Just i) else (x' + 1, n + 1, val)
geekingfrog/advent-of-code
src/Y2017/Day17.hs
bsd-3-clause
911
0
12
261
422
230
192
25
2
module Testrs where import Data.Conduit import Data.Conduit.Binary someFunc :: IO () someFunc = putStrLn "someFunc"
ppp4ppp/test3
src/Testrs.hs
bsd-3-clause
119
0
6
18
33
19
14
5
1
{-# LANGUAGE TypeFamilies, FlexibleInstances, MultiParamTypeClasses, RecordWildCards, DoAndIfThenElse, EmptyDataDecls, PatternGuards #-} module CLI where import Control.Monad.Trans import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Reader import Control.Monad.IO.Class import Control.Monad import Control.Applicative import Control.Arrow import System.Console.Haskeline import qualified Data.UUID as UUID import qualified System.UUID.V4 as UUID import qualified Data.Map as Map import qualified Data.Set as Set import qualified Text.Parsec as P import qualified Text.Parsec.String as P import qualified Text.PrettyPrint as PP import qualified System.IO.Temp as Temp import qualified Data.Char as Char import Data.Foldable (foldMap) import Data.List (intercalate, isPrefixOf, isInfixOf, tails, partition) import Data.Maybe (listToMaybe) import System.Process (system, rawSystem) import System.IO (hPutStrLn, hFlush, hClose) import System.Posix.Files (getFileStatus, modificationTime) import System.Directory (doesFileExist) import Solver import qualified Javascript as JS import qualified Scope data CLI data Definition = Definition { defCode :: String, defDeps :: [String] } deriving (Read,Show) data RuleDoc = RuleDoc { rdocName :: String, rdocDescription :: String } deriving (Read,Show) data Suite = Suite { suiteAssumptions :: [Prop CLI], suiteScope :: Scope.Scope String (PredName CLI), suiteName :: String, suiteDescription :: String } deriving (Read,Show) data Database = Database { dbRuleDocs :: Map.Map (PredName CLI) RuleDoc, dbRules :: Map.Map (PredName CLI) [Rule CLI], dbDefns :: Map.Map (DefID CLI) Definition, dbRuleScope :: Scope.Scope String (PredName CLI), dbSuites :: [Suite], dbAssumptions :: [Prop CLI] } deriving (Read,Show) eqDoc :: RuleDoc eqDoc = RuleDoc { rdocName = "eq", rdocDescription = "eq\n====\n`eq X Y` asserts that the objects X and Y are equal." } emptyDatabase = Database { dbRuleDocs = Map.singleton (PredBuiltin PredEq) eqDoc, dbRules = singletonRule $ [] :=> PredBuiltin PredEq :@ [ Var "X", Var "X" ], dbDefns = Map.empty, dbRuleScope = Scope.empty, dbSuites = [], dbAssumptions = [] } singletonRule :: Rule CLI -> Map.Map (PredName CLI) [Rule CLI] singletonRule r@(_ :=> p :@ _) = Map.singleton p [r] instance Functor (Effect CLI) where fmap f (Effect x) = Effect (fmap f x) instance Applicative (Effect CLI) where pure = Effect . pure Effect f <*> Effect x = Effect (f <*> x) instance Monad (Effect CLI) where return = pure Effect m >>= f = Effect $ m >>= runEffect . f data PredBuiltin = PredEq deriving (Read,Show,Eq,Ord) instance Config CLI where newtype DefID CLI = DefID UUID.UUID deriving (Eq,Ord,Read,Show) newtype Effect CLI a = Effect { runEffect :: Reader Database a } data PredName CLI = PredUser UUID.UUID | PredBuiltin PredBuiltin deriving (Eq,Ord,Read,Show) findRules name = maybe [] id <$> Effect (asks (Map.lookup name . dbRules)) type Shell = InputT (StateT Database IO) simpleEditor :: String -> String -> IO (Maybe String) simpleEditor ext str = Temp.withSystemTempDirectory "tigress" $ \dir -> do Temp.withTempFile dir ("edit." ++ ext) $ \path handle -> do hPutStrLn handle str hClose handle stat <- getFileStatus path system $ "vim + " ++ path stat' <- getFileStatus path if modificationTime stat' > modificationTime stat then Just <$> readFile path else return Nothing editor :: String -> String -> String -> String -> IO (Maybe String) editor ext env delim str = fmap strip <$> simpleEditor ext (unlines [env, delim, str]) where strip = unlines . safeTail . dropWhile (/= delim) . lines safeTail [] = [] safeTail (x:xs) = xs addDefn :: String -> Definition -> Shell () addDefn localName defn = do uuid <- DefID <$> liftIO UUID.uuid let prop = PredBuiltin PredEq :@ [Var localName, uuid :% map Var (defDeps defn)] lift . modify $ \db -> db { dbDefns = Map.insert uuid defn (dbDefns db) , dbAssumptions = prop : dbAssumptions db } makeDefn :: String -> Either String Definition makeDefn code = right (\v -> Definition { defCode = code, defDeps = Set.toList (JS.freeVars v)}) (JS.vars code) mentionedIn :: String -> Prop CLI -> Bool mentionedIn var (_ :@ objs) = any mentionedIn' objs where mentionedIn' (Var v) = v == var mentionedIn' (_ :% objs) = any mentionedIn' objs mentionedVars :: Prop CLI -> Set.Set String mentionedVars (_ :@ objs) = foldMap objMentionedVars objs objMentionedVars :: Object CLI -> Set.Set String objMentionedVars (Var v) = Set.singleton v objMentionedVars (_ :% objs) = foldMap objMentionedVars objs propDeps :: Database -> Prop CLI -> [Prop CLI] propDeps db prop = filter (intersects (mentionedVars prop) . mentionedVars) $ dbAssumptions db where intersects a b = not . Set.null $ Set.intersection a b withDeps :: Database -> Prop CLI -> Rule CLI withDeps db prop = propDeps db prop :=> prop showObject :: Object CLI -> PP.Doc showObject (Var v) = PP.text v showObject (DefID def :% deps) = PP.text (show def) PP.<> PP.brackets (PP.hsep (PP.punctuate PP.comma (map showObject deps))) showPredName :: Database -> PredName CLI -> PP.Doc showPredName db (PredBuiltin PredEq) = PP.text "eq" showPredName db o | Just n <- Scope.lookupName o (dbRuleScope db) = PP.text n | otherwise = PP.text (show o) showProp :: Database -> Prop CLI -> PP.Doc showProp db (n :@ args) = showPredName db n PP.<+> PP.hsep (map showObject args) showRule :: Database -> Rule CLI -> PP.Doc showRule db (assns :=> con) = showProp db con PP.<+> PP.text ":-" PP.<+> PP.vcat (map (showProp db) assns) showEnv :: Database -> PP.Doc showEnv db = PP.vcat [ PP.vcat (map (showProp db) (dbAssumptions db)) ] type Parser = P.Parsec String () predName :: Database -> Parser (PredName CLI) predName db = P.choice $ map P.try [ P.string "eq" *> pure (PredBuiltin PredEq), P.many1 P.alphaNum >>= \s -> do Just name <- return $ Scope.lookupObj s (dbRuleScope db) return name ] prop :: Database -> Parser (Prop CLI) prop db = liftA2 (:@) (predName db) (P.many (space *> object db)) object :: Database -> Parser (Object CLI) object db = Var <$> P.many1 P.alphaNum space :: Parser () space = P.space *> P.spaces defineLocal :: String -> String -> Shell () defineLocal name code = do case makeDefn code of Left err -> liftIO . putStrLn $ "Parse error: " ++ err Right defn -> do addDefn name defn liftIO . putStrLn $ "defined " ++ name defineEditor :: String -> Shell () defineEditor name = do db <- lift get let shEnv = unlines . map ("// " ++) . lines . PP.render $ showEnv db let prefix = shEnv ++ "// defining: " ++ name let go pfx code = do mcontents <- liftIO $ editor "js" (prefix ++ "\n// " ++ pfx) "//////////" code case mcontents of Just contents -> case makeDefn contents of Left err -> go ("Parse error: " ++ err) contents Right defn -> do addDefn name defn liftIO . putStrLn $ "defined " ++ name Nothing -> liftIO . putStrLn $ "cancelled" go "" "" wordInDoc :: String -> RuleDoc -> Bool wordInDoc s doc = find (rdocName doc) || find (rdocDescription doc) where find body = map Char.toLower s `isInfixOf` body wordInSuite :: String -> Suite -> Bool wordInSuite s suite = find (suiteName suite) || find (suiteDescription suite) where find body = map Char.toLower s `isInfixOf` body maybeRead :: Read a => String -> Maybe a maybeRead = fmap fst . listToMaybe . reads ppText :: String -> PP.Doc ppText = PP.vcat . map PP.text . lines discharge :: (Prop CLI -> Bool) -> Shell () discharge match = lift . modify $ \db -> db { dbAssumptions = filter (not . match) (dbAssumptions db) } clearAbs :: (String -> Bool) -> Shell () clearAbs match = do scope <- lift $ gets dbRuleScope discharge (\(n :@ _) -> (match <$> Scope.lookupName n scope) == Just True) lift . modify $ \db -> db { dbRuleScope = Scope.fromList . filter (\(n,d) -> not (match n)) . Scope.toList $ dbRuleScope db } searchInterface :: (m -> PP.Doc) -> [m] -> (m -> Shell ()) -> Shell () searchInterface showM matches select = do forM_ (zip [0..] matches) $ \(i, m) -> liftIO . putStrLn . PP.render $ PP.text (show i ++ ")") PP.<+> showM m input <- getInputLine "? " case input >>= maybeRead of Just num | num < length matches -> do select (matches !! num) _ -> liftIO . putStrLn $ "cancelled" searchDB :: [String] -> Shell () searchDB ws = do db <- lift get let matches = [ (name, doc) | (name,doc) <- Map.toList (dbRuleDocs db), all (`wordInDoc` doc) ws ] searchInterface (ppText . rdocDescription . snd) matches $ \(name, doc) -> do mname <- getInputLineWithInitial "name? " (rdocName doc, "") case mname of Just lname | not (null lname) -> do lift . put $ db { dbRuleScope = Scope.insert lname name (dbRuleScope db) } liftIO . putStrLn $ "brought " ++ lname ++ " into scope" _ -> liftIO . putStrLn $ "cancelled" searchSuite :: [String] -> Shell () searchSuite ws = do db <- lift get let matches = [ suite | suite <- dbSuites db, all (`wordInSuite` suite) ws ] searchInterface (ppText . suiteDescription) matches $ \suite -> do lift . put $ db { dbAssumptions = suiteAssumptions suite ++ dbAssumptions db, dbRuleScope = suiteScope suite `Scope.union` dbRuleScope db } liftIO . putStrLn $ "assumed suite " ++ suiteName suite errors :: (MonadPlus m) => m a -> (a -> Either String b) -> m a m `errors` p = do x <- m case p x of Left err -> fail err Right _ -> return x data Command = Command { cmdParser :: Parser (Shell ()), cmdScheme :: String, cmdDoc :: PP.Doc } cmd :: Database -> Parser (Shell ()) cmd db = P.choice [ P.try parser | Command parser _ _ <- commands ] where commands = [ Command (help <$> (P.string ":help" *> pure ())) ":help" $ doc [ "Shows all commands with descriptions" ], Command (defineInline <$> (identifier <* P.spaces <* P.char '=' <* P.spaces) <*> anything) "<name> = <defn>" $ doc [ "Introduces a new object with the given name and definition into the local" , "environment" ], Command (define <$> (P.string ":define" *> space *> identifier)) ":define <name>" $ doc [ "Defines a new object. Opens an editor to edit a new object, then defines" , "the given name to denote that object in the local environment" ], Command (defabs <$> (P.string ":defabs" *> space *> absId)) ":defabs <name>" $ doc [ "Defines a new abstraction. Opens an editor to edit the documentation for" , "a new abstraction and introduces it into the local environment" ], Command (defsuite <$> (P.string ":defsuite" *> space *> absId)) ":defsuite <name>" $ doc [ "Saves the current local environment into a suite." ], Command (search <$> (P.string ":search" *> P.spaces *> anything)) ":search <text>" $ doc [ "Searches the database for the given text in the documentation of an" , "abstraction. You have the option to introduce it into the local environment" , "with a name of your choosing" ], Command (suite <$> (P.string ":suite" *> P.spaces *> anything)) ":suite <text>" $ doc [ "Searches the database for the given text in the documentation of a suite" ], Command (env <$> (P.string ":env" *> pure ())) ":env" $ doc [ "List all the objects defined in the local environment" ], Command (assume <$> (P.string ":assume" *> space *> prop db)) ":assume <pred>" $ doc [ "Constrain the current abstract environment by the given predicate." , "Introduces any previously unmentioned identifiers into the local" , "environment." ], Command (assert <$> (P.string ":assert" *> space *> prop db)) ":assert <pred>" $ doc [ "Specify that the given proposition is true in the current environment." ], Command (abstract <$> (P.string ":abstract" *> P.many (space *> identifier))) ":abstract [ <name1> <name2> ... ]" $ doc [ "Clears the definitions of the given identifiers from the environment," , "allowing it to vary according to its constraints. If no identifiers are" , "given, abstracts all of them." ], Command (abs <$> (P.string ":abs" *> pure ())) ":abs" $ doc [ "List the abstraction environment." ], Command (clear <$> (P.string ":clear" *> P.many (space *> identifier))) ":clear [ <name1> ... ]" $ doc [ "If names are given, clears the given names from the local environment." , "Otherwise clears the entire environment." ], Command (eval <$> (anything `errors` JS.vars)) "<javascript expression>" $ doc [ "Evaluates the given expression as javascript in the local environment." ] ] identifier = P.many1 (P.alphaNum <|> P.oneOf("_$")) absId = P.many1 (P.alphaNum <|> P.oneOf("-_")) anything = P.many (P.satisfy (const True)) doc = PP.vcat . map PP.text help () = liftIO . print $ PP.vcat [ PP.text spec PP.$+$ PP.nest 4 doc | Command _ spec doc <- commands ] define = defineEditor defineInline = defineLocal defabs name = do mcontents <- liftIO $ simpleEditor "mkd" (unlines [name, "===="]) case mcontents of Nothing -> liftIO . putStrLn $ "cancelled" Just contents -> do pname <- PredUser <$> liftIO UUID.uuid db <- lift get let doc = RuleDoc { rdocName = name, rdocDescription = contents } lift . put $ db { dbRuleDocs = Map.insert pname doc (dbRuleDocs db), dbRuleScope = Scope.insert name pname (dbRuleScope db) } liftIO . putStrLn $ "defined" defsuite name = do db <- lift get let assumptions = PP.nest 4 . PP.vcat $ map (showProp db) (dbAssumptions db) mcontents <- liftIO $ simpleEditor "mkd" (unlines [name, "===", PP.render assumptions]) case mcontents of Nothing -> liftIO . putStrLn $ "cancelled" Just contents -> do let suite = Suite { suiteAssumptions = dbAssumptions db, suiteName = name, suiteScope = dbRuleScope db, suiteDescription = contents } lift . modify $ \db -> db { dbSuites = suite : dbSuites db } liftIO . putStrLn $ "defined suite " ++ name abs () = do db <- lift get forM_ (Scope.toList (dbRuleScope db)) $ \(k,v) -> do case Map.lookup v (dbRuleDocs db) of Nothing -> liftIO . putStrLn $ k Just doc -> liftIO . putStrLn . PP.render $ PP.text k PP.<+> ppText (rdocDescription doc) search = searchDB . words suite = searchSuite . words env () = do db <- lift get liftIO . putStrLn . PP.render . showEnv $ db assume p = do lift . modify $ \db -> db { dbAssumptions = p : dbAssumptions db } assert p = lift . modify $ \db -> db { dbRules = Map.unionWith (++) (singletonRule (withDeps db p)) (dbRules db) } abstract ids = discharge $ \p -> case p of PredBuiltin PredEq :@ [Var a,b] | a `elem` ids -> True _ -> False clear [] = discharge (const True) >> clearAbs (const True) clear ids = discharge (\a -> any (`mentionedIn` a) ids) >> clearAbs (\n -> any (== n) ids) eval str = do code <- assemble case code of Nothing -> return () Just code' -> do liftIO $ writeFile "assemble.js" code' liftIO $ rawSystem "node" ["-e", "require('./assemble.js'); console.log(" ++ str ++ ");" ] return () assemble :: Shell (Maybe String) assemble = do props <- lift $ gets dbAssumptions defns <- lift $ gets dbDefns db <- lift get case map fst $ runReader (runEffect (runSolver (mapM_ satisfy props) 1)) db of [] -> do liftIO . putStrLn $ "No solution" return Nothing [sub] -> do let defs = [ (k, assemble' defns v) | (k, v) <- Map.toList sub, not ("~" `isPrefixOf` k) ] let code = unlines $ map (\(k,code) -> k ++ " = " ++ code ++ ";") defs return $ Just code assemble' :: Map.Map (DefID CLI) Definition -> Object CLI -> String assemble' defns (Var x) = "\"<<<Variable " ++ x ++ ">>>\"" assemble' defns (defid :% args) = assembleDefn (defns Map.! defid) where assembleDefn (Definition {..}) = "(function(" ++ intercalate "," defDeps ++ ") { return (" ++ defCode ++ ") })(" ++ intercalate "," (map (assemble' defns) args) ++ ")" mainShell :: Shell () mainShell = do inp <- getInputLine "> " case inp of Nothing -> return () Just line -> do db <- lift get case P.runParser (cmd db <* P.eof) () "<input>" line of Left err -> liftIO $ print err Right m -> m mainShell load :: Shell () load = do ex <- liftIO $ doesFileExist "tigress.db" when ex $ do db <- fmap read . liftIO $ readFile "tigress.db" lift $ put $! db save :: Shell () save = do db <- lift get liftIO $ writeFile "tigress.db" (show db) main = do execStateT (runInputT defaultSettings (load >> mainShell >> save)) emptyDatabase return ()
luqui/tigress
CLI.hs
bsd-3-clause
18,823
0
22
5,684
6,348
3,207
3,141
-1
-1
module DobadoBots.GameEngine.Collisions ( nearestIntersection ,nearestDistance ,robotObjectiveIntersection ,robotColliderDistance ) where import Linear.V2 (V2(..)) import qualified Data.Foldable as F (toList) import qualified Data.SG.Geometry as GG (alongLine) import qualified Data.SG.Shape as GS (Shape'(..), intersectLineShape, overlap) import Data.List (minimumBy) import Data.Function (on) import qualified Data.SG.Geometry.TwoDim as G2 (Line2'(..), Rel2', Line2', Point2'(..), makeRel2, intersectLines2) import Data.Maybe (catMaybes, mapMaybe, maybeToList, listToMaybe, isJust, fromJust) import Data.HashMap.Strict as HM (lookup) import qualified Linear.Metric as LM (distance) import Control.Monad (liftM2) import DobadoBots.GameEngine.Data (Robot(..), GameState(..), Obstacle(..), Objective(..), Object(..), Collision(..), RobotId(..)) import DobadoBots.Interpreter.Data (Collider(..)) import DobadoBots.GameEngine.Utils (getXV2, getYV2, minTupleArray, v2toSGVect, point2ToV2, degreeToRadian, objectToShape) robotColliderDistance :: Robot -> V2 Float -> Integer robotColliderDistance rb col = floor $ LM.distance col robotPos - (robotWidth / 2) where robotWidth = getYV2 . size $ object rb robotPos = position $ object rb robotObjectiveIntersection :: RobotId -> GameState -> Bool robotObjectiveIntersection rId st = isJust $ GS.overlap rb obj where rb = objectToShape . object . fromJust . HM.lookup rId $ robots st obj = objectToShape $ objective st nearestIntersection :: Robot -> GameState -> Collision nearestIntersection r st | isJust nearestCol = (fst $ fromJust nearestCol, getV2IntersecPoint) | otherwise = error "no colliding point!" where getV2IntersecPoint = point2ToV2 . GG.alongLine (snd $ fromJust nearestCol) $ getRobotFrontLine r nearestCol = nearestIntersectionDistance r st nearestIntersectionDistance :: Robot -> GameState -> Maybe (Collider, Float) nearestIntersectionDistance r st = minCollider where nearObs = liftM2 (,) (Just Obstacle) . minTupleArray . obstacleIntersections r $ obstacles st nearRob = liftM2 (,) (Just Robot) . minTupleArray . robotIntersections r . F.toList $ robots st nearObj = liftM2 (,) (Just Objective) . minTupleArray . objectiveIntersections r $ objective st nearWall = Just (Wall, arenaIntersection r st) collidersList = catMaybes [nearObs, nearRob, nearObj, nearWall] colVector = filter ((>=0) . snd) collidersList minCollider = case colVector of (x:xs) -> Just $ minimumBy (compare `on` snd) colVector [] -> Nothing nearestDistance :: [(Float,Float)] -> Maybe Float nearestDistance = minTupleArray obstacleIntersections :: Robot -> [Obstacle] -> [(Float,Float)] obstacleIntersections r = mapMaybe $ returnObjectIntersection r objectiveIntersections :: Robot -> Objective -> [(Float,Float)] objectiveIntersections r obj = catMaybes [returnObjectIntersection r obj] arenaIntersection :: Robot -> GameState -> Float arenaIntersection r st = case length filteredIntersections of 0 -> 0 _ -> minimum filteredIntersections where filteredIntersections = filter (>= 0) wallsIntersections wallsIntersections = fst <$> catMaybes (G2.intersectLines2 (getRobotFrontLine r) <$> walls) walls = [leftWall,rightWall,topWall,bottomWall] leftWall = G2.Line2 (G2.Point2 (0,0)) (G2.makeRel2 (0,aHeight)) rightWall = G2.Line2 (G2.Point2 (aWidth,0)) (G2.makeRel2 (0,aHeight)) topWall = G2.Line2 (G2.Point2 (0,0)) (G2.makeRel2 (aWidth,0)) bottomWall = G2.Line2 (G2.Point2 (0,aHeight)) (G2.makeRel2 (aWidth,0)) (V2 aWidth aHeight) = arenaSize st robotIntersections :: Robot -> [Robot] -> [(Float,Float)] robotIntersections r rbs = mapMaybe (returnObjectIntersection r) otherRobots where otherRobots = object <$> filter (/= r) rbs returnObjectIntersection :: Robot -> Object -> Maybe (Float,Float) returnObjectIntersection robot obj = GS.intersectLineShape (getRobotFrontLine robot) shape where shape = objectToShape obj getRobotFrontLine :: Robot -> G2.Line2' Float getRobotFrontLine robot = line where line = G2.Line2 (G2.Point2 (xRobot,yRobot)) $ G2.makeRel2 (xFrontRobot,yFrontRobot) xRobot = getXV2 centerRobot yRobot = getYV2 centerRobot centerRobot = position (object robot) + size (object robot )/ 2 vRobot = currentVelocity $ object robot rot = rotation $ object robot xFrontRobot = vRobot * (cos . degreeToRadian $ rot) yFrontRobot = vRobot * (sin . degreeToRadian $ rot)
NinjaTrappeur/DobadoBots
src/DobadoBots/GameEngine/Collisions.hs
bsd-3-clause
5,501
0
13
1,715
1,509
834
675
86
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE ScopedTypeVariables #-} -- | See "Control.Monad.Ether.Except". module Control.Monad.Ether.Implicit.Except ( -- * MonadExcept class MonadExcept , throw , catch -- * The Except monad , Except , runExcept -- * The ExceptT monad transformer , ExceptT , exceptT , runExceptT -- * Handle functions , handle , handleT ) where import Data.Proxy import qualified Control.Monad.Ether.Except as Explicit -- | See 'Control.Monad.Ether.Except.MonadExcept'. type MonadExcept e = Explicit.MonadExcept e e -- | See 'Control.Monad.Ether.Except.throw'. throw :: forall e m a . MonadExcept e m => e -> m a throw = Explicit.throw (Proxy :: Proxy e) -- | See 'Control.Monad.Ether.Except.catch'. catch :: forall e m a . MonadExcept e m => m a -> (e -> m a) -> m a catch = Explicit.catch (Proxy :: Proxy e) -- | See 'Control.Monad.Ether.Except.Except'. type Except e = Explicit.Except e e -- | See 'Control.Monad.Ether.Except.runExcept'. runExcept :: Except e a -> Either e a runExcept = Explicit.runExcept Proxy -- | See 'Control.Monad.Ether.Except.ExceptT'. type ExceptT e = Explicit.ExceptT e e -- | See 'Control.Monad.Ether.Except.exceptT'. exceptT :: m (Either e a) -> ExceptT e m a exceptT = Explicit.exceptT Proxy -- | See 'Control.Monad.Ether.Except.runExceptT'. runExceptT :: ExceptT e m a -> m (Either e a) runExceptT = Explicit.runExceptT Proxy -- | See 'Control.Monad.Ether.Except.handle'. handle :: (e -> a) -> Except e a -> a handle = Explicit.handle (Proxy :: Proxy e) -- | See 'Control.Monad.Ether.Except.handleT'. handleT :: Functor m => (e -> a) -> ExceptT e m a -> m a handleT = Explicit.handleT (Proxy :: Proxy e)
bitemyapp/ether
src/Control/Monad/Ether/Implicit/Except.hs
bsd-3-clause
1,736
0
11
336
429
239
190
33
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DataKinds #-} module Monad ( module Monad , AuditEvent(..) ) where import Control.Lens import Control.Monad.Reader import Data.Default (def) import Database.Persist.Sql import qualified NejlaCommon as NC import Types import Audit import qualified SignedAuth -------------------------------------------------------------------------------- -- Api Monad ------------------------------------------------------------------- -------------------------------------------------------------------------------- type Ctx = ApiState data ApiState = ApiState { apiStateConfig :: Config , apiStateAuditSource :: AuditSource , apiStateNoncePool :: SignedAuth.NoncePool } makeLensesWith camelCaseFields ''ApiState type API a = NC.App ApiState 'NC.Privileged 'NC.ReadCommitted a -- newtype API a = API { unAPI :: ReaderT ApiState IO a } -- deriving ( Functor, Applicative, Monad, MonadIO -- , MonadThrow, MonadCatch) runDB :: ReaderT SqlBackend IO a -> API a runDB = NC.db' getConfig :: Lens' Config a -> API a getConfig g = NC.viewState $ config . g runAPI :: ConnectionPool -> ApiState -> API a -> IO a runAPI pool st m = NC.runApp' (def & NC.useTransactionLevels .~ (st ^. config . useTransactionLevels)) pool st m audit :: AuditEvent -> API () audit event = do src <- NC.viewState auditSource _ <- runDB $ addAuditLog src event return ()
nejla/auth-service
service/src/Monad.hs
bsd-3-clause
1,601
0
10
412
328
180
148
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} import System.Environment import Control.Monad import Control.Applicative import Control.Distributed.Process import Control.Distributed.Process.Node import Network.Transport.TCP (createTransport, defaultTCPParameters, defaultTCPAddr) import Data.Binary import qualified Data.ByteString.Lazy as BSL import Data.Typeable data SizedList a = SizedList { size :: Int , elems :: [a] } deriving (Typeable) instance Binary a => Binary (SizedList a) where put (SizedList sz xs) = put sz >> mapM_ put xs get = do sz <- get xs <- getMany sz return (SizedList sz xs) -- Copied from Data.Binary getMany :: Binary a => Int -> Get [a] getMany = go [] where go xs 0 = return $! reverse xs go xs i = do x <- get x `seq` go (x:xs) (i-1) {-# INLINE getMany #-} nats :: Int -> SizedList Int nats = \n -> SizedList n (aux n) where aux 0 = [] aux n = n : aux (n - 1) counter :: Process () counter = go 0 where go :: Int -> Process () go !n = receiveWait [ match $ \xs -> go (n + size (xs :: SizedList Int)) , match $ \them -> send them n >> go 0 ] count :: (Int, Int) -> ProcessId -> Process () count (packets, sz) them = do us <- getSelfPid replicateM_ packets $ send them (nats sz) send them us n' <- expect liftIO $ print (packets * sz, n' == packets * sz) initialProcess :: String -> Process () initialProcess "SERVER" = do us <- getSelfPid liftIO $ BSL.writeFile "counter.pid" (encode us) counter initialProcess "CLIENT" = do n <- liftIO getLine them <- liftIO $ decode <$> BSL.readFile "counter.pid" count (read n) them main :: IO () main = do [role, host, port] <- getArgs trans <- createTransport (defaultTCPAddr host port) defaultTCPParameters case trans of Right transport -> do node <- newLocalNode transport initRemoteTable runProcess node $ initialProcess role Left other -> error $ show other
haskell-distributed/distributed-process
benchmarks/Throughput.hs
bsd-3-clause
2,018
0
16
488
776
390
386
60
2
-- | -- module: Data.Text.Lazy.Encoding.Locale -- copyright: © kudah 2013 -- license: BSD3 -- -- maintainer: [email protected] -- stability: experimental -- portability: GHC-only -- -- This module provides functions to encode and decode 'Data.Text.Lazy.Text' -- to/from 'Data.ByteString.Lazy.ByteString' using 'System.IO.TextEncoding' -- -- For performance, Text\'s native encoding functions are used if the conditions -- are right (LF NewlineMode and UTF encoding). {-# LANGUAGE CPP #-} #ifdef TRUSTWORTHY {-# LANGUAGE Trustworthy #-} #endif module Data.Text.Lazy.Encoding.Locale (decodeLocale ,encodeLocale ,decodeLocale' ,encodeLocale' ,decodeFromHandle ,encodeFromHandle ) where import Import (getLocale' ,whenJust' ,hGetEncAndNlMode') import qualified Data.ByteString.Lazy as L import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.IO as TLIO import qualified Data.Text.Lazy.Encoding as TLE import System.IO import Data.ByteString.Handle import Data.Maybe handleDecoder :: Maybe TextEncoding -> Maybe NewlineMode -> L.ByteString -> IO TL.Text handleDecoder menc mnlmode = \bs -> do h <- readHandle False bs whenJust' menc $ hSetEncoding h whenJust' mnlmode $ hSetNewlineMode h TLIO.hGetContents h handleEncoder :: Maybe TextEncoding -> Maybe NewlineMode -> TL.Text -> IO L.ByteString handleEncoder menc mnlmode = \t -> do (res, ()) <- writeHandle False $ \h -> do whenJust' menc $ hSetEncoding h whenJust' mnlmode $ hSetNewlineMode h TLIO.hPutStr h t return res chooseDecoder :: Maybe TextEncoding -> Maybe NewlineMode -> L.ByteString -> IO TL.Text chooseDecoder menc mnlmode = \bs -> do if inputNL nlmode == LF -- decode* functions won't convert line ends then do enc <- maybe getLocale' return menc case show enc of 'U':'T':'F':'-':s -> case s of '8':[] -> return (TLE.decodeUtf8 bs) ('1':'6':x:'E':_) | 'L' == x -> return (TLE.decodeUtf16LE bs) | 'B' == x -> return (TLE.decodeUtf16BE bs) ('3':'2':x:'E':_) | 'L' == x -> return (TLE.decodeUtf32LE bs) | 'B' == x -> return (TLE.decodeUtf32BE bs) _ -> fallback bs _ -> fallback bs else fallback bs where nlmode = fromMaybe nativeNewlineMode mnlmode fallback = handleDecoder menc mnlmode chooseEncoder :: Maybe TextEncoding -> Maybe NewlineMode -> TL.Text -> IO L.ByteString chooseEncoder menc mnlmode = \bs -> if outputNL nlmode == LF -- encode* functions won't convert line ends then do enc <- maybe getLocale' return menc case show enc of 'U':'T':'F':'-':s -> case s of '8':[] -> return (TLE.encodeUtf8 bs) ('1':'6':x:'E':_) | 'L' == x -> return (TLE.encodeUtf16LE bs) | 'B' == x -> return (TLE.encodeUtf16BE bs) ('3':'2':x:'E':_) | 'L' == x -> return (TLE.encodeUtf32LE bs) | 'B' == x -> return (TLE.encodeUtf32BE bs) _ -> fallback bs _ -> fallback bs else fallback bs where nlmode = fromMaybe nativeNewlineMode mnlmode fallback = handleEncoder menc mnlmode -- | Decode 'L.ByteString' to 'TL.Text' using current locale decodeLocale :: L.ByteString -> IO TL.Text decodeLocale = chooseDecoder Nothing Nothing -- | Encode 'TL.Text' to 'L.ByteString' using current locale encodeLocale :: TL.Text -> IO L.ByteString encodeLocale = chooseEncoder Nothing Nothing -- | Decode 'L.ByteString' to 'TL.Text' using supplied 'TextEncoding' and 'NewlineMode' decodeLocale' :: TextEncoding -> NewlineMode -> L.ByteString -> IO TL.Text decodeLocale' enc nlmode = chooseDecoder (Just enc) (Just nlmode) -- | Encode 'TL.Text' to 'L.ByteString' using supplied 'TextEncoding' and 'NewlineMode' encodeLocale' :: TextEncoding -> NewlineMode -> TL.Text -> IO L.ByteString encodeLocale' enc nlmode = chooseEncoder (Just enc) (Just nlmode) -- | Decode 'L.ByteString' to 'TL.Text' using 'Handle's 'TextEncoding' and 'NewlineMode' decodeFromHandle :: Handle -> L.ByteString -> IO TL.Text decodeFromHandle h bs = do (enc, nlmode) <- hGetEncAndNlMode' h decodeLocale' enc nlmode bs -- | Encode 'TL.Text' to 'L.ByteString' using 'Handle's 'TextEncoding' and 'NewlineMode' encodeFromHandle :: Handle -> TL.Text -> IO L.ByteString encodeFromHandle h t = do (enc, nlmode) <- hGetEncAndNlMode' h encodeLocale' enc nlmode t
exbb2/text-locale-encoding
Data/Text/Lazy/Encoding/Locale.hs
bsd-3-clause
4,637
0
21
1,142
1,229
618
611
87
6
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : [email protected] Stability : experimental Portability : non-portable -} module Fragment.Bool.Helpers ( tyBool , ptBool , tmBool , tmAnd , tmOr ) where import Control.Lens (review) import Ast.Type import Ast.Pattern import Ast.Term import Fragment.Bool.Ast.Type import Fragment.Bool.Ast.Pattern import Fragment.Bool.Ast.Term tyBool :: AsTyBool ki ty => Type ki ty a tyBool = review _TyBool () ptBool :: AsPtBool pt => Bool -> Pattern pt a ptBool = review _PtBool tmBool :: AsTmBool ki ty pt tm => Bool -> Term ki ty pt tm a tmBool = review _TmBool tmAnd :: AsTmBool ki ty pt tm => Term ki ty pt tm a -> Term ki ty pt tm a -> Term ki ty pt tm a tmAnd = curry $ review _TmAnd tmOr :: AsTmBool ki ty pt tm => Term ki ty pt tm a -> Term ki ty pt tm a -> Term ki ty pt tm a tmOr = curry $ review _TmOr
dalaing/type-systems
src/Fragment/Bool/Helpers.hs
bsd-3-clause
899
0
8
197
316
165
151
23
1
{-# LANGUAGE PatternSynonyms #-} -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.IndirectParameters -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.IndirectParameters ( -- * Extension Support glGetARBIndirectParameters, gl_ARB_indirect_parameters, -- * Enums pattern GL_PARAMETER_BUFFER_ARB, pattern GL_PARAMETER_BUFFER_BINDING_ARB, -- * Functions glMultiDrawArraysIndirectCountARB, glMultiDrawElementsIndirectCountARB ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/IndirectParameters.hs
bsd-3-clause
839
0
5
108
65
48
17
11
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# language LambdaCase #-} module BMake.Interpreter ( interpret ) where import BMake.Base import Control.DeepSeq (NFData(..), force) import Control.Exception (evaluate) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Trans.Reader (ReaderT(..)) import qualified Control.Monad.Trans.Reader as Reader import Data.ByteString.Lazy (ByteString) -- import qualified Data.ByteString.Lazy.Char8 as BS8 import Data.Function ((&)) import Data.IORef import Data.List (intercalate) import Data.List.Split (splitOn) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) import GHC.Generics (Generic) import Lib.Makefile.Types () type Vars = Map ByteString [Expr] newtype Env = Env { envVars :: IORef Vars } type M = ReaderT Env IO run :: M a -> IO a run act = do varsRef <- newIORef Map.empty runReaderT act Env { envVars = varsRef } interpret :: Makefile -> IO () interpret = run . makefile -- | Expr after variable substitution data Expr1 = Expr1'Str ByteString | Expr1'OpenBrace | Expr1'CloseBrace | Expr1'Comma | Expr1'Spaces | Expr1'VarSpecial MetaVar MetaVarModifier deriving (Eq, Ord, Show, Generic) instance NFData Expr1 -- | Expr1 after Group parsing data Expr2 = Expr2'Str ByteString | Expr2'Group [[Expr2]] | Expr2'Spaces | Expr2'VarSpecial MetaVar MetaVarModifier deriving (Eq, Ord, Show, Generic) instance NFData Expr2 -- | Expr2 after Group expansions data Expr3 = Expr3'Str ByteString | Expr3'Spaces | Expr3'VarSpecial MetaVar MetaVarModifier deriving (Eq, Ord, Show, Generic) instance NFData Expr3 {- TODO: data ExprTopLevel = ExprTopLevel'Str ByteString | ExprTopLevel'Spaces -} makefile :: Makefile -> M () makefile (Makefile stmts) = statements stmts -- TODO: Take the data ctors so it can generate an ExprTopLevel subst :: Vars -> [Expr] -> [Expr1] subst vars = concatMap go where go OpenBrace = [Expr1'OpenBrace] go CloseBrace = [Expr1'CloseBrace] go Comma = [Expr1'Comma] go (Str text) = [Expr1'Str text] go Spaces = [Expr1'Spaces] go (VarSpecial flag modifier) = [Expr1'VarSpecial flag modifier] go (VarSimple var) = concatMap go val where val = Map.lookup var vars & fromMaybe (error ("Invalid var-ref: " ++ show var)) {-# INLINE first #-} first :: (a -> a') -> (a, b) -> (a', b) first f (x, y) = (f x, y) parseGroups :: [Expr1] -> [Expr2] parseGroups = \case Expr1'Str str:xs -> Expr2'Str str : parseGroups xs Expr1'OpenBrace:xs -> let (groups, ys) = commaSplit xs in Expr2'Group groups : parseGroups ys Expr1'CloseBrace:_ -> error "Close brace without open brace!" Expr1'Comma:xs -> Expr2'Str "," : parseGroups xs Expr1'Spaces:xs -> Expr2'Spaces : parseGroups xs Expr1'VarSpecial mv m:xs -> Expr2'VarSpecial mv m : parseGroups xs [] -> [] where prependFirstGroup :: Expr2 -> [[Expr2]] -> [[Expr2]] prependFirstGroup _ [] = error "Result with no options!" prependFirstGroup x (alt:alts) = (x:alt) : alts prepend = first . prependFirstGroup commaSplit :: [Expr1] -> ([[Expr2]], [Expr1]) commaSplit = \case Expr1'CloseBrace:xs -> ([[]], xs) Expr1'OpenBrace:xs -> let (childGroups, ys) = commaSplit xs in commaSplit ys & prepend (Expr2'Group childGroups) Expr1'Comma:xs -> commaSplit xs & first ([] :) Expr1'Str str:xs -> commaSplit xs & prepend (Expr2'Str str) Expr1'Spaces:xs -> commaSplit xs & prepend Expr2'Spaces Expr1'VarSpecial mv m:xs -> commaSplit xs & prepend (Expr2'VarSpecial mv m) [] -> error "Missing close brace!" cartesian :: [Expr2] -> [Expr3] cartesian input = -- (\output -> trace ("cartesian input: " ++ show input ++ "\n output: " ++ show output) output) . unwords2 . map unwords2 . map go . splitOn [Expr2'Spaces] $ input where unwords2 = intercalate [Expr3'Spaces] go :: [Expr2] -> [[Expr3]] go (Expr2'Spaces:_) = error "splitOn should leave no Spaces!" go (Expr2'Str str:xs) = (Expr3'Str str:) <$> go xs go (Expr2'VarSpecial mv m:xs) = (Expr3'VarSpecial mv m:) <$> go xs go (Expr2'Group options:xs) = (++) <$> concatMap go options <*> go xs go [] = [[]] normalize :: Vars -> [Expr] -> [Expr3] normalize vars = cartesian . parseGroups . subst vars assign :: ByteString -> AssignType -> [Expr] -> M () assign name assignType exprL = do varsRef <- Reader.asks envVars let f AssignConditional (Just old) = Just old f _ _ = Just exprL Map.alter (f assignType) name & modifyIORef' varsRef & liftIO local :: [Statement] -> M () local stmts = do varsRef <- Reader.asks envVars varsSnapshot <- readIORef varsRef & liftIO res <- statements stmts writeIORef varsRef varsSnapshot & liftIO return res -- showExprL :: [Expr3] -> String -- showExprL = concatMap showExpr -- showExpr :: Expr3 -> String -- showExpr (Expr3'Str text) = BS8.unpack text -- showExpr Expr3'Spaces = " " -- showExpr (Expr3'VarSpecial specialFlag specialModifier) = -- "$" ++ wrap flagChar -- where -- flagChar = -- case specialFlag of -- FirstOutput -> "@" -- FirstInput -> "<" -- AllInputs -> "^" -- AllOOInputs -> "|" -- Stem -> "*" -- wrap = -- case specialModifier of -- NoMod -> id -- ModFile -> ('(':) . (++"F)") -- ModDir -> ('(':) . (++"D)") statements :: [Statement] -> M () statements = mapM_ statement target :: [Expr] -> [Expr] -> [[Expr]] -> M () target outputs inputs {-orderOnly-} script = do vars <- Reader.asks envVars >>= liftIO . readIORef let norm = normalize vars -- let put = liftIO . putStrLn _ <- liftIO $ evaluate $ force $ norm outputs _ <- liftIO $ evaluate $ force $ norm inputs _ <- liftIO $ evaluate $ force $ map norm script return () -- put "target:" -- put $ " outs: " ++ showExprL (norm outputs) -- put $ " ins: " ++ showExprL (norm inputs) -- put $ " script:" -- mapM_ (put . (" "++) . showExprL . norm) script -- Expanded exprs given! -- TODO: Consider type-level marking of "expanded" exprs cmp :: IfCmpType -> [Expr3] -> [Expr3] -> Bool cmp IfEquals = (==) cmp IfNotEquals = (/=) ifCmp :: IfCmpType -> [Expr] -> [Expr] -> [Statement] -> [Statement] -> M () ifCmp ifCmpType exprA exprB thenStmts elseStmts = do vars <- Reader.asks envVars >>= liftIO . readIORef let norm = normalize vars statements $ if cmp ifCmpType (norm exprA) (norm exprB) then thenStmts else elseStmts statement :: Statement -> M () statement = \case Assign name assignType exprL -> assign name assignType exprL Local stmts -> local stmts Target outputs inputs script -> target outputs inputs script IfCmp cmpType exprA exprB thenStmts elseStmts -> ifCmp cmpType exprA exprB thenStmts elseStmts Include {} -> error "Include should have been expanded"
Peaker/buildsome-tst
app/BMake/Interpreter.hs
bsd-3-clause
7,678
0
15
2,236
2,136
1,122
1,014
167
14
------------------------------------------------------------------------ -- | -- Module : Data.CSV.Condense -- Copyright : (c) Amy de Buitléir 2014 -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Condenses a CSV table. The values in the second column are used as -- headings in the condensed table. Missing fields are handled -- appropriately. If there are multiple lines with the same values in -- the first and second columns, then the value from the third column -- of the first line of those lines will appear in the output. -- -- The easiest way to explain this is with an example. The input is -- the left, the output is on the right. -- @ -- heading1,heading2,heading3 heading1,a,b,c -- 1,a,s 1,s,t,u -- 1,b,t 2,v,w,x -- 1,c,u 3,y,,z -- 2,a,v -- 2,b,w -- 2,c,x -- 3,a,y -- 3,c,z -- @ -- ------------------------------------------------------------------------ import Data.List import Data.List.Split import Data.Maybe parseCSV :: String -> [(String,String,String)] parseCSV = map tokenise . lines tokenise :: String -> (String,String,String) tokenise s = (a,b,c) where (a:b:c:_) = splitOn "," (s ++ repeat ',') -- | -- > same p x y = (p x) == (p y) -- -- Useful combinator for use in conjunction with the @xxxBy@ family -- of functions from "Data.List", for example: -- -- > ... groupBy (same fst) ... same :: (Eq a) => (b -> a) -> b -> b -> Bool same p x y = (p x) == (p y) condenseGroup :: [String] -> [(String,String,String)] -> String condenseGroup keys xs = intercalate "," (a:cs) where (a,_,_) = head xs m = map col23 xs cs = map (flip (lookupWithDefault "") m) keys lookupWithDefault :: Eq k => v -> k -> [(k, v)] -> v lookupWithDefault v k m = fromMaybe v $ lookup k m col1 :: (String,String,String) -> String col1 (x,_,_) = x col2 :: (String,String,String) -> String col2 (_,x,_) = x -- col3 :: (String,String,String) -> String -- col3 (_,_,x) = x col23 :: (String,String,String) -> (String,String) col23 (_,x,y) = (x, y) condenseCSV :: String -> String condenseCSV s = unlines (newHeader:zs) where ((header:_):yss) = groupBy (same col1) $ parseCSV s heading1 = col1 header otherHeadings = nub . map col2 . head $ yss newHeader = intercalate "," (heading1:otherHeadings) zs = map (condenseGroup otherHeadings) yss main :: IO () main = fmap condenseCSV getContents >>= putStrLn
mhwombat/amy-csv
src/Data/CSV/Condense.hs
bsd-3-clause
2,539
0
11
571
651
372
279
32
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleContexts #-} {-| 'Pipe's for doing IO with text data. -} module Control.Pipe.Text.IO ( -- * Producers produceFile , produceHandle , produceIOHandle -- ** Ranges , produceFileRange , produceHandleRange , produceIOHandleRange -- * Consumers , consumeFile , consumeHandle , consumeIOHandle -- * Pipes , teeFile , teeHandle , teeIOHandle ) where import Control.Monad (forever) import Control.Monad.Exception.Class (MonadException) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Resource (MonadResource (with, release)) import Control.Monad.Trans (lift) import qualified Control.Pipe.Binary.IO as PB import Control.Pipe.Common import Control.Pipe.Text.Encoding import Data.Maybe (fromMaybe) import Data.Text (Text) import qualified Data.Text.IO as T import System.IO ( Handle , IOMode (ReadMode, WriteMode) , hClose , hGetEncoding , localeEncoding , openFile ) ------------------------------------------------------------------------------ -- | Stream the contents of a file as binary data. produceFile :: (MonadResource m, MonadException m) => FilePath -> Producer Text m () produceFile file = produceIOHandle (openFile file ReadMode) ------------------------------------------------------------------------------ -- | Stream the contents of a 'Handle' as text data. Note that this function -- will /not/ automatically close the Handle when processing completes, since -- it did not acquire the Handle in the first place. produceHandle :: (MonadIO m, MonadException m) => Handle -> Producer Text m () produceHandle h = do encoding <- liftIO $ hGetEncoding h PB.produceHandle h >+> decode (fromMaybe localeEncoding encoding) ------------------------------------------------------------------------------ -- | An alternative to 'produceHandle'. Instead of taking a pre-opened -- 'Handle', it takes an action that opens a 'Handle' (in read mode), so that -- it can open it only when needed and close it as soon as possible. produceIOHandle :: (MonadResource m, MonadException m) => IO Handle -> Producer Text m () produceIOHandle open = do (key, h) <- lift $ with open hClose produceHandle h lift $ release key ------------------------------------------------------------------------------ -- | Stream the contents of a file as text data, starting from a certain -- offset and only consuming up to a certain number of bytes. produceFileRange :: (MonadResource m, MonadException m) => FilePath -> Maybe Int -> Maybe Int -> Producer Text m () produceFileRange file = produceIOHandleRange (openFile file ReadMode) ------------------------------------------------------------------------------ -- | A version of 'produceFileRange' analogous to 'produceHandle'. produceHandleRange :: (MonadIO m, MonadException m) => Handle -> Maybe Int -> Maybe Int -> Producer Text m () produceHandleRange h s f = do encoding <- liftIO $ hGetEncoding h PB.produceHandleRange h s f >+> decode (fromMaybe localeEncoding encoding) ------------------------------------------------------------------------------ -- | A version of 'produceFileRange' analogous to 'produceIOHandle'. produceIOHandleRange :: (MonadResource m, MonadException m) => IO Handle -> Maybe Int -> Maybe Int -> Producer Text m () produceIOHandleRange open s f = do (key, h) <- lift $ with open hClose produceHandleRange h s f lift $ release key ------------------------------------------------------------------------------ -- | Stream all incoming data to the given file. consumeFile :: MonadResource m => FilePath -> Consumer Text m () consumeFile file = consumeIOHandle (openFile file WriteMode) ------------------------------------------------------------------------------ -- | Stream all incoming data to the given 'Handle'. Note that this function -- will /not/ automatically close the 'Handle' when processing completes. consumeHandle :: MonadIO m => Handle -> Consumer Text m () consumeHandle h = forever $ await >>= liftIO . T.hPutStr h ------------------------------------------------------------------------------ -- | An alternative to 'consumeHande'. Instead of taking a pre-opened -- 'Handle', it takes an action that opens a 'Handle' (in write mode), so that -- it can open it only when needed and close it as soon as possible. consumeIOHandle :: MonadResource m => IO Handle -> Consumer Text m () consumeIOHandle open = do (key, h) <- lift $ with open hClose consumeHandle h lift $ release key ------------------------------------------------------------------------------ -- | Stream all incoming data to a file, while also passing it along the -- pipeline. Similar in concept to the Unix command @tee@. teeFile :: MonadResource m => FilePath -> Pipe Text Text m r teeFile file = teeIOHandle (openFile file WriteMode) ------------------------------------------------------------------------------ -- | A version of 'teeFile' analogous to 'consumeHandle'. teeHandle :: MonadIO m => Handle -> Pipe Text Text m r teeHandle h = forever $ await >>= \bs -> yield bs >> liftIO (T.hPutStr h bs) ------------------------------------------------------------------------------ -- | A version of 'teeFile' analogous to 'consumeIOHandle'. teeIOHandle :: MonadResource m => IO Handle -> Pipe Text Text m r teeIOHandle open = do (key, h) <- lift $ with open hClose teeHandle h lift $ release key idP
duairc/pipes
src/Control/Pipe/Text/IO.hs
bsd-3-clause
5,907
0
11
1,306
1,071
568
503
117
1
module Config.Routes where routes = [ "/:controller/:action/:id.:format" , "/:controller/:action/:id" , "/:controller/:action.:format" , "/:controller/:action" , "/:controller" ]
abuiles/turbinado-blog
Config/Routes.hs
bsd-3-clause
225
0
5
62
26
17
9
6
1
module Lava.Error ( Error(..) , wrong ) where ---------------------------------------------------------------- -- Error data Error = DelayEval | VarEval | CombinationalLoop | BadCombinationalLoop | UndefinedWire | IncompatibleStructures | NoEquality | NoArithmetic | EnumOnSymbols | Internal_OptionNotFound deriving (Eq, Show) wrong :: Error -> a wrong err = error $ case err of DelayEval -> "evaluating a delay component" VarEval -> "evaluating a symbolic value" CombinationalLoop -> "combinational loop" BadCombinationalLoop -> "short circuit" UndefinedWire -> "undriven output" IncompatibleStructures -> "combining incompatible structures" NoEquality -> "no equality defined for this type" NoArithmetic -> "arithmetic operations are not supported" EnumOnSymbols -> "enumerating symbolic values" Internal_OptionNotFound -> internal "option not found" internal :: String -> String internal msg = "INTERNAL ERROR: " ++ msg ++ ".\nPlease report this as a bug to `[email protected]'." ---------------------------------------------------------------- -- the end.
shayan-najd/MiniLava
Lava/Error.hs
bsd-3-clause
1,250
0
9
318
180
101
79
32
10
{-# LANGUAGE MultiParamTypeClasses, TypeFamilies, FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS -Wall #-} module LambdaCalculus.Operations( getvalfromenv, setvalinenv, transtate, trans ) where import Basic.Memory import Basic.Types (Trans(Trans)) import LambdaCalculus.Types import Control.Lens -- 1. get the value from the environment getvalfromenv :: MapLike m => Var -> m Var (Atom m) -> Atom m getvalfromenv v m = if (memberM m v) then lookupM m v else ErrorA "invalid v in the environment" setvalinenv :: MapLike m => Var -> Atom m -> m Var (Atom m) -> m Var (Atom m) setvalinenv = insertM transtate :: (Stack s, MapLike m, HasCtrl st, HasDump st, HasEnv st, HasStack st, s Term ~ Ctrl st, Dump st ~ s (s (Atom m), m Var (Atom m), s Term), Env st ~ m Var (Atom m), Stck st ~ s (Atom m)) => Trans () st transtate = Trans f where f () st = let s = st^.stck e = st^.env c = st^.ctrl d = st^.dump in case (isEmpty c) of True -> stck .~ (push (top s) s1) $ env .~ e1 $ ctrl .~ c1 $ dump .~ (pop d) $ st where (s1, e1, c1) = top d False -> case (top c) of (ConstT x) -> stck .~ (push (ConstA x) s) $ ctrl .~ (pop c) $ st (VarT x) -> stck .~ (push (getvalfromenv x e) s) $ ctrl .~ (pop c) $ st (AppT t1 t2) -> ctrl .~ (push t1 $ push t2 $ push (PrimT ApplicationPP) $ (pop c)) $ st (AbsT var t) -> stck .~ (push (ClosureA var t e) s) $ ctrl .~ (pop c) $ st (PrimT ApplicationPP) -> case (top sx) of ClosureA var t e1 -> stck .~ empty $ env .~ (insertM var (top s) e1) $ ctrl .~ (initS [t]) $ dump .~ (push ((pop sx), e, (pop c)) d) $ st _ -> error "invalid Operations" where sx = pop s _ -> error "invalid Operations" trans :: (Stack st, MapLike m, s ~ st (Atom m), e ~ m Var (Atom m), c ~ st Term, d ~ st (s, e, c))=> Trans () (s, e, c, d) trans = Trans f where f () (s, e, c, d) = case (isEmpty c) of True -> (s', e', c', d') where s' = (push (top s) s1) e' = e1 c' = c1 d' = pop d (s1, e1, c1) = top d False -> case (top c) of (ConstT x) -> (s', e, c', d) where s' = (push (ConstA x) s) c' = (pop c) (VarT x) -> (s', e, c', d) where s' = (push (getvalfromenv x e) s) c' = (pop c) (AppT t1 t2) -> (s, e, c', d) where c' = (push t1 $ push t2 $ push (PrimT ApplicationPP) $ (pop c)) (AbsT var t) -> (s', e, c', d) where s' = (push (ClosureA var t e) s) c' = (pop c) (PrimT ApplicationPP) -> case (top sx) of ClosureA var t e1 -> (s', e', c', d') where s' = empty e' = (insertM var (top s) e1) c' = (initS [t]) d' = (push ((pop sx), e, (pop c)) d) _ -> error "invalid Operations" where sx = pop s _ -> error "invalid Operations"
davidzhulijun/TAM
LambdaCalculus/Operations.hs
bsd-3-clause
3,494
0
27
1,499
1,492
774
718
81
8
{-# LANGUAGE ScopedTypeVariables #-} import Prelude hiding (concat) import Data.Word import Data.Hash.SL2 import Data.Hash.SL2.Internal (Hash) import Data.Hash.SL2.Unsafe import qualified Data.ByteString as B import Foreign import Test.Tasty import Test.Tasty.QuickCheck as QC import Test.QuickCheck.Property.Monoid import Data.Monoid instance Arbitrary B.ByteString where arbitrary = fmap B.pack arbitrary instance Arbitrary Hash where arbitrary = fmap hash arbitrary main = defaultMain tests tests :: TestTree tests = testGroup "Properties" [ testGroup "equality" [ testProperty "true" $ \a -> hash a == hash a , testProperty "false" $ \a b -> (a /= b) ==> hash a /= hash b ] , testGroup "compare" [ testProperty "eq" $ \a -> compare (hash a) (hash a) == EQ , testProperty "gt" $ \a b c -> (a > b && b > c) ==> (a :: Hash) > c , testProperty "ge" $ \a b c -> (a >= b && b >= c) ==> (a :: Hash) >= c , testProperty "lt" $ \a b c -> (a < b && b < c) ==> (a :: Hash) < c , testProperty "le" $ \a b c -> (a <= b && b <= c) ==> (a :: Hash) <= c ] , testGroup "packing" [ testProperty "identity 8-bit" $ \a -> Just a == pack8 (unpack8 a) , testProperty "identity 16-bit" $ \a -> Just a == pack16 (unpack16 a) , testProperty "identity 32-bit" $ \a -> Just a == pack32 (unpack32 a) , testProperty "identity 64-bit" $ \a -> Just a == pack64 (unpack64 a) ] , testGroup "composition" [ testProperty "empty is valid" $ valid (mempty :: Hash) , testProperty "hash is valid" $ \a -> valid (hash a) , testProperty "append is valid" $ \a b -> valid (hash a <> hash b) , testProperty "forms a monoid" $ eq $ prop_Monoid (T :: T Hash) , testProperty "is distributive (mappend)" $ \a b -> hash (a <> b) == hash a <> hash b , testProperty "is distributive (mconcat)" $ \a b -> hash (a <> b) == mconcat (map hash [a, b]) ] , testGroup "append" [ testGroup "single string" $ [ testProperty "equal to ((. hash) . concat)" $ \a b -> ((. hash) . concat) a b == a `append` b ] , testGroup "multiple strings" $ [ testProperty "equal to (foldl append)" $ \a (b :: [B.ByteString]) -> foldl append a b == a `foldAppend` b ] ] , testGroup "prepend" [ testGroup "single string" $ [ testProperty "equal to (concat . hash)" $ \a b -> (concat . hash) a b == a `prepend` b ] , testGroup "multiple strings" $ [ testProperty "equal to (flip (foldr prepend)" $ \(a :: [B.ByteString]) b -> foldr prepend b a == a `foldPrepend` b ] ] ]
srijs/hwsl2-haskell
src/Data/Hash/SL2/Test.hs
mit
2,793
0
18
854
1,008
532
476
71
1
{-| Instances for anonymizing sensitive data in various types. Note that there is no clear way to anonymize numbers. -} module Hledger.Cli.Anon ( Anon(..) , anonAccount ) where import Control.Arrow (first) import Data.Hashable (hash) import Data.Word (Word32) import Numeric (showHex) import qualified Data.Text as T import Hledger.Data import Data.Map (mapKeys) class Anon a where -- | Consistent converter to structure with sensitive data anonymized anon :: a -> a instance Anon Journal where -- Apply the anonymisation transformation on a journal after finalisation anon j = j { jtxns = map anon . jtxns $ j , jparseparentaccounts = map anonAccount $ jparseparentaccounts j , jparsealiases = [] -- already applied , jdeclaredaccounts = map (first anon) $ jdeclaredaccounts j , jdeclaredaccounttags = mapKeys anon $ jdeclaredaccounttags j , jdeclaredaccounttypes = (map anon) <$> jdeclaredaccounttypes j } instance Anon Posting where anon p = p { paccount = anonAccount . paccount $ p , pcomment = T.empty , ptransaction = fmap anon . ptransaction $ p -- Note that this will be overridden , poriginal = anon <$> poriginal p } instance Anon Transaction where anon txn = txnTieKnot $ txn { tpostings = map anon . tpostings $ txn , tdescription = anon . tdescription $ txn , tcode = anon . tcode $ txn , tcomment = T.empty } -- | Anonymize account name preserving hierarchy anonAccount :: AccountName -> AccountName anonAccount = T.intercalate (T.pack ":") . map anon . T.splitOn (T.pack ":") instance Anon T.Text where anon = T.pack . flip showHex "" . (fromIntegral :: Int -> Word32) . hash
simonmichael/hledger
hledger/Hledger/Cli/Anon.hs
gpl-3.0
1,934
0
11
606
460
253
207
32
1
module Main where import AI.HNN.Net import AI.HNN.Layer import AI.HNN.Neuron import Control.Arrow import Data.List alpha, epsilon :: Double alpha = 0.8 -- learning ratio epsilon = 0.001 -- desired maximal bound for the quad error layer1, layer2 :: [Neuron] layer1 = map (createNeuronSigmoid 0.5) [[0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]] layer2 = [createNeuronSigmoid 0.5 [0.5, 0.4, 0.6, 0.3]] net = [layer1, layer2] finalnet = train alpha epsilon net [([1, 1, 1], [0]), ([1, 0, 1], [1]), ([1, 1, 0], [1]), ([1, 0, 0], [0])] good111 = computeNet finalnet [1, 1, 1] good101 = computeNet finalnet [1, 0, 1] good110 = computeNet finalnet [1, 1, 0] good100 = computeNet finalnet [1, 0, 0] main = do putStrLn $ "Final neural network : \n" ++ show finalnet putStrLn " ---- " putStrLn $ "Output for [1, 1, 1] (~ 0): " ++ show good111 putStrLn $ "Output for [1, 0, 1] (~ 1): " ++ show good101 putStrLn $ "Output for [1, 1, 0] (~ 1): " ++ show good110 putStrLn $ "Output for [1, 0, 0] (~ 0): " ++ show good100
alpmestan/HNN-0.1
tests/xor-3inputs.hs
lgpl-3.0
1,091
0
8
249
416
245
171
33
1
module Handler.Nomnichi ( getNomnichiR -- ノムニチトップ , getCreateArticleR -- 記事投稿ページの表示 , postCreateArticleR -- 記事の投稿 , getArticleR -- 記事の表示 , postArticleR -- 記事の編集 , getEditArticleR -- 記事の編集画面の表示 , postDeleteArticleR -- 記事の削除 , postCommentR -- コメントの投稿 ) where import Import as I import Data.Monoid import Data.Time import System.Locale (defaultTimeLocale) import System.IO.Unsafe (unsafePerformIO) import Yesod.Form.Nic (YesodNic, nicHtmlField) -- import Data.Attoparsec.Text import Data.Text as T import Yesod.Auth instance YesodNic App -- 記事作成,閲覧,更新 -- ノムニチトップ getNomnichiR :: Handler Html getNomnichiR = do creds <- maybeAuthId articles <- case creds of Just _ -> runDB $ selectList [] [Desc ArticleId] Nothing -> runDB $ selectList [ArticleApproved ==. True] [Desc ArticleId] paramPage <- lookupGetParam "page" defaultLayout $ do $(widgetFile "articles") convTextToInt :: Text -> Int convTextToInt text = read $ T.unpack text :: Int calcNumOfArticles :: Text -> Int calcNumOfArticles text = (convTextToInt text) * 20 calcNumOfDroppingArticles :: Text -> Int calcNumOfDroppingArticles text = (convTextToInt text - 1) * 20 getCreateArticleR :: Handler Html getCreateArticleR = do (articleWidget, enctype) <- generateFormPost entryForm defaultLayout $ do $(widgetFile "createArticleForm") -- 記事作成 postCreateArticleR :: Handler Html postCreateArticleR = do ((res, articleWidget), enctype) <- runFormPost entryForm case res of FormSuccess article -> do articleId <- runDB $ insert article setMessage $ toHtml (articleTitle article) <> " created." redirect $ ArticleR articleId _ -> defaultLayout $ do setTitle "Please correct your entry form." $(widgetFile "articleAddError") -- 記事表示 getArticleR :: ArticleId -> Handler Html getArticleR articleId = do creds <- maybeAuthId article <- runDB $ get404 articleId comments <- runDB $ selectList [CommentArticleId ==. articleId] [Asc CommentId] (commentWidget, enctype) <- generateFormPost $ commentForm articleId case creds of Just _ -> defaultLayout $ do setTitle $ toHtml $ articleTitle article $(widgetFile "article") Nothing -> case articleApproved article of True -> defaultLayout $ do setTitle $ toHtml $ articleTitle article $(widgetFile "article") False -> defaultLayout $ do redirect $ NomnichiR -- 記事更新 postArticleR :: ArticleId -> Handler Html postArticleR articleId = do ((res, articleWidget), enctype) <- runFormPost (editForm Nothing) case res of FormSuccess article -> do runDB $ do _article <- get404 articleId update articleId [ ArticleTitle =. articleTitle article , ArticleContent =. articleContent article , ArticleUpdatedOn =. articleUpdatedOn article , ArticlePublishedOn =. articlePublishedOn article , ArticleApproved =. articleApproved article ] setMessage $ toHtml $ (articleTitle article) <> " is updated." redirect $ ArticleR articleId _ -> defaultLayout $ do setTitle "Please correct your entry form." $(widgetFile "editArticleForm") -- 編集画面 getEditArticleR :: ArticleId -> Handler Html getEditArticleR articleId = do article <- runDB $ get404 articleId (articleWidget, enctype) <- generateFormPost $ editForm (Just article) defaultLayout $ do $(widgetFile "editArticleForm") -- 記事削除 postDeleteArticleR :: ArticleId -> Handler Html postDeleteArticleR articleId = do runDB $ do _post <- get404 articleId delete articleId deleteWhere [ CommentArticleId ==. articleId ] setMessage "successfully deleted." redirect $ NomnichiR -- コメント -- コメント送信 postCommentR :: ArticleId -> Handler Html postCommentR articleId = do _post <- runDB $ get404 articleId ((res, commentWidget), enctype) <- runFormPost $ commentForm articleId case res of FormSuccess comment -> do commentId <- runDB $ insert comment setMessage "your comment was successfully posted." redirect $ ArticleR articleId _ -> do setMessage "please fill up your comment form." redirect $ ArticleR articleId -- 記事表示時の公開時刻の整形 formatToNomnichiTime :: Article -> String formatToNomnichiTime article = formatTime defaultTimeLocale format $ utcToNomnichiTime $ articlePublishedOn article where format = "%Y/%m/%d (%a) %H:%M" utcToNomnichiTime = utcToLocalTime $ unsafePerformIO getCurrentTimeZone -- コメント投稿時刻の整形 formatToCommentTime :: Comment -> String formatToCommentTime comment = formatTime defaultTimeLocale format $ utcToNomnichiTime $ commentCreatedAt comment where format = "%Y/%m/%d (%a) %H:%M" utcToNomnichiTime = utcToLocalTime $ unsafePerformIO getCurrentTimeZone -- フォーム entryForm :: Form Article entryForm = renderDivs $ Article <$> areq textField "MemberName" Nothing <*> areq textField "Title" Nothing <*> areq textField "PermaLink" Nothing <*> areq nicHtmlField "Content" Nothing <*> lift (liftIO getCurrentTime) -- <*> lift (liftIO getCurrentTime) -- <*> lift (liftIO getCurrentTime) -- <*> areq boolField "Approved" (Just False) <*> areq intField "Count" Nothing <*> areq boolField "PromoteHeadline" (Just False) editForm :: Maybe Article -> Form Article editForm article = renderDivs $ Article <$> areq textField "MemberName" (articleMemberName <$> article) <*> areq textField "Title" (articleTitle <$> article) <*> areq textField "PermaLink" (articlePermaLink <$> article) <*> areq nicHtmlField "Content" (articleContent <$> article) <*> lift (liftIO getCurrentTime) <*> lift (liftIO getCurrentTime) <*> lift (liftIO getCurrentTime) <*> areq boolField "Approved" (articleApproved <$> article) <*> areq intField "Count" (articleCount <$> article) <*> areq boolField "PromoteHeadline" (articlePromoteHeadline <$> article) commentForm :: ArticleId -> Form Comment commentForm articleId = renderDivs $ Comment <$> areq textField "Name" Nothing <*> areq textareaField "Comment" Nothing <*> lift (liftIO getCurrentTime) <*> lift (liftIO getCurrentTime) <*> pure articleId
ikeda-yuko/nomnichi-haskell
Handler/Nomnichi.hs
bsd-2-clause
6,566
0
18
1,361
1,679
821
858
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} module Ros.Geometry_msgs.Pose where import qualified Prelude as P import Prelude ((.), (+), (*)) import qualified Data.Typeable as T import Control.Applicative import Ros.Internal.RosBinary import Ros.Internal.Msg.MsgInfo import qualified GHC.Generics as G import qualified Data.Default.Generics as D import qualified Ros.Geometry_msgs.Point as Point import qualified Ros.Geometry_msgs.Quaternion as Quaternion import Foreign.Storable (Storable(..)) import qualified Ros.Internal.Util.StorableMonad as SM import Lens.Family.TH (makeLenses) import Lens.Family (view, set) data Pose = Pose { _position :: Point.Point , _orientation :: Quaternion.Quaternion } deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic) $(makeLenses ''Pose) instance RosBinary Pose where put obj' = put (_position obj') *> put (_orientation obj') get = Pose <$> get <*> get instance Storable Pose where sizeOf _ = sizeOf (P.undefined::Point.Point) + sizeOf (P.undefined::Quaternion.Quaternion) alignment _ = 8 peek = SM.runStorable (Pose <$> SM.peek <*> SM.peek) poke ptr' obj' = SM.runStorable store' ptr' where store' = SM.poke (_position obj') *> SM.poke (_orientation obj') instance MsgInfo Pose where sourceMD5 _ = "e45d45a5a1ce597b249e23fb30fc871f" msgTypeName _ = "geometry_msgs/Pose" instance D.Default Pose
acowley/roshask
msgs/Geometry_msgs/Ros/Geometry_msgs/Pose.hs
bsd-3-clause
1,499
1
11
247
429
249
180
37
0
module Main(main) where import Flickr.API import Util.Keys ( hsflickrAPIKey ) import Flickr.Photos as Photos import System.Environment searchPhotos :: String -> FM [PhotoDetails] searchPhotos q = do (_, ps) <- Photos.search Nothing nullSearchConstraints{s_text=Just q} [] mapM (\ x -> Photos.getInfo (photoId x) Nothing) ps main :: IO () main = do ls <- getArgs case ls of [] -> do prg <- getProgName putStrLn ("Usage: " ++ prg ++ " search-term") (x:_) -> do ps <- flickAPI hsflickrAPIKey $ withPageSize 20 $ searchPhotos x putStrLn ("Search results for: " ++ x) mapM_ (\ p -> putStrLn (photoTitle (photoDetailsPhoto p) ++ " = " ++ getPhotoURL p)) ps
sof/flickr
examples/SearchPhotos.hs
bsd-3-clause
701
0
21
156
276
139
137
20
2
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Opaleye.Internal.RunQuery where import Control.Applicative (Applicative, pure, (<*>), liftA2) import Database.PostgreSQL.Simple.Internal (RowParser) import Database.PostgreSQL.Simple.FromField (FieldParser, FromField, fromField) import Database.PostgreSQL.Simple.FromRow (fieldWith) import Database.PostgreSQL.Simple.Types (fromPGArray) import Opaleye.Column (Column) import Opaleye.Internal.Column (Nullable) import qualified Opaleye.Internal.PackMap as PackMap import qualified Opaleye.Column as C import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.PGTypes as T import qualified Opaleye.Internal.PGTypes as IPT (strictDecodeUtf8) import qualified Data.Profunctor as P import Data.Profunctor (dimap) import qualified Data.Profunctor.Product as PP import Data.Profunctor.Product (empty, (***!)) import qualified Data.Profunctor.Product.Default as D import qualified Data.CaseInsensitive as CI import qualified Data.Text as ST import qualified Data.Text.Lazy as LT import qualified Data.ByteString as SBS import qualified Data.ByteString.Lazy as LBS import qualified Data.Time as Time import qualified Data.String as String import Data.UUID (UUID) import GHC.Int (Int64) -- { Only needed for annoying postgresql-simple patch below import Control.Applicative ((<$>)) import Database.PostgreSQL.Simple.FromField (Field, typoid, typeOid, typelem, TypeInfo, ResultError(UnexpectedNull, ConversionFailed, Incompatible), typdelim, typeInfo, returnError, Conversion) import Database.PostgreSQL.Simple.Types (PGArray(PGArray)) import Data.Attoparsec.ByteString.Char8 (Parser, parseOnly) import qualified Database.PostgreSQL.Simple.TypeInfo as TI import qualified Database.PostgreSQL.Simple.Arrays as Arrays import Database.PostgreSQL.Simple.Arrays (array, fmt) import Data.String (fromString) import Data.Typeable (Typeable) -- } -- | A 'QueryRunnerColumn' @pgType@ @haskellType@ encodes how to turn -- a value of Postgres type @pgType@ into a value of Haskell type -- @haskellType@. For example a value of type 'QueryRunnerColumn' -- 'T.PGText' 'String' encodes how to turn a 'PGText' result from the -- database into a Haskell 'String'. -- This is *not* a Product Profunctor because it is the only way I -- know of to get the instance generation to work for non-Nullable and -- Nullable types at once. -- I can no longer remember what the above comment means, but it might -- be that we can't add nullability to a RowParser, only to a -- FieldParser, so we have to have some type that we know contains -- just a FieldParser. data QueryRunnerColumn pgType haskellType = QueryRunnerColumn (U.Unpackspec (Column pgType) ()) (FieldParser haskellType) data QueryRunner columns haskells = QueryRunner (U.Unpackspec columns ()) (columns -> RowParser haskells) -- We never actually -- look at the columns -- except to see its -- "type" in the case -- of a sum profunctor (columns -> Bool) -- ^ Have we actually requested any columns? If we -- asked for zero columns then the SQL generator will -- have to put a dummy 0 into the SELECT statement, -- since we can't select zero columns. In that case we -- have to make sure we read a single Int. fieldQueryRunnerColumn :: FromField haskell => QueryRunnerColumn coltype haskell fieldQueryRunnerColumn = QueryRunnerColumn (P.rmap (const ()) U.unpackspecColumn) fromField queryRunner :: QueryRunnerColumn a b -> QueryRunner (Column a) b queryRunner qrc = QueryRunner u (const (fieldWith fp)) (const True) where QueryRunnerColumn u fp = qrc queryRunnerColumnNullable :: QueryRunnerColumn a b -> QueryRunnerColumn (Nullable a) (Maybe b) queryRunnerColumnNullable qr = QueryRunnerColumn (P.lmap C.unsafeCoerceColumn u) (fromField' fp) where QueryRunnerColumn u fp = qr fromField' :: FieldParser a -> FieldParser (Maybe a) fromField' _ _ Nothing = pure Nothing fromField' fp' f bs = fmap Just (fp' f bs) -- { Instances for automatic derivation instance QueryRunnerColumnDefault a b => QueryRunnerColumnDefault (Nullable a) (Maybe b) where queryRunnerColumnDefault = queryRunnerColumnNullable queryRunnerColumnDefault instance QueryRunnerColumnDefault a b => D.Default QueryRunner (Column a) b where def = queryRunner queryRunnerColumnDefault -- } -- { Instances that must be provided once for each type. Instances -- for Nullable are derived automatically from these. -- | A 'QueryRunnerColumnDefault' @pgType@ @haskellType@ represents -- the default way to turn a @pgType@ result from the database into a -- Haskell value of type @haskelType@. class QueryRunnerColumnDefault pgType haskellType where queryRunnerColumnDefault :: QueryRunnerColumn pgType haskellType instance QueryRunnerColumnDefault T.PGInt4 Int where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGInt8 Int64 where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText String where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGFloat8 Double where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBool Bool where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGUuid UUID where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBytea SBS.ByteString where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGBytea LBS.ByteString where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText ST.Text where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGText LT.Text where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGDate Time.Day where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTimestamptz Time.UTCTime where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTimestamp Time.LocalTime where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGTime Time.TimeOfDay where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGCitext (CI.CI ST.Text) where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGCitext (CI.CI LT.Text) where queryRunnerColumnDefault = fieldQueryRunnerColumn instance QueryRunnerColumnDefault T.PGJson String where queryRunnerColumnDefault = QueryRunnerColumn (P.rmap (const ()) U.unpackspecColumn) jsonFieldParser instance QueryRunnerColumnDefault T.PGJsonb String where queryRunnerColumnDefault = QueryRunnerColumn (P.rmap (const ()) U.unpackspecColumn) jsonbFieldParser -- No CI String instance since postgresql-simple doesn't define FromField (CI String) arrayColumn :: Column (T.PGArray a) -> Column a arrayColumn = C.unsafeCoerceColumn instance (Typeable b, QueryRunnerColumnDefault a b) => QueryRunnerColumnDefault (T.PGArray a) [b] where queryRunnerColumnDefault = QueryRunnerColumn (P.lmap arrayColumn c) ((fmap . fmap . fmap) fromPGArray (arrayFieldParser f)) where QueryRunnerColumn c f = queryRunnerColumnDefault -- } -- Boilerplate instances instance Functor (QueryRunner c) where fmap f (QueryRunner u r b) = QueryRunner u ((fmap . fmap) f r) b -- TODO: Seems like this one should be simpler! instance Applicative (QueryRunner c) where pure = flip (QueryRunner (P.lmap (const ()) PP.empty)) (const False) . pure . pure QueryRunner uf rf bf <*> QueryRunner ux rx bx = QueryRunner (P.dimap (\x -> (x,x)) (const ()) (uf PP.***! ux)) ((<*>) <$> rf <*> rx) (liftA2 (||) bf bx) instance P.Profunctor QueryRunner where dimap f g (QueryRunner u r b) = QueryRunner (P.lmap f u) (P.dimap f (fmap g) r) (P.lmap f b) instance PP.ProductProfunctor QueryRunner where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct instance PP.SumProfunctor QueryRunner where f +++! g = QueryRunner (P.rmap (const ()) (fu PP.+++! gu)) (PackMap.eitherFunction fr gr) (either fb gb) where QueryRunner fu fr fb = f QueryRunner gu gr gb = g -- } -- { Annoying postgresql-simple patch. Delete this when it is merged upstream. arrayFieldParser :: Typeable a => FieldParser a -> FieldParser (PGArray a) arrayFieldParser fieldParser f mdat = do info <- typeInfo f case info of TI.Array{} -> case mdat of Nothing -> returnError UnexpectedNull f "" Just dat -> do case parseOnly (fromArray fieldParser info f) dat of Left err -> returnError ConversionFailed f err Right conv -> PGArray <$> conv _ -> returnError Incompatible f "" fromArray :: FieldParser a -> TypeInfo -> Field -> Parser (Conversion [a]) fromArray fieldParser tInfo f = sequence . (parseIt <$>) <$> array delim where delim = typdelim (typelem tInfo) fElem = f{ typeOid = typoid (typelem tInfo) } parseIt item = fieldParser f' $ if item' == fromString "NULL" then Nothing else Just item' where item' = fmt delim item f' | Arrays.Array _ <- item = f | otherwise = fElem -- } -- { Allow @postgresql-simple@ conversions from JSON types to 'String' jsonFieldParser, jsonbFieldParser :: FieldParser String jsonFieldParser = jsonFieldTypeParser (String.fromString "json") jsonbFieldParser = jsonFieldTypeParser (String.fromString "jsonb") -- typenames, not type Oids are used in order to avoid creating -- a dependency on 'Database.PostgreSQL.LibPQ' jsonFieldTypeParser :: SBS.ByteString -> FieldParser String jsonFieldTypeParser jsonTypeName field mData = do ti <- typeInfo field if TI.typname ti == jsonTypeName then convert else returnError Incompatible field "types incompatible" where convert = case mData of Just bs -> pure $ IPT.strictDecodeUtf8 bs _ -> returnError UnexpectedNull field "" -- }
bergmark/haskell-opaleye
src/Opaleye/Internal/RunQuery.hs
bsd-3-clause
10,751
0
18
2,200
2,321
1,267
1,054
167
4
-- | -- Module : Crypto.System.CPU -- License : BSD-style -- Maintainer : Olivier Chéron <[email protected]> -- Stability : experimental -- Portability : unknown -- -- Gives information about cryptonite runtime environment. -- {-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ForeignFunctionInterface #-} module Crypto.System.CPU ( ProcessorOption (..) , processorOptions ) where import Data.Data import Data.List (findIndices) #ifdef SUPPORT_RDRAND import Data.Maybe (isJust) #endif import Data.Word (Word8) import Foreign.Ptr import Foreign.Storable import Crypto.Internal.Compat #ifdef SUPPORT_RDRAND import Crypto.Random.Entropy.RDRand import Crypto.Random.Entropy.Source #endif -- | CPU options impacting cryptography implementation and library performance. data ProcessorOption = AESNI -- ^ Support for AES instructions, with flag @support_aesni@ | PCLMUL -- ^ Support for CLMUL instructions, with flag @support_pclmuldq@ | RDRAND -- ^ Support for RDRAND instruction, with flag @support_rdrand@ deriving (Show,Eq,Enum,Data) -- | Options which have been enabled at compile time and are supported by the -- current CPU. processorOptions :: [ProcessorOption] processorOptions = unsafeDoIO $ do p <- cryptonite_aes_cpu_init options <- traverse (getOption p) aesOptions rdrand <- hasRDRand return (decodeOptions options ++ [ RDRAND | rdrand ]) where aesOptions = [ AESNI .. PCLMUL ] getOption p = peekElemOff p . fromEnum decodeOptions = map toEnum . findIndices (> 0) {-# NOINLINE processorOptions #-} hasRDRand :: IO Bool #ifdef SUPPORT_RDRAND hasRDRand = fmap isJust getRDRand where getRDRand = entropyOpen :: IO (Maybe RDRand) #else hasRDRand = return False #endif foreign import ccall unsafe "cryptonite_aes_cpu_init" cryptonite_aes_cpu_init :: IO (Ptr Word8)
vincenthz/cryptonite
Crypto/System/CPU.hs
bsd-3-clause
1,888
0
12
330
321
189
132
31
1
{- | Module : Data.Vector.Parallel Copyright : (c) Paweł Nowak License : MIT Maintainer : [email protected] Stability : experimental Parallel vector operations. -} module Data.Vector.Parallel where import Control.Parallel.Strategies import Data.Foldable import Data.Vector (Vector) import qualified Data.Vector as Vector import GHC.Conc -- | Boxed vectors with parallel operations. newtype ParVector a = ParVector { runParVector :: Vector a } instance Functor ParVector where fmap f (ParVector v) = ParVector (fmap f v `using` parTraversable rseq) instance Applicative ParVector where pure x = ParVector (pure x) ParVector f <*> ParVector x = ParVector (f <*> x `using` parTraversable rseq) instance Foldable ParVector where foldMap f = fold . parMap rseq (foldMap f) . chunk -- | Splits a vector into a sensible number of parts. chunk :: ParVector a -> [Vector a] chunk (ParVector v0) = go v0 where go v | Vector.length v <= n = [v] | otherwise = let (l, r) = Vector.splitAt n v in l : go r n = (Vector.length v0 `div` (numCapabilities * 4)) + 1
pawel-n/machine-learning
src/Data/Vector/Parallel.hs
mit
1,190
0
13
312
335
175
160
22
1
-- -- | Names of haskell functions used in the Pl code -- module Plugin.Pl.Names where import Plugin.Pl.Common -- | Expressions with holes -- No MLambda here because we only consider closed Terms (no alpha-renaming!). -- Has to be in this module, otherwise we get recursion data MExpr = MApp !MExpr !MExpr -- ^ Application | Hole !Int -- ^ Hole/argument where another expression could go | Quote !Expr deriving Eq -- Names idE, flipE, bindE, extE, returnE, consE, appendE, nilE, foldrE, foldlE, fstE, sndE, dollarE, constE, uncurryE, curryE, compE, headE, tailE, sE, commaE, fixE, foldl1E, notE, equalsE, nequalsE, plusE, multE, zeroE, oneE, lengthE, sumE, productE, concatE, concatMapE, joinE, mapE, fmapE, fmapIE, subtractE, minusE, liftME, apE, liftM2E, seqME, zipE, zipWithE, crossE, firstE, secondE, andE, orE, allE, anyE :: MExpr idE = Quote $ Var Pref "id" flipE = Quote $ Var Pref "flip" constE = Quote $ Var Pref "const" compE = Quote $ Var Inf "." sE = Quote $ Var Pref "ap" fixE = Quote $ Var Pref "fix" bindE = Quote $ Var Inf ">>=" extE = Quote $ Var Inf "=<<" returnE = Quote $ Var Pref "return" consE = Quote $ Var Inf ":" nilE = Quote $ Var Pref "[]" appendE = Quote $ Var Inf "++" foldrE = Quote $ Var Pref "foldr" foldlE = Quote $ Var Pref "foldl" fstE = Quote $ Var Pref "fst" sndE = Quote $ Var Pref "snd" dollarE = Quote $ Var Inf "$" uncurryE = Quote $ Var Pref "uncurry" curryE = Quote $ Var Pref "curry" headE = Quote $ Var Pref "head" tailE = Quote $ Var Pref "tail" commaE = Quote $ Var Inf "," foldl1E = Quote $ Var Pref "foldl1" equalsE = Quote $ Var Inf "==" nequalsE = Quote $ Var Inf "/=" notE = Quote $ Var Pref "not" plusE = Quote $ Var Inf "+" multE = Quote $ Var Inf "*" zeroE = Quote $ Var Pref "0" oneE = Quote $ Var Pref "1" lengthE = Quote $ Var Pref "length" sumE = Quote $ Var Pref "sum" productE = Quote $ Var Pref "product" concatE = Quote $ Var Pref "concat" concatMapE = Quote $ Var Pref "concatMap" joinE = Quote $ Var Pref "join" mapE = Quote $ Var Pref "map" fmapE = Quote $ Var Pref "fmap" fmapIE = Quote $ Var Inf "fmap" subtractE = Quote $ Var Pref "subtract" minusE = Quote $ Var Inf "-" liftME = Quote $ Var Pref "liftM" liftM2E = Quote $ Var Pref "liftM2" apE = Quote $ Var Inf "ap" seqME = Quote $ Var Inf ">>" zipE = Quote $ Var Pref "zip" zipWithE = Quote $ Var Pref "zipWith" crossE = Quote $ Var Inf "***" firstE = Quote $ Var Pref "first" secondE = Quote $ Var Pref "second" andE = Quote $ Var Pref "and" orE = Quote $ Var Pref "or" allE = Quote $ Var Pref "all" anyE = Quote $ Var Pref "any" a, c :: MExpr -> MExpr -> MExpr a = MApp c e1 e2 = compE `a` e1 `a` e2 infixl 9 `a` infixr 8 `c`
jwiegley/lambdabot
Plugin/Pl/Names.hs
mit
2,960
0
7
842
973
554
419
80
1
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances, ViewPatterns #-} module YesodCoreTest.Links ( linksTest , Widget , resourcesY ) where import Test.Hspec import Yesod.Core import Network.Wai import Network.Wai.Test import Data.Text (Text) import Data.ByteString.Builder (toLazyByteString) data Y = Y mkYesod "Y" [parseRoutes| / RootR GET /single/#Text TextR GET /multi/*Texts TextsR GET /route-test-1/+[Text] RT1 GET /route-test-2/*Vector-String RT2 GET /route-test-3/*Vector-(Maybe-Int) RT3 GET /route-test-4/#(Foo-Int-Int) RT4 GET /route-test-4-spaces/#{Foo Int Int} RT4Spaces GET |] data Vector a = Vector deriving (Show, Read, Eq) instance PathMultiPiece (Vector a) where toPathMultiPiece = error "toPathMultiPiece" fromPathMultiPiece = error "fromPathMultiPiece" data Foo x y = Foo deriving (Show, Read, Eq) instance PathPiece (Foo x y) where toPathPiece = error "toPathPiece" fromPathPiece = error "fromPathPiece" instance Yesod Y getRootR :: Handler Html getRootR = defaultLayout $ toWidget [hamlet|<a href=@{RootR}>|] getTextR :: Text -> Handler Html getTextR foo = defaultLayout $ toWidget [hamlet|%#{foo}%|] getTextsR :: [Text] -> Handler Html getTextsR foos = defaultLayout $ toWidget [hamlet|%#{show foos}%|] getRT1 :: [Text] -> Handler () getRT1 _ = return () getRT2 :: Vector String -> Handler () getRT2 _ = return () getRT3 :: Vector (Maybe Int) -> Handler () getRT3 _ = return () getRT4 :: Foo Int Int -> Handler () getRT4 _ = return () getRT4Spaces :: Foo Int Int -> Handler () getRT4Spaces _ = return () linksTest :: Spec linksTest = describe "Test.Links" $ do it "linkToHome" case_linkToHome it "blank path pieces" case_blanks runner :: Session () -> IO () runner f = toWaiApp Y >>= runSession f case_linkToHome :: IO () case_linkToHome = runner $ do res <- request defaultRequest assertBody "<!DOCTYPE html>\n<html><head><title></title></head><body><a href=\"/\"></a>\n</body></html>" res case_blanks :: IO () case_blanks = runner $ do liftIO $ do let go r = let (ps, qs) = renderRoute r in toLazyByteString $ joinPath Y "" ps qs (go $ TextR "-") `shouldBe` "/single/--" (go $ TextR "") `shouldBe` "/single/-" (go $ TextsR ["", "-", "foo", "", "bar"]) `shouldBe` "/multi/-/--/foo/-/bar" res1 <- request defaultRequest { pathInfo = ["single", "-"] , rawPathInfo = "dummy1" } assertBody "<!DOCTYPE html>\n<html><head><title></title></head><body>%%</body></html>" res1 res2 <- request defaultRequest { pathInfo = ["multi", "foo", "-", "bar"] , rawPathInfo = "dummy2" } assertBody "<!DOCTYPE html>\n<html><head><title></title></head><body>%[&quot;foo&quot;,&quot;&quot;,&quot;bar&quot;]%</body></html>" res2
psibi/yesod
yesod-core/test/YesodCoreTest/Links.hs
mit
2,940
0
18
579
778
405
373
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fprof-auto-top #-} -- -- Copyright (c) 2010, João Dias, Simon Marlow, Simon Peyton Jones, -- and Norman Ramsey -- -- Modifications copyright (c) The University of Glasgow 2012 -- -- This module is a specialised and optimised version of -- Compiler.Hoopl.Dataflow in the hoopl package. In particular it is -- specialised to the UniqSM monad. -- module Hoopl.Dataflow ( DataflowLattice(..), OldFact(..), NewFact(..), Fact, mkFactBase , ChangeFlag(..) , FwdPass(..), FwdTransfer, mkFTransfer, mkFTransfer3, getFTransfer3 -- * Respecting Fuel -- $fuel , FwdRewrite, mkFRewrite, mkFRewrite3, getFRewrite3, noFwdRewrite , wrapFR, wrapFR2 , BwdPass(..), BwdTransfer, mkBTransfer, mkBTransfer3, getBTransfer3 , wrapBR, wrapBR2 , BwdRewrite, mkBRewrite, mkBRewrite3, getBRewrite3, noBwdRewrite , analyzeAndRewriteFwd, analyzeAndRewriteBwd , analyzeFwd, analyzeFwdBlocks, analyzeBwd ) where import UniqSupply import Data.Maybe import Data.Array import Compiler.Hoopl hiding ( mkBRewrite3, mkFRewrite3, noFwdRewrite, noBwdRewrite , analyzeAndRewriteBwd, analyzeAndRewriteFwd ) import Compiler.Hoopl.Internals ( wrapFR, wrapFR2 , wrapBR, wrapBR2 , splice ) -- ----------------------------------------------------------------------------- noRewrite :: a -> b -> UniqSM (Maybe c) noRewrite _ _ = return Nothing noFwdRewrite :: FwdRewrite UniqSM n f noFwdRewrite = FwdRewrite3 (noRewrite, noRewrite, noRewrite) -- | Functions passed to 'mkFRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite3' respects fuel. mkFRewrite3 :: forall n f. (n C O -> f -> UniqSM (Maybe (Graph n C O))) -> (n O O -> f -> UniqSM (Maybe (Graph n O O))) -> (n O C -> f -> UniqSM (Maybe (Graph n O C))) -> FwdRewrite UniqSM n f mkFRewrite3 f m l = FwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> UniqSM (Maybe a)) -> t -> t1 -> UniqSM (Maybe (a, FwdRewrite UniqSM n f)) {-# INLINE lift #-} lift rw node fact = do a <- rw node fact case a of Nothing -> return Nothing Just a -> return (Just (a,noFwdRewrite)) noBwdRewrite :: BwdRewrite UniqSM n f noBwdRewrite = BwdRewrite3 (noRewrite, noRewrite, noRewrite) mkBRewrite3 :: forall n f. (n C O -> f -> UniqSM (Maybe (Graph n C O))) -> (n O O -> f -> UniqSM (Maybe (Graph n O O))) -> (n O C -> FactBase f -> UniqSM (Maybe (Graph n O C))) -> BwdRewrite UniqSM n f mkBRewrite3 f m l = BwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> UniqSM (Maybe a)) -> t -> t1 -> UniqSM (Maybe (a, BwdRewrite UniqSM n f)) {-# INLINE lift #-} lift rw node fact = do a <- rw node fact case a of Nothing -> return Nothing Just a -> return (Just (a,noBwdRewrite)) ----------------------------------------------------------------------------- -- Analyze and rewrite forward: the interface ----------------------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeAndRewriteFwd :: forall n f e x . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e x -> Fact e f -> UniqSM (Graph n e x, FactBase f, MaybeO x f) analyzeAndRewriteFwd pass entries g f = do (rg, fout) <- arfGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedExitFact g' fout) distinguishedExitFact :: forall n e x f . Graph n e x -> Fact x f -> MaybeO x f distinguishedExitFact g f = maybe g where maybe :: Graph n e x -> MaybeO x f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany _ _ x) = case x of NothingO -> NothingO JustO _ -> JustO f ---------------------------------------------------------------- -- Forward Implementation ---------------------------------------------------------------- type Entries e = MaybeC e [Label] arfGraph :: forall n f e x . NonLocal n => FwdPass UniqSM n f -> Entries e -> Graph n e x -> Fact e f -> UniqSM (DG f n e x, Fact x f) arfGraph pass@FwdPass { fp_lattice = lattice, fp_transfer = transfer, fp_rewrite = rewrite } entries g in_fact = graph g in_fact where {- nested type synonyms would be so lovely here type ARF thing = forall e x . thing e x -> f -> m (DG f n e x, Fact x f) type ARFX thing = forall e x . thing e x -> Fact e f -> m (DG f n e x, Fact x f) -} graph :: Graph n e x -> Fact e f -> UniqSM (DG f n e x, Fact x f) block :: forall e x . Block n e x -> f -> UniqSM (DG f n e x, Fact x f) body :: [Label] -> LabelMap (Block n C C) -> Fact C f -> UniqSM (DG f n C C, Fact C f) -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' cat :: forall e a x f1 f2 f3. (f1 -> UniqSM (DG f n e a, f2)) -> (f2 -> UniqSM (DG f n a x, f3)) -> (f1 -> UniqSM (DG f n e x, f3)) graph GNil f = return (dgnil, f) graph (GUnit blk) f = block blk f graph (GMany e bdy x) f = ((e `ebcat` bdy) `cat` exit x) f where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact e f -> UniqSM (DG f n e C, Fact C f) exit :: MaybeO x (Block n C O) -> Fact C f -> UniqSM (DG f n C x, Fact x f) exit (JustO blk) f = arfx block blk f exit NothingO f = return (dgnilC, f) ebcat entry bdy f = c entries entry f where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact e f -> UniqSM (DG f n e C, Fact C f) c NothingC (JustO entry) f = (block entry `cat` body (successors entry) bdy) f c (JustC entries) NothingO f = body entries bdy f c _ _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block BNil f = return (dgnil, f) block (BlockCO n b) f = (node n `cat` block b) f block (BlockCC l b n) f = (node l `cat` block b `cat` node n) f block (BlockOC b n) f = (block b `cat` node n) f block (BMiddle n) f = node n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` node n) f block (BCons n t) f = (node n `cat` block t) f {-# INLINE node #-} node :: forall e x . (ShapeLifter e x) => n e x -> f -> UniqSM (DG f n e x, Fact x f) node n f = do { grw <- frewrite rewrite n f ; case grw of Nothing -> return ( singletonDG f n , ftransfer transfer n f ) Just (g, rw) -> let pass' = pass { fp_rewrite = rw } f' = fwdEntryFact n f in arfGraph pass' (fwdEntryLabel n) g f' } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g1,f1) <- ft1 f ; (g2,f2) <- ft2 f1 ; let !g = g1 `dgSplice` g2 ; return (g, f2) } arfx :: forall x . (Block n C x -> f -> UniqSM (DG f n C x, Fact x f)) -> (Block n C x -> Fact C f -> UniqSM (DG f n C x, Fact x f)) arfx arf thing fb = arf thing $ fromJust $ lookupFact (entryLabel thing) $ joinInFacts lattice fb -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Fwd lattice do_block entries blockmap init_fbase where lattice = fp_lattice pass do_block :: forall x . Block n C x -> FactBase f -> UniqSM (DG f n C x, Fact x f) do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- Join all the incoming facts with bottom. -- We know the results _shouldn't change_, but the transfer -- functions might, for example, generate some debugging traces. joinInFacts :: DataflowLattice f -> FactBase f -> FactBase f joinInFacts (lattice @ DataflowLattice {fact_bot = bot, fact_join = fj}) fb = mkFactBase lattice $ map botJoin $ mapToList fb where botJoin (l, f) = (l, snd $ fj l (OldFact bot) (NewFact f)) forwardBlockList :: (NonLocal n) => [Label] -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for forward analysis, -- along with the list of Labels it may depend on for facts. forwardBlockList entries blks = postorder_dfs_from blks entries ---------------------------------------------------------------- -- Forward Analysis only ---------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeFwd :: forall n f e . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact e f -> FactBase f analyzeFwd FwdPass { fp_lattice = lattice, fp_transfer = FwdTransfer3 (ftr, mtr, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact e f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> block entry `cat` body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Fwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> FactBase f -> Fact x f do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> f -> Fact x f block BNil f = f block (BlockCO n b) f = (ftr n `cat` block b) f block (BlockCC l b n) f = (ftr l `cat` (block b `cat` ltr n)) f block (BlockOC b n) f = (block b `cat` ltr n) f block (BMiddle n) f = mtr n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` mtr n) f block (BCons n t) f = (mtr n `cat` block t) f {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f1 -> f2) -> (f2 -> f3) -> (f1 -> f3) cat ft1 ft2 = \f -> ft2 $! ft1 f -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeFwdBlocks :: forall n f e . NonLocal n => FwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact e f -> FactBase f analyzeFwdBlocks FwdPass { fp_lattice = lattice, fp_transfer = FwdTransfer3 (ftr, _, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact e f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> block entry `cat` body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Fwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> FactBase f -> Fact x f do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> f -> Fact x f block BNil f = f block (BlockCO n _) f = ftr n f block (BlockCC l _ n) f = (ftr l `cat` ltr n) f block (BlockOC _ n) f = ltr n f block _ _ = error "analyzeFwdBlocks" {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f1 -> f2) -> (f2 -> f3) -> (f1 -> f3) cat ft1 ft2 = \f -> ft2 $! ft1 f ---------------------------------------------------------------- -- Backward Analysis only ---------------------------------------------------------------- -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeBwd :: forall n f e . NonLocal n => BwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e C -> Fact C f -> FactBase f analyzeBwd BwdPass { bp_lattice = lattice, bp_transfer = BwdTransfer3 (ftr, mtr, ltr) } entries g in_fact = graph g in_fact where graph :: Graph n e C -> Fact C f -> FactBase f graph (GMany entry blockmap NothingO) = case (entries, entry) of (NothingC, JustO entry) -> body (successors entry) (JustC entries, NothingO) -> body entries _ -> error "bogus GADT pattern match failure" where body :: [Label] -> Fact C f -> Fact C f body entries f = fixpointAnal Bwd lattice do_block entries blockmap f where do_block :: forall x . Block n C x -> Fact x f -> FactBase f do_block b fb = mapSingleton (entryLabel b) (block b fb) -- NB. eta-expand block, GHC can't do this by itself. See #5809. block :: forall e x . Block n e x -> Fact x f -> f block BNil f = f block (BlockCO n b) f = (ftr n `cat` block b) f block (BlockCC l b n) f = ((ftr l `cat` block b) `cat` ltr n) f block (BlockOC b n) f = (block b `cat` ltr n) f block (BMiddle n) f = mtr n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` mtr n) f block (BCons n t) f = (mtr n `cat` block t) f {-# INLINE cat #-} cat :: forall f1 f2 f3 . (f2 -> f3) -> (f1 -> f2) -> (f1 -> f3) cat ft1 ft2 = \f -> ft1 $! ft2 f ----------------------------------------------------------------------------- -- Backward analysis and rewriting: the interface ----------------------------------------------------------------------------- -- | if the graph being analyzed is open at the exit, I don't -- quite understand the implications of possible other exits analyzeAndRewriteBwd :: NonLocal n => BwdPass UniqSM n f -> MaybeC e [Label] -> Graph n e x -> Fact x f -> UniqSM (Graph n e x, FactBase f, MaybeO e f) analyzeAndRewriteBwd pass entries g f = do (rg, fout) <- arbGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedEntryFact g' fout) distinguishedEntryFact :: forall n e x f . Graph n e x -> Fact e f -> MaybeO e f distinguishedEntryFact g f = maybe g where maybe :: Graph n e x -> MaybeO e f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany e _ _) = case e of NothingO -> NothingO JustO _ -> JustO f ----------------------------------------------------------------------------- -- Backward implementation ----------------------------------------------------------------------------- arbGraph :: forall n f e x . NonLocal n => BwdPass UniqSM n f -> Entries e -> Graph n e x -> Fact x f -> UniqSM (DG f n e x, Fact e f) arbGraph pass@BwdPass { bp_lattice = lattice, bp_transfer = transfer, bp_rewrite = rewrite } entries g in_fact = graph g in_fact where {- nested type synonyms would be so lovely here type ARB thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, f) type ARBX thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, Fact e f) -} graph :: Graph n e x -> Fact x f -> UniqSM (DG f n e x, Fact e f) block :: forall e x . Block n e x -> Fact x f -> UniqSM (DG f n e x, f) body :: [Label] -> Body n -> Fact C f -> UniqSM (DG f n C C, Fact C f) node :: forall e x . (ShapeLifter e x) => n e x -> Fact x f -> UniqSM (DG f n e x, f) cat :: forall e a x info info' info''. (info' -> UniqSM (DG f n e a, info'')) -> (info -> UniqSM (DG f n a x, info')) -> (info -> UniqSM (DG f n e x, info'')) graph GNil f = return (dgnil, f) graph (GUnit blk) f = block blk f graph (GMany e bdy x) f = ((e `ebcat` bdy) `cat` exit x) f where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact C f -> UniqSM (DG f n e C, Fact e f) exit :: MaybeO x (Block n C O) -> Fact x f -> UniqSM (DG f n C x, Fact C f) exit (JustO blk) f = arbx block blk f exit NothingO f = return (dgnilC, f) ebcat entry bdy f = c entries entry f where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact C f -> UniqSM (DG f n e C, Fact e f) c NothingC (JustO entry) f = (block entry `cat` body (successors entry) bdy) f c (JustC entries) NothingO f = body entries bdy f c _ _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block BNil f = return (dgnil, f) block (BlockCO n b) f = (node n `cat` block b) f block (BlockCC l b n) f = (node l `cat` block b `cat` node n) f block (BlockOC b n) f = (block b `cat` node n) f block (BMiddle n) f = node n f block (BCat b1 b2) f = (block b1 `cat` block b2) f block (BSnoc h n) f = (block h `cat` node n) f block (BCons n t) f = (node n `cat` block t) f {-# INLINE node #-} node n f = do { bwdres <- brewrite rewrite n f ; case bwdres of Nothing -> return (singletonDG entry_f n, entry_f) where entry_f = btransfer transfer n f Just (g, rw) -> do { let pass' = pass { bp_rewrite = rw } ; (g, f) <- arbGraph pass' (fwdEntryLabel n) g f ; return (g, bwdEntryFact lattice n f)} } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g2,f2) <- ft2 f ; (g1,f1) <- ft1 f2 ; let !g = g1 `dgSplice` g2 ; return (g, f1) } arbx :: forall x . (Block n C x -> Fact x f -> UniqSM (DG f n C x, f)) -> (Block n C x -> Fact x f -> UniqSM (DG f n C x, Fact C f)) arbx arb thing f = do { (rg, f) <- arb thing f ; let fb = joinInFacts (bp_lattice pass) $ mapSingleton (entryLabel thing) f ; return (rg, fb) } -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Bwd (bp_lattice pass) do_block entries blockmap init_fbase where do_block :: forall x. Block n C x -> Fact x f -> UniqSM (DG f n C x, LabelMap f) do_block b f = do (g, f) <- block b f return (g, mapSingleton (entryLabel b) f) {- The forward and backward cases are not dual. In the forward case, the entry points are known, and one simply traverses the body blocks from those points. In the backward case, something is known about the exit points, but this information is essentially useless, because we don't actually have a dual graph (that is, one with edges reversed) to compute with. (Even if we did have a dual graph, it would not avail us---a backward analysis must include reachable blocks that don't reach the exit, as in a procedure that loops forever and has side effects.) -} ----------------------------------------------------------------------------- -- fixpoint ----------------------------------------------------------------------------- data Direction = Fwd | Bwd -- | fixpointing for analysis-only -- fixpointAnal :: forall n f. NonLocal n => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> Fact C f) -> [Label] -> LabelMap (Block n C C) -> Fact C f -> FactBase f fixpointAnal direction DataflowLattice{ fact_bot = _, fact_join = join } do_block entries blockmap init_fbase = loop start init_fbase where blocks = sortBlocks direction entries blockmap n = length blocks block_arr = {-# SCC "block_arr" #-} listArray (0,n-1) blocks start = {-# SCC "start" #-} [0..n-1] dep_blocks = {-# SCC "dep_blocks" #-} mkDepBlocks direction blocks loop :: IntHeap -- blocks still to analyse -> FactBase f -- current factbase (increases monotonically) -> FactBase f loop [] fbase = fbase loop (ix:todo) fbase = let blk = block_arr ! ix out_facts = {-# SCC "do_block" #-} do_block blk fbase !(todo', fbase') = {-# SCC "mapFoldWithKey" #-} mapFoldWithKey (updateFact join dep_blocks) (todo,fbase) out_facts in -- trace ("analysing: " ++ show (entryLabel blk)) $ -- trace ("fbase': " ++ show (mapKeys fbase')) $ return () -- trace ("changed: " ++ show changed) $ return () -- trace ("to analyse: " ++ show to_analyse) $ return () loop todo' fbase' -- | fixpointing for combined analysis/rewriting -- fixpoint :: forall n f. NonLocal n => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> UniqSM (DG f n C C, Fact C f)) -> [Label] -> LabelMap (Block n C C) -> (Fact C f -> UniqSM (DG f n C C, Fact C f)) fixpoint direction DataflowLattice{ fact_bot = _, fact_join = join } do_block entries blockmap init_fbase = do -- trace ("fixpoint: " ++ show (case direction of Fwd -> True; Bwd -> False) ++ " " ++ show (mapKeys blockmap) ++ show entries ++ " " ++ show (mapKeys init_fbase)) $ return() (fbase, newblocks) <- loop start init_fbase mapEmpty -- trace ("fixpoint DONE: " ++ show (mapKeys fbase) ++ show (mapKeys newblocks)) $ return() return (GMany NothingO newblocks NothingO, mapDeleteList (mapKeys blockmap) fbase) -- The successors of the Graph are the the Labels -- for which we have facts and which are *not* in -- the blocks of the graph where blocks = sortBlocks direction entries blockmap n = length blocks block_arr = {-# SCC "block_arr" #-} listArray (0,n-1) blocks start = {-# SCC "start" #-} [0..n-1] dep_blocks = {-# SCC "dep_blocks" #-} mkDepBlocks direction blocks loop :: IntHeap -> FactBase f -- current factbase (increases monotonically) -> LabelMap (DBlock f n C C) -- transformed graph -> UniqSM (FactBase f, LabelMap (DBlock f n C C)) loop [] fbase newblocks = return (fbase, newblocks) loop (ix:todo) fbase !newblocks = do let blk = block_arr ! ix -- trace ("analysing: " ++ show (entryLabel blk)) $ return () (rg, out_facts) <- do_block blk fbase let !(todo', fbase') = mapFoldWithKey (updateFact join dep_blocks) (todo,fbase) out_facts -- trace ("fbase': " ++ show (mapKeys fbase')) $ return () -- trace ("changed: " ++ show changed) $ return () -- trace ("to analyse: " ++ show to_analyse) $ return () let newblocks' = case rg of GMany _ blks _ -> mapUnion blks newblocks loop todo' fbase' newblocks' {- Note [TxFactBase invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TxFactBase is used only during a fixpoint iteration (or "sweep"), and accumulates facts (and the transformed code) during the fixpoint iteration. * tfb_fbase increases monotonically, across all sweeps * At the beginning of each sweep tfb_cha = NoChange tfb_lbls = {} * During each sweep we process each block in turn. Processing a block is done thus: 1. Read from tfb_fbase the facts for its entry label (forward) or successors labels (backward) 2. Transform those facts into new facts for its successors (forward) or entry label (backward) 3. Augment tfb_fbase with that info We call the labels read in step (1) the "in-labels" of the sweep * The field tfb_lbls is the set of in-labels of all blocks that have been processed so far this sweep, including the block that is currently being processed. tfb_lbls is initialised to {}. It is a subset of the Labels of the *original* (not transformed) blocks. * The tfb_cha field is set to SomeChange iff we decide we need to perform another iteration of the fixpoint loop. It is initialsed to NoChange. Specifically, we set tfb_cha to SomeChange in step (3) iff (a) The fact in tfb_fbase for a block L changes (b) L is in tfb_lbls Reason: until a label enters the in-labels its accumuated fact in tfb_fbase has not been read, hence cannot affect the outcome Note [Unreachable blocks] ~~~~~~~~~~~~~~~~~~~~~~~~~ A block that is not in the domain of tfb_fbase is "currently unreachable". A currently-unreachable block is not even analyzed. Reason: consider constant prop and this graph, with entry point L1: L1: x:=3; goto L4 L2: x:=4; goto L4 L4: if x>3 goto L2 else goto L5 Here L2 is actually unreachable, but if we process it with bottom input fact, we'll propagate (x=4) to L4, and nuke the otherwise-good rewriting of L4. * If a currently-unreachable block is not analyzed, then its rewritten graph will not be accumulated in tfb_rg. And that is good: unreachable blocks simply do not appear in the output. * Note that clients must be careful to provide a fact (even if bottom) for each entry point. Otherwise useful blocks may be garbage collected. * Note that updateFact must set the change-flag if a label goes from not-in-fbase to in-fbase, even if its fact is bottom. In effect the real fact lattice is UNR bottom the points above bottom * Even if the fact is going from UNR to bottom, we still call the client's fact_join function because it might give the client some useful debugging information. * All of this only applies for *forward* ixpoints. For the backward case we must treat every block as reachable; it might finish with a 'return', and therefore have no successors, for example. -} ----------------------------------------------------------------------------- -- Pieces that are shared by fixpoint and fixpoint_anal ----------------------------------------------------------------------------- -- | Sort the blocks into the right order for analysis. sortBlocks :: NonLocal n => Direction -> [Label] -> LabelMap (Block n C C) -> [Block n C C] sortBlocks direction entries blockmap = case direction of Fwd -> fwd Bwd -> reverse fwd where fwd = forwardBlockList entries blockmap -- | construct a mapping from L -> block indices. If the fact for L -- changes, re-analyse the given blocks. mkDepBlocks :: NonLocal n => Direction -> [Block n C C] -> LabelMap [Int] mkDepBlocks Fwd blocks = go blocks 0 mapEmpty where go [] !_ m = m go (b:bs) !n m = go bs (n+1) $! mapInsert (entryLabel b) [n] m mkDepBlocks Bwd blocks = go blocks 0 mapEmpty where go [] !_ m = m go (b:bs) !n m = go bs (n+1) $! go' (successors b) m where go' [] m = m go' (l:ls) m = go' ls (mapInsertWith (++) l [n] m) -- | After some new facts have been generated by analysing a block, we -- fold this function over them to generate (a) a list of block -- indices to (re-)analyse, and (b) the new FactBase. -- updateFact :: JoinFun f -> LabelMap [Int] -> Label -> f -- out fact -> (IntHeap, FactBase f) -> (IntHeap, FactBase f) updateFact fact_join dep_blocks lbl new_fact (todo, fbase) = case lookupFact lbl fbase of Nothing -> let !z = mapInsert lbl new_fact fbase in (changed, z) -- Note [no old fact] Just old_fact -> case fact_join lbl (OldFact old_fact) (NewFact new_fact) of (NoChange, _) -> (todo, fbase) (_, f) -> let !z = mapInsert lbl f fbase in (changed, z) where changed = foldr insertIntHeap todo $ mapFindWithDefault [] lbl dep_blocks {- Note [no old fact] We know that the new_fact is >= _|_, so we don't need to join. However, if the new fact is also _|_, and we have already analysed its block, we don't need to record a change. So there's a tradeoff here. It turns out that always recording a change is faster. -} ----------------------------------------------------------------------------- -- DG: an internal data type for 'decorated graphs' -- TOTALLY internal to Hoopl; each block is decorated with a fact ----------------------------------------------------------------------------- type DG f = Graph' (DBlock f) data DBlock f n e x = DBlock f (Block n e x) -- ^ block decorated with fact instance NonLocal n => NonLocal (DBlock f n) where entryLabel (DBlock _ b) = entryLabel b successors (DBlock _ b) = successors b --- constructors dgnil :: DG f n O O dgnilC :: DG f n C C dgSplice :: NonLocal n => DG f n e a -> DG f n a x -> DG f n e x ---- observers normalizeGraph :: forall n f e x . NonLocal n => DG f n e x -> (Graph n e x, FactBase f) -- A Graph together with the facts for that graph -- The domains of the two maps should be identical normalizeGraph g = (mapGraphBlocks dropFact g, facts g) where dropFact :: DBlock t t1 t2 t3 -> Block t1 t2 t3 dropFact (DBlock _ b) = b facts :: DG f n e x -> FactBase f facts GNil = noFacts facts (GUnit _) = noFacts facts (GMany _ body exit) = bodyFacts body `mapUnion` exitFacts exit exitFacts :: MaybeO x (DBlock f n C O) -> FactBase f exitFacts NothingO = noFacts exitFacts (JustO (DBlock f b)) = mapSingleton (entryLabel b) f bodyFacts :: LabelMap (DBlock f n C C) -> FactBase f bodyFacts body = mapFoldWithKey f noFacts body where f :: forall t a x. (NonLocal t) => Label -> DBlock a t C x -> LabelMap a -> LabelMap a f lbl (DBlock f _) fb = mapInsert lbl f fb --- implementation of the constructors (boring) dgnil = GNil dgnilC = GMany NothingO emptyBody NothingO dgSplice = splice fzCat where fzCat :: DBlock f n e O -> DBlock t n O x -> DBlock f n e x fzCat (DBlock f b1) (DBlock _ b2) = DBlock f $! b1 `blockAppend` b2 -- NB. strictness, this function is hammered. ---------------------------------------------------------------- -- Utilities ---------------------------------------------------------------- -- Lifting based on shape: -- - from nodes to blocks -- - from facts to fact-like things -- Lowering back: -- - from fact-like things to facts -- Note that the latter two functions depend only on the entry shape. class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x fwdEntryFact :: NonLocal n => n e x -> f -> Fact e f fwdEntryLabel :: NonLocal n => n e x -> MaybeC e [Label] ftransfer :: FwdTransfer n f -> n e x -> f -> Fact x f frewrite :: FwdRewrite m n f -> n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f)) -- @ end node.tex bwdEntryFact :: NonLocal n => DataflowLattice f -> n e x -> Fact e f -> f btransfer :: BwdTransfer n f -> n e x -> Fact x f -> f brewrite :: BwdRewrite m n f -> n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f)) instance ShapeLifter C O where singletonDG f n = gUnitCO (DBlock f (BlockCO n BNil)) fwdEntryFact n f = mapSingleton (entryLabel n) f bwdEntryFact lat n fb = getFact lat (entryLabel n) fb ftransfer (FwdTransfer3 (ft, _, _)) n f = ft n f btransfer (BwdTransfer3 (bt, _, _)) n f = bt n f frewrite (FwdRewrite3 (fr, _, _)) n f = fr n f brewrite (BwdRewrite3 (br, _, _)) n f = br n f fwdEntryLabel n = JustC [entryLabel n] instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, ft, _)) n f = ft n f btransfer (BwdTransfer3 (_, bt, _)) n f = bt n f frewrite (FwdRewrite3 (_, fr, _)) n f = fr n f brewrite (BwdRewrite3 (_, br, _)) n f = br n f fwdEntryLabel _ = NothingC instance ShapeLifter O C where singletonDG f n = gUnitOC (DBlock f (BlockOC BNil n)) fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdTransfer3 (_, _, ft)) n f = ft n f btransfer (BwdTransfer3 (_, _, bt)) n f = bt n f frewrite (FwdRewrite3 (_, _, fr)) n f = fr n f brewrite (BwdRewrite3 (_, _, br)) n f = br n f fwdEntryLabel _ = NothingC {- class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x instance ShapeLifter C O where singletonDG f n = gUnitCO (DBlock f (BlockCO n BNil)) instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle instance ShapeLifter O C where singletonDG f n = gUnitOC (DBlock f (BlockOC BNil n)) -} -- Fact lookup: the fact `orelse` bottom getFact :: DataflowLattice f -> Label -> FactBase f -> f getFact lat l fb = case lookupFact l fb of Just f -> f Nothing -> fact_bot lat {- Note [Respects fuel] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} -- $fuel -- A value of type 'FwdRewrite' or 'BwdRewrite' /respects fuel/ if -- any function contained within the value satisfies the following properties: -- -- * When fuel is exhausted, it always returns 'Nothing'. -- -- * When it returns @Just g rw@, it consumes /exactly/ one unit -- of fuel, and new rewrite 'rw' also respects fuel. -- -- Provided that functions passed to 'mkFRewrite', 'mkFRewrite3', -- 'mkBRewrite', and 'mkBRewrite3' are not aware of the fuel supply, -- the results respect fuel. -- -- It is an /unchecked/ run-time error for the argument passed to 'wrapFR', -- 'wrapFR2', 'wrapBR', or 'warpBR2' to return a function that does not respect fuel. -- ----------------------------------------------------------------------------- -- a Heap of Int -- We should really use a proper Heap here, but my attempts to make -- one have not succeeded in beating the simple ordered list. Another -- alternative is IntSet (using deleteFindMin), but that was also -- slower than the ordered list in my experiments --SDM 25/1/2012 type IntHeap = [Int] -- ordered insertIntHeap :: Int -> [Int] -> [Int] insertIntHeap x [] = [x] insertIntHeap x (y:ys) | x < y = x : y : ys | x == y = x : ys | otherwise = y : insertIntHeap x ys
forked-upstream-packages-for-ghcjs/ghc
compiler/cmm/Hoopl/Dataflow.hs
bsd-3-clause
35,959
252
64
10,768
9,847
5,117
4,730
495
14
{-# LANGUAGE ScopedTypeVariables #-} module Demote.UsedAtLevel2 where foo :: IO () foo = do let xx = uses declaredPns [] return () where ---find how many matches/pattern bindings use 'pn'------- -- uses :: [GHC.Name] -> [GHC.LHsBind GHC.Name] -> [Int] uses pns t2 = concatMap used t2 where usedInMatch _ _ = [] used :: LHsBind Name -> [Int] used (L _ (FunBind _n _ (MatchGroup matches _) _ _ _)) = usedInMatch pns matches used (L _ (PatBind _pat _rhs _ _ _)) = [1::Int] used _ = [] duplicateDecls = undefined data HsBind a = FunBind a Int (MatchGroup a) Int Int Int | PatBind String String Int Int a data Name = N String data Located a = L Int a data MatchGroup a = MatchGroup [LMatch a] a type LMatch a = Located (Match a) data Match a = Match String Int a data Renamer = Renamer type LHsBind a = Located (HsBind a) declaredPns = undefined
RefactoringTools/HaRe
test/testdata/Demote/UsedAtLevel2.expected.hs
bsd-3-clause
1,074
0
15
393
326
173
153
26
3
module FindFixpoint(Ms, getVal, solve) where import Array import Control.Monad.Writer import Data.Array.IO import Data.Graph import Data.IntSet as IntSet import Util.Gen data Env b = Env {-# UNPACK #-} !(IOArray Int b) {-# UNPACK #-} !(IOArray Int (IntSet)) {-# UNPACK #-} !Int newtype Ms b c = Ms' (Env b -> IO c) instance Monad (Ms b) where return a = Ms' (\_ -> return a) Ms' comp >>= fun = Ms' (\v -> comp v >>= \r -> case fun r of Ms' x -> x v) Ms' a >> Ms' b = Ms' $ \v -> a v >> b v fail x = Ms' (\_ -> (putErrDie x)) {-# INLINE (>>) #-} {-# INLINE (>>=) #-} {-# INLINE return #-} instance Functor (Ms b) where fmap = liftM unMs' (Ms' x) = x {-# INLINE getVal #-} getVal :: Int -> Ms b b getVal n = Ms' $ \(Env arr ref self) -> do s <- readArray ref n writeArray ref n $ (IntSet.insert self s) readArray arr n solve :: (Eq b) => Maybe String -> b -> [Ms b b] -> IO [b] solve str' empty vs = do let put = case str' of Just _ -> putErrLn Nothing -> const (return ()) put' = case str' of Just _ -> putErr Nothing -> const (return ()) Just str = str' let len = length vs put $ "Finding Fixpoint for " ++ show len ++ " variables: " ++ str arr <- newArray (0,len - 1) empty ref <- newArray (0,len - 1) IntSet.empty let as = [ (i,(unMs' f) (Env arr ref i)) | f <- vs | i <- [0..]] fna = listArray (0,len - 1) (snds as) let li [] s | IntSet.null s = return () --li xs [] n = CharIO.putErr ("[" ++ show (I# n) ++ "]") >> li xs xs 0# li [] s = do let g i = do ds <- readArray ref i return (i,i,IntSet.toList ds) ds <- mapM g (IntSet.toList s) let xs = flattenSCCs scc scc = stronglyConnComp ds put' $ " " ++ show (IntSet.size s) li (reverse xs) IntSet.empty li (i:rs) s = do b <- readArray arr i b'<- fna Array.! i case b == b' of True -> li rs (IntSet.delete i s) False -> do writeArray arr i b' ns <- readArray ref i li rs (ns `IntSet.union` IntSet.delete i s) li [0 .. len - 1] IntSet.empty put $ " Done." mapM (readArray arr) [0 .. len - 1]
m-alvarez/jhc
src/FindFixpoint.hs
mit
2,395
1
21
876
1,028
506
522
64
6
{-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-overlapping-patterns #-} {-# LANGUAGE OverloadedStrings #-} module PMC007 where -- overloaded f "ab" = () f "ac" = () -- non-overloaded g :: String -> () g "ab" = () g "ac" = () -- non-overloaded due to type inference h :: String -> () h s = let s' = s in case s' of "ab" -> () "ac" -> ()
ezyang/ghc
testsuite/tests/pmcheck/should_compile/pmc007.hs
bsd-3-clause
374
0
10
100
110
59
51
13
2
{-# LANGUAGE ParallelArrays #-} {-# OPTIONS -fvectorise #-} module QuickHullVect (quickhull) where import Types import Data.Array.Parallel import Data.Array.Parallel.Prelude.Double as D import qualified Data.Array.Parallel.Prelude.Int as Int import qualified Prelude as P distance :: Point -> Line -> Double distance (xo, yo) ((x1, y1), (x2, y2)) = (x1 D.- xo) D.* (y2 D.- yo) D.- (y1 D.- yo) D.* (x2 D.- xo) hsplit :: [:Point:] -> Line -> [:Point:] hsplit points line@(p1, p2) | lengthP packed Int.< 2 = singletonP p1 +:+ packed | otherwise = concatP [: hsplit packed ends | ends <- [:(p1, pm), (pm, p2):] :] where cross = [: distance p line | p <- points :] packed = [: p | (p,c) <- zipP points cross, c D.> 0.0 :] pm = points !: maxIndexP cross quickHull' :: [:Point:] -> [:Point:] quickHull' points | lengthP points Int.== 0 = points | otherwise = concatP [: hsplit points ends | ends <- [: (minx, maxx), (maxx, minx) :] :] where xs = [: x | (x, y) <- points :] minx = points !: minIndexP xs maxx = points !: maxIndexP xs quickhull :: PArray Point -> PArray Point {-# NOINLINE quickhull #-} quickhull ps = toPArrayP (quickHull' (fromPArrayP ps))
urbanslug/ghc
testsuite/tests/dph/quickhull/QuickHullVect.hs
bsd-3-clause
1,208
33
11
260
541
298
243
30
1
-- | Convenient common interface for command line Futhark compilers. -- Using this module ensures that all compilers take the same options. -- A small amount of flexibility is provided for backend-specific -- options. module Futhark.Compiler.CLI ( compilerMain , CompilerOption , CompilerMode(..) ) where import Data.Maybe import System.FilePath import System.Console.GetOpt import Futhark.Pipeline import Futhark.Compiler import Futhark.Representation.AST (Prog) import Futhark.Representation.SOACS (SOACS) import Futhark.Util.Options import Language.Futhark.Futlib.Prelude -- | Run a parameterised Futhark compiler, where @cfg@ is a user-given -- configuration type. Call this from @main@. compilerMain :: cfg -- ^ Initial configuration. -> [CompilerOption cfg] -- ^ Options that affect the configuration. -> String -- ^ The short action name (e.g. "compile to C"). -> String -- ^ The longer action description. -> Pipeline SOACS lore -- ^ The pipeline to use. -> (cfg -> CompilerMode -> FilePath -> Prog lore -> FutharkM ()) -- ^ The action to take on the result of the pipeline. -> IO () compilerMain cfg cfg_opts name desc pipeline doIt = reportingIOErrors $ mainWithOptions (newCompilerConfig cfg) (commandLineOptions ++ map wrapOption cfg_opts) inspectNonOptions where inspectNonOptions [file] config = Just $ compile config file inspectNonOptions _ _ = Nothing compile config filepath = runCompilerOnProgram (futharkConfig config) preludeBasis pipeline (action config filepath) filepath action config filepath = Action { actionName = name , actionDescription = desc , actionProcedure = doIt (compilerConfig config) (compilerMode config) $ outputFilePath filepath config } -- | An option that modifies the configuration of type @cfg@. type CompilerOption cfg = OptDescr (Either (IO ()) (cfg -> cfg)) type CoreCompilerOption cfg = OptDescr (Either (IO ()) (CompilerConfig cfg -> CompilerConfig cfg)) commandLineOptions :: [CoreCompilerOption cfg] commandLineOptions = [ Option "o" [] (ReqArg (\filename -> Right $ \config -> config { compilerOutput = Just filename }) "FILE") "Name of the compiled binary." , Option "v" ["verbose"] (OptArg (\file -> Right $ \config -> config { compilerVerbose = Just file }) "FILE") "Print verbose output on standard error; wrong program to FILE." , Option [] ["library"] (NoArg $ Right $ \config -> config { compilerMode = ToLibrary }) "Generate a library instead of an executable." , Option [] ["executable"] (NoArg $ Right $ \config -> config { compilerMode = ToExecutable }) "Generate an executable instead of a library (set by default)." , Option "I" ["include"] (ReqArg (\path -> Right $ \config -> config { compilerImportPaths = compilerImportPaths config `mappend` importPath path } ) "DIR") "Add directory to search path." ] wrapOption :: CompilerOption cfg -> CoreCompilerOption cfg wrapOption = fmap wrap where wrap f = do g <- f return $ \cfg -> cfg { compilerConfig = g (compilerConfig cfg) } data CompilerConfig cfg = CompilerConfig { compilerOutput :: Maybe FilePath , compilerVerbose :: Maybe (Maybe FilePath) , compilerMode :: CompilerMode , compilerImportPaths :: ImportPaths , compilerConfig :: cfg } -- | Are we compiling a library or an executable? data CompilerMode = ToLibrary | ToExecutable deriving (Eq, Ord, Show) -- | The configuration of the compiler. newCompilerConfig :: cfg -> CompilerConfig cfg newCompilerConfig x = CompilerConfig { compilerOutput = Nothing , compilerVerbose = Nothing , compilerMode = ToExecutable , compilerImportPaths = mempty , compilerConfig = x } outputFilePath :: FilePath -> CompilerConfig cfg -> FilePath outputFilePath srcfile = fromMaybe (srcfile `replaceExtension` "") . compilerOutput futharkConfig :: CompilerConfig cfg -> FutharkConfig futharkConfig config = newFutharkConfig { futharkVerbose = compilerVerbose config , futharkImportPaths = compilerImportPaths config }
ihc/futhark
src/Futhark/Compiler/CLI.hs
isc
4,717
0
17
1,400
951
524
427
86
2
{- My wife and I recently attended a party at which there were four other married couples. Various handshakes took place. No one shook hands with oneself, nor with one's spouse, and no one shook hands with the same person more than once. After all the handshakes were over, I asked each person, including my wife, how many hands he (or she) had shaken. To my surprise each gave a different answer. How many hands did my wife shake? http://http://www.cut-the-knot.org/pigeonhole/FiveCouples.shtml -} module Main where import Control.Applicative import Booleans import Ersatz import Data.Map (Map) import qualified Data.Map as Map import Prelude hiding ((&&), (||), all) data Spouse = Husband | Wife deriving (Eq, Ord, Show, Read) couples :: Int couples = 5 type Handshakes = Map (Int, Spouse, Int, Spouse) Bit countHandshakes :: Handshakes -> Int -> Spouse -> Bits countHandshakes m x xS = countBits [ met | ((i,iS,j,jS),met) <- Map.toList m , i == x && iS == xS || j == x && jS == xS ] handshakesExist :: MonadSAT s m => m (Map (Int, Spouse, Int, Spouse) Bit) handshakesExist = sequence $ Map.fromList [ ((i,iS,j,jS), exists) | i <- [1..couples] , iS <- [Husband,Wife] , j <- [i+1..couples] , jS <- [Husband,Wife] ] problem :: MonadSAT s m => m Bits problem = do m <- handshakesExist let consider = (1,Wife) : liftA2 (,) [2..couples] [Husband,Wife] handshakes = uncurry (countHandshakes m) <$> consider assert (unique handshakes) return (head handshakes) main :: IO () main = do Just res <- getModel problem Nothing <- getModel (problem `checking` (/== encode res)) print res
glguy/5puzzle
Handshakes.hs
isc
1,855
0
14
544
514
282
232
35
1
{-# LANGUAGE NoImplicitPrelude #-} module Advent.Day3Spec (main, spec) where import Advent.Day3 import BasePrelude import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "day3Part1" $ do it "count the houses according to directions" $ do day3part1 ">" `shouldBe` 2 day3part1 "^>v<" `shouldBe` 4 day3part1 "^v^v^v^v^v" `shouldBe` 2 describe "day3Part2" $ do it "Santa and Robo-Santa part ways" $ do day3part2 "^v" `shouldBe` 3 day3part2 "^>v<" `shouldBe` 3 day3part2 "^v^v^v^v^v" `shouldBe` 11
jhenahan/adventofcode
test/Advent/Day3Spec.hs
mit
602
0
14
160
168
85
83
19
1
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified HoogleApi as H import Control.Monad import Control.Monad.STM import Control.Concurrent.Async (async, wait) import Control.Concurrent (threadDelay, forkIO) import Control.Concurrent.STM.TChan import qualified Data.Text.IO as T import Data.Text (Text, unpack, pack) import Data.Maybe import Data.Monoid ((<>)) import Web.Telegram.API.Bot token :: Token token = Token "" pollTimeout :: Int pollTimeout = 300 -- seconds main :: IO () main = do broadcastChan <- newTChanIO _ <- forkIO $ retrieveMessages broadcastChan Nothing _ <- forkIO $ answerMessages broadcastChan _ <- getLine return () answerMessages :: TChan Message -> IO () answerMessages broadcastChan = do chan <- atomically $ dupTChan broadcastChan -- dupTChan for every recursive call ? forever $ do msg <- atomically $ readTChan chan respondToMsg msg -- |Retrieve messages via Telegram API retrieveMessages :: TChan Message -> Maybe Int -> IO () retrieveMessages broadcastChan offset = do putStrLn $ "Retrieving with max offset " <> show (maybe 0 id offset) resp <- getUpdates token offset Nothing (Just pollTimeout) -- Longpoll case resp of Left err -> do putStrLn $ show err retrieveMessages broadcastChan offset Right r -> do putStrLn $ show r mapM_ writeMsg (filterMessages r) retrieveMessages broadcastChan (nextOffset r) where writeMsg m = atomically $ writeTChan broadcastChan m nextOffset r = Just $ (+1) (maxOffset r) -- |Filter for non empty messages filterMessages :: UpdatesResponse -> [Message] filterMessages response = catMaybes $ map message (update_result response) -- |Determine highest offset in update. maxOffset :: UpdatesResponse -> Int maxOffset response = maximum $ map update_id (update_result response) -- |Format bot response formatHoogleResponse :: H.HoogleQuery -> Text formatHoogleResponse qry = let formatRes r = "\n[" <> (H.self r) <> "](" <> (H.location r) <> ")" <> "```" <> (H.docs r) <> "```" in mconcat $ map formatRes $ H.results qry -- |Respond to a msg send by a client respondToMsg :: Message-> IO () respondToMsg req = do h <- async $ H.query (fromJust $ text req) Nothing Nothing -- avoid fromJust hoogleResp <- wait h sr <- async $ sendMessage token (messageReq $ answer hoogleResp) sendResp <- wait sr case sendResp of Left err -> putStrLn $ show err Right m-> putStrLn $ show $ message_id $ message_result m where chatId = pack $ show $ chat_id $ chat req replyToMsgId = Just (message_id req) markdown = Just Markdown answer hr = either (\_ -> "Can not reach hoogle") formatHoogleResponse hr messageReq a = SendMessageRequest chatId a markdown Nothing replyToMsgId Nothing
muhbaasu/telegram-hoogle-bot
src/Main.hs
mit
2,839
0
18
597
876
438
438
68
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE NamedFieldPuns #-} module Nauva.Catalog ( CatalogProps(..) , catalog , module Nauva.App , module Nauva.View , module Nauva.Catalog.Types ) where import Data.Text (Text) import qualified Data.Aeson as A import Data.Maybe import Control.Concurrent.STM import Nauva.App import Nauva.Internal.Types (Signal(..), Element, Component(..), createComponent, emptyHooks) import Nauva.View import Nauva.Catalog.Shell import Nauva.Catalog.Types ------------------------------------------------------------------------------- -- The 'catalog' element is meant to be used as the root element of the -- application. It renders the sidebar (navigation) and page content depending -- on the current location. data CatalogProps = CatalogProps { p_title :: !Text , p_pages :: ![Page] , p_appH :: !AppH } catalog :: CatalogProps -> Element catalog = component_ catalogComponent ------------------------------------------------------------------------------- data State = State { path :: !Text } catalogComponent :: Component CatalogProps () State () catalogComponent = createComponent $ \componentId -> Component { componentId = componentId , componentDisplayName = "Catalog" , initialComponentState = \props@CatalogProps{..} -> do loc <- readTVar $ fst $ hLocation $ routerH $ p_appH pure ( State (locPathname loc) , [ Signal (snd $ hLocation $ routerH $ p_appH) (\(Location p) props' s -> (s { path = p }, [updateHead props' p])) ] , [ updateHead props (locPathname loc) ] ) , componentEventListeners = const [] , componentHooks = emptyHooks , processLifecycleEvent = \() _ s -> (s, []) , receiveProps = \CatalogProps{..} s -> pure (s, [Signal (snd $ hLocation $ routerH $ p_appH) (\(Location p) props' s' -> (s' { path = p }, [updateHead props' p]))], []) , update = update , renderComponent = render , componentSnapshot = \_ -> A.object [] , restoreComponent = \_ s -> Right (s, []) } where updateHead :: CatalogProps -> Text -> IO (Maybe ()) updateHead CatalogProps{..} path = do hReplace (headH p_appH) [ style_ [str_ "*,*::before,*::after{box-sizing:inherit}body{margin:0;box-sizing:border-box}"] , title_ [str_ $ title p_pages path] , link_ [rel_ ("stylesheet" :: Text), type_ ("text/css" :: Text), href_ ("https://fonts.googleapis.com/css?family=Roboto:400,700,400italic" :: Text)] , link_ [rel_ ("stylesheet" :: Text), type_ ("text/css" :: Text), href_ ("https://fonts.googleapis.com/css?family=Source+Code+Pro:400,700" :: Text)] , link_ [rel_ ("stylesheet" :: Text), type_ ("text/css" :: Text), href_ ("https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700" :: Text)] ] pure Nothing update () props s = ( s , [ updateHead props (path s) ] ) title :: [Page] -> Text -> Text title pages p = case lookup p (flattenedPages pages) of Nothing -> "Unknown Page" Just leaf -> leafTitle leaf flattenPage :: Page -> [(Text, Leaf)] flattenPage (PLeaf leaf@(Leaf {..})) = [(leafHref, leaf)] flattenPage (PDirectory (Directory {..})) = map (\x -> (leafHref x, x)) directoryChildren flattenedPages pages = concat $ map flattenPage pages render CatalogProps{..} State{..} = div_ [style_ rootStyle] [ div_ [style_ mainStyle] [ header (HeaderProps { section, title = title p_pages path }) , div_ [style_ pageStyle] [page] ] , sidebar $ SidebarProps { p_routerH = routerH p_appH , p_logoUrl , p_pages = p_pages } ] where p_logoUrl = "/" page = case lookup path (flattenedPages $ p_pages) of Nothing -> div_ [style_ pageInnerStyle] [str_ "page not found"] Just leaf -> leafElement leaf section :: Text section = findSection Nothing $ p_pages where findSection mbTitle [] = fromMaybe p_title mbTitle findSection _ (PDirectory (Directory {..}):xs) = findSection (Just directoryTitle) xs findSection mbTitle (PLeaf (Leaf {..}):xs) = if leafHref == path then fromMaybe p_title mbTitle else findSection mbTitle xs rootStyle = mkStyle $ do position relative background "rgb(249, 249, 249)" margin "0px" padding "0px" width "100%" height "100%" mainStyle = mkStyle $ do display flex flexDirection column minHeight (vh 100) position relative -- media "(min-width: 1000px)" $ do marginLeft (px 251) pageStyle = mkStyle $ do flex "1 1 0%" pageInnerStyle = mkStyle $ do margin "0 30px 0 40px" maxWidth "64em" display flex flexFlow row wrap padding "48px 0px"
wereHamster/nauva
pkg/hs/nauva-catalog/src/Nauva/Catalog.hs
mit
5,286
0
20
1,534
1,461
784
677
113
7
module Data.String.StripSpec (spec) where import Test.Hspec import Data.String.Strip spec :: Spec spec = do describe "strip" $ do it "removes leading and trailing whitespace" $ do strip "\t foo bar\n" `shouldBe` "foo bar"
hspec/hspec-example
test/Data/String/StripSpec.hs
mit
237
0
14
48
65
35
30
8
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Travis.Types where import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), withObject, (.:)) import Data.Aeson.Types (Object (..), Parser (..), defaultOptions, fieldLabelModifier, genericParseJSON, genericToJSON) import GHC.Generics (Generic) -- |Data types representing: <http://docs.travis-ci.com/api/?http#repositories> -- TODO: more precise parsing / types data RepoRaw = RepoRaw { repo :: RepositoryRaw } deriving (Show, Generic) data RepositoryRaw = RepositoryRaw { id :: Int , slug :: String , active :: Bool , description :: String , last_build_id :: Int , last_build_number :: String , last_build_state :: String , last_build_duration :: Int , last_build_started_at :: String , last_build_finished_at :: String , github_language :: String } deriving (Show, Generic) instance FromJSON RepositoryRaw instance ToJSON RepositoryRaw instance FromJSON RepoRaw instance ToJSON RepoRaw -- |Data types representing: <http://docs.travis-ci.com/api/?http#builds> -- TODO: more precise parsing / types data BuildsRaw = BuildsRaw { builds :: [BuildRaw] , jobs :: Maybe [Object] , commits :: [Commit] } deriving (Show, Generic) data BuildRaw = BuildRaw { _commit_id :: Int , _config :: Object , _duration :: Int , _finished_at :: String , _id :: Int , _job_ids :: [Int] , _number :: String , _pull_request :: Bool , _pull_request_number :: Maybe Int , _pull_request_title :: Maybe String , _repository_id :: Int , _started_at :: String , _state :: String } deriving (Show, Generic) instance FromJSON BuildsRaw instance ToJSON BuildsRaw instance FromJSON BuildRaw where parseJSON = genericParseJSON defaultOptions { fieldLabelModifier = drop 1 } instance ToJSON BuildRaw where toJSON = genericToJSON defaultOptions { fieldLabelModifier = drop 1 } -- |Data type representing: <http://docs.travis-ci.com/api/#commits> -- TODO: more precise parsing / types data Commit = Commit { cid :: Int , csha :: String , cbranch :: String , cmessage :: String , ccommitted_at :: String , cauthor_name :: String , cauthor_email :: String , ccommitter_name :: String , ccommitter_email :: String , ccompare_url :: String } deriving (Show, Generic) instance FromJSON Commit where parseJSON = genericParseJSON defaultOptions { fieldLabelModifier = drop 1 } instance ToJSON Commit where toJSON = genericToJSON defaultOptions { fieldLabelModifier = drop 1 }
tomtau/travis
src/Travis/Types.hs
mit
3,381
0
10
1,312
593
358
235
75
0
----------------------------------------------------------------------------- -- | -- Module : Reactive.Banana.JsHs -- Copyright : (c) Artem Chirkin -- License : MIT -- -- Maintainer : Artem Chirkin <[email protected]> -- Stability : experimental -- -- ----------------------------------------------------------------------------- module Reactive.Banana.JsHs ( -- * Event handler for an html element module ElementHandler -- * Basic types , module Types ) where import Reactive.Banana.JsHs.ElementHandler as ElementHandler import Reactive.Banana.JsHs.Types as Types
mb21/qua-kit
libs/hs/reactive-banana-ghcjs/src/Reactive/Banana/JsHs.hs
mit
615
0
4
107
48
39
9
6
0
{-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} -- | Block processing related workers. module Pos.Worker.Block ( blkWorkers ) where import Universum import Control.Lens (ix) import qualified Data.List.NonEmpty as NE import Data.Time.Units (Microsecond, Second, fromMicroseconds) import Formatting (Format, bprint, build, fixed, int, now, sformat, shown, (%)) import qualified Prelude import Serokell.Util (enumerate, listJson, pairF) import qualified System.Metrics.Label as Label import System.Random (randomRIO) import Pos.Chain.Block (BlockHeader (..), HasBlockConfiguration, blockHeaderHash, criticalCQ, criticalCQBootstrap, fixedTimeCQSec, gbHeader, lsiFlatSlotId, networkDiameter, nonCriticalCQ, nonCriticalCQBootstrap, scCQFixedMonitorState, scCQOverallMonitorState, scCQkMonitorState, scCrucialValuesLabel, scDifficultyMonitorState, scEpochMonitorState, scGlobalSlotMonitorState, scLocalSlotMonitorState) import qualified Pos.Chain.Block.Slog.LastBlkSlots as LastBlkSlots import Pos.Chain.Delegation (ProxySKBlockInfo) import Pos.Chain.Genesis as Genesis (Config (..), configBlkSecurityParam, configEpochSlots, configSlotSecurityParam) import Pos.Chain.Txp (TxpConfiguration) import Pos.Chain.Update (BlockVersionData (..), ConsensusEra (..)) import Pos.Core (BlockCount, ChainDifficulty, EpochIndex (..), FlatSlotId, SlotCount, SlotId (..), Timestamp (Timestamp), addressHash, difficultyL, epochIndexL, epochOrSlotToSlot, flattenSlotId, getEpochOrSlot, getOurPublicKey, getSlotIndex, kEpochSlots, localSlotIndexFromEnum, localSlotIndexMinBound, slotIdF, slotIdSucc, unflattenSlotId) import Pos.Core.Chrono (NewestFirst (..), OldestFirst (..)) import Pos.Core.Conc (delay) import Pos.Core.JsonLog (CanJsonLog (..)) import Pos.Core.Reporting (HasMisbehaviorMetrics, MetricMonitor (..), MetricMonitorState, noReportMonitor, recordValue) import Pos.Crypto (ProxySecretKey (pskDelegatePk)) import Pos.DB (gsIsBootstrapEra) import Pos.DB.Block (calcChainQualityFixedTime, calcChainQualityM, calcOverallChainQuality, createGenesisBlockAndApply, createMainBlockAndApply, getBlund, lrcSingleShot, normalizeMempool, rollbackBlocks, slogGetLastBlkSlots) import qualified Pos.DB.BlockIndex as DB import Pos.DB.Delegation (getDlgTransPsk, getPskByIssuer) import qualified Pos.DB.Lrc as LrcDB (getLeadersForEpoch) import Pos.DB.Lrc.OBFT (getSlotLeaderObft) import Pos.DB.Update (getAdoptedBVData, getConsensusEra) import Pos.Infra.Diffusion.Types (Diffusion) import qualified Pos.Infra.Diffusion.Types as Diffusion (Diffusion (announceBlockHeader)) import Pos.Infra.Recovery.Info (getSyncStatus, needTriggerRecovery, recoveryCommGuard) import Pos.Infra.Reporting (reportOrLogE) import Pos.Infra.Slotting (ActionTerminationPolicy (..), OnNewSlotParams (..), currentTimeSlotting, defaultOnNewSlotParams, getSlotStartEmpatically, onNewSlot) import Pos.Infra.Util.JsonLog.Events (jlCreatedBlock) import Pos.Infra.Util.LogSafe (logDebugS, logInfoS, logWarningS) import Pos.Infra.Util.TimeLimit (logWarningSWaitLinear) import Pos.Network.Block.Logic (triggerRecovery) import Pos.Network.Block.Retrieval (retrievalWorker) import Pos.Network.Block.WorkMode (BlockWorkMode) import Pos.Util.Wlog (logDebug, logError, logInfo, logWarning) ---------------------------------------------------------------------------- -- All workers ---------------------------------------------------------------------------- -- | All workers specific to block processing. blkWorkers :: ( BlockWorkMode ctx m , HasMisbehaviorMetrics ctx ) => Genesis.Config -> TxpConfiguration -> [ (Text, Diffusion m -> m ()) ] blkWorkers genesisConfig txpConfig = [ ("block creator", blkCreatorWorker genesisConfig txpConfig) , ("block informer", informerWorker $ configBlkSecurityParam genesisConfig) , ("block retrieval", retrievalWorker genesisConfig txpConfig) , ("block recovery trigger", recoveryTriggerWorker genesisConfig) ] informerWorker :: BlockWorkMode ctx m => BlockCount -> Diffusion m -> m () informerWorker k _ = onNewSlot epochSlots defaultOnNewSlotParams $ \slotId -> recoveryCommGuard k "onNewSlot worker, informerWorker" $ do tipHeader <- DB.getTipHeader -- Printe tip header logDebug $ sformat ("Our tip header: "%build) tipHeader -- Print the difference between tip slot and current slot. logHowManySlotsBehind slotId tipHeader -- Compute and report metrics metricWorker k slotId where epochSlots = kEpochSlots k logHowManySlotsBehind slotId tipHeader = let tipSlot = epochOrSlotToSlot (getEpochOrSlot tipHeader) slotDiff = flattenSlotId epochSlots slotId - flattenSlotId epochSlots tipSlot in logInfo $ sformat ("Difference between current slot and tip slot is: " %int) slotDiff ---------------------------------------------------------------------------- -- Block creation worker ---------------------------------------------------------------------------- blkCreatorWorker :: ( BlockWorkMode ctx m , HasMisbehaviorMetrics ctx ) => Genesis.Config -> TxpConfiguration -> Diffusion m -> m () blkCreatorWorker genesisConfig txpConfig diffusion = onNewSlot (configEpochSlots genesisConfig) onsp $ \slotId -> recoveryCommGuard (configBlkSecurityParam genesisConfig) "onNewSlot worker, blkCreatorWorker" $ blockCreator genesisConfig txpConfig slotId diffusion `catchAny` onBlockCreatorException where onBlockCreatorException = reportOrLogE "blockCreator failed: " onsp :: OnNewSlotParams onsp = defaultOnNewSlotParams {onspTerminationPolicy = NewSlotTerminationPolicy "block creator"} blockCreator :: ( BlockWorkMode ctx m , HasMisbehaviorMetrics ctx ) => Genesis.Config -> TxpConfiguration -> SlotId -> Diffusion m -> m () blockCreator genesisConfig txpConfig slotId diffusion = do era <- getConsensusEra case era of Original -> blockCreatorOriginal genesisConfig txpConfig slotId diffusion OBFT _ -> do tipHeader <- DB.getTipHeader whenEpochBoundaryObft (siEpoch slotId) tipHeader (\ei -> do logDebug $ "blockCreator OBFT: running lrcSingleShot" lrcSingleShot genesisConfig ei) dropObftEbb genesisConfig txpConfig blockCreatorObft genesisConfig txpConfig slotId diffusion where whenEpochBoundaryObft :: ( Applicative m ) => EpochIndex -> BlockHeader -> (EpochIndex -> m ()) -> m () whenEpochBoundaryObft currentEpoch tipHeader actn = do case tipHeader of BlockHeaderGenesis _ -> pass BlockHeaderMain mb -> if mb ^. epochIndexL /= currentEpoch - 1 then pass else actn currentEpoch blockCreatorObft :: ( BlockWorkMode ctx m ) => Genesis.Config -> TxpConfiguration -> SlotId -> Diffusion m -> m () blockCreatorObft genesisConfig txpConfig (slotId@SlotId {..}) diffusion = do (leader, pske) <- getSlotLeaderObft genesisConfig slotId ourPk <- getOurPublicKey let ourPkHash = addressHash ourPk finalHeavyPsk = fst <$> pske let weAreLeader = leader == ourPkHash weAreHeavyDelegate = maybe False ((== ourPk) . pskDelegatePk) finalHeavyPsk when (weAreLeader || weAreHeavyDelegate) $ onNewSlotWhenLeader genesisConfig txpConfig slotId pske diffusion dropObftEbb :: forall ctx m. ( BlockWorkMode ctx m ) => Genesis.Config -> TxpConfiguration -> m () dropObftEbb genesisConfig txpConfig = do -- not sure if everything needs to run inside StateLock tipHeader <- DB.getTipHeader case tipHeader of BlockHeaderMain _ -> pure () BlockHeaderGenesis _ -> do mbEbbBlund <- getBlund (configGenesisHash genesisConfig) (blockHeaderHash tipHeader) case mbEbbBlund of Nothing -> Prelude.error "Pos.Worker.Block.dropObftEbb: unable to get blund for EBB" Just ebbBlund -> do rollbackBlocks genesisConfig $ NewestFirst (ebbBlund :| []) normalizeMempool genesisConfig txpConfig blockCreatorOriginal :: ( BlockWorkMode ctx m , HasMisbehaviorMetrics ctx ) => Genesis.Config -> TxpConfiguration -> SlotId -> Diffusion m -> m () blockCreatorOriginal genesisConfig txpConfig (slotId@SlotId {..}) diffusion = do -- First of all we create genesis block if necessary. mGenBlock <- createGenesisBlockAndApply genesisConfig txpConfig siEpoch -- the ConsensusEra could've changed due to to this -- call trace (thing above calls thing below): -- blockCreatorOriginal -- -> createGenesisBlockAndApply -- -> createGenesisBlockDo -- -> verifyBlocksPrefix -- -> usVerifyBlocks -- -> verifyBlock -- -> processGenesisBlock -- -> adoptBlockVersion era <- getConsensusEra case era of -- If the ConsensusEra has changed due to `createGenesisBlockAndApply` -- being run, then we want to switch over to `blockCreatorObft`, while -- running the logic which precedes its call in `blockCreator`. -- So we just re-enter `blockCreator`. OBFT _ -> blockCreator genesisConfig txpConfig slotId diffusion Original -> do whenJust mGenBlock $ \createdBlk -> do logInfo $ sformat ("Created genesis block:\n" %build) createdBlk jsonLog $ jlCreatedBlock (configEpochSlots genesisConfig) (Left createdBlk) -- Then we get leaders for current epoch. leadersMaybe <- LrcDB.getLeadersForEpoch siEpoch case leadersMaybe of -- If we don't know leaders, we can't do anything. Nothing -> logWarning "Leaders are not known for new slot" -- If we know leaders, we check whether we are leader and -- create a new block if we are. We also create block if we -- have suitable PSK. Just leaders -> maybe onNoLeader (onKnownLeader leaders) (leaders ^? ix (fromIntegral $ getSlotIndex siSlot)) where onNoLeader = logError "Couldn't find a leader for current slot among known ones" logOnEpochFS = if siSlot == localSlotIndexMinBound then logInfoS else logDebugS logOnEpochF = if siSlot == localSlotIndexMinBound then logInfo else logDebug onKnownLeader leaders leader = do ourPk <- getOurPublicKey let ourPkHash = addressHash ourPk logOnEpochFS $ sformat ("Our pk: "%build%", our pkHash: "%build) ourPk ourPkHash logOnEpochF $ sformat ("Current slot leader: "%build) leader let -- position, how many to drop, list. This is to show some -- of leaders before and after current slot, but not all -- of them. dropAround :: Int -> Int -> [a] -> [a] dropAround p s = take (2*s + 1) . drop (max 0 (p - s)) strLeaders = map (bprint pairF) (enumerate @Int (toList leaders)) logDebug $ sformat ("Trimmed leaders: "%listJson) $ dropAround (localSlotIndexFromEnum siSlot) 10 strLeaders ourHeavyPsk <- getPskByIssuer (Left ourPk) let heavyWeAreIssuer = isJust ourHeavyPsk dlgTransM <- getDlgTransPsk leader let finalHeavyPsk = snd <$> dlgTransM logDebug $ "End delegation psk for this slot: " <> maybe "none" pretty finalHeavyPsk let heavyWeAreDelegate = maybe False ((== ourPk) . pskDelegatePk) finalHeavyPsk let weAreLeader = leader == ourPkHash if | weAreLeader && heavyWeAreIssuer -> logInfoS $ sformat ("Not creating the block (though we're leader) because it's "% "delegated by heavy psk: "%build) ourHeavyPsk | weAreLeader -> onNewSlotWhenLeader genesisConfig txpConfig slotId Nothing diffusion | heavyWeAreDelegate -> let pske = swap <$> dlgTransM in onNewSlotWhenLeader genesisConfig txpConfig slotId pske diffusion | otherwise -> pass onNewSlotWhenLeader :: BlockWorkMode ctx m => Genesis.Config -> TxpConfiguration -> SlotId -> ProxySKBlockInfo -> Diffusion m -> m () onNewSlotWhenLeader genesisConfig txpConfig slotId pske diffusion = do let logReason = sformat ("I have a right to create a block for the slot "%slotIdF%" ") slotId logLeader = "because i'm a leader" logCert (psk,_) = sformat ("using heavyweight proxy signature key "%build%", will do it soon") psk logInfoS $ logReason <> maybe logLeader logCert pske nextSlotStart <- getSlotStartEmpatically (slotIdSucc (configEpochSlots genesisConfig) slotId) currentTime <- currentTimeSlotting let timeToCreate = max currentTime (nextSlotStart - Timestamp networkDiameter) Timestamp timeToWait = timeToCreate - currentTime logInfoS $ sformat ("Waiting for "%shown%" before creating block") timeToWait delay timeToWait logWarningSWaitLinear 8 "onNewSlotWhenLeader" onNewSlotWhenLeaderDo where onNewSlotWhenLeaderDo = do logInfoS "It's time to create a block for current slot" createdBlock <- createMainBlockAndApply genesisConfig txpConfig slotId pske logInfoS "Created block for current slot" either whenNotCreated whenCreated createdBlock logInfoS "onNewSlotWhenLeader: done" whenCreated createdBlk = do logInfoS $ sformat ("Created a new block:\n" %build) createdBlk jsonLog $ jlCreatedBlock (configEpochSlots genesisConfig) (Right createdBlk) void $ Diffusion.announceBlockHeader diffusion $ createdBlk ^. gbHeader whenNotCreated = logWarningS . (mappend "I couldn't create a new block: ") ---------------------------------------------------------------------------- -- Recovery trigger worker ---------------------------------------------------------------------------- recoveryTriggerWorker :: forall ctx m. ( BlockWorkMode ctx m ) => Genesis.Config -> Diffusion m -> m () recoveryTriggerWorker genesisConfig diffusion = do -- Initial heuristic delay is needed (the system takes some time -- to initialize). -- TBD why 3 seconds? Why delay at all? Come on, we can do better. delay (3 :: Second) repeatOnInterval $ do doTrigger <- needTriggerRecovery <$> getSyncStatus epochSlots (configSlotSecurityParam genesisConfig) when doTrigger $ do logInfo "Triggering recovery because we need it" triggerRecovery genesisConfig diffusion -- Sometimes we want to trigger recovery just in case. Maybe -- we're just 5 slots late, but nobody wants to send us -- blocks. It may happen sometimes, because nobody actually -- guarantees that node will get updates on time. So we -- sometimes ask for tips even if we're in relatively safe -- situation. (d :: Double) <- liftIO $ randomRIO (0,1) -- P = 0.004 ~ every 250th time (250 seconds ~ every 4.2 minutes) let triggerSafety = not doTrigger && d < 0.004 when triggerSafety $ do logInfo "Checking if we need recovery as a safety measure" whenM (needTriggerRecovery <$> getSyncStatus epochSlots 5) $ do logInfo "Triggering recovery as a safety measure" triggerRecovery genesisConfig diffusion -- We don't want to ask for tips too frequently. -- E.g. there may be a tip processing mistake so that we -- never go into recovery even though we recieve -- headers. Or it may happen that we will receive only -- useless broken tips for some reason (attack?). This -- will minimize risks and network load. when (doTrigger || triggerSafety) $ delay (20 :: Second) where epochSlots = configEpochSlots genesisConfig repeatOnInterval action = void $ do delay (1 :: Second) -- REPORT:ERROR 'reportOrLogE' in recovery trigger worker void $ action `catchAny` \e -> do reportOrLogE "recoveryTriggerWorker" e delay (15 :: Second) repeatOnInterval action ---------------------------------------------------------------------------- -- Metric worker ---------------------------------------------------------------------------- -- This worker computes various metrics and records them using 'MetricMonitor'. -- -- Chain quality checker should be called only when we are -- synchronized with the network. The goal of this checker is not to -- detect violation of chain quality assumption, but to produce -- warnings when this assumption is close to being violated. -- -- Apart from chain quality check we also record some generally useful values. metricWorker :: BlockWorkMode ctx m => BlockCount -> SlotId -> m () metricWorker k curSlot = do lastSlots <- LastBlkSlots.lbsList <$> slogGetLastBlkSlots reportTotalBlocks reportSlottingData (kEpochSlots k) curSlot reportCrucialValues k -- If total number of blocks is less than `blkSecurityParam' we do -- nothing with regards to chain quality for two reasons: -- 1. Usually after we deploy cluster we monitor it manually for a while. -- 2. Sometimes we deploy after start time, so chain quality may indeed by -- poor right after launch. case nonEmpty (getOldestFirst lastSlots) of Nothing -> pass Just slotsNE | length slotsNE < fromIntegral k -> pass | otherwise -> chainQualityChecker k curSlot (lsiFlatSlotId $ NE.head slotsNE) ---------------------------------------------------------------------------- -- -- General metrics ---------------------------------------------------------------------------- reportTotalBlocks :: forall ctx m. BlockWorkMode ctx m => m () reportTotalBlocks = do difficulty <- view difficultyL <$> DB.getTipHeader monitor <- difficultyMonitor <$> view scDifficultyMonitorState recordValue monitor difficulty -- We don't need debug messages, we can see it from other messages. difficultyMonitor :: MetricMonitorState ChainDifficulty -> MetricMonitor ChainDifficulty difficultyMonitor = noReportMonitor fromIntegral Nothing reportSlottingData :: BlockWorkMode ctx m => SlotCount -> SlotId -> m () reportSlottingData epochSlots slotId = do -- epoch let epoch = siEpoch slotId epochMonitor <- noReportMonitor fromIntegral Nothing <$> view scEpochMonitorState recordValue epochMonitor epoch -- local slot let localSlot = siSlot slotId localSlotMonitor <- noReportMonitor (fromIntegral . getSlotIndex) Nothing <$> view scLocalSlotMonitorState recordValue localSlotMonitor localSlot -- global slot let globalSlot = flattenSlotId epochSlots slotId globalSlotMonitor <- noReportMonitor fromIntegral Nothing <$> view scGlobalSlotMonitorState recordValue globalSlotMonitor globalSlot reportCrucialValues :: BlockWorkMode ctx m => BlockCount -> m () reportCrucialValues k = do label <- view scCrucialValuesLabel BlockVersionData {..} <- getAdoptedBVData let slotDur = bvdSlotDuration let epochDur = fromIntegral (kEpochSlots k) * slotDur let crucialValuesText = sformat crucialValuesFmt slotDur epochDur k liftIO $ Label.set label crucialValuesText where crucialValuesFmt = "slot duration: " %build % ", epoch duration: " %build % ", k: " %int ---------------------------------------------------------------------------- -- -- Chain quality ---------------------------------------------------------------------------- chainQualityChecker :: ( BlockWorkMode ctx m ) => BlockCount -> SlotId -> FlatSlotId -> m () chainQualityChecker k curSlot kThSlot = do logDebug $ sformat ("Block with depth 'k' ("%int% ") was created during slot "%slotIdF) k (unflattenSlotId epochSlots kThSlot) let curFlatSlot = flattenSlotId epochSlots curSlot isBootstrapEra <- gsIsBootstrapEra (siEpoch curSlot) monitorStateK <- view scCQkMonitorState let monitorK = cqkMetricMonitor k monitorStateK isBootstrapEra monitorOverall <- cqOverallMetricMonitor <$> view scCQOverallMonitorState monitorFixed <- cqFixedMetricMonitor <$> view scCQFixedMonitorState whenJustM (calcChainQualityM k curFlatSlot) (recordValue monitorK) whenJustM (calcOverallChainQuality epochSlots) $ recordValue monitorOverall whenJustM (calcChainQualityFixedTime epochSlots) $ recordValue monitorFixed where epochSlots = kEpochSlots k -- Monitor for chain quality for last k blocks. cqkMetricMonitor :: HasBlockConfiguration => BlockCount -> MetricMonitorState Double -> Bool -> MetricMonitor Double cqkMetricMonitor k st isBootstrapEra = MetricMonitor { mmState = st , mmReportMisbehaviour = classifier , mmMisbehFormat = "Poor chain quality for the last 'k' ("%kFormat%") blocks, "% "less than "%now (bprint cqF criticalThreshold)%": "%cqF , mmDebugFormat = Just $ "Chain quality for the last 'k' ("%kFormat% ") blocks is "%cqF , mmConvertValue = convertCQ } where classifier :: Microsecond -> Maybe Double -> Double -> Maybe Bool classifier timePassed prevVal newVal -- report at most once per 400 sec, unless decreased | not decreased && timePassed < fromMicroseconds 400000000 = Nothing | newVal < criticalThreshold = Just True | newVal < nonCriticalThreshold = Just False | otherwise = Nothing where decreased = maybe False (newVal <) prevVal criticalThreshold | isBootstrapEra = criticalCQBootstrap | otherwise = criticalCQ nonCriticalThreshold | isBootstrapEra = nonCriticalCQBootstrap | otherwise = nonCriticalCQ -- Can be used to insert the value of 'blkSecurityParam' into a 'Format'. kFormat :: Format r r kFormat = now (bprint int k) cqOverallMetricMonitor :: MetricMonitorState Double -> MetricMonitor Double cqOverallMetricMonitor = noReportMonitor convertCQ (Just debugFormat) where debugFormat = "Overall chain quality is " %cqF cqFixedMetricMonitor :: HasBlockConfiguration => MetricMonitorState Double -> MetricMonitor Double cqFixedMetricMonitor = noReportMonitor convertCQ (Just debugFormat) where debugFormat = "Chain quality for last "%now (bprint build fixedTimeCQSec)% " is "%cqF -- Private chain quality formatter. cqF :: Format r (Double -> r) cqF = fixed 3 -- Private converter to integer. convertCQ :: Double -> Int64 convertCQ = round . (* 100)
input-output-hk/pos-haskell-prototype
lib/src/Pos/Worker/Block.hs
mit
24,385
0
21
6,512
4,561
2,367
2,194
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} module Bot.GameAPI ( getKills , GameEvent (..) , Character (..) , Event (..) ) where import Control.Applicative import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Either import Data.Aeson import Data.Aeson.Types import qualified Data.Attoparsec.ByteString.Char8 as A import Data.Either import Data.Maybe import Data.Monoid import Data.Proxy import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import GHC.Generics import Servant.API import Servant.Client -- API definition type AchaeaAPI = "characters.json" :> Get '[JSON] Online :<|> "characters" :> Capture "name" Text :> Get '[JSON] Character :<|> "gamefeed.json" :> QueryParam "id" Int :> Get '[JSON] [Event] achaeaAPI :: Proxy AchaeaAPI achaeaAPI = Proxy getOnline :: EitherT ServantError IO Online getCharacter' :: Text -> EitherT ServantError IO Character getCharacter :: Text -> EitherT ServantError IO Character getCharacter char = getCharacter' $ char `T.append` ".json" gameFeed :: Maybe Int -> EitherT ServantError IO [Event] getOnline :<|> getCharacter' :<|> gameFeed = client achaeaAPI (BaseUrl Http "api.achaea.com" 80) data Online = Online { count :: Int , characters :: [Text] } deriving (Show) instance FromJSON Online where parseJSON (Object o) = do count <- read <$> o .: "count" charInfo <- o .: "characters" let names = mapMaybe (parseMaybe $ \obj -> obj .: "name") charInfo return $ Online count names parseJSON _ = mempty data Character = Character { name :: Text , city :: Text --City , house :: Text , level :: Int , class_ :: Text --Class , playerKills :: Int } deriving (Show, Eq) -- TODO: handle city being (hidden) instance FromJSON Character where parseJSON (Object o) = do name <- o .: "name" city <- o .:? "city" .!= "(none)" house <- o .:? "house" .!= "(none)" level <- read <$> o .: "level" class_ <- o .: "class" playerKills <- read <$> o .: "player_kills" return $ Character name city house level class_ playerKills parseJSON _ = mempty data EventType = DEA | LUP | LDN | DUE | NEW | ARE deriving (Show, Read, Eq, Generic) instance FromJSON EventType data Event = Event { id_ :: Int , desc :: Text , type_ :: EventType , date :: Text } deriving (Show, Eq) instance FromJSON Event where parseJSON (Object o) = do id_ <- o .: "id" desc <- o .: "description" type_ <- o .: "type" date <- o .: "date" return $ Event id_ desc type_ date parseJSON _ = mempty data GameEvent = GameEvent { details :: Event , killer :: Character , victim :: Character } deriving (Show, Eq) getKills :: Maybe Int -> IO (Maybe [GameEvent]) getKills id_ = do feed <- runEitherT $ gameFeed id_ case feed of Right goodData -> do evts <- liftM catMaybes . sequence $ map makeGameEvent (onlyDeaths goodData) return . Just $ evts Left str -> do return Nothing where onlyDeaths = filter (\evt -> type_ evt == DEA) makeGameEvent :: Event -> IO (Maybe GameEvent) makeGameEvent evt = do k <- getKInfo evt v <- getVInfo evt case (k, v) of (Just k', Just v') -> return . Just $ GameEvent evt k' v' _ -> return Nothing getKInfo = getCharInfo extractKiller getVInfo = getCharInfo extractVictim getCharInfo :: (Event -> Maybe Text) -> Event -> IO (Maybe Character) getCharInfo f evt = case f evt of Nothing -> return Nothing Just validName -> do info <- runEitherT $ getCharacter validName case info of Left _ -> return Nothing Right validInfo -> return $ Just validInfo extractKiller = getNameFromEvent fst extractVictim = getNameFromEvent snd getNameFromEvent :: ((Text, Text) -> a) -> Event -> Maybe a getNameFromEvent f evt = case runParser evt of Left _ -> Nothing Right validParse -> Just (f validParse) runParser :: Event -> Either String (Text, Text) runParser = A.parseOnly parsePlayers . T.encodeUtf8 . desc parsePlayers :: A.Parser (Text, Text) parsePlayers = do victim <- name A.space A.string "was slain by" A.space killer <- name A.char '.' case killer of "misadventure" -> fail "not a player" _ -> return $ mapTuple T.pack (killer, victim) where mapTuple f (a,b) = (f a, f b) name = A.many1 A.letter_ascii
narrative/achaeabot
src/Bot/GameAPI.hs
mit
5,010
0
16
1,505
1,544
803
741
134
3
{-# htermination (toEnumChar :: MyInt -> Char) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data Char = Char MyInt ; data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; primIntToChar :: MyInt -> Char; primIntToChar x = Char x; toEnumChar :: MyInt -> Char toEnumChar = primIntToChar;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/toEnum_4.hs
mit
360
0
8
84
112
66
46
10
1
import Classifier.NBClassifier call:: String -> IO () call file = do classifier <- buildNBClassifier file case classifier of Right a -> do putStrLn "\nHeader\n" print $ fst a putStrLn "\nData\n" print $ snd a Left a -> putStrLn a return ()
anirudhhkumarr/ml-lib
Examples/printData.hs
gpl-2.0
509
0
13
310
110
46
64
13
2
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, PatternGuards #-} {- Copyright (C) 2006-2014 John MacFarlane <[email protected]> Copyright (C) 2014 Tim T.Y. Lin <[email protected]> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Writers.LaTeX Copyright : Copyright (C) 2006-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable Conversion of 'Pandoc' format into LaTeX. -} module Text.Pandoc.Writers.LaTeX ( writeLaTeX ) where import Text.Pandoc.Definition import Text.Pandoc.Walk import Text.Pandoc.Shared import Text.Pandoc.Writers.Shared import Text.Pandoc.Options import Text.Pandoc.Scholarly import Text.Pandoc.Templates import Text.Printf ( printf ) import Network.URI ( isURI, unEscapeString ) import System.FilePath ( dropExtension ) import Data.List ( (\\), isSuffixOf, isInfixOf, stripPrefix, isPrefixOf, intercalate, intersperse ) import Data.Char ( toLower, isPunctuation, isAscii, isLetter, isDigit, ord ) import Data.Maybe ( fromMaybe , isJust, fromJust ) import qualified Data.Map as M import Control.Applicative ((<|>)) import Control.Monad.State import Text.Pandoc.Pretty import Text.Pandoc.Slides import Text.Pandoc.Highlighting (highlight, styleToLaTeX, formatLaTeXInline, formatLaTeXBlock, toListingsLanguage) data WriterState = WriterState { stInNote :: Bool -- true if we're in a note , stInQuote :: Bool -- true if in a blockquote , stInMinipage :: Bool -- true if in minipage , stInHeading :: Bool -- true if in a section heading , stNotes :: [Doc] -- notes in a minipage , stOLLevel :: Int -- level of ordered list nesting , stOptions :: WriterOptions -- writer options, so they don't have to be parameter , stVerbInNote :: Bool -- true if document has verbatim text in note , stTable :: Bool -- true if document has a table , stStrikeout :: Bool -- true if document has strikeout , stUrl :: Bool -- true if document has visible URL link , stGraphics :: Bool -- true if document contains images , stFloats :: Bool -- true if document contains floats , stSubfigs :: Bool -- true if document contains subfigures , stAlgorithms :: Bool -- true if document contains algorithm floats , stLHS :: Bool -- true if document has literate haskell code , stBook :: Bool -- true if document uses book or memoir class , stLevelZero :: Bool -- true if document contains H1 treated as part or chapter , stCsquotes :: Bool -- true if document uses csquotes , stHighlighting :: Bool -- true if document has highlighted code , stIncremental :: Bool -- true if beamer lists should be displayed bit by bit , stInternalLinks :: [String] -- list of internal link targets , stUsesEuro :: Bool -- true if euro symbol used , stMathIds :: [String] -- list of math identifiers, , stLastHeight :: Maybe String -- last img height value , stLastWidth :: Maybe String -- last img width value } -- | Convert Pandoc to LaTeX. writeLaTeX :: WriterOptions -> Pandoc -> String writeLaTeX options document = evalState (pandocToLaTeX options document) $ WriterState { stInNote = False, stInQuote = False, stInMinipage = False, stInHeading = False, stNotes = [], stOLLevel = 1, stOptions = options, stVerbInNote = False, stTable = False, stStrikeout = False, stUrl = False, stGraphics = False, stFloats = False, stSubfigs = False, stAlgorithms = False, stLHS = False, stBook = writerBook options, stLevelZero = False, stCsquotes = False, stHighlighting = False, stIncremental = writerIncremental options, stInternalLinks = [], stUsesEuro = False, stMathIds = [], stLastHeight = Nothing, stLastWidth = Nothing } pandocToLaTeX :: WriterOptions -> Pandoc -> State WriterState String pandocToLaTeX options (Pandoc meta blocks) = do -- Strip off final 'references' header if --natbib or --biblatex let method = writerCiteMethod options let blocks' = if method == Biblatex || method == Natbib then case reverse blocks of (Div (_,["references"],_) _):xs -> reverse xs _ -> blocks else blocks -- see if there are internal links let isInternalLink (Link _ ('#':xs,_)) = [xs] isInternalLink _ = [] modify $ \s -> s{ stInternalLinks = query isInternalLink blocks' } -- see if there are images let isGraphic (Image _ _ _) = [True] isGraphic _ = [] modify $ \s -> s{ stGraphics = not $ null $ query isGraphic blocks' } let template = writerTemplate options -- set stBook depending on documentclass let bookClasses = ["memoir","book","report","scrreprt","scrbook"] case lookup "documentclass" (writerVariables options) of Just x | x `elem` bookClasses -> modify $ \s -> s{stBook = True} | otherwise -> return () Nothing | any (\x -> "\\documentclass" `isPrefixOf` x && (any (`isSuffixOf` x) bookClasses)) (lines template) -> modify $ \s -> s{stBook = True} | otherwise -> return () -- check for \usepackage...{csquotes}; if present, we'll use -- \enquote{...} for smart quotes: when ("{csquotes}" `isInfixOf` template) $ modify $ \s -> s{stCsquotes = True} let colwidth = if writerWrapText options then Just $ writerColumns options else Nothing metadata <- metaToJSON options (fmap (render colwidth) . blockListToLaTeX) (fmap (render colwidth) . inlineListToLaTeX) meta initSt <- get let mathIds = extractMetaStringList $ lookupMeta "identifiersForMath" meta put initSt{ stMathIds = mathIds } let mathDefs = lookupMeta "latexMacrosForMath" meta let (blocks'', lastHeader) = if writerCiteMethod options == Citeproc then (blocks', []) else case last blocks' of Header 2 _ il | writerChapters options && writerScholarly options -> (init blocks', il) Header 1 _ il -> (init blocks', il) _ -> (blocks', []) blocks''' <- if writerBeamer options then toSlides blocks'' else return blocks'' body <- mapM (elementToLaTeX options) $ hierarchicalize blocks''' (biblioTitle :: String) <- liftM (render colwidth) $ inlineListToLaTeX lastHeader let biblioFiles = extractMetaStringList $ lookupMeta "bibliography" meta let main = render colwidth $ vsep body st <- get titleMeta <- stringToLaTeX TextString $ stringify $ docTitle meta authorsMeta <- mapM (stringToLaTeX TextString . stringify) $ docAuthors meta let numberPartsChap = stBook st -- possibly implement override in the future let context = defField "toc" (writerTableOfContents options) $ defField "toc-depth" (show (writerTOCDepth options - if stLevelZero st then 1 else 0)) $ defField "body" main $ defField "title-meta" titleMeta $ defField "author-meta" (intercalate "; " authorsMeta) $ defField "documentclass" (if writerBeamer options then ("beamer" :: String) else if stBook st then "book" else "article") $ defField "verbatim-in-note" (stVerbInNote st) $ defField "tables" (stTable st) $ defField "strikeout" (stStrikeout st) $ defField "url" (stUrl st) $ defField "numbersections" (writerNumberSections options) $ -- the above implies the following defField "numberparts-and-chapters" numberPartsChap $ defField "lhs" (stLHS st) $ defField "graphics" (stGraphics st) $ defField "floats" (stFloats st) $ defField "subfigures" (stSubfigs st) $ defField "algorithms" (stAlgorithms st) $ defField "book-class" (stBook st) $ defField "euro" (stUsesEuro st) $ defField "listings" (writerListings options || writerScholarly options || stLHS st ) $ defField "beamer" (writerBeamer options) $ defField "mainlang" (maybe "" (reverse . takeWhile (/=',') . reverse) (lookup "lang" $ writerVariables options)) $ (if isJust mathDefs then defField "math-macros" (extractMetaString $ fromJust mathDefs) else id) $ (if stHighlighting st then defField "highlighting-macros" (styleToLaTeX $ writerHighlightStyle options ) else id) $ (case writerCiteMethod options of Natbib -> defField "biblio-title" biblioTitle . defField "biblio-files" (intercalate "," $ map dropExtension $ biblioFiles) . defField "natbib" True Biblatex -> defField "biblio-title" biblioTitle . defField "biblio-files" (intercalate "," biblioFiles) . defField "biblatex" True _ -> id) $ metadata return $ if writerStandalone options then renderTemplate' template context else main -- | Convert Elements to LaTeX elementToLaTeX :: WriterOptions -> Element -> State WriterState Doc elementToLaTeX _ (Blk block) = blockToLaTeX block elementToLaTeX opts (Sec level _ (id',classes,_) title' elements) = do modify $ \s -> s{stInHeading = True} header' <- sectionHeader ("unnumbered" `elem` classes) id' level title' modify $ \s -> s{stInHeading = False} innerContents <- mapM (elementToLaTeX opts) elements return $ vsep (header' : innerContents) data StringContext = TextString | URLString | CodeString deriving (Eq) -- escape things as needed for LaTeX stringToLaTeX :: StringContext -> String -> State WriterState String stringToLaTeX _ [] = return "" stringToLaTeX ctx (x:xs) = do opts <- gets stOptions rest <- stringToLaTeX ctx xs let ligatures = writerTeXLigatures opts && ctx == TextString let isUrl = ctx == URLString when (x == '€') $ modify $ \st -> st{ stUsesEuro = True } return $ case x of '€' -> "\\euro{}" ++ rest '{' -> "\\{" ++ rest '}' -> "\\}" ++ rest '$' | not isUrl -> "\\$" ++ rest '%' -> "\\%" ++ rest '&' -> "\\&" ++ rest '_' | not isUrl -> "\\_" ++ rest '#' -> "\\#" ++ rest '-' | not isUrl -> case xs of -- prevent adjacent hyphens from forming ligatures ('-':_) -> "-\\/" ++ rest _ -> '-' : rest '~' | not isUrl -> "\\textasciitilde{}" ++ rest '^' -> "\\^{}" ++ rest '\\'| isUrl -> '/' : rest -- NB. / works as path sep even on Windows | otherwise -> "\\textbackslash{}" ++ rest '|' -> "\\textbar{}" ++ rest '<' -> "\\textless{}" ++ rest '>' -> "\\textgreater{}" ++ rest '[' -> "{[}" ++ rest -- to avoid interpretation as ']' -> "{]}" ++ rest -- optional arguments '\'' | ctx == CodeString -> "\\textquotesingle{}" ++ rest '\160' -> "~" ++ rest '\x2026' -> "\\ldots{}" ++ rest '\x2018' | ligatures -> "`" ++ rest '\x2019' | ligatures -> "'" ++ rest '\x201C' | ligatures -> "``" ++ rest '\x201D' | ligatures -> "''" ++ rest '\x2014' | ligatures -> "---" ++ rest '\x2013' | ligatures -> "--" ++ rest _ -> x : rest toLabel :: String -> State WriterState String toLabel z = go `fmap` stringToLaTeX URLString z where go [] = "" go (x:xs) | (isLetter x || isDigit x) && isAscii x = x:go xs | elem x ("-+=:;." :: String) = x:go xs | otherwise = "ux" ++ printf "%x" (ord x) ++ go xs -- | Puts contents into LaTeX command. inCmd :: String -> Doc -> Doc inCmd cmd contents = char '\\' <> text cmd <> braces contents toSlides :: [Block] -> State WriterState [Block] toSlides bs = do opts <- gets stOptions let slideLevel = fromMaybe (getSlideLevel bs) $ writerSlideLevel opts let bs' = prepSlides slideLevel bs concat `fmap` (mapM (elementToBeamer slideLevel) $ hierarchicalize bs') elementToBeamer :: Int -> Element -> State WriterState [Block] elementToBeamer _slideLevel (Blk b) = return [b] elementToBeamer slideLevel (Sec lvl _num (ident,classes,kvs) tit elts) | lvl > slideLevel = do bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ Para ( RawInline "latex" "\\begin{block}{" : tit ++ [RawInline "latex" "}"] ) : bs ++ [RawBlock "latex" "\\end{block}"] | lvl < slideLevel = do bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ (Header lvl (ident,classes,kvs) tit) : bs | otherwise = do -- lvl == slideLevel -- note: [fragile] is required or verbatim breaks let hasCodeBlock (CodeBlock _ _) = [True] hasCodeBlock _ = [] let hasCode (Code _ _) = [True] hasCode _ = [] opts <- gets stOptions let fragile = not $ null $ query hasCodeBlock elts ++ if writerListings opts then query hasCode elts else [] let allowframebreaks = "allowframebreaks" `elem` classes let optionslist = ["fragile" | fragile] ++ ["allowframebreaks" | allowframebreaks] let options = if null optionslist then "" else "[" ++ intercalate "," optionslist ++ "]" let slideStart = Para $ RawInline "latex" ("\\begin{frame}" ++ options) : if tit == [Str "\0"] -- marker for hrule then [] else (RawInline "latex" "{") : tit ++ [RawInline "latex" "}"] let slideEnd = RawBlock "latex" "\\end{frame}" -- now carve up slide into blocks if there are sections inside bs <- concat `fmap` mapM (elementToBeamer slideLevel) elts return $ slideStart : bs ++ [slideEnd] isListBlock :: Block -> Bool isListBlock (BulletList _) = True isListBlock (OrderedList _ _) = True isListBlock (DefinitionList _) = True isListBlock _ = False isLineBreakOrSpace :: Inline -> Bool isLineBreakOrSpace LineBreak = True isLineBreakOrSpace Space = True isLineBreakOrSpace _ = False -- | Convert Pandoc block element to LaTeX. blockToLaTeX :: Block -- ^ Block to convert -> State WriterState Doc blockToLaTeX Null = return empty blockToLaTeX (Div (identifier,classes,_) bs) = do beamer <- writerBeamer `fmap` gets stOptions ref <- toLabel identifier let linkAnchor = if null identifier then empty else "\\hyperdef{}" <> braces (text ref) <> "{}" contents <- blockListToLaTeX bs if beamer && "notes" `elem` classes -- speaker notes then return $ "\\note" <> braces contents else return (linkAnchor $$ contents) blockToLaTeX (Plain lst) = inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst -- title beginning with fig: indicates that the image is a figure -- the identifiers in attr will be lifted to the Figure block blockToLaTeX (Para [Image attr txt (src,'f':'i':'g':':':tit)]) = imageGridToLaTeX attr [ImageGrid [[Image attr [] (src,tit)]]] noPrepContent txt -- . . . indicates pause in beamer slides blockToLaTeX (Para [Str ".",Space,Str ".",Space,Str "."]) = do beamer <- writerBeamer `fmap` gets stOptions if beamer then blockToLaTeX (RawBlock "latex" "\\pause") else inlineListToLaTeX [Str ".",Space,Str ".",Space,Str "."] blockToLaTeX (Para lst) = inlineListToLaTeX $ dropWhile isLineBreakOrSpace lst blockToLaTeX (BlockQuote lst) = do beamer <- writerBeamer `fmap` gets stOptions case lst of [b] | beamer && isListBlock b -> do oldIncremental <- gets stIncremental modify $ \s -> s{ stIncremental = not oldIncremental } result <- blockToLaTeX b modify $ \s -> s{ stIncremental = oldIncremental } return result _ -> do oldInQuote <- gets stInQuote modify (\s -> s{stInQuote = True}) contents <- blockListToLaTeX lst modify (\s -> s{stInQuote = oldInQuote}) return $ "\\begin{quote}" $$ contents $$ "\\end{quote}" blockToLaTeX (CodeBlock (identifier,classes,keyvalAttr) str) = do opts <- gets stOptions ref <- toLabel identifier let linkAnchor = if null identifier then empty else "\\hyperdef{}" <> braces (text ref) <> braces ("\\label" <> braces (text ref)) let lhsCodeBlock = do modify $ \s -> s{ stLHS = True } return $ flush (linkAnchor $$ "\\begin{code}" $$ text str $$ "\\end{code}") $$ cr let rawCodeBlock = do st <- get env <- if stInNote st then modify (\s -> s{ stVerbInNote = True }) >> return "Verbatim" else return "verbatim" return $ flush (linkAnchor $$ text ("\\begin{" ++ env ++ "}") $$ text str $$ text ("\\end{" ++ env ++ "}")) <> cr let listingsCodeBlock = do st <- get let params = if writerListings (stOptions st) then (case getListingsLanguage classes of Just l -> [ "language=" ++ l ] Nothing -> []) ++ [ "numbers=left" | "numberLines" `elem` classes || "number" `elem` classes || "number-lines" `elem` classes ] ++ [ (if key == "startFrom" then "firstnumber" else key) ++ "=" ++ attr | (key,attr) <- keyvalAttr ] ++ (if identifier == "" then [] else [ "label=" ++ ref ]) else [] printParams | null params = empty | otherwise = brackets $ hcat (intersperse ", " (map text params)) return $ flush ("\\begin{lstlisting}" <> printParams $$ text str $$ "\\end{lstlisting}") $$ cr let highlightedCodeBlock = case highlight formatLaTeXBlock ("",classes,keyvalAttr) str of Nothing -> rawCodeBlock Just h -> modify (\st -> st{ stHighlighting = True }) >> return (flush $ linkAnchor $$ text h) case () of _ | isEnabled Ext_literate_haskell opts && "haskell" `elem` classes && "literate" `elem` classes -> lhsCodeBlock | writerListings opts -> listingsCodeBlock | writerHighlight opts && not (null classes) -> highlightedCodeBlock | otherwise -> rawCodeBlock blockToLaTeX (RawBlock f x) | f == Format "latex" || f == Format "tex" = return $ text x | otherwise = return empty blockToLaTeX (BulletList []) = return empty -- otherwise latex error blockToLaTeX (BulletList lst) = do incremental <- gets stIncremental let inc = if incremental then "[<+->]" else "" items <- mapM listItemToLaTeX lst let spacing = if isTightList lst then text "\\itemsep1pt\\parskip0pt\\parsep0pt" else empty return $ text ("\\begin{itemize}" ++ inc) $$ spacing $$ vcat items $$ "\\end{itemize}" blockToLaTeX (OrderedList _ []) = return empty -- otherwise latex error blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do st <- get let inc = if stIncremental st then "[<+->]" else "" let oldlevel = stOLLevel st put $ st {stOLLevel = oldlevel + 1} items <- mapM listItemToLaTeX lst modify (\s -> s {stOLLevel = oldlevel}) let tostyle x = case numstyle of Decimal -> "\\arabic" <> braces x UpperRoman -> "\\Roman" <> braces x LowerRoman -> "\\roman" <> braces x UpperAlpha -> "\\Alph" <> braces x LowerAlpha -> "\\alph" <> braces x Example -> "\\arabic" <> braces x DefaultStyle -> "\\arabic" <> braces x let todelim x = case numdelim of OneParen -> x <> ")" TwoParens -> parens x Period -> x <> "." _ -> x <> "." let enum = text $ "enum" ++ map toLower (toRomanNumeral oldlevel) let stylecommand = if numstyle == DefaultStyle && numdelim == DefaultDelim then empty else "\\def" <> "\\label" <> enum <> braces (todelim $ tostyle enum) let resetcounter = if start == 1 || oldlevel > 4 then empty else "\\setcounter" <> braces enum <> braces (text $ show $ start - 1) let spacing = if isTightList lst then text "\\itemsep1pt\\parskip0pt\\parsep0pt" else empty return $ text ("\\begin{enumerate}" ++ inc) $$ stylecommand $$ resetcounter $$ spacing $$ vcat items $$ "\\end{enumerate}" blockToLaTeX (DefinitionList []) = return empty blockToLaTeX (DefinitionList lst) = do incremental <- gets stIncremental let inc = if incremental then "[<+->]" else "" items <- mapM defListItemToLaTeX lst let spacing = if all isTightList (map snd lst) then text "\\itemsep1pt\\parskip0pt\\parsep0pt" else empty return $ text ("\\begin{description}" ++ inc) $$ spacing $$ vcat items $$ "\\end{description}" blockToLaTeX HorizontalRule = return $ "\\begin{center}\\rule{0.5\\linewidth}{\\linethickness}\\end{center}" blockToLaTeX (Header level (id',classes,_) lst) = do modify $ \s -> s{stInHeading = True} hdr <- sectionHeader ("unnumbered" `elem` classes) id' level lst modify $ \s -> s{stInHeading = False} return hdr blockToLaTeX (Table caption aligns widths heads rows) = do headers <- if all null heads then return empty else ($$ "\\midrule\n") `fmap` (tableRowToLaTeX True aligns widths) heads let endhead = if all null heads then empty else text "\\endhead" captionText <- inlineListToLaTeX caption let capt = if isEmpty captionText then empty else text "\\caption" <> braces captionText <> "\\tabularnewline\n\\toprule\n" <> headers <> "\\endfirsthead" rows' <- mapM (tableRowToLaTeX False aligns widths) rows let colDescriptors = text $ concat $ map toColDescriptor aligns modify $ \s -> s{ stTable = True } return $ "\\begin{longtable}[c]" <> braces ("@{}" <> colDescriptors <> "@{}") -- the @{} removes extra space at beginning and end $$ capt $$ "\\toprule" $$ headers $$ endhead $$ vcat rows' $$ "\\bottomrule" $$ "\\end{longtable}" blockToLaTeX (Figure figType attr content pc txt) = figureToLaTeXfloat figType attr content pc txt blockToLaTeX (ImageGrid _) = return empty blockToLaTeX (Statement _ _) = return empty blockToLaTeX (Proof _ _) = return empty toColDescriptor :: Alignment -> String toColDescriptor align = case align of AlignLeft -> "l" AlignRight -> "r" AlignCenter -> "c" AlignDefault -> "l" blockListToLaTeX :: [Block] -> State WriterState Doc blockListToLaTeX lst = vsep `fmap` mapM blockToLaTeX lst tableRowToLaTeX :: Bool -> [Alignment] -> [Double] -> [[Block]] -> State WriterState Doc tableRowToLaTeX header aligns widths cols = do -- scale factor compensates for extra space between columns -- so the whole table isn't larger than columnwidth let scaleFactor = 0.97 ** fromIntegral (length aligns) let widths' = map (scaleFactor *) widths cells <- mapM (tableCellToLaTeX header) $ zip3 widths' aligns cols return $ hsep (intersperse "&" cells) <> "\\tabularnewline" -- For simple latex tables (without minipages or parboxes), -- we need to go to some lengths to get line breaks working: -- as LineBreak bs = \vtop{\hbox{\strut as}\hbox{\strut bs}}. fixLineBreaks :: Block -> Block fixLineBreaks (Para ils) = Para $ fixLineBreaks' ils fixLineBreaks (Plain ils) = Plain $ fixLineBreaks' ils fixLineBreaks x = x fixLineBreaks' :: [Inline] -> [Inline] fixLineBreaks' ils = case splitBy (== LineBreak) ils of [] -> [] [xs] -> xs chunks -> RawInline "tex" "\\vtop{" : concatMap tohbox chunks ++ [RawInline "tex" "}"] where tohbox ys = RawInline "tex" "\\hbox{\\strut " : ys ++ [RawInline "tex" "}"] -- We also change display math to inline math, since display -- math breaks in simple tables. displayMathToInline :: Inline -> Inline displayMathToInline (Math (DisplayMath _) x) = Math InlineMath x displayMathToInline x = x tableCellToLaTeX :: Bool -> (Double, Alignment, [Block]) -> State WriterState Doc tableCellToLaTeX _ (0, _, blocks) = blockListToLaTeX $ walk fixLineBreaks $ walk displayMathToInline blocks tableCellToLaTeX header (width, align, blocks) = do modify $ \st -> st{ stInMinipage = True, stNotes = [] } cellContents <- blockListToLaTeX blocks notes <- gets stNotes modify $ \st -> st{ stInMinipage = False, stNotes = [] } let valign = text $ if header then "[b]" else "[t]" let halign = case align of AlignLeft -> "\\raggedright" AlignRight -> "\\raggedleft" AlignCenter -> "\\centering" AlignDefault -> "\\raggedright" return $ ("\\begin{minipage}" <> valign <> braces (text (printf "%.2f\\hsize" width)) <> (halign <> "\\strut" <> cr <> cellContents <> cr) <> "\\strut\\end{minipage}") $$ case notes of [] -> empty ns -> (case length ns of n | n > 1 -> "\\addtocounter" <> braces "footnote" <> braces (text $ show $ 1 - n) | otherwise -> empty) $$ vcat (intersperse ("\\addtocounter" <> braces "footnote" <> braces "1") $ map (\x -> "\\footnotetext" <> braces x) $ reverse ns) listItemToLaTeX :: [Block] -> State WriterState Doc listItemToLaTeX lst -- we need to put some text before a header if it's the first -- element in an item. This will look ugly in LaTeX regardless, but -- this will keep the typesetter from throwing an error. | ((Header _ _ _) :_) <- lst = blockListToLaTeX lst >>= return . (text "\\item ~" $$) . (nest 2) | otherwise = blockListToLaTeX lst >>= return . (text "\\item" $$) . (nest 2) defListItemToLaTeX :: ([Inline], [[Block]]) -> State WriterState Doc defListItemToLaTeX (term, defs) = do term' <- inlineListToLaTeX term -- put braces around term if it contains an internal link, -- since otherwise we get bad bracket interactions: \item[\hyperref[..] let isInternalLink (Link _ ('#':_,_)) = True isInternalLink _ = False let term'' = if any isInternalLink term then braces term' else term' def' <- liftM vsep $ mapM blockListToLaTeX defs return $ case defs of (((Header _ _ _) : _) : _) -> "\\item" <> brackets term'' <> " ~ " $$ def' _ -> "\\item" <> brackets term'' $$ def' -- | Craft the section header, inserting the secton reference, if supplied. sectionHeader :: Bool -- True for unnumbered -> [Char] -> Int -> [Inline] -> State WriterState Doc sectionHeader unnumbered ref level lst = do txt <- inlineListToLaTeX lst lab <- text `fmap` toLabel ref plain <- stringToLaTeX TextString $ foldl (++) "" $ map stringify lst let noNote (Note _) = Str "" noNote x = x let lstNoNotes = walk noNote lst txtNoNotes <- inlineListToLaTeX lstNoNotes let star = if unnumbered then text "*" else empty -- footnotes in sections don't work (except for starred variants) -- unless you specify an optional argument: -- \section[mysec]{mysec\footnote{blah}} optional <- if unnumbered || lstNoNotes == lst then return empty else do return $ brackets txtNoNotes let contents = if render Nothing txt == plain then braces txt else braces (text "\\texorpdfstring" <> braces txt <> braces (text plain)) let stuffing = star <> optional <> contents book <- gets stBook opts <- gets stOptions let useChapters = book || writerChapters opts let level' = if useChapters || writerScholarly opts then level - 1 else level -- Scholdoc always maps H1 to Part or Chapter when (level' == 0) $ modify $ \ s -> s { stLevelZero = True } -- Presence of level 0 headers have implications on TOC depth internalLinks <- gets stInternalLinks let refLabel x = (if ref `elem` internalLinks then text "\\hyperdef" <> braces empty <> braces lab <> braces x else x) let headerWith x y = refLabel $ text x <> y <> if null ref then empty else text "\\label" <> braces lab let sectionType = case level' of 0 | writerBeamer opts -> "part" | writerScholarly opts && not useChapters -> "part" | otherwise -> "chapter" 1 -> "section" 2 -> "subsection" 3 -> "subsubsection" 4 -> "paragraph" 5 -> "subparagraph" _ -> "" inQuote <- gets stInQuote let prefix = if inQuote && level' >= 4 then text "\\mbox{}%" -- needed for \paragraph, \subparagraph in quote environment -- see http://tex.stackexchange.com/questions/169830/ else empty return $ if level' > 5 then txt else prefix $$ headerWith ('\\':sectionType) stuffing $$ if unnumbered then "\\addcontentsline{toc}" <> braces (text sectionType) <> braces txtNoNotes else empty -- | Convert list of inline elements to LaTeX. inlineListToLaTeX :: [Inline] -- ^ Inlines to convert -> State WriterState Doc inlineListToLaTeX lst = mapM inlineToLaTeX (prependNbsp $ fixBreaks $ fixLineInitialSpaces lst) >>= return . hcat -- ## fixLineInitialSpaces -- nonbreaking spaces (~) in LaTeX don't work after line breaks, -- so we turn nbsps after hard breaks to \hspace commands. -- this is mostly used in verse. -- ## prependNbsp -- usually numbered cross-references should be prepended with -- a nonbreaking space, so we do that, except when a bunch of -- them appears in a comma-separated list where fixLineInitialSpaces [] = [] fixLineInitialSpaces (LineBreak : Str s@('\160':_) : xs) = LineBreak : fixNbsps s ++ fixLineInitialSpaces xs fixLineInitialSpaces (x:xs) = x : fixLineInitialSpaces xs fixNbsps s = let (ys,zs) = span (=='\160') s in replicate (length ys) hspace ++ [Str zs] hspace = RawInline "latex" "\\hspace*{0.333em}" prependNbsp [] = [] prependNbsp (Str "," : Space : NumRef a as : xs) = Str "," : Space : NumRef a as : prependNbsp xs prependNbsp (Str a : Space : NumRef b bs : xs) = Str (a ++ "\160") : NumRef b bs : prependNbsp xs prependNbsp (x:xs) = x : prependNbsp xs -- linebreaks after blank lines cause problems: fixBreaks [] = [] fixBreaks ys@(LineBreak : LineBreak : _) = case span (== LineBreak) ys of (lbs, rest) -> RawInline "latex" ("\\\\[" ++ show (length lbs) ++ "\\baselineskip]") : fixBreaks rest fixBreaks (y:ys) = y : fixBreaks ys isQuoted :: Inline -> Bool isQuoted (Quoted _ _) = True isQuoted _ = False -- | Convert inline element to LaTeX inlineToLaTeX :: Inline -- ^ Inline to convert -> State WriterState Doc inlineToLaTeX (Span (id',classes,_) ils) = do let noEmph = "csl-no-emph" `elem` classes let noStrong = "csl-no-strong" `elem` classes let noSmallCaps = "csl-no-smallcaps" `elem` classes ref <- toLabel id' let linkAnchor = if null id' then empty else "\\hyperdef{}" <> braces (text ref) <> "{}" fmap (linkAnchor <>) ((if noEmph then inCmd "textup" else id) . (if noStrong then inCmd "textnormal" else id) . (if noSmallCaps then inCmd "textnormal" else id) . (if not (noEmph || noStrong || noSmallCaps) then braces else id)) `fmap` inlineListToLaTeX ils inlineToLaTeX (Emph lst) = inlineListToLaTeX lst >>= return . inCmd "emph" inlineToLaTeX (Strong lst) = inlineListToLaTeX lst >>= return . inCmd "textbf" inlineToLaTeX (Strikeout lst) = do -- we need to protect VERB in an mbox or we get an error -- see #1294 contents <- inlineListToLaTeX $ protectCode lst modify $ \s -> s{ stStrikeout = True } return $ inCmd "sout" contents inlineToLaTeX (Superscript lst) = inlineListToLaTeX lst >>= return . inCmd "textsuperscript" inlineToLaTeX (Subscript lst) = do inlineListToLaTeX lst >>= return . inCmd "textsubscript" inlineToLaTeX (SmallCaps lst) = inlineListToLaTeX lst >>= return . inCmd "textsc" inlineToLaTeX (Cite cits lst) = do st <- get let opts = stOptions st case writerCiteMethod opts of Natbib -> citationsToNatbib cits Biblatex -> citationsToBiblatex cits _ -> inlineListToLaTeX lst inlineToLaTeX (NumRef numref _raw) = do let refId = numRefId numref case numRefStyle numref of PlainNumRef -> return $ text $ "\\ref{" ++ refId ++ "}" ParenthesesNumRef -> return $ text $ "\\eqref{" ++ refId ++ "}" inlineToLaTeX (Code (_,classes,_) str) = do opts <- gets stOptions case () of _ | writerListings opts -> listingsCode | writerHighlight opts && not (null classes) -> highlightCode | otherwise -> rawCode where listingsCode = do inNote <- gets stInNote when inNote $ modify $ \s -> s{ stVerbInNote = True } let chr = case "!\"&'()*,-./:;?@_" \\ str of (c:_) -> c [] -> '!' return $ text $ "\\lstinline" ++ [chr] ++ str ++ [chr] highlightCode = do case highlight formatLaTeXInline ("",classes,[]) str of Nothing -> rawCode Just h -> modify (\st -> st{ stHighlighting = True }) >> return (text h) rawCode = liftM (text . (\s -> "\\texttt{" ++ escapeSpaces s ++ "}")) $ stringToLaTeX CodeString str where escapeSpaces = concatMap (\c -> if c == ' ' then "\\phantom{\\ }" else [c]) inlineToLaTeX (Quoted qt lst) = do contents <- inlineListToLaTeX lst csquotes <- liftM stCsquotes get opts <- gets stOptions if csquotes then return $ "\\enquote" <> braces contents else do let s1 = if (not (null lst)) && (isQuoted (head lst)) then "\\," else empty let s2 = if (not (null lst)) && (isQuoted (last lst)) then "\\," else empty let inner = s1 <> contents <> s2 return $ case qt of DoubleQuote -> if writerTeXLigatures opts then text "``" <> inner <> text "''" else char '\x201C' <> inner <> char '\x201D' SingleQuote -> if writerTeXLigatures opts then char '`' <> inner <> char '\'' else char '\x2018' <> inner <> char '\x2019' inlineToLaTeX (Str str) = liftM text $ stringToLaTeX TextString str inlineToLaTeX (Math InlineMath str) = return $ char '$' <> text str <> char '$' inlineToLaTeX (Math (DisplayMath attr) str) = return $ cr <> char '%' <> cr <> text (dispMathToLaTeX attr str) <> cr <> char '%' <> cr inlineToLaTeX (RawInline f str) | f == Format "latex" || f == Format "tex" = return $ text str | otherwise = return empty inlineToLaTeX (LineBreak) = return "\\\\" inlineToLaTeX Space = return space inlineToLaTeX (Link txt ('#':ident, _)) = do contents <- inlineListToLaTeX txt lab <- toLabel ident return $ text "\\hyperref" <> brackets (text lab) <> braces contents inlineToLaTeX (Link txt (src, _)) = case txt of [Str x] | escapeURI x == src -> -- autolink do modify $ \s -> s{ stUrl = True } src' <- stringToLaTeX URLString src return $ text $ "\\url{" ++ src' ++ "}" [Str x] | Just rest <- stripPrefix "mailto:" src, escapeURI x == rest -> -- email autolink do modify $ \s -> s{ stUrl = True } src' <- stringToLaTeX URLString src contents <- inlineListToLaTeX txt return $ "\\href" <> braces (text src') <> braces ("\\nolinkurl" <> braces contents) _ -> do contents <- inlineListToLaTeX txt src' <- stringToLaTeX URLString src return $ text ("\\href{" ++ src' ++ "}{") <> contents <> char '}' inlineToLaTeX (Image attr _ (source, _)) = do modify $ \s -> s{ stGraphics = True } source' <- handleImageSrc source inHeading <- gets stInHeading return $ imageWithAttrToLatex "\\textwidth" attr source' inHeading inlineToLaTeX (Note contents) = do inMinipage <- gets stInMinipage modify (\s -> s{stInNote = True}) contents' <- blockListToLaTeX contents modify (\s -> s {stInNote = False}) let optnl = case reverse contents of (CodeBlock _ _ : _) -> cr _ -> empty let noteContents = nest 2 contents' <> optnl opts <- gets stOptions -- in beamer slides, display footnote from current overlay forward let beamerMark = if writerBeamer opts then text "<.->" else empty modify $ \st -> st{ stNotes = noteContents : stNotes st } return $ if inMinipage then "\\footnotemark{}" -- note: a \n before } needed when note ends with a Verbatim environment else "\\footnote" <> beamerMark <> braces noteContents protectCode :: [Inline] -> [Inline] protectCode [] = [] protectCode (x@(Code ("",[],[]) _) : xs) = x : protectCode xs protectCode (x@(Code _ _) : xs) = ltx "\\mbox{" : x : ltx "}" : xs where ltx = RawInline (Format "latex") protectCode (x : xs) = x : protectCode xs citationsToNatbib :: [Citation] -> State WriterState Doc citationsToNatbib (one:[]) = citeCommand c p s k where Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = one c = case m of AuthorInText -> "citet" SuppressAuthor -> "citeyearpar" NormalCitation -> "citep" citationsToNatbib cits | noPrefix (tail cits) && noSuffix (init cits) && ismode NormalCitation cits = citeCommand "citep" p s ks where noPrefix = all (null . citationPrefix) noSuffix = all (null . citationSuffix) ismode m = all (((==) m) . citationMode) p = citationPrefix $ head $ cits s = citationSuffix $ last $ cits ks = intercalate ", " $ map citationId cits citationsToNatbib (c:cs) | citationMode c == AuthorInText = do author <- citeCommand "citeauthor" [] [] (citationId c) cits <- citationsToNatbib (c { citationMode = SuppressAuthor } : cs) return $ author <+> cits citationsToNatbib cits = do cits' <- mapM convertOne cits return $ text "\\citetext{" <> foldl combineTwo empty cits' <> text "}" where combineTwo a b | isEmpty a = b | otherwise = a <> text "; " <> b convertOne Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = case m of AuthorInText -> citeCommand "citealt" p s k SuppressAuthor -> citeCommand "citeyear" p s k NormalCitation -> citeCommand "citealp" p s k citeCommand :: String -> [Inline] -> [Inline] -> String -> State WriterState Doc citeCommand c p s k = do args <- citeArguments p s k return $ text ("\\" ++ c) <> args citeArguments :: [Inline] -> [Inline] -> String -> State WriterState Doc citeArguments p s k = do let s' = case s of (Str (x:[]) : r) | isPunctuation x -> dropWhile (== Space) r (Str (x:xs) : r) | isPunctuation x -> Str xs : r _ -> s pdoc <- inlineListToLaTeX p sdoc <- inlineListToLaTeX s' let optargs = case (isEmpty pdoc, isEmpty sdoc) of (True, True ) -> empty (True, False) -> brackets sdoc (_ , _ ) -> brackets pdoc <> brackets sdoc return $ optargs <> braces (text k) citationsToBiblatex :: [Citation] -> State WriterState Doc citationsToBiblatex (one:[]) = citeCommand cmd p s k where Citation { citationId = k , citationPrefix = p , citationSuffix = s , citationMode = m } = one cmd = case m of SuppressAuthor -> "autocite*" AuthorInText -> "textcite" NormalCitation -> "autocite" citationsToBiblatex (c:cs) = do args <- mapM convertOne (c:cs) return $ text cmd <> foldl (<>) empty args where cmd = case citationMode c of AuthorInText -> "\\textcites" _ -> "\\autocites" convertOne Citation { citationId = k , citationPrefix = p , citationSuffix = s } = citeArguments p s k citationsToBiblatex _ = return empty -- Determine listings language from list of class attributes. getListingsLanguage :: [String] -> Maybe String getListingsLanguage [] = Nothing getListingsLanguage (x:xs) = toListingsLanguage x <|> getListingsLanguage xs -- -- ScholarlyMarkdown floating figures -- -- Handles all float types figureToLaTeXfloat :: FigureType -> Attr -> [Block] -> PreparedContent -> [Inline] -> State WriterState Doc figureToLaTeXfloat ImageFigure = imageGridToLaTeX figureToLaTeXfloat TableFigure = tableFloatToLaTeX figureToLaTeXfloat LineBlockFigure = algorithmToLaTeX figureToLaTeXfloat ListingFigure = codeFloatToLaTeX -- Handles writing image figure floats imageGridToLaTeX :: Attr -> [Block] -> PreparedContent -> [Inline] -> State WriterState Doc imageGridToLaTeX attr imageGrid _fallback caption = do modify $ \s -> s{ stFloats = True } modify $ \s -> s{ stGraphics = True } let ident = getIdentifier attr let (subfigRows, snglImg) = case head imageGrid of -- get rid of any subcaption and label for single image ImageGrid [[Image a _ c]] -> ([[Image (setIdentifier "" a) [] c]], True) ImageGrid ig -> (ig, False) _ -> ([[]], True) -- should never happen unless snglImg $ modify $ \s -> s{ stSubfigs = True } let subfigIds = fromMaybe [""] ((safeRead $ fromMaybe [] $ lookupKey "subfigIds" attr) :: Maybe [String]) -- show subfig labels (a), (b), etc let showSubfigLabel = any (not . null) subfigIds && not (hasClass "nonumber" attr) let subfiglist = intercalate [LineBreak] subfigRows let myNumLabel = fromMaybe "0" $ lookupKey "numLabel" attr let addCaptPrefix = myNumLabel /= "0" -- infers that num. label is not needed -- this requires the "caption" package which is provided by "subfig" let capstar = if not addCaptPrefix then text "*" else empty let widestar = if hasClass "wide" attr then text "*" else empty let fullWidth = "\\hsize" capt <- if null caption then return empty else (\c -> "\\caption" <> capstar <> braces c) `fmap` inlineListToLaTeX caption let capt' = if null caption && not addCaptPrefix then empty else capt img <- mapM (subfigsToLaTeX fullWidth snglImg) subfiglist let label = if not $ null ident then "\\label" <> braces (text ident) else empty let disableSubfigLabel = if showSubfigLabel || snglImg then empty else "\\captionsetup" <> brackets (text "subfigure") <> braces (text "labelformat=empty") return $ "\\begin{figure" <> widestar <> "}" $$ "\\centering" $$ disableSubfigLabel $$ foldl ($$) empty img $$ capt' <> label $$ "\\end{figure" <> widestar <> "}" -- Handles writing figure subfloats (using the subfig package) -- (requires "fullWidth" argument, which is a command that defines 100% width -- of container, such as @\\textwidth@) subfigsToLaTeX :: String -> Bool -> Inline -> State WriterState Doc subfigsToLaTeX _ _ LineBreak = inlineToLaTeX LineBreak subfigsToLaTeX fullWidth singleImage (Image attr txt (src,_)) = do let ident = getIdentifier attr capt <- if null txt then return empty else inlineListToLaTeX txt let label = if not $ null ident then "\\label" <> braces (text ident) else empty src' <- handleImageSrc src attr' <- setWidthFromHistory attr let img = imageWithAttrToLatex fullWidth attr' src' False return $ if singleImage then img <> label else "\\subfloat" <> brackets (capt <> label) <> braces img subfigsToLaTeX _ _ _ = return empty handleImageSrc :: String -> State WriterState String handleImageSrc source = let source' = if isURI source then source else unEscapeString source in stringToLaTeX URLString source' setWidthFromHistory :: Attr -> State WriterState Attr setWidthFromHistory attr = do let attrWidth = fromMaybe "" $ lookupKey "width" attr st <- get let lastWidth = fromMaybe "" $ stLastWidth st let replaceWidth = attrWidth == "same" || attrWidth == "^" let currWidth = if replaceWidth then lastWidth else attrWidth unless (null currWidth) $ put st { stLastWidth = Just currWidth } return $ insertReplaceKeyVal ("width",currWidth) attr -- Extracts dimension attributes and include in the @includegraphics@ directive -- (requires "fullWidth" argument, which is a command that defines 100% width -- of container, such as @\\textwidth@) imageWithAttrToLatex :: String -> Attr -> String -> Bool -> Doc imageWithAttrToLatex fullWidth attr src needProtect = let keyval' = M.fromList $ getKeyVals attr width = case M.lookup "width" keyval' of Just len -> filterLength fullWidth len Nothing -> case M.lookup "max-width" keyval' of Just len -> filterLength fullWidth len Nothing -> "" hight = case M.lookup "height" keyval' of Just len -> filterLength fullWidth len Nothing -> case M.lookup "max-height" keyval' of Just len -> filterLength fullWidth len Nothing -> "" width' = if null width then "" else "width=" ++ width hight' = if null hight then "" else "height=" ++ hight keepAspectRatio = if not (null width) && not (null hight) then "keepaspectratio=true" else "" graphicxAttr = intercalate "," [ x | x <- [width', hight', keepAspectRatio], not $ null x] graphicsCmd = if needProtect then "\\protect\\includegraphics" else "\\includegraphics" in graphicsCmd <> brackets (text graphicxAttr) <> braces (text src) -- Ensures that dimension is understandable by LaTeX, -- mostly converts unit of percentage @%@ to measure of relative width. -- If unit not recognized, then returns empty string. -- (required "fullWidth" argument, which is a command that defines 100% width -- of container, such as @\\textwidth@) filterLength :: String -> String -> String filterLength fullWidth len = case reads len :: [(Float, String)] of (val,"%"):_ -> (printf "%.3f" (val/100)) ++ fullWidth (val,unit):_ | unit `elem` validLaTeXUnits -> (printf "%.3f" val) ++ unit _ -> "" validLaTeXUnits :: [String] validLaTeXUnits = ["mm","cm","in","pt","em","ex","%"] -- Handles writing algorithm/pseudocode floats algorithmToLaTeX :: Attr -> [Block] -> PreparedContent -> [Inline] -> State WriterState Doc algorithmToLaTeX attr alg _fallback caption = do modify $ \s -> s{ stAlgorithms = True, stFloats = True } let ident = getIdentifier attr let myNumLabel = fromMaybe "0" $ lookupKey "numLabel" attr let addCaptPrefix = myNumLabel /= "0" -- infers that num. label is not needed -- this requires the "caption" package which is provided by "subfig" let capstar = if not addCaptPrefix then text "*" else empty let widestar = if hasClass "wide" attr then text "*" else empty capt <- if null caption then return empty else (\c -> "\\caption" <> capstar <> braces c) `fmap` inlineListToLaTeX caption let capt' = if null caption && not addCaptPrefix then empty else capt algorithm <- blockListToLaTeX alg let label = if not $ null ident then "\\label" <> braces (text ident) else empty return $ "\\begin{scholmdAlgorithm" <> widestar <> "}" $$ algorithm $$ capt' <> label $$ "\\end{scholmdAlgorithm" <> widestar <> "}" -- Handles writing algorithm/pseudocode floats tableFloatToLaTeX :: Attr -> [Block] -> PreparedContent -> [Inline] -> State WriterState Doc tableFloatToLaTeX attr tabl _fallback caption = do modify $ \s -> s{ stTable = True, stFloats = True } let ident = getIdentifier attr let myNumLabel = fromMaybe "0" $ lookupKey "numLabel" attr let addCaptPrefix = myNumLabel /= "0" -- infers that num. label is not needed -- this requires the "caption" package which is provided by "subfig" let capstar = if not addCaptPrefix then text "*" else empty let widestar = if hasClass "wide" attr then text "*" else empty capt <- if null caption then return empty else (\c -> "\\caption" <> capstar <> braces c) `fmap` inlineListToLaTeX caption let capt' = if null caption && not addCaptPrefix then empty else capt table <- mapM tableToTabular tabl let label = if not $ null ident then "\\label" <> braces (text ident) else empty return $ "\\begin{table" <> widestar <> "}" $$ "\\centering" $$ foldl ($$) empty table $$ capt' <> label $$ "\\end{table" <> widestar <> "}" -- Specifically for table floats tableToTabular :: Block -> State WriterState Doc tableToTabular (Table _caption aligns widths heads rows) = do headers <- if all null heads then return empty else ($$ "\\midrule") `fmap` (tableRowToLaTeX True aligns widths) heads rows' <- mapM (tableRowToLaTeX False aligns widths) rows let colDescriptors = text $ concatMap toColDescriptor aligns return $ "\\begin{tabular}" <> braces colDescriptors $$ "\\toprule\\addlinespace" $$ headers $$ vcat rows' $$ "\\bottomrule" $$ "\\end{tabular}" tableToTabular _ = return empty -- Handles writing code-block/listing floats -- (Scholarly automatically uses Listings for floating block) codeFloatToLaTeX :: Attr -> [Block] -> PreparedContent -> [Inline] -> State WriterState Doc codeFloatToLaTeX attr codeblock _fallback caption = do modify $ \s -> s{ stFloats = True } let myNumLabel = fromMaybe "0" $ lookupKey "numLabel" attr let addCaptPrefix = myNumLabel /= "0" -- infers that num. label is not needed let codeblock' = dropWhile notCodeBlock codeblock codeToListingsFloat (head codeblock') attr caption addCaptPrefix notCodeBlock :: Block -> Bool notCodeBlock (CodeBlock _ _) = False notCodeBlock _ = True codeToListingsFloat :: Block -> Attr -> [Inline] -> Bool -> State WriterState Doc codeToListingsFloat (CodeBlock (_,classes,keyvalAttr) str) attrib caption captPref = do ident <- toLabel $ getIdentifier attrib let params = (case getListingsLanguage classes of Just l -> [ "language=" ++ l ] Nothing -> []) ++ [ "numbers=left" | "numberLines" `elem` classes || "number" `elem` classes || "number-lines" `elem` classes ] ++ [ (if key == "startFrom" then "firstnumber" else key) ++ "=" ++ attr | (key,attr) <- keyvalAttr ] ++ (if ident == "" then [] else [ "label=" ++ ident ]) ++ (if not captPref then [ "nolol=true" ] else []) ++ (if not (hasClass "wide" attrib) then [ "float=htbp" ] else [ "float=*htbp" ] ) capt <- if null caption then return empty else (\c -> "caption=" <> braces c) `fmap` inlineListToLaTeX caption let printParams | null params = empty | otherwise = brackets $ hcat (intersperse ", " $ capt:(map text params) ) return $ flush ("\\begin{lstlisting}" <> printParams $$ text str $$ "\\end{lstlisting}") $$ cr codeToListingsFloat _ _ _ _ = return empty
timtylin/scholdoc
src/Text/Pandoc/Writers/LaTeX.hs
gpl-2.0
57,974
0
41
19,541
15,459
7,763
7,696
1,080
32
module Type.Quiz where -- $Id$ import Type.Data import Type.Check import Autolib.NFTA import Autolib.NFTA.Shortest ( shortest, shortest0 ) import Autolib.Size import Autolib.ToDoc import Autolib.NFTA.Trim import Autolib.NFTA.Normalize import qualified Autolib.Relation as Relation import Autolib.Informed import Autolib.TES.Identifier import Autolib.Util.Zufall import Control.Monad ( guard ) import Inter.Quiz import Inter.Types import Debug import Data.Array blank :: NFTAC c s => Set c -> Set s -> s -> NFTA c s blank cs stats fin = NFTA { nfta_info = funni "blank" [ info cs, info stats ] , alphabet = cs , states = stats , finals = unitSet fin , trans = Relation.make [] , eps = Relation.empty $ stats } -- | add transitions until final state is reachable roller :: NFTAC (Int) s => Conf -> Set (Int) -> Set s -> s -> IO ( NFTA (Int) s ) roller conf cs stats fin = extend (blank cs stats fin) extend :: NFTAC Int s => NFTA Int s -> IO (NFTA Int s) extend au = do let tau = trim au if not $ isEmptySet $ finals tau then return tau else do q <- eins $ lstates au a <- eins $ setToList $ alphabet au ps <- sequence $ replicate a $ eins $ lstates au extend $ au { trans = trans au `Relation.plus` Relation.make [ (q, (a, ps)) ] } roll :: Conf -> IO ( NFTA Int Type, TI ) roll conf = do let ts = types conf fin <- eins ts -- final state au <- roller conf ( mkSet [ 0 .. max_arity conf ] ) (mkSet ts) fin let fs = do c <- [ 'a' .. ] ; return $ mknullary [c] let vfs = do (f, (p, (c, qs))) <- zip fs $ Relation.pairs $ trans au if null qs then return $ Left $ Variable { vname = f, vtype = p } else return $ Right $ Function { fname = f , arguments = qs , result = p } return ( au , TI { target = fin , signature = sammel vfs } ) instance Generator TypeCheck Conf ( NFTA Int Type, TI ) where generator p conf key = roll conf `repeat_until` \ ( au, ti ) -> min_symbols conf <= size (signature ti) && size (signature ti) <= max_symbols conf && let s = size $ head $ shortest au in min_size conf <= s && s <= max_size conf instance Project TypeCheck ( NFTA Int Type, TI ) TI where project p ( au, ti ) = ti make :: Make make = quiz TypeCheck conf
florianpilz/autotool
src/Type/Quiz.hs
gpl-2.0
2,494
22
16
789
971
509
462
-1
-1
module Numerical.PETSc.TestFEM where import Numerical.PETSc.Test2 import Foreign.C.Types import Control.Monad import Control.Concurrent import Control.Exception import Foreign import qualified Data.Vector as V t11' h m n = withMatAssembleQ4 cs m n (ke h) $ \mat -> matViewStdout mat where cs = commWorld t11 = withPetsc0 $ t11' 2.0 10 11 withMatAssembleQ4 comm m n localmat | length localmat == 16 = withMatPipeline comm nNodes nNodes (\mat -> assembleQ4 mat m n localmat) | otherwise = error "withMatAssembleQ4: localmat must be length 16" where nnrow = m+1 nncol = n+1 nNodes = nnrow * nncol assembleQ4 mat m n localmat = forM_ [0 .. nElem] (\j -> matSetValues mat (idx j) (idx j) localmat AddValues) where nElem = m * n idx j = indices4 j m indices4 i m = [idx0, idx1, idx2, idx3] where idx0 = (m+1)*(i `div` m) + (i `mod` m) idx1 = idx0 + 1 idx2 = idx1 + m + 1 idx3 = idx1 + m ke0 :: Fractional a => [a] ke0 = [1/6, -1/8, 1/12, -1/8, -1/8, 1/6, -1/8, 1/12, 1/12, -1/8, 1/6, -1/8, -1/8, 1/12, -1/8, 1/6] ke h = map (*h) ke0
ocramz/petsc-hs
examples/TestFEM.hs
gpl-3.0
1,130
0
10
292
539
294
245
35
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module FreeTracker.Database.TH ( persist , persistFile , derivePersistField , IssueFieldType(..) ) where import Data.Char import qualified Data.Text as T import Database.Persist.Quasi import Database.Persist.TH import Language.Haskell.TH.Quote import Language.Haskell.TH.Syntax data IssueFieldType = Reference | Text deriving (Read, Show, Eq) derivePersistField "IssueFieldType" persistSettings :: PersistSettings persistSettings = PersistSettings { psToDBName = \l -> T.cons (toUpper $ T.head l) (T.tail l) , psStrictFields = True , psIdName = "ID" } persist :: QuasiQuoter persist = persistWith persistSettings persistFile :: FilePath -> Q Exp persistFile = persistFileWith persistSettings
sirius94/free-tracker
free-tracker-server/src/FreeTracker/Database/TH.hs
gpl-3.0
890
0
12
196
193
115
78
26
1
module Mastermind where import Control.Monad (replicateM) import Data.List ((\\), sort, group) type Color = Int type Pattern = [Color] type Feedback = (Int, Int) type Turn = (Pattern, Feedback) parseTurns :: [String] -> [Turn] parseTurns [] = [] parseTurns (p : f : ts) = (p', f') : parseTurns ts where p' = map (read . return) $ pad '0' 4 p f' = (b, w) where [b, w] = map (read . return) $ pad '0' 2 f universe :: [Pattern] universe = replicateM 4 [1..8] check :: Pattern -> Pattern -> Feedback check pattern guess = (black, white) where black = length . filter (uncurry (==)) $ zip pattern guess white = length . (phi intersect' (map fst) (map snd)) . filter (uncurry (/=)) $ zip pattern guess possible :: [Turn] -> [Pattern] possible turns = filter (consistent turns) universe where consistent turns pattern = all (\t -> check pattern (fst t) == (snd t)) turns best :: [Turn] -> [(Int, Pattern)] best turns = sort . map evaluate $ universe' where evaluate :: Pattern -> (Int, Pattern) evaluate p = (maximum . map length . group . sort . map (check p) $ universe', p) universe' :: [Pattern] universe' = possible turns -- Helper functions pad :: a -> Int -> [a] -> [a] pad c n s = replicate (n - length s) c ++ s intersect' :: Eq a => [a] -> [a] -> [a] intersect' xs ys = xs \\ (xs \\ ys) phi :: (b -> c -> d) -> (a -> b) -> (a -> c) -> a -> d phi f g h x = f (g x) (h x)
bolo1729/Mastermind
Mastermind.hs
gpl-3.0
1,402
0
13
308
723
392
331
33
1
module CodeGen (codeGen,genMain) where import Control.Monad(foldM,unless,when,zipWithM_) import Data.Char(isAlphaNum,isAscii,ord) import Data.Set(Set) import qualified Data.Set as Set import Ast(Identifier(..),Param(..),Def(..),Expr(..),Func) import GenLLVM (GenLLVM,Local,Label,genLLVM, writeCode,writeLocal,writeLabelRef, writeNewLocal,writeNewLabel,writeNewLabelBack, writeForwardRefLabel,writeBranch,writePhi, writeGetElementPtr,writeLoad,writeStore) debugMemory :: Bool debugMemory = False debugMemoryAllocs :: Bool debugMemoryAllocs = False debugAborts :: Bool debugAborts = False debugIndirectCalls :: Bool debugIndirectCalls = False debugDeref :: Bool debugDeref = False -- Generate code for LLVM 3.7 codeGen :: [Func] -> String codeGen funcs = (concatMap writeLiteral . Set.toList . foldl collectLiterals Set.empty) funcs ++ concatMap genLLVM [ -- runtime functions writeDecls, writeUnrefDefn, writeEvalLiteralValueDefn, writeFreeEvalParamLiteralValueDefn, writeEvalConcatValueDefn, writeFreeEvalParamConcatValueDefn, writeEvalFileValueDefn, writeFreeEvalParamFileValueDefn, writeFreeEvalParamFuncValueDefn, writeFreeEvalParamNullaryFuncValueDefn, writeDebugDefns, writeDebugMemoryMallocDefn, writeDebugMemoryFreeDefn ] ++ (concatMap genLLVM . map writeFunc) funcs ++ (concatMap genLLVM . map writeEvalFuncValue) funcs collectLiterals :: Set [Bool] -> Func -> Set [Bool] collectLiterals literals (_,defs) = foldl collectDefLiterals literals defs where collectDefLiterals literals (Def _ expr) = collectExprLiterals literals expr collectExprLiterals literals (ExprLiteral _ bits) = Set.insert bits literals collectExprLiterals literals (ExprFuncall _ exprs) = foldl collectExprLiterals literals exprs collectExprLiterals literals (ExprConcat expr1 expr2) = collectExprLiterals (collectExprLiterals literals expr1) expr2 collectExprLiterals literals _ = literals writeLiteral :: [Bool] -> String writeLiteral bits | null bits = "" | otherwise = literalName bits ++ " = private constant " ++ literalType bits ++ " [" ++ drop 1 (concatMap writeBit bits) ++ "]" where writeBit bit = ",i1 " ++ if bit then "1" else "0" literalName :: [Bool] -> String literalName bits = "@L" ++ map (\ bit -> if bit then '1' else '0') bits literalType :: [Bool] -> String literalType bits = "[" ++ show (length bits) ++ " x i1]" writeName :: String -> GenLLVM () writeName name = writeCode ("@_" ++ quoteName name) evalFuncName :: String -> String evalFuncName name = "@evalFunc_" ++ quoteName name quoteName :: String -> String quoteName name = concatMap quote name where quote c | isAscii c && isAlphaNum c = [c] | otherwise = "_" ++ show (ord c) ++ "_" quoteStringConstant :: String -> String quoteStringConstant s = concatMap quote s where quote '\\' = "\\\\" quote '"' = "\\\"" quote c = [c] writeValueType :: String -> GenLLVM () writeValueType code = -- 0:i32 ref count -- 1:i2 status (0:0,1:1,2:nil,3:unevaluated) -- 2:i8* next/eval param -- 3:{i2,i8*}(i8*,i8*)* eval(eval param,value) -- 4:void(i8*)* free(eval param) writeCode ("{i32,i2,i8*,{i2,i8*}(i8*,i8*)*,void(i8*)*}" ++ code) writeValueFieldPtr :: Local -> Int -> GenLLVM Local writeValueFieldPtr value field = writeGetElementPtr (writeValueType "") (Left value) ("i32 0,i32 " ++ show field) writeFunc :: Func -> GenLLVM () writeFunc (name,Def params _:_) = do writeCode "define fastcc " writeValueType "* " writeName name writeCode "(" zipWithM_ (\ comma i -> do writeCode comma writeValueType ("* %a" ++ show i)) ("":repeat ",") [0 .. length params - 1] writeCode ") {" writeNewLabel (value,_) <- writeAllocateNewValue 3 if null params then return () else do sizePtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Right "null") ("i32 0,i32 1,i32 " ++ show (length params)) size <- writeNewLocal "ptrtoint " writeValueType "** " writeLocal sizePtr " to i32" rawPtr <- writeMalloc size evalParam <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeFuncValueEvalParamType "*" argCountPtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Left evalParam) "i32 0,i32 0" writeStore (writeCode "i32") (Right (show (length params))) argCountPtr mapM_ (\ i -> do argPtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Left evalParam) ("i32 0,i32 1,i32 " ++ show i) writeStore (writeValueType "*") (Right ("%a" ++ show i)) argPtr) [0 .. length params - 1] evalParamPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left rawPtr) evalParamPtr evalFuncPtr <- writeValueFieldPtr value 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right (evalFuncName name)) evalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr value 4 writeStore (writeCode "void(i8*)*") (Right (if null params then "@freeEvalParamNullaryFunc" else "@freeEvalParamFunc")) freeEvalParamFuncPtr writeCode " ret " writeValueType "* " writeLocal value "" writeCode " }" writeFuncValueEvalParamType :: String -> GenLLVM () writeFuncValueEvalParamType code = do -- 0:i32 number of arguments -- 1:[0 x {i32,i2,i8*,{i2,i8*}(i8*,i8*)*,void(i8*)*}] arguments writeCode "{i32,[0 x " writeValueType ("*]}" ++ code) writeFreeEvalParamFuncValueDefn :: GenLLVM () writeFreeEvalParamFuncValueDefn = do writeCode "define private fastcc void " writeCode "@freeEvalParamFunc(i8* %evalParam) {" entryLabel <- writeNewLabel writeDebugDeref "FPF" "%evalParam" evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeFuncValueEvalParamType "*" argCountPtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Left evalParam) "i32 0,i32 0" argCount <- writeLoad (writeCode "i32") argCountPtr writeCode " br label " loopLabelRef <- writeForwardRefLabel loopLabel <- writeNewLabelBack [loopLabelRef] (argIndex,argIndexPhiRef) <- writePhi (writeCode "i32") (Right "0") entryLabel cmp <- writeNewLocal "icmp ult i32 " writeLocal argIndex "," writeLocal argCount "" (continueLoopLabelRef,doneLabelRef) <- writeBranch cmp continueLoopLabel <- writeNewLabelBack [continueLoopLabelRef] argPtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Left evalParam) "i32 0,i32 1,i32 " writeLocal argIndex "" arg <- writeLoad (writeValueType "*") argPtr writeUnref (Left arg) newArgIndex <- writeNewLocal "add i32 1," writeLocal argIndex "" argIndexPhiRef newArgIndex continueLoopLabel writeCode " br label " writeLabelRef loopLabel "" writeNewLabelBack [doneLabelRef] writeFree (Right "%evalParam") writeCode " ret void" writeCode " }" writeFreeEvalParamNullaryFuncValueDefn :: GenLLVM () writeFreeEvalParamNullaryFuncValueDefn = do writeCode "define private fastcc void " writeCode "@freeEvalParamNullaryFunc(i8* %evalParam) {" writeCode " ret void" writeCode " }" writeEvalFuncValue :: Func -> GenLLVM () writeEvalFuncValue (name,defs) = do writeCode "define private fastcc {i2,i8*} " writeCode (evalFuncName name) writeCode "(i8* %evalParam,i8* %value) {" writeNewLabel value <- writeNewLocal "bitcast i8* %value to " writeValueType "*" let Def params _:_ = defs args <- if null params then return [] else do writeDebugDeref "EFP" "%evalParam" evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeFuncValueEvalParamType "*" args <- mapM (\ i -> do argPtr <- writeGetElementPtr (writeFuncValueEvalParamType "") (Left evalParam) ("i32 0,i32 1,i32 " ++ show i) writeLoad (writeValueType "*") argPtr) [0 .. length params - 1] writeFree (Right "%evalParam") return args writeCode " br label " labelRef <- writeForwardRefLabel labelRefs <- foldM (\ labelRefs def -> do writeNewLabelBack labelRefs writeDef def value args) [labelRef] defs unless (null labelRefs) (do writeNewLabelBack labelRefs when debugAborts (do writeNewLocal ("call i32 @write(i32 1,i8* getelementptr ([" ++ show (length name) ++ " x i8],[" ++ show (length name) ++ " x i8]* @name_" ++ quoteName name ++ ",i32 0,i32 0),i32 " ++ show (length name) ++ ")") return ()) writeCode " call void @abort() noreturn" writeCode " ret {i2,i8*} undef") writeCode " }" when debugAborts (do writeCode ("@name_" ++ quoteName name ++ " = private constant [" ++ show (length name) ++ " x i8] c\"" ++ quoteStringConstant name ++ "\"")) writeDef :: Def -> Local -> [Local] -> GenLLVM [Label -> GenLLVM ()] writeDef (Def params expr) value args = do (bindings,nextDefLabelRefs) <- foldM writeBindParam ([],[]) (zip args params) mapM_ writeAddRef bindings mapM_ (writeUnref . Left) args writeDefExpr value bindings expr return nextDefLabelRefs writeDefExpr :: Local -> [Local] -> Expr -> GenLLVM () writeDefExpr value bindings expr = w expr where w (ExprLiteral _ []) = do mapM_ (writeUnref . Left) bindings statusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Right "2") statusPtr retValue (Right "2") Nothing w (ExprLiteral _ bits) = do mapM_ (writeUnref . Left) bindings evalParamRawPtr <- writeNewLiteralValueEvalParam bits tailCallForceRetValue evalParamRawPtr (Right "@evalLiteral") w (ExprBound index) = do let rhs = bindings !! index mapM_ (writeUnref . Left) (take index bindings ++ drop (index+1) bindings) rhsStatusPtr <- writeValueFieldPtr rhs 1 rhsStatus <- writeLoad (writeCode "i2") rhsStatusPtr cmp <- writeNewLocal "icmp ne i2 3," writeLocal rhsStatus "" (evaluatedLabelRef,unevaluatedLabelRef) <- writeBranch cmp writeNewLabelBack [evaluatedLabelRef] valueStatusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Left rhsStatus) valueStatusPtr cmp <- writeNewLocal "icmp eq i2 2," writeLocal rhsStatus "" (nilLabelRef,nonnilLabelRef) <- writeBranch cmp writeNewLabelBack [nilLabelRef] writeUnref (Left rhs) retValue (Right "2") Nothing writeNewLabelBack [nonnilLabelRef] rhsNextPtrPtr <- writeValueFieldPtr rhs 2 rhsNextRawPtr <- writeLoad (writeCode "i8*") rhsNextPtrPtr valueNextPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left rhsNextRawPtr) valueNextPtrPtr valueNext <- writeNewLocal "bitcast i8* " writeLocal rhsNextRawPtr " to " writeValueType "*" writeAddRef valueNext writeUnref (Left rhs) retValue (Left rhsStatus) (Just rhsNextRawPtr) writeNewLabelBack [unevaluatedLabelRef] rhsEvalParamPtr <- writeValueFieldPtr rhs 2 rhsEvalParam <- writeLoad (writeCode "i8*") rhsEvalParamPtr rhsEvalFuncPtr <- writeValueFieldPtr rhs 3 rhsEvalFunc <- writeLoad (writeCode "{i2,i8*}(i8*,i8*)*") rhsEvalFuncPtr rhsRawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal rhs " to i8*" refCountPtr <- writeValueFieldPtr rhs 0 refCount <- writeLoad (writeCode "i32") refCountPtr cmp <- writeNewLocal "icmp ule i32 " writeLocal refCount ",1" (noOtherRefsLabelRef,hasOtherRefsLabelRef) <- writeBranch cmp writeNewLabelBack [noOtherRefsLabelRef] writeFree (Left rhsRawPtr) tailCallForceRetValue rhsEvalParam (Left rhsEvalFunc) writeNewLabelBack [hasOtherRefsLabelRef] when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 69,{i2,i8*}(i8*,i8*)* ") writeLocal rhsEvalFunc ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) forcedResult <- writeNewLocal "call fastcc {i2,i8*} " writeLocal rhsEvalFunc "(i8* " writeLocal rhsEvalParam ",i8* " writeLocal rhsRawPtr ")" forcedStatus <- writeNewLocal "extractvalue {i2,i8*} " writeLocal forcedResult ",0" forcedNext <- writeNewLocal "extractvalue {i2,i8*} " writeLocal forcedResult ",1" nextValue <- writeNewLocal "bitcast i8* " writeLocal forcedNext " to " writeValueType "*" writeAddRef nextValue writeUnref (Left rhs) valueStatusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Left forcedStatus) valueStatusPtr valueNextPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left forcedNext) valueNextPtrPtr writeCode " ret {i2,i8*} " writeLocal forcedResult "" w (ExprFuncall (Identifier _ name) exprs) = do rhs <- writeExpr bindings expr mapM_ (writeUnref . Left) bindings -- rhs.refcount must be 1, so copy rhs into value -- future optimization: rewrite function def to take a value to -- write into instead of allocating and returning a new value rhsEvalParamPtr <- writeValueFieldPtr rhs 2 rhsEvalParam <- writeLoad (writeCode "i8*") rhsEvalParamPtr rhsEvalFuncPtr <- writeValueFieldPtr rhs 3 rhsEvalFunc <- writeLoad (writeCode "{i2,i8*}(i8*,i8*)*") rhsEvalFuncPtr rhsRawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal rhs " to i8*" writeFree (Left rhsRawPtr) tailCallForceRetValue rhsEvalParam (Left rhsEvalFunc) w (ExprConcat expr1 expr2) = do value1 <- writeExpr bindings expr1 value2 <- writeExpr bindings expr2 mapM_ (writeUnref . Left) bindings evalParamRawPtr <- writeNewConcatValueEvalParam value1 value2 tailCallForceRetValue evalParamRawPtr (Right "@evalConcat") retValue status nextValue = do retval1 <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " either (flip writeLocal "") writeCode status writeCode ",0" retval <- maybe (return retval1) (\ nextValue -> do result <- writeNewLocal "insertvalue {i2,i8*} " writeLocal retval1 ",i8* " writeLocal nextValue ",1" return result) nextValue writeCode " ret {i2,i8*} " writeLocal retval "" tailCallForceRetValue evalParam evalFunc = do when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 101,{i2,i8*}(i8*,i8*)* ") either (flip writeLocal "") writeCode evalFunc writeCode ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) retval <- writeNewLocal "musttail call fastcc {i2,i8*} " either (flip writeLocal "") writeCode evalFunc writeCode "(i8* " writeLocal evalParam ",i8* %value)" writeCode " ret {i2,i8*} " writeLocal retval "" writeBindParam :: ([Local],[Label -> GenLLVM ()]) -> (Local,Param) -> GenLLVM ([Local],[Label -> GenLLVM ()]) writeBindParam (bindings,nextDefLabelRefs) (arg,param) = w param where w (ParamBound _ bits _) = do (value,nextDefLabelRefs2) <- foldM writeCheckBit (arg,nextDefLabelRefs) bits return (bindings ++ [value],nextDefLabelRefs2) w (ParamIgnored _ bits) = do (value,nextDefLabelRefs2) <- foldM writeCheckBit (arg,nextDefLabelRefs) bits return (bindings,nextDefLabelRefs2) w (ParamLiteral _ bits) = do (value,nextDefLabelRefs2) <- foldM writeCheckBit (arg,nextDefLabelRefs) bits (_,nextDefLabelRefs3) <- writeCheckForceEval value nextDefLabelRefs2 "2" return (bindings,nextDefLabelRefs3) writeCheckBit (value,nextDefLabelRefs) bit = do writeDebugDerefValue "EFb" value (nextRawPtr,nextDefLabelRefs2) <- writeCheckForceEval value nextDefLabelRefs (if bit then "1" else "0") nextValue <- writeNewLocal "bitcast i8* " writeLocal nextRawPtr " to " writeValueType "*" return (nextValue,nextDefLabelRefs2) writeCheckForceEval value nextDefLabelRefs matchStatus = do writeCode " br label " checkForceLabelRef <- writeForwardRefLabel checkForceLabel <- writeNewLabelBack [checkForceLabelRef] writeDebugDerefValue "EF_" value statusPtr <- writeValueFieldPtr value 1 status <- writeLoad (writeCode "i2") statusPtr evalParamPtr <- writeValueFieldPtr value 2 evalParam <- writeLoad (writeCode "i8*") evalParamPtr cmp <- writeNewLocal "icmp eq i2 3," writeLocal status "" (unevaluatedLabelRef,evaluatedLabelRef) <- writeBranch cmp unevaluatedLabel <- writeNewLabelBack [unevaluatedLabelRef] evalFuncPtr <- writeValueFieldPtr value 3 evalFunc <- writeLoad (writeCode "{i2,i8*}(i8*,i8*)*") evalFuncPtr valueRawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal value " to i8*" when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 69,{i2,i8*}(i8*,i8*)* ") writeLocal evalFunc ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) forcedResult <- writeNewLocal "call fastcc {i2,i8*} " writeLocal evalFunc "(i8* " writeLocal evalParam ",i8* " writeLocal valueRawPtr ")" forcedStatus <- writeNewLocal "extractvalue {i2,i8*} " writeLocal forcedResult ",0" forcedNextRawPtr <- writeNewLocal "extractvalue {i2,i8*} " writeLocal forcedResult ",1" writeCode " br label " evaluatedLabelRef2 <- writeForwardRefLabel writeNewLabelBack [evaluatedLabelRef,evaluatedLabelRef2] status2 <- writeNewLocal "phi i2 [" writeLocal status "," writeLabelRef checkForceLabel "],[" writeLocal forcedStatus "," writeLabelRef unevaluatedLabel "]" nextRawPtr2 <- writeNewLocal "phi i8* [" writeLocal evalParam "," writeLabelRef checkForceLabel "],[" writeLocal forcedNextRawPtr "," writeLabelRef unevaluatedLabel "]" cmp <- writeNewLocal ("icmp eq i2 " ++ matchStatus ++ ",") writeLocal status2 "" (matchLabelRef,nextDefLabelRef) <- writeBranch cmp writeNewLabelBack [matchLabelRef] return (nextRawPtr2,nextDefLabelRef:nextDefLabelRefs) writeExpr :: [Local] -> Expr -> GenLLVM Local writeExpr bindings expr = w expr where w (ExprLiteral _ bits) = do writeNewConstantLiteralValue bits w (ExprBound index) = do writeAddRef (bindings !! index) return (bindings !! index) w (ExprFuncall (Identifier _ name) exprs) = do args <- mapM (writeExpr bindings) exprs value <- writeNewLocal "call fastcc " writeValueType "* " writeName name writeCode "(" zipWithM_ (\ comma arg -> do writeCode comma writeValueType "* " writeLocal arg "") ("":repeat ",") args writeCode ")" return value w (ExprConcat expr1 expr2) = do value1 <- writeExpr bindings expr1 value2 <- writeExpr bindings expr2 (value,_) <- writeNewConcatValue value1 value2 return value writeForceEval :: Local -> GenLLVM (Local,Local) writeForceEval value = do statusPtr <- writeValueFieldPtr value 1 status <- writeLoad (writeCode "i2") statusPtr cmp <- writeNewLocal "icmp ne i2 3," writeLocal status "" (evaluatedLabelRef,unevaluatedLabelRef) <- writeBranch cmp evaluatedLabel <- writeNewLabelBack [evaluatedLabelRef] cmp <- writeNewLocal "icmp ne i2 2," writeLocal status "" (nonnilLabelRef,doneLabelRef) <- writeBranch cmp nonnilLabel <- writeNewLabelBack [nonnilLabelRef] nextPtrPtr <- writeValueFieldPtr value 2 nextRawPtr <- writeLoad (writeCode "i8*") nextPtrPtr next <- writeNewLocal "bitcast i8* " writeLocal nextRawPtr " to " writeValueType "*" writeCode " br label " doneLabelRef2 <- writeForwardRefLabel unevaluatedLabel <- writeNewLabelBack [unevaluatedLabelRef] (forcedStatus,forcedNext,_,_) <- writeForceEvalUnevaluated value writeCode " br label " doneLabelRef3 <- writeForwardRefLabel writeNewLabelBack [doneLabelRef,doneLabelRef2,doneLabelRef3] finalStatus <- writeNewLocal "phi i2 [" writeLocal status "," writeLabelRef evaluatedLabel "],[" writeLocal status "," writeLabelRef nonnilLabel "],[" writeLocal forcedStatus "," writeLabelRef unevaluatedLabel "]" finalNext <- writeNewLocal "phi " writeValueType "* [null," writeLabelRef evaluatedLabel "],[" writeLocal next "," writeLabelRef nonnilLabel "],[" writeLocal forcedNext "," writeLabelRef unevaluatedLabel "]" return (finalStatus,finalNext) writeForceEvalUnevaluated :: Local -> GenLLVM (Local,Local,Local,Local) writeForceEvalUnevaluated value = do evalParamPtr <- writeValueFieldPtr value 2 evalParam <- writeLoad (writeCode "i8*") evalParamPtr evalPtr <- writeValueFieldPtr value 3 valueRawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal value " to i8*" eval <- writeLoad (writeCode "{i2,i8*}(i8*,i8*)*") evalPtr when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 69,{i2,i8*}(i8*,i8*)* ") writeLocal eval ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) evalResult <- writeNewLocal "call fastcc {i2,i8*} " writeLocal eval "(i8* " writeLocal evalParam ",i8* " writeLocal valueRawPtr ")" status <- writeNewLocal "extractvalue {i2,i8*} " writeLocal evalResult ",0" nextValueRawPtr <- writeNewLocal "extractvalue {i2,i8*} " writeLocal evalResult ",1" nextValue <- writeNewLocal "bitcast i8* " writeLocal nextValueRawPtr " to " writeValueType "*" return (status,nextValue,nextValueRawPtr,evalResult) writeAddRef :: Local -> GenLLVM () writeAddRef value = do refCountPtr <- writeValueFieldPtr value 0 oldRefCount <- writeLoad (writeCode "i32") refCountPtr newRefCount <- writeNewLocal "add i32 1," writeLocal oldRefCount "" writeStore (writeCode "i32") (Left newRefCount) refCountPtr writeUnref :: Either Local String -> GenLLVM () writeUnref value = do writeCode " call fastcc void @unref(" writeValueType "* " either (flip writeLocal "") writeCode value writeCode ")" writeDecls :: GenLLVM () writeDecls = do writeCode "declare i8* @malloc(i32)" writeCode "declare void @free(i8*)" writeCode "declare void @abort() noreturn " writeCode "declare i32 @read(i32,i8*,i32)" writeCode "declare i32 @write(i32,i8*,i32)" writeCode "declare i32 @open(i8*,i32)" writeCode "declare i32 @close(i32)" writeCode "declare void @perror(i8*)" writeCode "declare void @exit(i32) noreturn " writeUnrefDefn :: GenLLVM () writeUnrefDefn = do writeCode "define private fastcc void @unref(" writeValueType "* %value) {" writeNewLabel refCountPtr <- writeGetElementPtr (writeValueType "") (Right "%value") "i32 0,i32 0" oldRefCount <- writeLoad (writeCode "i32") refCountPtr newRefCount <- writeNewLocal "sub i32 " writeLocal oldRefCount ",1" cmp <- writeNewLocal "icmp ugt i32 " writeLocal newRefCount ",0" (aliveRef,deadRef) <- writeBranch cmp writeNewLabelBack [aliveRef] writeStore (writeCode "i32") (Left newRefCount) refCountPtr writeCode " ret void" writeNewLabelBack [deadRef] statusPtr <- writeGetElementPtr (writeValueType "") (Right "%value") "i32 0,i32 1" status <- writeLoad (writeCode "i2") statusPtr cmp <- writeNewLocal "icmp eq i2 3," writeLocal status "" (unevaluatedRef,evaluatedRef) <- writeBranch cmp writeNewLabelBack [unevaluatedRef] evalParamPtr <- writeGetElementPtr (writeValueType "") (Right "%value") "i32 0,i32 2" evalParam <- writeLoad (writeCode "i8*") evalParamPtr freeEvalParamPtr <- writeGetElementPtr (writeValueType "") (Right "%value") "i32 0,i32 4" freeEvalParam <- writeLoad (writeCode "void(i8*)*") freeEvalParamPtr when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 70,void(i8*)* ") writeLocal freeEvalParam ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) writeCode " call fastcc void " writeLocal freeEvalParam "(i8* " writeLocal evalParam ")" rawPtr <- writeNewLocal "bitcast " writeValueType "* %value to i8*" writeFree (Left rawPtr) writeCode " ret void" writeNewLabelBack [evaluatedRef] cmp <- writeNewLocal "icmp eq i2 2," writeLocal status "" (nilRef,nonnilRef) <- writeBranch cmp writeNewLabelBack [nilRef] rawPtr <- writeNewLocal "bitcast " writeValueType "* %value to i8*" writeFree (Left rawPtr) writeCode " ret void" writeNewLabelBack [nonnilRef] nextValueRawPtrPtr <- writeGetElementPtr (writeValueType "") (Right "%value") "i32 0,i32 2" nextValueRawPtr <- writeLoad (writeCode "i8*") nextValueRawPtrPtr nextValue <- writeNewLocal "bitcast i8* " writeLocal nextValueRawPtr " to " writeValueType "*" rawPtr <- writeNewLocal "bitcast " writeValueType "* %value to i8*" writeFree (Left rawPtr) writeCode " musttail call fastcc void @unref(" writeValueType "* " writeLocal nextValue ")" writeCode " ret void" writeCode " }" writeAllocateNewValue :: Int -> GenLLVM (Local,Local) writeAllocateNewValue initialStatus = do rawPtr <- writeAlloc (writeValueType "") value <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeValueType "*" refCountPtr <- writeValueFieldPtr value 0 writeStore (writeCode "i32") (Right "1") refCountPtr statusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Right (show initialStatus)) statusPtr return (value,rawPtr) writeLiteralValueEvalParamType :: String -> GenLLVM () writeLiteralValueEvalParamType code = do -- 0:[0 x i1]* bit array -- 1:i32 current index -- 2:i32 array length writeCode ("{[0 x i1]*,i32,i32}" ++ code) writeNewConstantLiteralValue :: [Bool] -> GenLLVM Local writeNewConstantLiteralValue bits | null bits = writeNewNilValue | otherwise = do bitArray <- writeNewLocal ("bitcast " ++ literalType bits ++ "* " ++ literalName bits ++ " to [0 x i1]*") value <- writeNewLiteralValue (Right (length bits)) bitArray return value writeNewLiteralValueEvalParam :: [Bool] -> GenLLVM Local writeNewLiteralValueEvalParam bits = do rawPtr <- writeAlloc (writeLiteralValueEvalParamType "") evalParam <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeLiteralValueEvalParamType "*" bitArrayPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 0" bitArray <- writeNewLocal ("bitcast " ++ literalType bits ++ "* " ++ literalName bits ++ " to [0 x i1]*") writeStore (writeCode "[0 x i1]*") (Left bitArray) bitArrayPtr currentIndexPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 1" writeStore (writeCode "i32") (Right "0") currentIndexPtr arraySizePtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 2" writeStore (writeCode "i32") (Right (show (length bits))) arraySizePtr return rawPtr writeNewLiteralValue :: Either Local Int -> Local -> GenLLVM Local writeNewLiteralValue arraySize bitArray = do (value,valueRawPtr) <- writeAllocateNewValue 3 rawPtr <- writeAlloc (writeLiteralValueEvalParamType "") evalParamRawPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left rawPtr) evalParamRawPtrPtr evalParam <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeLiteralValueEvalParamType "*" bitArrayPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 0" writeStore (writeCode "[0 x i1]*") (Left bitArray) bitArrayPtr currentIndexPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 1" writeStore (writeCode "i32") (Right "0") currentIndexPtr arraySizePtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 2" writeStore (writeCode "i32") (fmap show arraySize) arraySizePtr evalFuncPtr <- writeValueFieldPtr value 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right "@evalLiteral") evalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr value 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamLiteral") freeEvalParamFuncPtr return value writeEvalLiteralValueDefn :: GenLLVM () writeEvalLiteralValueDefn = do writeCode "define private fastcc {i2,i8*} " writeCode "@evalLiteral(i8* %evalParam,i8* %value) {" writeNewLabel evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeLiteralValueEvalParamType "*" value <- writeNewLocal "bitcast i8* %value to " writeValueType "*" statusPtr <- writeValueFieldPtr value 1 currentIndexPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 1" currentIndex <- writeLoad (writeCode "i32") currentIndexPtr arraySizePtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 2" arraySize <- writeLoad (writeCode "i32") arraySizePtr cmp <- writeNewLocal "icmp ult i32 " writeLocal currentIndex "," writeLocal arraySize "" (anotherBitLabelRef,nilLabelRef) <- writeBranch cmp writeNewLabelBack [anotherBitLabelRef] nextIndex <- writeNewLocal "add i32 1," writeLocal currentIndex "" writeStore (writeCode "i32") (Left nextIndex) currentIndexPtr bitArrayPtr <- writeGetElementPtr (writeLiteralValueEvalParamType "") (Left evalParam) "i32 0,i32 0" bitArray <- writeLoad (writeCode "[0 x i1]*") bitArrayPtr bitPtr <- writeGetElementPtr (writeCode "[0 x i1]") (Left bitArray) "i32 0,i32 " writeLocal currentIndex "" bit <- writeLoad (writeCode "i1") bitPtr newStatus <- writeNewLocal "zext i1 " writeLocal bit " to i2" writeStore (writeCode "i2") (Left newStatus) statusPtr (nextValue,nextValueRawPtr) <- writeAllocateNewValue 3 valueNextPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left nextValueRawPtr) valueNextPtr nextValueEvalParamPtr <- writeValueFieldPtr nextValue 2 writeStore (writeCode "i8*") (Right "%evalParam") nextValueEvalParamPtr nextValueEvalFuncPtr <- writeValueFieldPtr nextValue 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right "@evalLiteral") nextValueEvalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr nextValue 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamLiteral") freeEvalParamFuncPtr retVal1 <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " writeLocal newStatus ",0" retVal <- writeNewLocal "insertvalue {i2,i8*} " writeLocal retVal1 ",i8* " writeLocal nextValueRawPtr ",1" writeCode " ret {i2,i8*} " writeLocal retVal "" writeNewLabelBack [nilLabelRef] writeFree (Right "%evalParam") writeStore (writeCode "i2") (Right "2") statusPtr retVal <- writeNewLocal "insertvalue {i2,i8*} undef,i2 2,0" writeCode " ret {i2,i8*} " writeLocal retVal "" writeCode " }" writeFreeEvalParamLiteralValueDefn :: GenLLVM () writeFreeEvalParamLiteralValueDefn = do writeCode "define private fastcc void " writeCode "@freeEvalParamLiteral(i8* %evalParam) {" writeFree (Right "%evalParam") writeCode " ret void" writeCode " }" writeConcatValueEvalParamType :: String -> GenLLVM () writeConcatValueEvalParamType code = do -- 0:value type* first -- 1:value type* rest writeCode "{" writeValueType "*," writeValueType ("*}" ++ code) writeNewConcatValueEvalParam :: Local -> Local -> GenLLVM Local writeNewConcatValueEvalParam value1 value2 = do rawPtr <- writeAlloc (writeConcatValueEvalParamType "") evalParam <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeConcatValueEvalParamType "*" ptr1 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 0" writeStore (writeValueType "*") (Left value1) ptr1 ptr2 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 1" writeStore (writeValueType "*") (Left value2) ptr2 return rawPtr writeNewConcatValue :: Local -> Local -> GenLLVM (Local,Local) writeNewConcatValue value1 value2 = do (value,valueRawPtr) <- writeAllocateNewValue 3 rawPtr <- writeAlloc (writeConcatValueEvalParamType "") evalParamRawPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left rawPtr) evalParamRawPtrPtr evalParam <- writeNewLocal "bitcast i8* " writeLocal rawPtr " to " writeConcatValueEvalParamType "*" ptr1 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 0" writeStore (writeValueType "*") (Left value1) ptr1 ptr2 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 1" writeStore (writeValueType "*") (Left value2) ptr2 evalFuncPtr <- writeValueFieldPtr value 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right "@evalConcat") evalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr value 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamConcat") freeEvalParamFuncPtr return (value,valueRawPtr) writeEvalConcatValueDefn :: GenLLVM () writeEvalConcatValueDefn = do writeCode "define private fastcc {i2,i8*} " writeCode "@evalConcat(i8* %evalParam,i8* %value) {" writeNewLabel evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeConcatValueEvalParamType "*" value <- writeNewLocal "bitcast i8* %value to " writeValueType "*" ptr1 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 0" value1 <- writeLoad (writeValueType "*") ptr1 ptr2 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 1" value2 <- writeLoad (writeValueType "*") ptr2 (status1,nextValue1) <- writeForceEval value1 cmp <- writeNewLocal "icmp eq i2 3," writeLocal status1 "" (abortLabelRef1,okLabelRef1) <- writeBranch cmp abortLabel <- writeNewLabelBack [abortLabelRef1] writeCode " call void @abort() noreturn" writeCode " ret {i2,i8*} undef" writeNewLabelBack [okLabelRef1] cmp <- writeNewLocal "icmp ne i2 2," writeLocal status1 "" (nonnilLabelRef1,nilLabelRef1) <- writeBranch cmp writeNewLabelBack [nonnilLabelRef1] writeAddRef nextValue1 writeUnref (Left value1) writeStore (writeValueType "*") (Left nextValue1) ptr1 (newNext,newNextRawPtr) <- writeAllocateNewValue 3 nextEvalParamPtr <- writeValueFieldPtr newNext 2 writeStore (writeCode "i8*") (Right "%evalParam") nextEvalParamPtr evalFuncPtr <- writeValueFieldPtr newNext 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right "@evalConcat") evalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr newNext 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamConcat") freeEvalParamFuncPtr valueStatusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Left status1) valueStatusPtr valueNextPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left newNextRawPtr) valueNextPtrPtr retValue1 <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " writeLocal status1 ",0" retValue <- writeNewLocal "insertvalue {i2,i8*} " writeLocal retValue1 ",i8* " writeLocal newNextRawPtr ",1" writeCode " ret {i2,i8*} " writeLocal retValue "" writeNewLabelBack [nilLabelRef1] writeUnref (Left value1) writeFree (Right "%evalParam") statusPtr2 <- writeValueFieldPtr value2 1 status2 <- writeLoad (writeCode "i2") statusPtr2 cmp <- writeNewLocal "icmp eq i2 3," writeLocal status2 "" (unevaluatedLabelRef2,evaluatedLabelRef2) <- writeBranch cmp writeNewLabelBack [unevaluatedLabelRef2] value2RawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal value2 " to i8*" evalParamPtr2 <- writeValueFieldPtr value2 2 evalParam2 <- writeLoad (writeCode "i8*") evalParamPtr2 evalFuncPtr2 <- writeValueFieldPtr value2 3 evalFunc2 <- writeLoad (writeCode "{i2,i8*}(i8*,i8*)*") evalFuncPtr2 refCountPtr <- writeValueFieldPtr value2 0 refCount <- writeLoad (writeCode "i32") refCountPtr cmp <- writeNewLocal "icmp ule i32 " writeLocal refCount ",1" (noOtherRefsLabelRef2,hasOtherRefsLabelRef2) <- writeBranch cmp writeNewLabelBack [noOtherRefsLabelRef2] writeFree (Left value2RawPtr) when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 101,{i2,i8*}(i8*,i8*)* ") writeLocal evalFunc2 ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) retValue <- writeNewLocal "musttail call fastcc {i2,i8*} " writeLocal evalFunc2 "(i8* " writeLocal evalParam2 ",i8* %value)" writeCode " ret {i2,i8*} " writeLocal retValue "" hasOtherRefsLabel2 <- writeNewLabelBack [hasOtherRefsLabelRef2] when debugIndirectCalls (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([7 x i8],[7 x i8]* @debugIndirectCallsFmt" ++ ",i32 0,i32 0),i8 69,{i2,i8*}(i8*,i8*)* ") writeLocal evalFunc2 ")" writeNewLocal "call i32 @fflush(i8* null)" return ()) value2Eval <- writeNewLocal "call fastcc {i2,i8*} " writeLocal evalFunc2 "(i8* " writeLocal evalParam2 ",i8* %value)" value2Status <- writeNewLocal "extractvalue {i2,i8*} " writeLocal value2Eval ",0" value2NextRawPtr <- writeNewLocal "extractvalue {i2,i8*} " writeLocal value2Eval ",1" writeCode " br label " copyLabelRef2 <- writeForwardRefLabel evaluatedLabel2 <- writeNewLabelBack [evaluatedLabelRef2] value2NextPtr <- writeValueFieldPtr value2 2 value2NextRawPtr2 <- writeLoad (writeCode "i8*") value2NextPtr writeCode " br label " copyLabelRef3 <- writeForwardRefLabel writeNewLabelBack [copyLabelRef2,copyLabelRef3] copyStatus2 <- writeNewLocal "phi i2 [" writeLocal value2Status "," writeLabelRef hasOtherRefsLabel2 "],[" writeLocal status2 "," writeLabelRef evaluatedLabel2 "]" copyNextRawPtr2 <- writeNewLocal "phi i8* [" writeLocal value2NextRawPtr "," writeLabelRef hasOtherRefsLabel2 "],[" writeLocal value2NextRawPtr2 "," writeLabelRef evaluatedLabel2 "]" valueStatusPtr <- writeValueFieldPtr value 1 writeStore (writeCode "i2") (Left copyStatus2) valueStatusPtr cmp <- writeNewLocal "icmp eq i2 2," writeLocal copyStatus2 "" (copy2NilLabelRef,copy2NotNilLabelRef) <- writeBranch cmp writeNewLabelBack [copy2NilLabelRef] writeUnref (Left value2) retValue <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " writeLocal copyStatus2 ",0" writeCode " ret {i2,i8*} " writeLocal retValue "" writeNewLabelBack [copy2NotNilLabelRef] valueNextPtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left copyNextRawPtr2) valueNextPtrPtr copyNext <- writeNewLocal "bitcast i8* " writeLocal copyNextRawPtr2 " to " writeValueType "*" writeAddRef copyNext writeUnref (Left value2) retValue1 <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " writeLocal copyStatus2 ",0" retValue <- writeNewLocal "insertvalue {i2,i8*} " writeLocal retValue1 ",i8* " writeLocal copyNextRawPtr2 ",1" writeCode " ret {i2,i8*} " writeLocal retValue "" writeCode " }" writeFreeEvalParamConcatValueDefn :: GenLLVM () writeFreeEvalParamConcatValueDefn = do writeCode "define private fastcc void " writeCode "@freeEvalParamConcat(i8* %evalParam) {" writeNewLabel evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeConcatValueEvalParamType "*" ptr1 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 0" value1 <- writeLoad (writeValueType "*") ptr1 writeUnref (Left value1) ptr2 <- writeGetElementPtr (writeConcatValueEvalParamType "") (Left evalParam) "i32 0,i32 1" value2 <- writeLoad (writeValueType "*") ptr2 writeUnref (Left value2) writeFree (Right "%evalParam") writeCode " ret void" writeCode " }" writeFileValueEvalParamType :: String -> GenLLVM () writeFileValueEvalParamType code = do -- 0:i32 file descriptor -- 1:i8 current bit index -- 2:i8 current byte writeCode ("{i32,i8,i8}" ++ code) writeNewFileValue :: Either Local String -> GenLLVM Local writeNewFileValue fd = do (value,_) <- writeAllocateNewValue 3 evalParamRawPtr <- writeAlloc (writeFileValueEvalParamType "") evalParam <- writeNewLocal "bitcast i8* " writeLocal evalParamRawPtr " to " writeFileValueEvalParamType "*" fdPtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 0" writeStore (writeCode "i32") fd fdPtr bitIndexPtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 1" writeStore (writeCode "i8") (Right "-1") bitIndexPtr evalParamPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left evalParamRawPtr) evalParamPtr evalFuncPtr <- writeValueFieldPtr value 3 writeCode " store {i2,i8*}(i8*,i8*)* @evalFile,{i2,i8*}(i8*,i8*)** " writeLocal evalFuncPtr "" freeEvalParamFuncPtr <- writeValueFieldPtr value 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamFile") freeEvalParamFuncPtr return value writeEvalFileValueDefn :: GenLLVM () writeEvalFileValueDefn = do writeCode "define private fastcc {i2,i8*} " writeCode "@evalFile(i8* %evalParam,i8* %value) {" entryLabel <- writeNewLabel evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeFileValueEvalParamType "*" value <- writeNewLocal "bitcast i8* %value to " writeValueType "*" statusPtr <- writeValueFieldPtr value 1 bitIndexPtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 1" bytePtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 2" bitIndex <- writeLoad (writeCode "i8") bitIndexPtr cmp <- writeNewLocal "icmp slt i8 " writeLocal bitIndex ",0" (readNewByteLabelRef,evalNextBitLabelRef) <- writeBranch cmp readNewByteLabel <- writeNewLabelBack [readNewByteLabelRef] fdPtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 0" fd <- writeLoad (writeCode "i32") fdPtr readResult <- writeNewLocal "call i32 @read(i32 " writeLocal fd ",i8* " writeLocal bytePtr ",i32 1)" cmp <- writeNewLocal "icmp eq i32 1," writeLocal readResult "" (evalNextBitLabelRef2,eofLabelRef) <- writeBranch cmp writeNewLabelBack [evalNextBitLabelRef,evalNextBitLabelRef2] currentBitIndex <- writeNewLocal "phi i8 [" writeLocal bitIndex "," writeLabelRef entryLabel "],[7," writeLabelRef readNewByteLabel "]" nextBitIndex <- writeNewLocal "sub i8 " writeLocal currentBitIndex ",1" writeStore (writeCode "i8") (Left nextBitIndex) bitIndexPtr byte <- writeLoad (writeCode "i8") bytePtr shiftedByte <- writeNewLocal "lshr i8 " writeLocal byte "," writeLocal currentBitIndex "" almostNewStatus <- writeNewLocal "trunc i8 " writeLocal shiftedByte " to i2" newStatus <- writeNewLocal "and i2 1," writeLocal almostNewStatus "" writeStore (writeCode "i2") (Left newStatus) statusPtr (nextValue,nextValueRawPtr) <- writeAllocateNewValue 3 nextValuePtrPtr <- writeValueFieldPtr value 2 writeStore (writeCode "i8*") (Left nextValueRawPtr) nextValuePtrPtr nextValueEvalParamPtr <- writeValueFieldPtr nextValue 2 writeStore (writeCode "i8*") (Right "%evalParam") nextValueEvalParamPtr evalFuncPtr <- writeValueFieldPtr nextValue 3 writeStore (writeCode "{i2,i8*}(i8*,i8*)*") (Right "@evalFile") evalFuncPtr freeEvalParamFuncPtr <- writeValueFieldPtr nextValue 4 writeStore (writeCode "void(i8*)*") (Right "@freeEvalParamFile") freeEvalParamFuncPtr retVal1 <- writeNewLocal "insertvalue {i2,i8*} undef,i2 " writeLocal newStatus ",0" retVal <- writeNewLocal "insertvalue {i2,i8*} " writeLocal retVal1 ",i8* " writeLocal nextValueRawPtr ",1" writeCode " ret {i2,i8*} " writeLocal retVal "" writeNewLabelBack [eofLabelRef] writeNewLocal "call i32 @close(i32 " writeLocal fd ")" writeFree (Right "%evalParam") writeStore (writeCode "i2") (Right "2") statusPtr retVal <- writeNewLocal "insertvalue {i2,i8*} undef,i2 2,0" writeCode " ret {i2,i8*} " writeLocal retVal "" writeCode " }" writeFreeEvalParamFileValueDefn :: GenLLVM () writeFreeEvalParamFileValueDefn = do writeCode "define private fastcc void " writeCode "@freeEvalParamFile(i8* %evalParam) {" writeNewLabel evalParam <- writeNewLocal "bitcast i8* %evalParam to " writeFileValueEvalParamType "*" fdPtr <- writeGetElementPtr (writeFileValueEvalParamType "") (Left evalParam) "i32 0,i32 0" fd <- writeLoad (writeCode "i32") fdPtr writeNewLocal "call i32 @close(i32 " writeLocal fd ")" writeFree (Right "%evalParam") writeCode " ret void" writeCode " }" writeNewNilValue :: GenLLVM Local writeNewNilValue = do (value,_) <- writeAllocateNewValue 2 return value genMain :: String -> [Def] -> String genMain name (Def params _:_) = genLLVM (do writeCode "define void @main(i32 %argc,i8** %argv) {" writeNewLabel writeInitDebugMemory args <- if null params then return [] else do nilValue <- writeNewNilValue stdinValue <- writeNewFileValue (Right "0") args <- mapM (writeArg nilValue stdinValue) [1 .. length params] writeUnref (Left nilValue) writeUnref (Left stdinValue) return args result <- writeNewLocal "call fastcc " writeValueType "* " writeName name writeCode "(" zipWithM_ (\ comma arg -> do writeCode comma writeValueType "* " writeLocal arg "") ("":repeat ",") args writeCode ")" writeCode " br label " entryLabelRef <- writeForwardRefLabel entryLabel <- writeNewLabelBack [entryLabelRef] buffer <- writeNewLocal "alloca i8,i32 1" writeCode " br label " loopLabelRef <- writeForwardRefLabel loopLabel <- writeNewLabelBack [loopLabelRef] (value,valuePhiRef) <- writePhi (writeValueType "*") (Left result) entryLabel (bitIndex,bitIndexPhiRef) <- writePhi (writeCode "i8") (Right "7") entryLabel writeCode ",[7," bitIndexPhiLabelRef <- writeForwardRefLabel writeCode "]" (byte,bytePhiRef) <- writePhi (writeCode "i8") (Right "0") entryLabel writeCode ",[0," bytePhiLabelRef <- writeForwardRefLabel writeCode "]" (status,nextValue) <- writeForceEval value cmp <- writeNewLocal "icmp eq i2 3," writeLocal status "" (abortLabelRef,okLabelRef) <- writeBranch cmp writeNewLabelBack [abortLabelRef] writeCode " call void @abort() noreturn" writeCode " ret void" writeNewLabelBack [okLabelRef] cmp <- writeNewLocal "icmp eq i2 2," writeLocal status "" (eofLabelRef,nextBitLabelRef) <- writeBranch cmp writeNewLabelBack [eofLabelRef] writeUnref (Left value) writeFinalizeDebugMemory writeCode " call void @exit(i32 0) noreturn" writeCode " ret void" nextBitLabel <- writeNewLabelBack [nextBitLabelRef] writeAddRef nextValue writeUnref (Left value) nextBit <- writeNewLocal "zext i2 " writeLocal status " to i8" shiftedBit <- writeNewLocal "shl i8 " writeLocal nextBit "," writeLocal bitIndex "" nextByte <- writeNewLocal "or i8 " writeLocal byte "," writeLocal shiftedBit "" nextBitIndex <- writeNewLocal "sub i8 " writeLocal bitIndex ",1" valuePhiRef nextValue nextBitLabel bitIndexPhiRef nextBitIndex nextBitLabel bytePhiRef nextByte nextBitLabel cmp <- writeNewLocal "icmp sge i8 " writeLocal nextBitIndex ",0" (continueRef,nextByteRef) <- writeBranch cmp continueRef loopLabel nextByteLabel <- writeNewLabelBack [nextByteRef,bitIndexPhiLabelRef,bytePhiLabelRef] valuePhiRef nextValue nextByteLabel writeStore (writeCode "i8") (Left nextByte) buffer writeNewLocal "call i32 @write(i32 1,i8* " writeLocal buffer ",i32 1)" writeCode " br label " writeLabelRef loopLabel "" writeCode " }") where writeArg nilValue stdinValue index = do -- if index < argc, open(argv[index]) -- else if index == argc, stdin -- else nil cmp <- writeNewLocal ("icmp ult i32 " ++ show index ++ ",%argc") (fileArgLabelRef,unspecifiedArgLabelRef) <- writeBranch cmp writeNewLabelBack [fileArgLabelRef] filenamePtr <- writeNewLocal ("getelementptr i8*,i8** %argv,i32 "++ show index) filename <- writeLoad (writeCode "i8*") filenamePtr fd <- writeNewLocal "call i32 @open(i8* " writeLocal filename ",i32 0)" cmp <- writeNewLocal "icmp sge i32 " writeLocal fd ",0" (openFileSuccessLabelRef,openFileFailLabelRef) <- writeBranch cmp openFileSuccessLabel <- writeNewLabelBack [openFileSuccessLabelRef] fileValue <- writeNewFileValue (Left fd) writeCode " br label " endArgLabelRef1 <- writeForwardRefLabel writeNewLabelBack [openFileFailLabelRef] writeCode " call void @perror(i8* " writeLocal filename ")" writeCode " call void @exit(i32 -1) noreturn" writeCode " ret void" writeNewLabelBack [unspecifiedArgLabelRef] cmp <- writeNewLocal ("icmp eq i32 " ++ show index ++ ",%argc") (stdinArgLabelRef,nilArgLabelRef) <- writeBranch cmp stdinArgLabel <- writeNewLabelBack [stdinArgLabelRef] writeAddRef stdinValue writeCode " br label " endArgLabelRef2 <- writeForwardRefLabel nilArgLabel <- writeNewLabelBack [nilArgLabelRef] writeAddRef nilValue writeCode " br label " endArgLabelRef3 <- writeForwardRefLabel writeNewLabelBack [endArgLabelRef1,endArgLabelRef2,endArgLabelRef3] argValue <- writeNewLocal "phi " writeValueType "* [" writeLocal fileValue "," writeLabelRef openFileSuccessLabel "],[" writeLocal stdinValue "," writeLabelRef stdinArgLabel "],[" writeLocal nilValue "," writeLabelRef nilArgLabel "]" return argValue writeAlloc :: GenLLVM () -> GenLLVM Local writeAlloc writeType = do sizePtr <- writeGetElementPtr writeType (Right "null") "i32 1" size <- writeNewLocal "ptrtoint " writeType writeCode "* " writeLocal sizePtr " to i32" writeMalloc size writeMalloc :: Local -> GenLLVM Local writeMalloc size = do result <- writeNewLocal "call " if debugMemory then writeCode "fastcc i8* @debugMalloc" else writeCode "i8* @malloc" writeCode "(i32 " writeLocal size ")" return result writeFree :: Either Local String -> GenLLVM () writeFree value = do if debugMemory then writeCode " call fastcc void @debugFree" else writeCode " call void @free" writeCode "(i8* " either (flip writeLocal "") writeCode value writeCode ")" writeInitDebugMemory :: GenLLVM () writeInitDebugMemory | not debugMemory = return () | otherwise = do writeCode " store i32 0,i32* @debugMemoryCount" writeFinalizeDebugMemory :: GenLLVM () writeFinalizeDebugMemory | not debugMemory = return () | otherwise = do count <- writeNewLocal "load i32,i32* @debugMemoryCount" fmt <- writeNewLocal "getelementptr [10 x i8],[10 x i8]* @debugMemoryOutputFmt,i32 0,i32 0" writeNewLocal "call i32(i8*,...) @printf(i8* " writeLocal fmt ",i32 " writeLocal count ")" writeDebugDefns :: GenLLVM () writeDebugDefns | not (debugMemory || debugIndirectCalls || debugDeref) = return () | otherwise = do writeCode "@debugMemoryCount = private global i32 0 " writeCode "@debugMemoryOutputFmt = private constant [10 x i8] " writeCode "c\"count=%d\\0a\\00\" " writeCode "declare i32 @printf(i8*,...)" writeCode "declare i32 @fflush(i8*)" when debugMemoryAllocs (do writeCode ("@debugMemoryAllocsFmt = private constant " ++ "[9 x i8] c\"%c%d:%x\\0A\\00\"")) when debugIndirectCalls (do writeCode ("@debugIndirectCallsFmt = private constant " ++ "[7 x i8] c\"%c:%x\\0A\\00\"")) when debugDeref (do writeCode ("@debugDerefFmt = private constant " ++ "[12 x i8] c\"*%c%c%c:%x\\0A\\00\"")) writeDebugMemoryMallocDefn :: GenLLVM () writeDebugMemoryMallocDefn | not debugMemory = return () | otherwise = do writeCode "define fastcc i8* @debugMalloc(i32 %size) {" writeNewLabel oldCount <- writeNewLocal "load i32,i32* @debugMemoryCount" newCount <- writeNewLocal "add i32 1," writeLocal oldCount "" writeCode " store i32 " writeLocal newCount ",i32* @debugMemoryCount" result <- writeNewLocal "call i8* @malloc(i32 %size)" when debugMemoryAllocs (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([9 x i8],[9 x i8]* @debugMemoryAllocsFmt" ++ ",i32 0,i32 0),i8 65,i32 ") writeLocal newCount ",i8* " writeLocal result ")" writeNewLocal "call i32(i8*) @fflush(i8* null)" return ()) writeCode " ret i8* " writeLocal result "" writeCode " }" writeDebugMemoryFreeDefn :: GenLLVM () writeDebugMemoryFreeDefn | not debugMemory = return () | otherwise = do writeCode "define fastcc void @debugFree(i8* %value) {" writeNewLabel oldCount <- writeNewLocal "load i32,i32* @debugMemoryCount" newCount <- writeNewLocal "sub i32 " writeLocal oldCount ",1" writeCode " store i32 " writeLocal newCount ",i32* @debugMemoryCount" when debugMemoryAllocs (do writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([9 x i8],[9 x i8]* @debugMemoryAllocsFmt" ++ ",i32 0,i32 0),i8 70,i32 ") writeLocal newCount ",i8* %value)" writeNewLocal "call i32(i8*) @fflush(i8* null)" return ()) writeCode " call void @free(i8* %value)" writeCode " ret void" writeCode " }" writeDebugDeref :: String -> String -> GenLLVM () writeDebugDeref tag value | not debugDeref = return () | otherwise = do rawPtr <- writeNewLocal ("select i1 1,i8* " ++ value ++ ",i8* " ++ value) writeDebugDerefRawPtr tag rawPtr writeDebugDerefValue :: String -> Local -> GenLLVM () writeDebugDerefValue tag value | not debugDeref = return () | otherwise = do rawPtr <- writeNewLocal "bitcast " writeValueType "* " writeLocal value " to i8*" writeDebugDerefRawPtr tag rawPtr writeDebugDerefRawPtr :: String -> Local -> GenLLVM () writeDebugDerefRawPtr tag rawPtr | not debugDeref = return () | otherwise = do let (tag1:tag2:tag3:_) = tag ++ repeat ' ' writeNewLocal ("call i32(i8*,...) @printf(i8* getelementptr " ++ "([12 x i8],[12 x i8]* @debugDerefFmt" ++ ",i32 0,i32 0),i8 " ++ show (ord tag1) ++ ",i8 " ++ show (ord tag2) ++ ",i8 " ++ show (ord tag3) ++ ",i8* ") writeLocal rawPtr ")" writeNewLocal "call i32(i8*) @fflush(i8* null)" return ()
qpliu/esolang
01_/hs/compiler2/CodeGen.hs
gpl-3.0
59,554
0
27
15,217
14,354
6,356
7,998
1,322
5
{-# LANGUAGE OverloadedStrings #-} -- | Implements the org.mpris.MediaPlayer2 interface. -- -- More information at <http://specifications.freedesktop.org/mpris-spec/latest/Media_Player.html> module DBus.Mpris.MediaPlayer2 ( module DBus.Mpris.MediaPlayer2.Methods , module DBus.Mpris.MediaPlayer2.Properties , module DBus.Mpris.MediaPlayer2.Data ) where import DBus.Mpris.MediaPlayer2.Methods import DBus.Mpris.MediaPlayer2.Properties import DBus.Mpris.MediaPlayer2.Data
Fuco1/mpris
src/DBus/Mpris/MediaPlayer2.hs
gpl-3.0
500
0
5
65
58
43
15
8
0
{- Symbol This file is part of AEx. Copyright (C) 2016 Jeffrey Sharp AEx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AEx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AEx. If not, see <http://www.gnu.org/licenses/>. -} module Aex.Symbol where import Aex.Types import Aex.Util data Symbol = Symbol { name :: !Name , typé :: !Type } deriving (Eq, Show)
sharpjs/haskell-learning
src/Aex/Symbol.hs
gpl-3.0
876
1
9
223
52
31
21
11
0
-- | Parse HMMCompare output module Bio.HMMCompareResult ( HMMCompareResult(..), parseHMMCompareResult, readHMMCompareResult, getHMMCompareResults, getModelsNames, getModelNames ) where import Text.ParserCombinators.Parsec import Data.List -- | Datastructure for result strings of comparisons between covariance models by HMMCompare data HMMCompareResult = HMMCompareResult { model1Name :: String, model2Name :: String, linkscore1 :: Double, linkscore2 :: Double, linksequence :: String, model1matchednodes :: [Int], model2matchednodes :: [Int] } deriving () instance Show HMMCompareResult where show (HMMCompareResult _model1Name _model2Name _linkscore1 _linkscore2 _linksequence _model1matchednodes _model2matchednodes) = _model1Name ++ " " ++ _model2Name ++ " " ++ show _linkscore1 ++ " " ++ show _linkscore2 ++ " " ++ _linksequence ++ " " ++ formatMatchedNodes _model1matchednodes ++ " " ++ formatMatchedNodes _model2matchednodes ++ "\n" formatMatchedNodes :: [Int] -> String formatMatchedNodes nodes = "[" ++ intercalate "," (map show nodes) ++ "]" -- | parse HMMCompareResult model from input string parseHMMCompareResult :: String -> Either ParseError [HMMCompareResult] parseHMMCompareResult input = parse genParseHMMCompareResults "HMMCompareResult" input -- | parse HMMCompareResult from input filePath readHMMCompareResult :: String -> IO (Either ParseError [HMMCompareResult]) readHMMCompareResult filePath = do parseFromFile genParseHMMCompareResults filePath -- | Parse the input as HMMCompareResult datatype genParseHMMCompareResults :: GenParser Char st [HMMCompareResult] genParseHMMCompareResults = do hmmcs <- many1 (try genParseHMMCompareResult) eof return hmmcs readDouble :: String -> Double readDouble = read readInt :: String -> Int readInt = read -- | Parse a HMMCompare result string genParseHMMCompareResult :: GenParser Char st HMMCompareResult genParseHMMCompareResult = do name1 <- many1 (noneOf " ") _ <- many1 space name2 <- many1 (noneOf " ") _ <- many1 space score1 <- many1 (noneOf " ") _ <- many1 space score2 <- many1 (noneOf " ") _ <- many1 space linkseq <- many1 (oneOf "AGTCUagtcu") _ <- many1 space _ <- char '[' nodes1 <- many1 parseMatchedNodes _ <- char ']' _ <- many1 space _ <- char '[' nodes2 <- many1 parseMatchedNodes _ <- char ']' return $ HMMCompareResult name1 name2 (readDouble score1) (readDouble score2) linkseq nodes1 nodes2 -- | Parse indices of matched nodes between models as integers parseMatchedNodes :: GenParser Char st Int parseMatchedNodes = do nodeNumber <- many1 digit optional (char ',') return (readInt nodeNumber) -- | Parser for HMMCompare result strings getHMMCompareResults :: FilePath -> IO [Either ParseError HMMCompareResult] getHMMCompareResults filePath = let fp = filePath doParseLine' = parse genParseHMMCompareResult "genParseHMMCompareResults" --doParseLine l = case (doParseLine' l) of -- Right x -> x -- Left _ -> error "Failed to parse line" in do fileContent <- fmap lines $ readFile fp return $ map doParseLine' fileContent getModelsNames :: [HMMCompareResult] -> [String] getModelsNames models = concatMap getModelNames models getModelNames :: HMMCompareResult -> [String] getModelNames model = [model1Name model,model2Name model]
eggzilla/BioHMM
src/Bio/HMMCompareResult.hs
gpl-3.0
3,499
0
18
714
836
417
419
73
1
module JSBoiler.Statement where import Data.Text (Text) data Statement = Expression Expression | ConstDeclaration [(Declaration, Expression)] | LetDeclaration [(Declaration, Maybe Expression)] | BlockScope [Statement] | IfStatement { condition :: Expression , thenWhat :: Maybe Statement , elseWhat :: Maybe Statement } | WhileStatement { condition :: Expression , whileBody :: Maybe Statement } | BreakStatement | ContinueStatement | ReturnStatement (Maybe Expression) deriving (Show, Eq) data Expression = LiteralNumber Double | LiteralString Text | LiteralNull | LiteralBoolean Bool | LiteralObject [(PropertyKey, Expression)] | LiteralFunction [(Declaration, Maybe Expression)] [Statement] | Identifier Text | CurrentThis | Expression :.: PropertyKey | Expression `FunctionCall` [Expression] -- arithmetic operators | Expression :+: Expression | Expression :-: Expression | Expression :*: Expression | Expression :/: Expression | Expression :%: Expression -- prefix operators | PrefixPlus Expression | PrefixMinus Expression | PrefixNot Expression | PrefixTilde Expression -- logical operators | Expression :&&: Expression | Expression :||: Expression -- assignment | LValue :=: Expression -- | New Expression [Expression] -- new :( deriving (Show, Eq) data PropertyKey = IdentifierKey Text | ExpressionKey Expression deriving (Show, Eq) data Declaration = DeclareBinding Text | DeclareDestructObject [(Text, Declaration)] (Maybe Text) | DeclareDestructIterable [Maybe Declaration] (Maybe Text) deriving (Show, Eq) data LValue = LValueBinding Text | LValueProperty Expression PropertyKey | LValueDestructIterable [Maybe Declaration] (Maybe Text) deriving (Show, Eq)
cuklev/JSBoiler
src/JSBoiler/Statement.hs
gpl-3.0
2,528
0
9
1,072
450
264
186
49
0
--reverse implementada myReverse :: [a] -> [a] myReverse [] = [] myReverse xs = last xs : myReverse (init xs) --fibo
jmlb23/haskell
ch07/exercicies.hs
gpl-3.0
122
0
8
26
54
28
26
3
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-missing-import-lists #-} {-# OPTIONS_GHC -fno-warn-implicit-prelude #-} module Paths_HaScheme ( version, getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude #if defined(VERSION_base) #if MIN_VERSION_base(4,0,0) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #else catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a #endif #else catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a #endif catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/bin" libdir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/lib/x86_64-linux-ghc-8.0.2/HaScheme-0.1.0.0-IJwmEsD2WSkAN9S6TT5ZOb" dynlibdir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/lib/x86_64-linux-ghc-8.0.2" datadir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/share/x86_64-linux-ghc-8.0.2/HaScheme-0.1.0.0" libexecdir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/libexec" sysconfdir = "/home/promethorn/Projects/HaScheme/.stack-work/install/x86_64-linux-ncurses6-nopie/lts-9.9/8.0.2/etc" getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "HaScheme_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "HaScheme_libdir") (\_ -> return libdir) getDynLibDir = catchIO (getEnv "HaScheme_dynlibdir") (\_ -> return dynlibdir) getDataDir = catchIO (getEnv "HaScheme_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "HaScheme_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "HaScheme_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
jdcannon/hascheme
.stack-work/dist/x86_64-linux-ncurses6-nopie/Cabal-1.24.2.0/build/autogen/Paths_HaScheme.hs
gpl-3.0
2,299
0
10
239
410
238
172
33
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetHTTPSProxies.Insert -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a TargetHttpsProxy resource in the specified project using the -- data included in the request. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetHttpsProxies.insert@. module Network.Google.Resource.Compute.TargetHTTPSProxies.Insert ( -- * REST Resource TargetHTTPSProxiesInsertResource -- * Creating a Request , targetHTTPSProxiesInsert , TargetHTTPSProxiesInsert -- * Request Lenses , thpiProject , thpiPayload ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetHttpsProxies.insert@ method which the -- 'TargetHTTPSProxiesInsert' request conforms to. type TargetHTTPSProxiesInsertResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetHttpsProxies" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] TargetHTTPSProxy :> Post '[JSON] Operation -- | Creates a TargetHttpsProxy resource in the specified project using the -- data included in the request. -- -- /See:/ 'targetHTTPSProxiesInsert' smart constructor. data TargetHTTPSProxiesInsert = TargetHTTPSProxiesInsert' { _thpiProject :: !Text , _thpiPayload :: !TargetHTTPSProxy } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetHTTPSProxiesInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'thpiProject' -- -- * 'thpiPayload' targetHTTPSProxiesInsert :: Text -- ^ 'thpiProject' -> TargetHTTPSProxy -- ^ 'thpiPayload' -> TargetHTTPSProxiesInsert targetHTTPSProxiesInsert pThpiProject_ pThpiPayload_ = TargetHTTPSProxiesInsert' { _thpiProject = pThpiProject_ , _thpiPayload = pThpiPayload_ } -- | Project ID for this request. thpiProject :: Lens' TargetHTTPSProxiesInsert Text thpiProject = lens _thpiProject (\ s a -> s{_thpiProject = a}) -- | Multipart request metadata. thpiPayload :: Lens' TargetHTTPSProxiesInsert TargetHTTPSProxy thpiPayload = lens _thpiPayload (\ s a -> s{_thpiPayload = a}) instance GoogleRequest TargetHTTPSProxiesInsert where type Rs TargetHTTPSProxiesInsert = Operation type Scopes TargetHTTPSProxiesInsert = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetHTTPSProxiesInsert'{..} = go _thpiProject (Just AltJSON) _thpiPayload computeService where go = buildClient (Proxy :: Proxy TargetHTTPSProxiesInsertResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetHTTPSProxies/Insert.hs
mpl-2.0
3,623
0
15
803
395
238
157
65
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.ProximityBeacon.Beacons.Register -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Registers a previously unregistered beacon given its \`advertisedId\`. -- These IDs are unique within the system. An ID can be registered only -- once. Authenticate using an [OAuth access -- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2) -- from a signed-in user with **Is owner** or **Can edit** permissions in -- the Google Developers Console project. -- -- /See:/ <https://developers.google.com/beacons/proximity/ Google Proximity Beacon API Reference> for @proximitybeacon.beacons.register@. module Network.Google.Resource.ProximityBeacon.Beacons.Register ( -- * REST Resource BeaconsRegisterResource -- * Creating a Request , beaconsRegister , BeaconsRegister -- * Request Lenses , brXgafv , brUploadProtocol , brPp , brAccessToken , brUploadType , brPayload , brBearerToken , brProjectId , brCallback ) where import Network.Google.Prelude import Network.Google.ProximityBeacon.Types -- | A resource alias for @proximitybeacon.beacons.register@ method which the -- 'BeaconsRegister' request conforms to. type BeaconsRegisterResource = "v1beta1" :> "beacons:register" :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "projectId" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Beacon :> Post '[JSON] Beacon -- | Registers a previously unregistered beacon given its \`advertisedId\`. -- These IDs are unique within the system. An ID can be registered only -- once. Authenticate using an [OAuth access -- token](https:\/\/developers.google.com\/identity\/protocols\/OAuth2) -- from a signed-in user with **Is owner** or **Can edit** permissions in -- the Google Developers Console project. -- -- /See:/ 'beaconsRegister' smart constructor. data BeaconsRegister = BeaconsRegister' { _brXgafv :: !(Maybe Text) , _brUploadProtocol :: !(Maybe Text) , _brPp :: !Bool , _brAccessToken :: !(Maybe Text) , _brUploadType :: !(Maybe Text) , _brPayload :: !Beacon , _brBearerToken :: !(Maybe Text) , _brProjectId :: !(Maybe Text) , _brCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'BeaconsRegister' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'brXgafv' -- -- * 'brUploadProtocol' -- -- * 'brPp' -- -- * 'brAccessToken' -- -- * 'brUploadType' -- -- * 'brPayload' -- -- * 'brBearerToken' -- -- * 'brProjectId' -- -- * 'brCallback' beaconsRegister :: Beacon -- ^ 'brPayload' -> BeaconsRegister beaconsRegister pBrPayload_ = BeaconsRegister' { _brXgafv = Nothing , _brUploadProtocol = Nothing , _brPp = True , _brAccessToken = Nothing , _brUploadType = Nothing , _brPayload = pBrPayload_ , _brBearerToken = Nothing , _brProjectId = Nothing , _brCallback = Nothing } -- | V1 error format. brXgafv :: Lens' BeaconsRegister (Maybe Text) brXgafv = lens _brXgafv (\ s a -> s{_brXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). brUploadProtocol :: Lens' BeaconsRegister (Maybe Text) brUploadProtocol = lens _brUploadProtocol (\ s a -> s{_brUploadProtocol = a}) -- | Pretty-print response. brPp :: Lens' BeaconsRegister Bool brPp = lens _brPp (\ s a -> s{_brPp = a}) -- | OAuth access token. brAccessToken :: Lens' BeaconsRegister (Maybe Text) brAccessToken = lens _brAccessToken (\ s a -> s{_brAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). brUploadType :: Lens' BeaconsRegister (Maybe Text) brUploadType = lens _brUploadType (\ s a -> s{_brUploadType = a}) -- | Multipart request metadata. brPayload :: Lens' BeaconsRegister Beacon brPayload = lens _brPayload (\ s a -> s{_brPayload = a}) -- | OAuth bearer token. brBearerToken :: Lens' BeaconsRegister (Maybe Text) brBearerToken = lens _brBearerToken (\ s a -> s{_brBearerToken = a}) -- | The project id of the project the beacon will be registered to. If the -- project id is not specified then the project making the request is used. -- Optional. brProjectId :: Lens' BeaconsRegister (Maybe Text) brProjectId = lens _brProjectId (\ s a -> s{_brProjectId = a}) -- | JSONP brCallback :: Lens' BeaconsRegister (Maybe Text) brCallback = lens _brCallback (\ s a -> s{_brCallback = a}) instance GoogleRequest BeaconsRegister where type Rs BeaconsRegister = Beacon type Scopes BeaconsRegister = '["https://www.googleapis.com/auth/userlocation.beacon.registry"] requestClient BeaconsRegister'{..} = go _brXgafv _brUploadProtocol (Just _brPp) _brAccessToken _brUploadType _brBearerToken _brProjectId _brCallback (Just AltJSON) _brPayload proximityBeaconService where go = buildClient (Proxy :: Proxy BeaconsRegisterResource) mempty
rueshyna/gogol
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/Register.hs
mpl-2.0
6,255
0
19
1,507
949
554
395
130
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Script.Projects.Versions.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new immutable version using the current code, with a unique -- version number. -- -- /See:/ <https://developers.google.com/apps-script/api/ Apps Script API Reference> for @script.projects.versions.create@. module Network.Google.Resource.Script.Projects.Versions.Create ( -- * REST Resource ProjectsVersionsCreateResource -- * Creating a Request , projectsVersionsCreate , ProjectsVersionsCreate -- * Request Lenses , pvcXgafv , pvcUploadProtocol , pvcAccessToken , pvcUploadType , pvcPayload , pvcScriptId , pvcCallback ) where import Network.Google.Prelude import Network.Google.Script.Types -- | A resource alias for @script.projects.versions.create@ method which the -- 'ProjectsVersionsCreate' request conforms to. type ProjectsVersionsCreateResource = "v1" :> "projects" :> Capture "scriptId" Text :> "versions" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Version :> Post '[JSON] Version -- | Creates a new immutable version using the current code, with a unique -- version number. -- -- /See:/ 'projectsVersionsCreate' smart constructor. data ProjectsVersionsCreate = ProjectsVersionsCreate' { _pvcXgafv :: !(Maybe Xgafv) , _pvcUploadProtocol :: !(Maybe Text) , _pvcAccessToken :: !(Maybe Text) , _pvcUploadType :: !(Maybe Text) , _pvcPayload :: !Version , _pvcScriptId :: !Text , _pvcCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsVersionsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pvcXgafv' -- -- * 'pvcUploadProtocol' -- -- * 'pvcAccessToken' -- -- * 'pvcUploadType' -- -- * 'pvcPayload' -- -- * 'pvcScriptId' -- -- * 'pvcCallback' projectsVersionsCreate :: Version -- ^ 'pvcPayload' -> Text -- ^ 'pvcScriptId' -> ProjectsVersionsCreate projectsVersionsCreate pPvcPayload_ pPvcScriptId_ = ProjectsVersionsCreate' { _pvcXgafv = Nothing , _pvcUploadProtocol = Nothing , _pvcAccessToken = Nothing , _pvcUploadType = Nothing , _pvcPayload = pPvcPayload_ , _pvcScriptId = pPvcScriptId_ , _pvcCallback = Nothing } -- | V1 error format. pvcXgafv :: Lens' ProjectsVersionsCreate (Maybe Xgafv) pvcXgafv = lens _pvcXgafv (\ s a -> s{_pvcXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pvcUploadProtocol :: Lens' ProjectsVersionsCreate (Maybe Text) pvcUploadProtocol = lens _pvcUploadProtocol (\ s a -> s{_pvcUploadProtocol = a}) -- | OAuth access token. pvcAccessToken :: Lens' ProjectsVersionsCreate (Maybe Text) pvcAccessToken = lens _pvcAccessToken (\ s a -> s{_pvcAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pvcUploadType :: Lens' ProjectsVersionsCreate (Maybe Text) pvcUploadType = lens _pvcUploadType (\ s a -> s{_pvcUploadType = a}) -- | Multipart request metadata. pvcPayload :: Lens' ProjectsVersionsCreate Version pvcPayload = lens _pvcPayload (\ s a -> s{_pvcPayload = a}) -- | The script project\'s Drive ID. pvcScriptId :: Lens' ProjectsVersionsCreate Text pvcScriptId = lens _pvcScriptId (\ s a -> s{_pvcScriptId = a}) -- | JSONP pvcCallback :: Lens' ProjectsVersionsCreate (Maybe Text) pvcCallback = lens _pvcCallback (\ s a -> s{_pvcCallback = a}) instance GoogleRequest ProjectsVersionsCreate where type Rs ProjectsVersionsCreate = Version type Scopes ProjectsVersionsCreate = '["https://www.googleapis.com/auth/script.projects"] requestClient ProjectsVersionsCreate'{..} = go _pvcScriptId _pvcXgafv _pvcUploadProtocol _pvcAccessToken _pvcUploadType _pvcCallback (Just AltJSON) _pvcPayload scriptService where go = buildClient (Proxy :: Proxy ProjectsVersionsCreateResource) mempty
brendanhay/gogol
gogol-script/gen/Network/Google/Resource/Script/Projects/Versions/Create.hs
mpl-2.0
5,141
0
18
1,195
785
458
327
114
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.FirewallPolicies.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns the specified firewall policy. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.firewallPolicies.get@. module Network.Google.Resource.Compute.FirewallPolicies.Get ( -- * REST Resource FirewallPoliciesGetResource -- * Creating a Request , firewallPoliciesGet , FirewallPoliciesGet -- * Request Lenses , fpgFirewallPolicy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.firewallPolicies.get@ method which the -- 'FirewallPoliciesGet' request conforms to. type FirewallPoliciesGetResource = "compute" :> "v1" :> "locations" :> "global" :> "firewallPolicies" :> Capture "firewallPolicy" Text :> QueryParam "alt" AltJSON :> Get '[JSON] FirewallPolicy -- | Returns the specified firewall policy. -- -- /See:/ 'firewallPoliciesGet' smart constructor. newtype FirewallPoliciesGet = FirewallPoliciesGet' { _fpgFirewallPolicy :: Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'FirewallPoliciesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'fpgFirewallPolicy' firewallPoliciesGet :: Text -- ^ 'fpgFirewallPolicy' -> FirewallPoliciesGet firewallPoliciesGet pFpgFirewallPolicy_ = FirewallPoliciesGet' {_fpgFirewallPolicy = pFpgFirewallPolicy_} -- | Name of the firewall policy to get. fpgFirewallPolicy :: Lens' FirewallPoliciesGet Text fpgFirewallPolicy = lens _fpgFirewallPolicy (\ s a -> s{_fpgFirewallPolicy = a}) instance GoogleRequest FirewallPoliciesGet where type Rs FirewallPoliciesGet = FirewallPolicy type Scopes FirewallPoliciesGet = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly"] requestClient FirewallPoliciesGet'{..} = go _fpgFirewallPolicy (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy FirewallPoliciesGetResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/FirewallPolicies/Get.hs
mpl-2.0
3,107
0
14
683
313
192
121
54
1
module Main where import CommonMain import DictMt import CompositeMt import CommandsMt import Frontend main :: IO () main = commonMain Maltese data Maltese = Maltese deriving Show instance Language Maltese where internDict _ = malteseDict -- composition _ = decomposeMt composition _ = Just $ compDesc paradigms _ = foldr insertCommand emptyC commands -- compDesc :: CompDesc compDesc = [[]]
johnjcamilleri/maltese-functional-morphology
malti/Main.hs
lgpl-3.0
409
0
6
77
102
57
45
15
1
add a b = a + b -- add 4 5 add' a b c = a + b + c -- add' (add 3 4) 5 6 add'' a b c d = a + b + c + d add003composed = sum [add 1 2, add' 3 4 5, add'' 6 7 8 9] -- *Main> add003composed -- 45
evx001/FS
_fs/adder.hs
apache-2.0
202
0
7
72
103
53
50
4
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} -- | This module allows for lazy decoding of hadoop sequence files from a lazy -- 'L.ByteString'. In the future an incremental API using strict -- 'Data.ByteString.ByteString' will be provided, but for now if you need that -- level of control you need to use the attoparsec parsers in -- "Data.Hadoop.SequenceFile.Parser" directly. -- -- __Basic Examples__ -- -- > import Control.Applicative ((<$>)) -- > import qualified Data.ByteString.Lazy as L -- > import qualified Data.Foldable as F -- > import Data.Int (Int32) -- > import Data.Text (Text) -- > import qualified Data.Text.IO as T -- > -- > import Data.Hadoop.SequenceFile -- > -- > -- | Print all the keys in a sequence file. -- > printKeys :: FilePath -> IO () -- > printKeys path = do -- > bs <- L.readFile path -- > let records = decode bs :: Stream (RecordBlock Text Int32) -- > F.for_ records $ \rb -> do -- > F.mapM_ T.putStrLn (rbKeys rb) -- > -- > -- | Count the number of records in a sequence file. -- > recordCount :: FilePath -> IO () -- > recordCount path = do -- > bs <- L.readFile path -- > let records = decode bs :: Stream (RecordBlock Text Int32) -- > print $ F.sum $ rbCount <$> records -- -- __Integration with Conduit__ -- -- > sourceRecords :: MonadIO m => FilePath -> Source m (RecordBlock Text ByteString) -- > sourceRecords path = do -- > bs <- liftIO (L.readFile path) -- > F.traverse_ yield (decode bs) module Data.Hadoop.SequenceFile ( Stream(..) , Writable(..) , RecordBlock(..) , decode ) where import qualified Data.Attoparsec.ByteString.Lazy as A import qualified Data.ByteString.Lazy as L import Data.Foldable (Foldable(..)) import Data.Monoid ((<>), mempty) import Data.Hadoop.SequenceFile.Parser import Data.Hadoop.SequenceFile.Types import Data.Hadoop.Writable ------------------------------------------------------------------------ -- | A lazy stream of values. data Stream a = Error !String | Value !a (Stream a) | Done deriving (Eq, Ord, Show) instance Functor Stream where fmap f (Value x s) = Value (f x) (fmap f s) fmap _ (Error err) = Error err fmap _ Done = Done instance Foldable Stream where foldMap f (Value x s) = f x <> foldMap f s foldMap _ _ = mempty ------------------------------------------------------------------------ -- | Decode a lazy 'L.ByteString' in to a stream of record blocks. decode :: (Writable ck k, Writable cv v) => L.ByteString -> Stream (RecordBlock k v) decode bs = case A.parse header bs of A.Fail _ ctx err -> mkError ctx err A.Done bs' hdr -> untilEnd (recordBlock hdr) bs' untilEnd :: A.Parser a -> L.ByteString -> Stream a untilEnd p bs = case A.parse p bs of A.Fail _ ctx err -> mkError ctx err A.Done bs' x -> Value x (untilEnd p bs') mkError :: [String] -> String -> Stream a mkError [] err = Error err mkError ctx err = Error (err <> "\ncontext:\n" <> concatMap indentLn ctx) where indentLn str = " " <> str <> "\n"
jystic/hadoop-formats
src/Data/Hadoop/SequenceFile.hs
apache-2.0
3,257
0
10
769
587
331
256
43
2
{-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ParallelListComp #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. 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. -} module CodeWorld.Parameter {-# WARNING "This is an experimental API. It can change at any time." #-} ( Parameter, parametricDrawingOf, slider, toggle, counter, constant, random, timer, currentHour, currentMinute, currentSecond, converted, renamed, ) where import CodeWorld import CodeWorld.Driver (runInspect) import Data.Function (on) import Data.List (sortBy) import Data.Text (Text, pack) import qualified Data.Text as T import Data.Time.Clock import Data.Time.LocalTime import Numeric (showFFloatAlt) import System.IO.Unsafe (unsafePerformIO) import System.Random (newStdGen, randomR) -- | Bounds information for a parameter UI. The fields are the -- left and top coordinate, then the width and height. type Bounds = (Double, Double, Double, Double) -- | The source for a parameter that can be adjusted in a parametric -- drawing. Parameters can get their values from sliders, buttons, -- counters, timers, etc. data Parameter where Parameter :: Text -> Double -> Picture -> Bounds -> (Event -> Parameter) -> Parameter -- | A drawing that depends on parameters. The first argument is a -- list of parameters. The second is a picture, which depends on the -- values of those parameters. Each number used to retrieve the picture -- is the value of the corresponding parameter in the first list. parametricDrawingOf :: [Parameter] -> ([Double] -> Picture) -> IO () parametricDrawingOf initialParams mainPic = runInspect (zip [0 :: Int ..] (layoutParams 0 (-9.5) 9.5 initialParams), True, 5) (const id) change picture rawPicture where change (KeyPress " ") (params, vis, _) = (params, not vis, 2) change (PointerPress pt) (params, vis, t) = case (vis, pullMatch (hitTest pt . snd) params) of (True, (Just p, ps)) -> (fmap (changeParam (PointerPress pt)) p : ps, vis, t) _ -> (params, vis, t) change event (params, vis, t) = (map (fmap (changeParam event)) params, vis, changeTime event t) picture (params, vis, t) = showHideBanner t & (picWhen vis $ pictures (map (showParam . snd) params)) & rawPicture (params, vis, t) rawPicture (params, _, _) = mainPic (map (getParam . snd) (sortBy (compare `on` fst) params)) changeParam event (Parameter _ _ _ _ handle) = handle event showParam (Parameter _ _ pic _ _) = pic getParam (Parameter _ val _ _ _) = val changeTime (TimePassing dt) t = max 0 (t - dt) changeTime _ t = t showHideBanner t = picWhen (t > 0) $ translated 0 (-9) $ dilated 0.5 $ colored (RGBA 0 0 0 t) (rectangle 18 2) & colored (RGBA 0 0 0 t) (lettering "Press Space to show/hide parameters.") & colored (RGBA 0.75 0.75 0.75 (min 0.8 t)) (solidRectangle 18 2) -- | Wraps a list of parameters in frames to lay them out on the screen. layoutParams :: Double -> Double -> Double -> [Parameter] -> [Parameter] layoutParams _ _ _ [] = [] layoutParams maxw x y (p : ps) | y > (-9.5) + h + titleHeight = framedParam (x - left) (y - top - titleHeight) p : layoutParams (max maxw w) x (y - h - titleHeight - gap) ps | otherwise = layoutParams 0 (x + maxw + gap) 9.5 (p : ps) where Parameter _ _ _ (left, top, w, h) _ = p gap = 0.5 -- | Finds the first element of a list that matches the predicate, if any, -- and removes it from the list, returning it separately from the remaining -- elements. pullMatch :: (a -> Bool) -> [a] -> (Maybe a, [a]) pullMatch _ [] = (Nothing, []) pullMatch p (a : as) | p a = (Just a, as) | otherwise = fmap (a :) (pullMatch p as) -- | Determines if a point is inside the screen area for a given parameter. hitTest :: Point -> Parameter -> Bool hitTest (x, y) (Parameter _ _ _ (left, top, w, h) _) = x > left && x < left + w && y < top && y > top - h -- | Builds a parameter from an explicit state. parameterOf :: Text -> state -> (Event -> state -> state) -> (state -> Double) -> (state -> Picture) -> (state -> Bounds) -> Parameter parameterOf name initial change value picture bounds = Parameter name (value initial) (picture initial) (bounds initial) (\e -> parameterOf name (change e initial) change value picture bounds) -- Puts a simple parameter in a draggable widget that let the user -- manipulate it on the screen, and displays the name and value. -- All parameters are enclosed in one of these automatically. framedParam :: Double -> Double -> Parameter -> Parameter framedParam ix iy iparam = parameterOf name (iparam, (ix, iy), True, Nothing) framedHandle (\(Parameter _ v _ _ _, _, _, _) -> v) framedPicture framedBounds where (Parameter name _ _ _ _) = iparam -- | The state of a framedParam, which includes the original parameter, -- its location, whether it's open (expanded) or not, and the anchor if -- it is currently being dragged. type FrameState = (Parameter, Point, Bool, Maybe Point) framedHandle :: Event -> FrameState -> FrameState framedHandle (PointerPress (px, py)) (param, (x, y), open, anchor) | onOpenButton = (param, (x, y), not open, anchor) | onTitleBar = (param, (x, y), open, Just (px, py)) where Parameter _ _ _ (left, top, w, h) _ = param onTitleBar = abs (px - x - (left + w / 2)) < w / 2 && abs (py - y - top - titleHeight / 2) < titleHeight / 2 onOpenButton | w * h > 0 = abs (px - x - (left + w - titleHeight / 2)) < 0.2 && abs (py - y - (top + titleHeight / 2)) < 0.2 | otherwise = False framedHandle (PointerRelease _) (param, loc, open, Just _) = (param, loc, open, Nothing) framedHandle (PointerMovement (px, py)) (param, (x, y), open, Just (ax, ay)) = (param, (x + px - ax, y + py - ay), open, Just (px, py)) framedHandle (TimePassing dt) (Parameter _ _ _ _ handle, loc, open, anchor) = (handle (TimePassing dt), loc, open, anchor) framedHandle event (Parameter _ _ _ _ handle, (x, y), True, anchor) = (handle (untranslated x y event), (x, y), True, anchor) framedHandle _ other = other framedPicture :: FrameState -> Picture framedPicture (Parameter n v pic (left, top, w, h) _, (x, y), open, _) = translated x y $ translated (left + w / 2) (top + titleHeight / 2) titleBar & translated (left + w / 2) (top - h / 2) clientArea where titleBar | w * h > 0 = rectangle w titleHeight & translated ((w - titleHeight) / 2) 0 (if open then collapseButton else expandButton) & translated (- titleHeight / 2) 0 ( clipped (w - titleHeight) titleHeight (dilated 0.5 (lettering titleText)) ) & colored titleColor (solidRectangle w titleHeight) | otherwise = rectangle w titleHeight & clipped w titleHeight (dilated 0.5 (lettering titleText)) & colored titleColor (solidRectangle w titleHeight) titleText | T.length n > 10 = T.take 8 n <> "... = " <> formattedVal | otherwise = n <> " = " <> formattedVal formattedVal = pack (showFFloatAlt (Just 2) v "") collapseButton = rectangle 0.4 0.4 & solidPolygon [(-0.1, -0.1), (0.1, -0.1), (0, 0.1)] expandButton = rectangle 0.4 0.4 & solidPolygon [(-0.1, 0.1), (0.1, 0.1), (0, -0.1)] clientArea = picWhen (w * h > 0) $ rectangle w h & clipped w h pic & colored bgColor (solidRectangle 5 1) framedBounds :: FrameState -> Bounds framedBounds (Parameter _ _ _ (left, top, w, h) _, (x, y), True, _) = (x + left, y + top + titleHeight, w, h + titleHeight) framedBounds (Parameter _ _ _ (left, top, w, _) _, (x, y), False, _) = (x + left, y + top + titleHeight, w, titleHeight) titleHeight :: Double titleHeight = 0.7 untranslated :: Double -> Double -> Event -> Event untranslated x y (PointerPress (px, py)) = PointerPress (px - x, py - y) untranslated x y (PointerRelease (px, py)) = PointerRelease (px - x, py - y) untranslated x y (PointerMovement (px, py)) = PointerMovement (px - x, py - y) untranslated _ _ other = other -- | Adjusts the output of a parameter by passing it through a conversion -- function. Built-in parameters usually range from 0 to 1, and conversions -- can be used to rescale the output to a different range. converted :: (Double -> Double) -> Parameter -> Parameter converted c (Parameter name val pic bounds handle) = Parameter name (c val) pic bounds (converted c . handle) -- | Changes the name of an existing parameter. renamed :: Text -> Parameter -> Parameter renamed name (Parameter _ val pic bounds handle) = Parameter name val pic bounds (renamed name . handle) -- | A 'Parameter' with a constant value, and no way to change it. constant :: Text -> Double -> Parameter constant name n = parameterOf name n (const id) id (const blank) (const (-2.5, 0, 5, 0)) -- | Builder for 'Parameter' types that are clickable and 5x1 in size. buttonOf :: Text -> state -> (state -> state) -> (state -> Double) -> (state -> Picture) -> Parameter buttonOf name initial click value pic = parameterOf name (initial, False) change (value . fst) ( \(state, press) -> pic state & picWhen press (colored (RGBA 0 0 0 0.3) (solidRectangle 5 1)) ) (const (-2.5, 0.5, 5, 1)) where change (PointerPress (px, py)) (state, _) | abs px < 2.5, abs py < 0.5 = (state, True) change (PointerRelease (px, py)) (state, True) | abs px < 2.5, abs py < 0.5 = (click state, False) | otherwise = (state, False) change _ (state, press) = (state, press) -- | A 'Parameter' that can be toggled between 0 (off) and 1 (on). toggle :: Text -> Parameter toggle name = buttonOf name False not value picture where value True = 1 value False = 0 picture True = dilated 0.5 $ lettering "\x2611" picture False = dilated 0.5 $ lettering "\x2610" -- | A 'Parameter' that counts how many times it has been clicked. counter :: Text -> Parameter counter name = buttonOf name 0 (+ 1) id picture where picture _ = dilated 0.5 (lettering "Next") -- | A 'Parameter' that can be adjusted continuously between 0 and 1. slider :: Text -> Parameter slider name = parameterOf name (0.5, False) change fst picture (const (-2.5, 0.5, 5, 1)) where change (PointerPress (px, py)) (_, _) | abs px < 2, abs py < 0.25 = (min 1 $ max 0 $ (px + 2) / 4, True) change (PointerRelease _) (v, _) = (v, False) change (PointerMovement (px, _)) (_, True) = (min 1 $ max 0 $ (px + 2) / 4, True) change _ state = state picture (v, _) = translated (v * 4 - 2) 0 (solidRectangle 0.125 0.5) & solidRectangle 4 0.1 -- | A 'Parameter' that has a randomly chosen value. It offers a button to -- regenerate its value. random :: Text -> Parameter random name = buttonOf name initial (next . snd) fst picture where initial = next (unsafePerformIO newStdGen) picture _ = dilated 0.5 $ lettering "\x21ba Regenerate" next = randomR (0.0, 1.0) -- | A 'Parameter' that changes over time. It can be paused or reset. timer :: Text -> Parameter timer name = parameterOf name (0, 1) change fst picture (const (-2.5, 0.5, 5, 1)) where change (TimePassing dt) (t, r) = (t + r * dt, r) change (PointerPress (px, py)) (t, r) | abs (px - 5 / 6) < 5 / 6, abs py < 0.75 = (t, 1 - r) | abs (px + 5 / 6) < 5 / 6, abs py < 0.75 = (0, 0) change _ state = state picture (_, 0) = (translated (5 / 6) 0 $ dilated 0.5 $ lettering "\x23e9") & (translated (-5 / 6) 0 $ dilated 0.5 $ lettering "\x23ee") picture _ = (translated (5 / 6) 0 $ dilated 0.5 $ lettering "\x23f8") & (translated (-5 / 6) 0 $ dilated 0.5 $ lettering "\x23ee") -- | A 'Parameter' that tracks the current hour, in local time. The hour -- is on a scale from 0 (meaning midnight) to 23 (meaning 11:00 pm). currentHour :: Parameter currentHour = parameterOf "hour" () (const id) (\_ -> unsafePerformIO $ fromIntegral <$> todHour <$> getTimeOfDay) (const blank) (const (-2.5, 0, 5, 0)) -- | A 'Parameter' that tracks the current minute, in local time. It -- ranges from 0 to 59. currentMinute :: Parameter currentMinute = parameterOf "minute" () (const id) (\_ -> unsafePerformIO $ fromIntegral <$> todMin <$> getTimeOfDay) (const blank) (const (-2.5, 0, 5, 0)) -- | A 'Parameter' that tracks the current second, in local time. It -- ranges from 0.0 up to (but not including) 60.0. This includes -- fractions of a second. If that's not what you want, you can use -- 'withConversion' to truncate the number. currentSecond :: Parameter currentSecond = parameterOf "second" () (const id) (\_ -> unsafePerformIO $ realToFrac <$> todSec <$> getTimeOfDay) (const blank) (const (-2.5, 0, 5, 0)) getTimeOfDay :: IO TimeOfDay getTimeOfDay = do now <- getCurrentTime timezone <- getCurrentTimeZone return (localTimeOfDay (utcToLocalTime timezone now)) titleColor :: Color titleColor = RGBA 0.7 0.7 0.7 0.9 bgColor :: Color bgColor = RGBA 0.8 0.85 0.95 0.8 picWhen :: Bool -> Picture -> Picture picWhen True = id picWhen False = const blank
google/codeworld
codeworld-api/src/CodeWorld/Parameter.hs
apache-2.0
14,183
0
17
3,564
4,813
2,590
2,223
316
5
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ContainerPort where import GHC.Generics import Data.Text import qualified Data.Aeson -- | ContainerPort represents a network port in a single container. data ContainerPort = ContainerPort { name :: Maybe Text -- ^ If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services. , hostPort :: Maybe Integer -- ^ Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this. , containerPort :: Integer -- ^ Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536. , protocol :: Maybe Text -- ^ Protocol for port. Must be UDP or TCP. Defaults to \"TCP\". , hostIP :: Maybe Text -- ^ What host IP to bind the external port to. } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ContainerPort instance Data.Aeson.ToJSON ContainerPort
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ContainerPort.hs
apache-2.0
1,246
0
9
235
120
73
47
18
0
module SSync.SignatureTable ( SignatureTable , emptySignature , emptySignature' , consumeSignatureTable , SignatureTableException(..) ) where import SSync.SignatureTable.Internal
socrata-platform/ssync
src/main/haskell/SSync/SignatureTable.hs
apache-2.0
182
0
5
19
33
22
11
7
0
{- - Copyright 2012 Fabio Riga - - 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. -} module Defaults where import System.FilePath workdir = "archhaskell" mainRepoDir = workdir </> "habs" thisRepoDir = workdir </> "habs-web" cabalPath = ".cabal/packages/hackage.haskell.org/" chrootRootDir = "x86_64-chroot/root/" chrootBuildDir = "x86_64-chroot/build/" sourceFiles = ["00-index.tar.gz", "00-index.tar", "00-index.cache"] cblrepoIdx = "index.tar.gz"
EffeErre/cbladmin
src/Defaults.hs
apache-2.0
963
0
5
155
67
41
26
10
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionProgressBar.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:30 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QStyleOptionProgressBar ( QqStyleOptionProgressBar(..) ,QqStyleOptionProgressBar_nf(..) ,progress ,setProgress ,textVisible ,qStyleOptionProgressBar_delete ) where 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 QqStyleOptionProgressBar x1 where qStyleOptionProgressBar :: x1 -> IO (QStyleOptionProgressBar ()) instance QqStyleOptionProgressBar (()) where qStyleOptionProgressBar () = withQStyleOptionProgressBarResult $ qtc_QStyleOptionProgressBar foreign import ccall "qtc_QStyleOptionProgressBar" qtc_QStyleOptionProgressBar :: IO (Ptr (TQStyleOptionProgressBar ())) instance QqStyleOptionProgressBar ((QStyleOptionProgressBar t1)) where qStyleOptionProgressBar (x1) = withQStyleOptionProgressBarResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionProgressBar1 cobj_x1 foreign import ccall "qtc_QStyleOptionProgressBar1" qtc_QStyleOptionProgressBar1 :: Ptr (TQStyleOptionProgressBar t1) -> IO (Ptr (TQStyleOptionProgressBar ())) class QqStyleOptionProgressBar_nf x1 where qStyleOptionProgressBar_nf :: x1 -> IO (QStyleOptionProgressBar ()) instance QqStyleOptionProgressBar_nf (()) where qStyleOptionProgressBar_nf () = withObjectRefResult $ qtc_QStyleOptionProgressBar instance QqStyleOptionProgressBar_nf ((QStyleOptionProgressBar t1)) where qStyleOptionProgressBar_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionProgressBar1 cobj_x1 instance Qqmaximum (QStyleOptionProgressBar a) (()) (IO (Int)) where qmaximum x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_maximum cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_maximum" qtc_QStyleOptionProgressBar_maximum :: Ptr (TQStyleOptionProgressBar a) -> IO CInt instance Qqminimum (QStyleOptionProgressBar a) (()) (IO (Int)) where qminimum x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_minimum cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_minimum" qtc_QStyleOptionProgressBar_minimum :: Ptr (TQStyleOptionProgressBar a) -> IO CInt progress :: QStyleOptionProgressBar a -> (()) -> IO (Int) progress x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_progress cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_progress" qtc_QStyleOptionProgressBar_progress :: Ptr (TQStyleOptionProgressBar a) -> IO CInt instance QsetMaximum (QStyleOptionProgressBar a) ((Int)) where setMaximum x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_setMaximum cobj_x0 (toCInt x1) foreign import ccall "qtc_QStyleOptionProgressBar_setMaximum" qtc_QStyleOptionProgressBar_setMaximum :: Ptr (TQStyleOptionProgressBar a) -> CInt -> IO () instance QsetMinimum (QStyleOptionProgressBar a) ((Int)) where setMinimum x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_setMinimum cobj_x0 (toCInt x1) foreign import ccall "qtc_QStyleOptionProgressBar_setMinimum" qtc_QStyleOptionProgressBar_setMinimum :: Ptr (TQStyleOptionProgressBar a) -> CInt -> IO () setProgress :: QStyleOptionProgressBar a -> ((Int)) -> IO () setProgress x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_setProgress cobj_x0 (toCInt x1) foreign import ccall "qtc_QStyleOptionProgressBar_setProgress" qtc_QStyleOptionProgressBar_setProgress :: Ptr (TQStyleOptionProgressBar a) -> CInt -> IO () instance QsetText (QStyleOptionProgressBar a) ((String)) where setText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QStyleOptionProgressBar_setText cobj_x0 cstr_x1 foreign import ccall "qtc_QStyleOptionProgressBar_setText" qtc_QStyleOptionProgressBar_setText :: Ptr (TQStyleOptionProgressBar a) -> CWString -> IO () instance QsetTextAlignment (QStyleOptionProgressBar a) ((Alignment)) where setTextAlignment x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_setTextAlignment cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QStyleOptionProgressBar_setTextAlignment" qtc_QStyleOptionProgressBar_setTextAlignment :: Ptr (TQStyleOptionProgressBar a) -> CLong -> IO () instance QsetTextVisible (QStyleOptionProgressBar a) ((Bool)) where setTextVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_setTextVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QStyleOptionProgressBar_setTextVisible" qtc_QStyleOptionProgressBar_setTextVisible :: Ptr (TQStyleOptionProgressBar a) -> CBool -> IO () instance Qtext (QStyleOptionProgressBar a) (()) (IO (String)) where text x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_text cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_text" qtc_QStyleOptionProgressBar_text :: Ptr (TQStyleOptionProgressBar a) -> IO (Ptr (TQString ())) instance QtextAlignment (QStyleOptionProgressBar a) (()) (IO (Alignment)) where textAlignment x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_textAlignment cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_textAlignment" qtc_QStyleOptionProgressBar_textAlignment :: Ptr (TQStyleOptionProgressBar a) -> IO CLong textVisible :: QStyleOptionProgressBar a -> (()) -> IO (Bool) textVisible x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_textVisible cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_textVisible" qtc_QStyleOptionProgressBar_textVisible :: Ptr (TQStyleOptionProgressBar a) -> IO CBool qStyleOptionProgressBar_delete :: QStyleOptionProgressBar a -> IO () qStyleOptionProgressBar_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionProgressBar_delete cobj_x0 foreign import ccall "qtc_QStyleOptionProgressBar_delete" qtc_QStyleOptionProgressBar_delete :: Ptr (TQStyleOptionProgressBar a) -> IO ()
uduki/hsQt
Qtc/Gui/QStyleOptionProgressBar.hs
bsd-2-clause
6,570
0
12
851
1,564
809
755
-1
-1
module Main (main) where import System.Exit import System.Environment import System.IO import System.Console.GetOpt import Text.ParserCombinators.Parsec import Text.Printf import Data.List (intersect, intercalate) import qualified Data.Char as Char import qualified Data.Set as Set import qualified Data.Map as Map import qualified Data.Maybe as Maybe import Naa import Debug.Trace version = " ." authors = "André Scholz ([email protected])" main :: IO() main = do hSetBuffering stdout NoBuffering args <- getArgs -- Parse options, getting a list of option actions let (actions, nonOptions, errors) = getOpt RequireOrder options args -- Here we thread defaultOptions through all supplied option actions opts <- foldl (>>=) (return defaultOptions) actions let Options { optVerbose = verbose , optInput = input , optOutput = output } = opts putStrLn ("\nSearching for homomorphisms from " ++ (takeWhile (/= '.') (nonOptions !! 0)) ++ " to " ++ (takeWhile (/= '.') (nonOptions !! 2)) ++ ".\n") -- read files and generate mappings for composition and converse convMap1 <- loadConvFile (nonOptions !! 0) ((identity1, baserelations1), compMap1) <- loadCompFile (nonOptions !! 1) convMap2 <- loadConvFile (nonOptions !! 2) ((identity2, baserelations2), compMap2) <- loadCompFile (nonOptions !! 3) let naa1 = NonAssociativeAlgebra { baserelations = baserelations1 , identity = identity1 , converse = convMap1 , composition = compMap1 } let naa2 = NonAssociativeAlgebra { baserelations = baserelations2 , identity = identity2 , converse = convMap2 , composition = compMap2 } let maxLength = Set.findMax $ Set.map (\x -> length ((Set.toList x) !! 0)) baserelations1 let foundHoms = (findHom naa1 naa2 (trivialHom naa1 naa2)) if (Set.size baserelations1) <= (Set.size baserelations2) then do putStrLn "Searching for identities..." putStrLn ("Found: Id1 = ( " ++ intercalate ", " (Set.toList identity1) ++ " )") putStrLn (" Id2 = ( " ++ intercalate ", " (Set.toList identity2) ++ " )\n") else putStrLn ( (takeWhile (/= '.') (nonOptions !! 0)) ++ " has more baserelations than " ++ (takeWhile (/= '.') (nonOptions !! 2)) ++ ".") if ( (Set.size baserelations1) > (Set.size baserelations2) || (foundHoms == Set.empty) ) then putStrLn ("I found no homomorphism from " ++ (takeWhile (/= '.') (nonOptions !! 0)) ++ " to " ++ (takeWhile (/= '.') (nonOptions !! 2)) ++ ".\n") else do mapM_ (\(x,y) -> do printf "======== %d. Homomorphism ========\n\n" (x+1 :: Int) mapM_ (\(u,v) -> do printf ("%-" ++ show (maxLength + 1) ++ "s") (intercalate ", " (Set.toList u)) putStrLn ("↦ ( " ++ (intercalate ", " (Set.toList v) ++ " )"))) (Map.toList y) putStrLn "" ) (foldl (\x y -> x ++ [(length x, y)]) [] (Set.toList foundHoms)) putStrLn ("These are all homomorphisms from " ++ (takeWhile (/= '.') (nonOptions !! 0)) ++ " to " ++ (takeWhile (/= '.') (nonOptions !! 2)) ++ ".\n") -- begin commandline option handling ------------------------------------------ -- define the type of options data Options = Options { optInput :: IO String , optOutput :: String -> IO () , optVerbose :: Bool } -- define default values and actions for options defaultOptions :: Options defaultOptions = Options { optInput = getContents , optOutput = putStr , optVerbose = False } -- define the commandline options options :: [OptDescr (Options -> IO Options)] options = [ Option ['h'] ["help"] (NoArg showUsage) "Print this usage information" -- , Option ['i'] ["input"] -- (ReqArg readInput "FILE") -- "Input file to read" -- , Option ['o'] ["output"] -- (ReqArg writeOutput "FILE") -- "Output file to write" -- , Option ['v'] ["verbose"] -- (NoArg verboseTrue) -- "Enable verbose messages" , Option ['V'] ["version"] (NoArg showVersion) "Show version" , Option [] ["authors"] (NoArg showAuthors) "Who the heck wrote this program?" ] -- functions used in the section above showUsage _ = do prg <- getProgName hPutStrLn stderr ( usageInfo ("\nUsage: " ++ prg ++ " [Option]... ConvFile1 CompFile1 " ++ "ConvFile2 CompFile2\n") options) exitWith ExitSuccess showVersion _ = do putStrLn version exitWith ExitSuccess showAuthors _ = do putStrLn authors exitWith ExitSuccess -- verboseTrue opt = return opt { optVerbose = True } -- readInput arg opt = return opt { optInput = readFile arg } -- writeOutput arg opt = return opt { optOutput = writeFile arg } -- end commandline option handling -------------------------------------------- -- begin parsing composition tables ------------------------------------------- parseGqrRelation :: GenParser Char st String parseGqrRelation = do spaces -- a <- many1 (alphaNum <|> char '_' <|> char '=' <|> char '<' <|> char '>' -- <|> char '^' <|> char '~' <|> char '+' <|> char '-') a <- many1 (noneOf " :;,()\n\t") spaces return a -- parse composition file parseGqrComp :: GenParser Char st ((Relation, Relation), Relation) parseGqrComp = do a <- parseGqrRelation char ':' b <- parseGqrRelation count 2 (char ':') spaces char '(' spaces -- this is only needed if the composition is not fully definied. c <- sepBy parseGqrRelation spaces char ')' spaces return ( ( Set.singleton (map Char.toLower a) , Set.singleton (map Char.toLower b) ) , Set.fromList [map Char.toLower x | x <- c] ) parseGqrCompTable :: GenParser Char st [((Relation, Relation), Relation)] parseGqrCompTable = many1 parseGqrComp -- parse converses file parseGqrConv :: GenParser Char st (Relation, Relation) parseGqrConv = do a <- parseGqrRelation count 2 (char ':') b <- parseGqrRelation return ( Set.singleton (map Char.toLower a) , Set.singleton (map Char.toLower b) ) parseGqrConvTable :: GenParser Char st [(Relation, Relation)] parseGqrConvTable = many1 parseGqrConv getIdentityAndBaserelations :: [((Relation, Relation), Relation)] -> (Relation, Set.Set Relation) getIdentityAndBaserelations a = ( foldl1 Set.union $ intersect ( filter ( \u -> and [ y == z | ((x,y),z) <- a, x == u ] ) (allBaserelations) ) ( filter (\u -> and [ x == z | ((x,y),z) <- a, y == u ] ) (allBaserelations) ) , Set.fromList allBaserelations ) where allBaserelations = [ x | ((x,_),_) <- a ] -- read the input file loadCompFile :: FilePath -> IO ( (Relation, Set.Set Relation) , Map.Map (Relation,Relation) Relation ) loadCompFile filename = do file <- readFile filename let table = runParser parseGqrCompTable () "" file case table of Left error -> do fail $ "parse error in " ++ filename ++ " at " ++ show(error) Right success -> return ( getIdentityAndBaserelations success , Map.fromList success ) loadConvFile :: FilePath -> IO (Map.Map Relation Relation) loadConvFile filename = do file <- readFile filename let table = runParser parseGqrConvTable () "" file case table of Left error -> do fail $ "parse error in " ++ filename ++ " at " ++ show(error) Right success -> return (Map.fromList success) -- end parsing composition tables ---------------------------------------------
spatial-reasoning/homer
homer.hs
bsd-2-clause
8,638
0
28
2,865
2,172
1,143
1,029
167
3
{-# LANGUAGE DeriveDataTypeable #-} module Propellor.Types.Docker where import Propellor.Types import Propellor.Types.Empty import Propellor.Types.Info import Data.Monoid import qualified Data.Map as M data DockerInfo = DockerInfo { _dockerRunParams :: [DockerRunParam] , _dockerContainers :: M.Map String Host } deriving (Show, Typeable) instance IsInfo DockerInfo where propagateInfo _ = PropagateInfo False instance Monoid DockerInfo where mempty = DockerInfo mempty mempty mappend old new = DockerInfo { _dockerRunParams = _dockerRunParams old <> _dockerRunParams new , _dockerContainers = M.union (_dockerContainers old) (_dockerContainers new) } instance Empty DockerInfo where isEmpty i = and [ isEmpty (_dockerRunParams i) , isEmpty (_dockerContainers i) ] newtype DockerRunParam = DockerRunParam (HostName -> String) instance Show DockerRunParam where show (DockerRunParam a) = a ""
ArchiveTeam/glowing-computing-machine
src/Propellor/Types/Docker.hs
bsd-2-clause
922
36
9
142
263
148
115
25
0
module Network.BitcoinRPC.TestTypes ( ArbBitcoinAddress(..) , ArbTransactionID(..) , ArbBitcoinAmount(..) , ArbTransaction(..) ) where import Control.Applicative import Test.QuickCheck import qualified Data.Text as T import Network.BitcoinRPC.Types -- Define newtype wrappers to avoid the 'orphan instance' warning. newtype ArbBitcoinAddress = ABAddr { unABAddr :: BitcoinAddress } deriving (Show) newtype ArbTransactionID = ATI { unATI :: TransactionID } deriving (Show) newtype ArbBitcoinAmount = ABAmount { unABAmount :: BitcoinAmount } deriving (Show) newtype ArbTransaction = ATX { unATX :: Transaction } deriving (Show) instance Arbitrary ArbBitcoinAddress where arbitrary = do a <- choose ('a', 'z') b <- choose ('a', 'z') c <- choose ('a', 'z') return $ ABAddr (BitcoinAddress (T.pack ['1', a, b, c])) instance Arbitrary ArbTransactionID where arbitrary = do str <- suchThat arbitrary (\s -> length s > 0) :: Gen String return $ ATI (TransactionID (T.pack str)) instance Arbitrary ArbBitcoinAmount where arbitrary = do int <- choose (0,10 * 10 ^ (8::Integer)) return $ ABAmount (BitcoinAmount int) instance Arbitrary ArbTransaction where arbitrary = do entry <- choose (0, 2) amount <- unABAmount <$> arbitrary address <- unABAddr <$> arbitrary confs <- choose (0,200) txid <- unATI <$> arbitrary time <- choose (0, 1000000000) return $ ATX (ReceiveTx entry amount address confs txid time)
javgh/bitcoin-rpc
Network/BitcoinRPC/TestTypes.hs
bsd-3-clause
1,672
0
14
474
488
267
221
40
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} module ClientProxyApi where import System.Random import Control.Monad.Trans.Except import Control.Monad.Trans.Resource import Control.Monad.IO.Class import Data.Aeson import Data.Aeson.TH import Data.Bson.Generic import GHC.Generics import Network.Wai hiding(Response) import Network.Wai.Handler.Warp import Network.Wai.Logger import Servant import Servant.API import Servant.Client import System.IO import System.Directory import System.Environment (getArgs, getProgName, lookupEnv) import System.Log.Formatter import System.Log.Handler (setFormatter) import System.Log.Handler.Simple import System.Log.Handler.Syslog import System.Log.Logger import Data.Bson.Generic import qualified Data.List as DL import Data.Maybe (catMaybes) import Data.Text (pack, unpack) import Data.Time.Clock (UTCTime, getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime) import Control.Monad (when) import Network.HTTP.Client (newManager, defaultManagerSettings) import System.Process data File = File { fileName :: FilePath, fileContent :: String } deriving (Eq, Show, Generic) instance ToJSON File instance FromJSON File data Response = Response{ response :: String } deriving (Eq, Show, Generic) instance ToJSON Response instance FromJSON Response type ApiHandler = ExceptT ServantErr IO serverport :: String serverport = "8080" serverhost :: String serverhost = "localhost" type DirectoryApi = "open" :> Capture "fileName" String :> Get '[JSON] File :<|> "close" :> ReqBody '[JSON] File :> Post '[JSON] Response directoryApi :: Proxy DirectoryApi directoryApi = Proxy open :: String -> ClientM File close :: File -> ClientM Response open :<|> close = client directoryApi openQuery:: String -> ClientM File openQuery filename = do openquery <- open fileName return openQuery closeQuery:: File -> Response closeQuery file = do closequery <- close file return closequery --type ClientApi = -- "get" :> Capture "fileName" String :> Get '[JSON] File :<|> -- "put" :> ReqBody '[JSON] File :> Post '[JSON] Response --clientApi :: Proxy ClientApi --clientApi = Proxy --server :: Server ClientApi --server = -- getFile :<|> -- putFile --clientApp :: Application --clientApp = serve clientApi server mkApp :: IO() mkApp = do createDirectoryIfMissing True ("tmp/") setCurrentDirectory ("tmp/") putStrLn $ "Enter one of the following commands: UPLOAD/DOWNLOAD/CLOSE" cmd <- getLine case cmd of "UPLOAD" -> uploadFile "DOWNLOAD" -> downloadFile "CLOSE" -> putStrLn $ "Closing service!" _ -> do putStrLn $ "Invalid Command. Try Again" mkApp uploadFile :: IO() uploadFile = do putStrLn "Please enter the name of the file to upload" fileName <- getLine putStrLn "Please enter the contents of the file to upload" fileContent <- getLine let file = File fileName fileContent response <- putFile file putStrLn "Response: " ++ response mkApp downloadFile :: IO() downloadFile = do putStrLn "Please enter the name of the file to download" fileName <- getLine response <- getFile fileName liftIO (writeFile (fileName response) (fileContent response)) cmd <- shell ("vim " ++ fileName) result <- createProcess cmd mkApp getFile:: String -> ApiHandler File getFile filename = do manager <- newManager defaultManagerSettings res <- runClientM (openQuery filename) (ClientEnv manager (BaseUrl Http "localhost" 7008 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> return (response) putFile:: File -> ApiHandler Response putFile file = do manager <- newManager defaultManagerSettings res <- runClientM (closeQuery file) (ClientEnv manager (BaseUrl Http "localhost" 7008 "")) case res of Left err -> putStrLn $ "Error: " ++ show err Right response -> return (response)
Garygunn94/DFS
ClientProxy/.stack-work/intero/intero9387mAF.hs
bsd-3-clause
4,781
12
12
1,306
1,070
563
507
119
4
module Day8 where -- unfinished, grids are lameassshit import Grid import Data.Char import Text.Megaparsec import Text.Megaparsec.String import qualified Data.Map as M -- screen = 50x6 data Pixel = Hash | Dot deriving (Show, Eq, Enum) ppPixel :: Pixel -> String ppPixel Hash = "#" ppPixel Dot = "." screen = grid 6 50 (repeat Dot) testG = grid 3 7 (repeat Dot) testA = parseSteps "rect 3x2\nrotate column x=1 by 1\nrotate row y=0 by 4\nrotate column x=1 by 1" showTest = mapM_ (putStrLn . (++"\n") . ppGrid ppPixel) $ scanl doAction testG testA type Wide = Int type Tall = Int type Index = Int data Step = RotC Index Int | RotR Index Int | Rect Wide Tall deriving Show parseSteps :: String -> [Step] parseSteps s = either (const (error "bad parse")) id $ parse (some $ (rect' <|> rot) <* space) "" s rect' :: Parser Step rect' = do _ <- string "rect" <* space x <- read <$> some digitChar <* char 'x' y <- read <$> some digitChar return $ Rect x y rot :: Parser Step rot = do _ <- string "rotate" <* space con <- ((string "column" *> return RotC) <|> (string "row" *> return RotR)) <* space i <- read <$> (skipSome (satisfy (not . isDigit)) *> some digitChar) n <- read <$> (skipSome (satisfy (not . isDigit)) *> some digitChar) return $ con i n doAction :: Grid Pixel -> Step -> Grid Pixel doAction g (RotC i n) = cycleCol i n g doAction g (RotR i n) = cycleRow i n g doAction g (Rect x y) = rect y x Hash g showActions :: Grid Pixel -> [Step] -> [Grid Pixel] showActions = scanl doAction doActions :: Grid Pixel -> [Step] -> Grid Pixel doActions = foldl doAction runFirst :: IO Int runFirst = length . filter (==Hash) . concat . gridToList . doActions screen . parseSteps <$> readFile "./input/d8.txt" runSecond :: IO () runSecond = doActions screen . parseSteps <$> readFile "./input/d8.txt" >>= printGrid ppPixel
MarcelineVQ/advent2016
src/Day8.hs
bsd-3-clause
1,853
0
15
376
752
381
371
45
1