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 TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE QuasiQuotes #-} module Vectors where import Feldspar import Feldspar.Array.Vector import Feldspar.Array.Buffered import Feldspar.Software import Feldspar.Software as Soft (icompile) import Feldspar.Software.Compile import Feldspar.Software.Marshal import Feldspar.Hardware hiding (Arr, IArr, Ref) import Feldspar.Hardware as Hard (icompile, icompileSig, icompileAXILite) import Control.Monad (void) import Data.Complex (Complex) -- language-c-quote import Language.C.Quote.GCC import qualified Language.C.Syntax as C -- imperative-edsl import qualified Language.Embedded.Backend.C as Imp import Prelude hiding (take, drop, reverse, length, zip, zipWith, sum, tail, map) -------------------------------------------------------------------------------- -- * ... -------------------------------------------------------------------------------- sumLast5 :: SPull (SExp Word32) -> SExp Word32 sumLast5 = sum . take 5 . reverse -------------------------------------------------------------------------------- test1 :: IO () test1 = Soft.icompile $ printf "%d" $ sumLast5 inp where inp :: SPull (SExp Word32) inp = 0 ... 10 -------------------------------------------------------------------------------- -- * ... -------------------------------------------------------------------------------- dot :: (Vector exp, Pully exp vec a, Num a, Syntax exp a) => vec -> vec -> a dot a b = sum $ zipWith (*) a b dotArr :: IArr (SExp Int32) -> IArr (SExp Int32) -> SExp Int32 dotArr = dot dotProg :: Software () dotProg = connectStdIO $ return . uncurry dotArr dotIO :: IO () dotIO = Soft.icompile dotProg -------------------------------------------------------------------------------- fir :: (Vector exp, Num a, Syntax exp a) => Pull exp a -> Pull exp a -> Pull exp a fir coeff = map (dot coeff . reverse) . tail . inits firArr :: IArr (SExp Int32) -> IArr (SExp Int32) -> Pull SExp (SExp Int32) firArr a b = fir (toPull a) (toPull b) firProg :: Software () firProg = connectStdIO $ manifestFresh . uncurry firArr firIO :: IO () firIO = Soft.icompile firProg -------------------------------------------------------------------------------- type SStore a = Store Software a printTime_def = [cedecl| void printTime(typename clock_t start, typename clock_t end) { printf("CPU time (sec): %f\n", (double)(end-start) / CLOCKS_PER_SEC); } |] sizeOf_double_complex :: SExp Length sizeOf_double_complex = 16 -- | Measure the time for 100 runs of 'fftCore' (excluding initialization) for -- arrays of the given size benchmark :: SExp Length -> Software () benchmark n = do addInclude "<stdio.h>" addInclude "<string.h>" addInclude "<time.h>" addDefinition printTime_def start <- newObject "clock_t" False end <- newObject "clock_t" False st1 :: SStore (SExp (Complex Double)) <- newStore n inp1 <- unsafeFreezeStore n st1 callProc "memset" [ iarrArg (manifest inp1) , valArg (0 :: SExp Index) , valArg (n*sizeOf_double_complex) ] st2 :: SStore (SExp (Complex Double)) <- newStore n inp2 <- unsafeFreezeStore n st2 callProc "memset" [ iarrArg (manifest inp1) , valArg (0 :: SExp Index) , valArg (n*sizeOf_double_complex) ] callProcAssign start "clock" [] for 0 1 99 $ \(_ :: SExp Index) -> void $ manifestFresh (fir (toPull inp1) (toPull inp2)) callProcAssign end "clock" [] callProc "printTime" [objArg start, objArg end] runBenchmark n = runCompiled' (Imp.def :: CompilerOpts) (Imp.def {Imp.externalFlagsPre = ["-O3"], Imp.externalFlagsPost = ["-lm"]}) (benchmark n) printBenchmark n = Soft.icompile (benchmark n) -------------------------------------------------------------------------------- dot_sig :: HSig (SArr Word32 -> SArr Word32 -> Signal Word32 -> ()) dot_sig = inputIArr 1 $ \a -> inputIArr 1 $ \b -> ret $ pure $ dot a b -- `dot` is pure, so we lift its result. test3 :: IO () test3 = Hard.icompileSig $ dot_sig -- Seems the optimizer isn't happy, might be just my installation tho. test4 :: IO () test4 = Hard.icompileAXILite $ dot_sig -------------------------------------------------------------------------------- dot_mmap :: Software () dot_mmap = do dot <- mmap "0x43C00000" dot_sig a :: Arr (SExp Word32) <- initArr [1] b :: Arr (SExp Word32) <- initArr [1] c :: Ref (SExp Word32) <- newRef -- call dot (a >>: b >>: c >: nil) -- result <- getRef c printf "dot: %d\n" result test5 :: IO () test5 = Soft.icompile dot_mmap --------------------------------------------------------------------------------
markus-git/co-feldspar
examples/Vectors.hs
bsd-3-clause
4,753
0
14
813
1,369
709
660
97
1
module OperationalTransformation ( Operation , transform ) where class Operation a where transform :: a -> a -> (a, a) -- compose :: a -> a -> a
aztecrex/haskell-ot-spike
src/OperationalTransformation.hs
bsd-3-clause
163
0
9
46
41
24
17
5
0
---------------------------------------------------------------------------- -- | -- Module : Imported2 -- Copyright : (c) Sergey Vinokurov 2015 -- License : BSD3-style (see LICENSE) -- Maintainer : serg.foo@gmail.com ---------------------------------------------------------------------------- {-# LANGUAGE TypeOperators #-} module Imported2 where foo2 :: a -> a foo2 x = x bar2 :: a -> a bar2 x = x ($$*) :: a -> a -> a x $$* _ = x data (:$$*:) a b = (:$$$*:) a b
sergv/tags-server
test-data/0001module_with_imports/Imported2.hs
bsd-3-clause
490
1
8
94
91
55
36
10
1
module VideoCore4.QPU.Instruction.SemaphoreId ( SemaphoreId , semaphore_0 , semaphore_1 , semaphore_2 , semaphore_3 , semaphore_4 , semaphore_5 , semaphore_6 , semaphore_7 , semaphore_8 , semaphore_9 , semaphore_10 , semaphore_11 , semaphore_12 , semaphore_13 , semaphore_14 , semaphore_15 ) where import Data.Typeable import Data.Word import VideoCore4.QPU.Instruction.Types newtype SemaphoreId = SemaphoreId { unSemaphoreId :: Word8 } deriving (Eq, Show, Typeable) instance To64 SemaphoreId where to64 = toEnum . fromEnum . unSemaphoreId semaphore_0 :: SemaphoreId semaphore_0 = SemaphoreId 0 semaphore_1 :: SemaphoreId semaphore_1 = SemaphoreId 1 semaphore_2 :: SemaphoreId semaphore_2 = SemaphoreId 2 semaphore_3 :: SemaphoreId semaphore_3 = SemaphoreId 3 semaphore_4 :: SemaphoreId semaphore_4 = SemaphoreId 4 semaphore_5 :: SemaphoreId semaphore_5 = SemaphoreId 5 semaphore_6 :: SemaphoreId semaphore_6 = SemaphoreId 6 semaphore_7 :: SemaphoreId semaphore_7 = SemaphoreId 7 semaphore_8 :: SemaphoreId semaphore_8 = SemaphoreId 8 semaphore_9 :: SemaphoreId semaphore_9 = SemaphoreId 9 semaphore_10 :: SemaphoreId semaphore_10 = SemaphoreId 10 semaphore_11 :: SemaphoreId semaphore_11 = SemaphoreId 11 semaphore_12 :: SemaphoreId semaphore_12 = SemaphoreId 12 semaphore_13 :: SemaphoreId semaphore_13 = SemaphoreId 13 semaphore_14 :: SemaphoreId semaphore_14 = SemaphoreId 14 semaphore_15 :: SemaphoreId semaphore_15 = SemaphoreId 15
notogawa/VideoCore4
src/VideoCore4/QPU/Instruction/SemaphoreId.hs
bsd-3-clause
1,579
0
7
321
335
192
143
57
1
{-| Module : Idris.Elab.Term Description : Code to elaborate terms. Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Elab.Term where import Idris.AbsSyntax import Idris.AbsSyntaxTree import Idris.DSL import Idris.Delaborate import Idris.Error import Idris.ProofSearch import Idris.Output (pshow) import Idris.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs) import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Unify import Idris.Core.ProofTerm (getProofTerm) import Idris.Core.Typecheck (check, recheck, converts, isType) import Idris.Core.WHNF (whnf) import Idris.Coverage (buildSCG, checkDeclTotality, checkPositive, genClauses, recoverableCoverage, validCoverageCase) import Idris.ErrReverse (errReverse) import Idris.Elab.Quasiquote (extractUnquotes) import Idris.Elab.Utils import Idris.Elab.Rewrite import Idris.Reflection import qualified Util.Pretty as U import Control.Applicative ((<$>)) import Control.Monad import Control.Monad.State.Strict import Data.Foldable (for_) import Data.List import qualified Data.Map as M import Data.Maybe (mapMaybe, fromMaybe, catMaybes, maybeToList) import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace data ElabMode = ETyDecl | ETransLHS | ELHS | ERHS deriving Eq data ElabResult = ElabResult { -- | The term resulting from elaboration resultTerm :: Term -- | Information about new metavariables , resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))] -- | Deferred declarations as the meaning of case blocks , resultCaseDecls :: [PDecl] -- | The potentially extended context from new definitions , resultContext :: Context -- | Meta-info about the new type declarations , resultTyDecls :: [RDeclInstructions] -- | Saved highlights from elaboration , resultHighlighting :: [(FC, OutputAnnotation)] -- | The new global name counter , resultName :: Int } -- | Using the elaborator, convert a term in raw syntax to a fully -- elaborated, typechecked term. -- -- If building a pattern match, we convert undeclared variables from -- holes to pattern bindings. -- -- Also find deferred names in the term and their types build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD ElabResult build ist info emode opts fn tm = do elab ist info emode opts fn tm let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False hs <- get_holes ivs <- get_instances ptm <- get_term -- Resolve remaining type classes. Two passes - first to get the -- default Num instances, second to clean up the rest when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal try (resolveTC' True True 10 g fn ist) (movelast n)) ivs ivs <- get_instances hs <- get_holes when (not pattern) $ mapM_ (\n -> when (n `elem` hs) $ do focus n g <- goal ptm <- get_term resolveTC' True True 10 g fn ist) ivs when (not pattern) $ solveAutos ist fn False tm <- get_term ctxt <- get_context probs <- get_probs u <- getUnifyLog hs <- get_holes when (not pattern) $ traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++ "Remaining problems:\n" ++ qshow probs) $ do unify_all; matchProblems True; unifyProblems when (not pattern) $ solveAutos ist fn True probs <- get_probs case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $ if inf then return () else lift (Error e) when tydecl (do mkPat update_term liftPats update_term orderPats) EState is _ impls highlights _ _ <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog g_nextname <- get_global_nextname if log /= "" then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname) else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname) where pattern = emode == ELHS tydecl = emode == ETyDecl mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () -- | Build a term autogenerated as a typeclass method definition. -- -- (Separate, so we don't go overboard resolving things that we don't -- know about yet on the LHS of a pattern def) buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> [Name] -> -- Cached names in the PTerm, before adding PAlternatives PTerm -> ElabD ElabResult buildTC ist info emode opts fn ns tm = do let tmIn = tm let inf = case lookupCtxt fn (idris_tyinfodata ist) of [TIPartial] -> True _ -> False -- set name supply to begin after highest index in tm initNextNameFrom ns elab ist info emode opts fn tm probs <- get_probs tm <- get_term case probs of [] -> return () ((_,_,_,_,e,_,_):es) -> if inf then return () else lift (Error e) dots <- get_dotterm -- 'dots' are the PHidden things which have not been solved by -- unification when (not (null dots)) $ lift (Error (CantMatch (getInferTerm tm))) EState is _ impls highlights _ _ <- getAux tt <- get_term ctxt <- get_context let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) [] log <- getLog g_nextname <- get_global_nextname if (log /= "") then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname) else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname) where pattern = emode == ELHS -- | return whether arguments of the given constructor name can be -- matched on. If they're polymorphic, no, unless the type has beed -- made concrete by the time we get around to elaborating the -- argument. getUnmatchable :: Context -> Name -> [Bool] getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon = case lookupTyExact n ctxt of Nothing -> [] Just ty -> checkArgs [] [] ty where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool] checkArgs env ns (Bind n (Pi _ t _) sc) = let env' = case t of TType _ -> n : env _ -> env in checkArgs env' (intersect env (refsIn t) : ns) (instantiate (P Bound n t) sc) checkArgs env ns t = map (not . null) (reverse ns) getUnmatchable ctxt n = [] data ElabCtxt = ElabCtxt { e_inarg :: Bool, e_isfn :: Bool, -- ^ Function part of application e_guarded :: Bool, e_intype :: Bool, e_qq :: Bool, e_nomatching :: Bool -- ^ can't pattern match } initElabCtxt = ElabCtxt False False False False False False goal_polymorphic :: ElabD Bool goal_polymorphic = do ty <- goal case ty of P _ n _ -> do env <- get_env case lookup n env of Nothing -> return False _ -> return True _ -> return False -- | Returns the set of declarations we need to add to complete the -- definition (most likely case blocks to elaborate) as well as -- declarations resulting from user tactic scripts (%runElab) elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm -> ElabD () elab ist info emode opts fn tm = do let loglvl = opt_logLevel (idris_options ist) when (loglvl > 5) $ unifyLog True compute -- expand type synonyms, etc let fc = maybe "(unknown)" elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote) est <- getAux sequence_ (get_delayed_elab est) end_unify ptm <- get_term when (pattern || intransform) -- convert remaining holes to pattern vars (do unify_all matchProblems False -- only the ones we matched earlier unifyProblems mkPat update_term liftPats) where pattern = emode == ELHS intransform = emode == ETransLHS bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS autoimpls = opt_autoimpls (idris_options ist) get_delayed_elab est = let ds = delayed_elab est in map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds tcgen = Dictionary `elem` opts reflection = Reflection `elem` opts isph arg = case getTm arg of Placeholder -> (True, priority arg) tm -> (False, priority arg) toElab ina arg = case getTm arg of Placeholder -> Nothing v -> Just (priority arg, elabE ina (elabFC info) v) toElab' ina arg = case getTm arg of Placeholder -> Nothing v -> Just (elabE ina (elabFC info) v) mkPat = do hs <- get_holes tm <- get_term case hs of (h: hs) -> do patvar h; mkPat [] -> return () elabRec = elabE initElabCtxt Nothing -- | elabE elaborates an expression, possibly wrapping implicit coercions -- and forces/delays. If you make a recursive call in elab', it is -- normally correct to call elabE - the ones that don't are desugarings -- typically elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD () elabE ina fc' t = do solved <- get_recents as <- get_autos hs <- get_holes -- If any of the autos use variables which have recently been solved, -- have another go at solving them now. mapM_ (\(a, (failc, ns)) -> if any (\n -> n `elem` solved) ns && head hs /= a then solveAuto ist fn False (a, failc) else return ()) as apt <- expandToArity t itm <- if not pattern then insertImpLam ina apt else return apt ct <- insertCoerce ina itm t' <- insertLazy ct g <- goal tm <- get_term ps <- get_probs hs <- get_holes --trace ("Elaborating " ++ show t' ++ " in " ++ show g -- ++ "\n" ++ show tm -- ++ "\nholes " ++ show hs -- ++ "\nproblems " ++ show ps -- ++ "\n-----------\n") $ --trace ("ELAB " ++ show t') $ env <- get_env let fc = fileFC "Force" handleError (forceErr t' env) (elab' ina fc' t') (elab' ina fc' (PApp fc (PRef fc [] (sUN "Force")) [pimp (sUN "t") Placeholder True, pimp (sUN "a") Placeholder True, pexp ct])) forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Delayed" = notDelay orig forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'), ht == txt "Delayed" = notDelay orig forceErr orig env (InfiniteUnify _ t _) | (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t), ht == txt "Delayed" = notDelay orig forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t forceErr orig env (At _ t) = forceErr orig env t forceErr orig env t = False notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False notDelay _ = True local f = do e <- get_env return (f `elem` map fst e) -- | Is a constant a type? constType :: Const -> Bool constType (AType _) = True constType StrType = True constType VoidType = True constType _ = False -- "guarded" means immediately under a constructor, to help find patvars elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote) -> Maybe FC -- ^ The closest FC in the syntax tree, if applicable -> PTerm -- ^ The term to elaborate -> ElabD () elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step elab' ina fc (PType fc') = do apply RType [] solve highlightSource fc' (AnnType "Type" "The type of types") elab' ina fc (PUniverse u) = do apply (RUType u) []; solve -- elab' (_,_,inty) (PConstant c) -- | constType c && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ina fc tm@(PConstant fc' c) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTypeConst c = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do apply (RConstant c) [] solve highlightSource fc' (AnnConst c) elab' ina fc (PQuote r) = do fill r; solve elab' ina _ (PTrue fc _) = do hnf_compute g <- goal case g of TType _ -> elab' ina (Just fc) (PRef fc [] unitTy) UType _ -> elab' ina (Just fc) (PRef fc [] unitTy) _ -> elab' ina (Just fc) (PRef fc [] unitCon) elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent classes = do g <- goal; resolveTC False False 5 g fn elabRec ist elab' ina fc (PResolveTC fc') = do c <- getNameFrom (sMN 0 "__class") instanceArg c -- Elaborate the equality type first homogeneously, then -- heterogeneously as a fallback elab' ina _ (PApp fc (PRef _ _ n) args) | n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args = try (do tyn <- getNameFrom (sMN 0 "aqty") claim tyn RType movelast tyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] tyn) True, pimp (sUN "B") (PRef NoFC [] tyn) False, pexp l, pexp r])) (do atyn <- getNameFrom (sMN 0 "aqty") btyn <- getNameFrom (sMN 0 "bqty") claim atyn RType movelast atyn claim btyn RType movelast btyn elab' ina (Just fc) (PApp fc (PRef fc [] eqTy) [pimp (sUN "A") (PRef NoFC [] atyn) True, pimp (sUN "B") (PRef NoFC [] btyn) False, pexp l, pexp r])) elab' ina _ (PPair fc hls _ l r) = do hnf_compute g <- goal let (tc, _) = unApply g case g of TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy) [pexp l,pexp r]) UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy) [pexp l,pexp r]) _ -> case tc of P _ n _ | n == upairTy -> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon) [pimp (sUN "A") Placeholder False, pimp (sUN "B") Placeholder False, pexp l, pexp r]) elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r) = case p of IsType -> asType IsTerm -> asValue TypeOrTerm -> do hnf_compute g <- goal case g of TType _ -> asType _ -> asValue where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy) [pexp t, pexp (PLam fc n nfc Placeholder r)]) asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon) [pimp (sMN 0 "a") t False, pimp (sMN 0 "P") Placeholder True, pexp l, pexp r]) elab' ina fc (PAlternative ms (ExactlyOne delayok) as) = do as_pruned <- doPrune as -- Finish the mkUniqueNames job with the pruned set, rather than -- the full set. uns <- get_usedns let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned (h : hs) <- get_holes ty <- goal case as' of [] -> do hds <- mapM showHd as lift $ tfail $ NoValidAlts hds [x] -> elab' ina fc x -- If there's options, try now, and if that fails, postpone -- to later. _ -> handleError isAmbiguous (do hds <- mapM showHd as' tryAll (zip (map (elab' ina fc) as') hds)) (do movelast h delayElab 5 $ do hs <- get_holes when (h `elem` hs) $ do focus h as'' <- doPrune as' case as'' of [x] -> elab' ina fc x _ -> do hds <- mapM showHd as'' tryAll' False (zip (map (elab' ina fc) as'') hds)) where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = showHd (getTm arg) showHd (PApp _ (PRef _ _ n) _) = return n showHd (PRef _ _ n) = return n showHd (PApp _ h _) = showHd h showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here doPrune as = do compute ty <- goal let (tc, _) = unApply (unDelay ty) env <- get_env return $ pruneByType env tc (unDelay ty) ist as unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t, l == txt "Delayed" = unDelay arg | otherwise = t isAmbiguous (CantResolveAlts _) = delayok isAmbiguous (Elaborating _ _ _ e) = isAmbiguous e isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e isAmbiguous (At _ e) = isAmbiguous e isAmbiguous _ = False elab' ina fc (PAlternative ms FirstSuccess as_in) = do -- finish the mkUniqueNames job uns <- get_usedns let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in trySeq as where -- if none work, take the error from the first trySeq (x : xs) = let e1 = elab' ina fc x in try' e1 (trySeq' e1 xs) True trySeq [] = fail "Nothing to try in sequence" trySeq' deferr [] = do deferr; unifyProblems trySeq' deferr (x : xs) = try' (tryCatch (do elab' ina fc x solveAutos ist fn False unifyProblems) (\_ -> trySeq' deferr [])) (trySeq' deferr xs) True elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do env <- get_env compute ty <- goal let doelab = elab' ina fc orig tryCatch doelab (\err -> if recoverableErr err then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++ -- show alts ++ "\n" ++ -- showQuick err) $ -- Prune the coercions so that only the ones -- with the right type to fix the error will be tried! case pruneAlts err alts env of [] -> lift $ tfail err alts' -> do try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts')) (lift $ tfail err) -- take error from original if all fail True else lift $ tfail err) where recoverableErr (CantUnify _ _ _ _ _ _) = True recoverableErr (TooManyArguments _) = False recoverableErr (CantSolveGoal _ _) = False recoverableErr (CantResolveAlts _) = False recoverableErr (NoValidAlts _) = True recoverableErr (ProofSearchFail (Msg _)) = True recoverableErr (ProofSearchFail _) = False recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e recoverableErr (At _ e) = recoverableErr e recoverableErr (ElabScriptDebug _ _ _) = False recoverableErr _ = True pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env = case unApply (normalise (tt_ctxt ist) env inc) of (P (TCon _ _) n _, _) -> filter (hasArg n env) alts (Constant _, _) -> alts _ -> filter isLend alts -- special case hack for 'Borrowed' pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env pruneAlts (At _ e) alts env = pruneAlts e alts env pruneAlts (NoValidAlts as) alts env = alts pruneAlts err alts _ = filter isLend alts hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed' hasArg n env (PApp _ (PRef _ _ a) _) = case lookupTyExact a (tt_ctxt ist) of Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in any (fnIs n) args Nothing -> False hasArg n env (PAlternative _ _ as) = any (hasArg n env) as hasArg n _ tm = False isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"] isLend _ = False fnIs n ty = case unApply ty of (P _ n' _, _) -> n == n' _ -> False showQuick (CantUnify _ (l, _) (r, _) _ _ _) = show (l, r) showQuick (ElaboratingArg _ _ _ e) = showQuick e showQuick (At _ e) = showQuick e showQuick (ProofSearchFail (Msg _)) = "search fail" showQuick _ = "No chance" elab' ina _ (PPatvar fc n) | bindfree = do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) -- elab' (_, _, inty) (PRef fc f) -- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty -- = lift $ tfail (Msg "Typecase is not allowed") elab' ec _ tm@(PRef fc hl n) | pattern && not reflection && not (e_qq ec) && not (e_intype ec) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ec) && e_nomatching ec = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec) = do ty <- goal testImplicitWarning fc n ty let ina = e_inarg ec guarded = e_guarded ec inty = e_intype ec ctxt <- get_context let defined = case lookupTy n ctxt of [] -> False _ -> True -- this is to stop us resolve type classes recursively -- trace (show (n, guarded)) $ if (tcname n && ina && not intransform) then erun fc $ do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) else if (defined && not guarded) then do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot else try (do apply (Var n) [] annot <- findHighlight n solve highlightSource fc annot) (do patvar n update_term liftPats highlightSource fc (AnnBoundName n False)) where inparamBlock n = case lookupCtxtName n (inblock info) of [] -> False _ -> True bindable (NS _ _) = False bindable (MN _ _) = True bindable n = implicitable n && autoimpls elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f []) elab' ina fc' tm@(PRef fc hls n) | pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName n (tt_ctxt ist) = lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = do fty <- get_type (Var n) -- check for implicits ctxt <- get_context env <- get_env let a' = insertScopedImps fc (normalise ctxt env fty) [] if null a' then erun fc $ do apply (Var n) [] hilite <- findHighlight n solve mapM_ (uncurry highlightSource) $ (fc, hilite) : map (\f -> (f, hilite)) hls else elab' ina fc' (PApp fc tm []) elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible" elab' ina _ (PLam fc n nfc Placeholder sc) = do -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n attack; intro (Just n); addPSname n -- okay for proof search -- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm) elabE (ina { e_inarg = True } ) (Just fc) sc; solve highlightSource nfc (AnnBoundName n False) elab' ec _ (PLam fc n nfc ty sc) = do tyn <- getNameFrom (sMN 0 "lamty") -- if n is a type constructor name, this makes no sense... ctxt <- get_context when (isTConName n ctxt) $ lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here") checkPiGoal n claim tyn RType explicit tyn attack ptm <- get_term hs <- get_holes introTy (Var tyn) (Just n) addPSname n -- okay for proof search focus tyn elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty elabE (ec { e_inarg = True }) (Just fc) sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc Placeholder sc) = do attack; arg n (is_scoped p) (sMN 0 "ty") addAutoBind p n addPSname n -- okay for proof search elabE (ina { e_inarg = True, e_intype = True }) fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina fc (PPi p n nfc ty sc) = do attack; tyn <- getNameFrom (sMN 0 "ty") claim tyn RType n' <- case n of MN _ _ -> unique_hole n _ -> return n forall n' (is_scoped p) (Var tyn) addAutoBind p n' addPSname n' -- okay for proof search focus tyn let ec' = ina { e_inarg = True, e_intype = True } elabE ec' fc ty elabE ec' fc sc solve highlightSource nfc (AnnBoundName n False) elab' ina _ tm@(PLet fc n nfc ty val sc) = do attack ivs <- get_instances tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) explicit valn letbind n (Var tyn) (Var valn) addPSname n case ty of Placeholder -> return () _ -> do focus tyn explicit tyn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) ty focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) val ivs' <- get_instances env <- get_env elabE (ina { e_inarg = True }) (Just fc) sc when (not (pattern || intransform)) $ mapM_ (\n -> do focus n g <- goal hs <- get_holes if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g) then handleError (tcRecoverable emode) (resolveTC True False 10 g fn elabRec ist) (movelast n) else movelast n) (ivs' \\ ivs) -- HACK: If the name leaks into its type, it may leak out of -- scope outside, so substitute in the outer scope. expandLet n (case lookup n env of Just (Let t v) -> v other -> error ("Value not a let binding: " ++ show other)) solve highlightSource nfc (AnnBoundName n False) elab' ina _ (PGoal fc r n sc) = do rty <- goal attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letbind n (Var tyn) (Var valn) focus valn elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)]) env <- get_env computeLet n elabE (ina { e_inarg = True }) (Just fc) sc solve -- elab' ina fc (PLet n Placeholder -- (PApp fc r [pexp (delab ist rty)]) sc) elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do rty <- goal ds <- get_deferred ctxt <- get_context -- make a function type a -> b -> c -> ... -> rty for the -- new function name env <- get_env argTys <- claimArgTys env args fn <- getNameFrom (sMN 0 "inf_fn") let fty = fnTy argTys rty -- trace (show (ptm, map fst argTys)) $ focus fn -- build and defer the function application attack; deferType (mkN f) fty (map fst argTys); solve -- elaborate the arguments, to unify their types. They all have to -- be explicit. mapM_ elabIArg (zip argTys args) where claimArgTys env [] = return [] claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg) = do nty <- get_type (Var n) ans <- claimArgTys env xs return ((n, (False, forget nty)) : ans) claimArgTys env (_ : xs) = do an <- getNameFrom (sMN 0 "inf_argTy") aval <- getNameFrom (sMN 0 "inf_arg") claim an RType claim aval (Var an) ans <- claimArgTys env xs return ((aval, (True, (Var an))) : ans) fnTy [] ret = forget ret fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi Nothing xt RType) (fnTy xs ret) localVar env (PRef _ _ x) = case lookup x env of Just _ -> Just x _ -> Nothing localVar env _ = Nothing elabIArg ((n, (True, ty)), def) = do focus n; elabE ina (Just fc) (getTm def) elabIArg _ = return () -- already done, just a name mkN n@(NS _ _) = n mkN n@(SN _) = n mkN n = case namespace info of xs@(_:_) -> sNS n xs _ -> n elab' ina _ (PMatchApp fc fn) = do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of [(n, args)] -> return (n, map (const True) args) _ -> lift $ tfail (NoSuchVariable fn) ns <- match_apply (Var fn') (map (\x -> (x,0)) imps) solve -- if f is local, just do a simple_app -- FIXME: Anyone feel like refactoring this mess? - EB elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in) | pattern && not reflection && not (e_qq ina) && e_nomatching ina = lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm) | otherwise = implicitApp $ do env <- get_env ty <- goal fty <- get_type (Var f) ctxt <- get_context annot <- findHighlight f mapM_ checkKnownImplicit args_in let args = insertScopedImps fc (normalise ctxt env fty) args_in let unmatchableArgs = if pattern then getUnmatchable (tt_ctxt ist) f else [] -- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $ when (pattern && not reflection && not (e_qq ina) && not (e_intype ina) && isTConName f (tt_ctxt ist)) $ lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm) -- trace (show (f, args_in, args)) $ if (f `elem` map fst env && length args == 1 && length args_in == 1) then -- simple app, as below do simple_app False (elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f)) (elabE (ina { e_inarg = True }) (Just fc) (getTm (head args))) (show tm) solve mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls return [] else do ivs <- get_instances ps <- get_probs -- HACK: we shouldn't resolve type classes if we're defining an instance -- function or default definition. let isinf = f == inferCon || tcname f -- if f is a type class, we need to know its arguments so that -- we can unify with them case lookupCtxt f (idris_classes ist) of [] -> return () _ -> do mapM_ setInjective (map getTm args) -- maybe more things are solvable now unifyProblems let guarded = isConName f ctxt -- trace ("args is " ++ show args) $ return () ns <- apply (Var f) (map isph args) -- trace ("ns is " ++ show ns) $ return () -- mark any type class arguments as injective when (not pattern) $ mapM_ checkIfInjective (map snd ns) unifyProblems -- try again with the new information, -- to help with disambiguation ulog <- getUnifyLog annot <- findHighlight f mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls elabArgs ist (ina { e_inarg = e_inarg ina || not isinf }) [] fc False f (zip ns (unmatchableArgs ++ repeat False)) (f == sUN "Force") (map (\x -> getTm x) args) -- TODO: remove this False arg imp <- if (e_isfn ina) then do guess <- get_guess env <- get_env case safeForgetEnv (map fst env) guess of Nothing -> return [] Just rguess -> do gty <- get_type rguess let ty_n = normalise ctxt env gty return $ getReqImps ty_n else return [] -- Now we find out how many implicits we needed at the -- end of the application by looking at the goal again -- - Have another go, but this time add the -- implicits (can't think of a better way than this...) case imp of rs@(_:_) | not pattern -> return rs -- quit, try again _ -> do solve hs <- get_holes ivs' <- get_instances -- Attempt to resolve any type classes which have 'complete' types, -- i.e. no holes in them when (not pattern || (e_inarg ina && not tcgen && not (e_guarded ina))) $ mapM_ (\n -> do focus n g <- goal env <- get_env hs <- get_holes if all (\n -> not (n `elem` hs)) (freeNames g) then handleError (tcRecoverable emode) (resolveTC False False 10 g fn elabRec ist) (movelast n) else movelast n) (ivs' \\ ivs) return [] where -- Run the elaborator, which returns how many implicit -- args were needed, then run it again with those args. We need -- this because we have to elaborate the whole application to -- find out whether any computations have caused more implicits -- to be needed. implicitApp :: ElabD [ImplicitInfo] -> ElabD () implicitApp elab | pattern || intransform = do elab; return () | otherwise = do s <- get imps <- elab case imps of [] -> return () es -> do put s elab' ina topfc (PAppImpl tm es) checkKnownImplicit imp | UnknownImp `elem` argopts imp = lift $ tfail $ UnknownImplicit (pname imp) f checkKnownImplicit _ = return () getReqImps (Bind x (Pi (Just i) ty _) sc) = i : getReqImps sc getReqImps _ = [] checkIfInjective n = do env <- get_env case lookup n env of Nothing -> return () Just b -> case unApply (normalise (tt_ctxt ist) env (binderTy b)) of (P _ c _, args) -> case lookupCtxtExact c (idris_classes ist) of Nothing -> return () Just ci -> -- type class, set as injective do mapM_ setinjArg (getDets 0 (class_determiners ci) args) -- maybe we can solve more things now... ulog <- getUnifyLog probs <- get_probs traceWhen ulog ("Injective now " ++ show args ++ "\n" ++ qshow probs) $ unifyProblems probs <- get_probs traceWhen ulog (qshow probs) $ return () _ -> return () setinjArg (P _ n _) = setinj n setinjArg _ = return () getDets i ds [] = [] getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as | otherwise = getDets (i + 1) ds as tacTm (PTactics _) = True tacTm (PProof _) = True tacTm _ = False setInjective (PRef _ _ n) = setinj n setInjective (PApp _ (PRef _ _ n) _) = setinj n setInjective _ = return () elab' ina _ tm@(PApp fc f [arg]) = erun fc $ do simple_app (not $ headRef f) (elabE (ina { e_isfn = True }) (Just fc) f) (elabE (ina { e_inarg = True }) (Just fc) (getTm arg)) (show tm) solve where headRef (PRef _ _ _) = True headRef (PApp _ f _) = headRef f headRef (PAlternative _ _ as) = all headRef as headRef _ = False elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look... solve where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits appImpl (e : es) = simple_app False (appImpl es) (elab' ina fc Placeholder) (show f) elab' ina fc Placeholder = do (h : hs) <- get_holes movelast h elab' ina fc (PMetavar nfc n) = do ptm <- get_term -- When building the metavar application, leave out the unique -- names which have been used elsewhere in the term, since we -- won't be able to use them in the resulting application. let unique_used = getUniqueUsed (tt_ctxt ist) ptm let n' = metavarName (namespace info) n attack psns <- getPSnames n' <- defer unique_used n' solve highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing) elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts elab' ina fc (PTactics ts) | not pattern = do mapM_ (runTac False ist fc fn) ts | otherwise = elab' ina fc Placeholder elab' ina fc (PElabError e) = lift $ tfail e elab' ina mfc (PRewrite fc substfn rule sc newg) = elabRewrite (elab' ina mfc) ist fc substfn rule sc newg elab' ina _ c@(PCase fc scr opts) = do attack tyn <- getNameFrom (sMN 0 "scty") claim tyn RType valn <- getNameFrom (sMN 0 "scval") scvn <- getNameFrom (sMN 0 "scvar") claim valn (Var tyn) letbind scvn (Var tyn) (Var valn) -- Start filling in the scrutinee type, if we can work one -- out from the case options let scrTy = getScrType (map fst opts) case scrTy of Nothing -> return () Just ty -> do focus tyn elabE ina (Just fc) ty focus valn elabE (ina { e_inarg = True }) (Just fc) scr -- Solve any remaining implicits - we need to solve as many -- as possible before making the 'case' type unifyProblems matchProblems True args <- get_env envU <- mapM (getKind args) args let namesUsedInRHS = nub $ scvn : concatMap (\(_,rhs) -> allNamesIn rhs) opts -- Drop the unique arguments used in the term already -- and in the scrutinee (since it's -- not valid to use them again anyway) -- -- Also drop unique arguments which don't appear explicitly -- in either case branch so they don't count as used -- unnecessarily (can only do this for unique things, since we -- assume they don't appear implicitly in types) ptm <- get_term let inOpts = (filter (/= scvn) (map fst args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts) let argsDropped = filter (isUnique envU) (nub $ allNamesIn scr ++ inApp ptm ++ inOpts) let args' = filter (\(n, _) -> n `notElem` argsDropped) args attack cname' <- defer argsDropped (mkN (mkCaseName fc fn)) solve -- if the scrutinee is one of the 'args' in env, we should -- inspect it directly, rather than adding it as a new argument let newdef = PClauses fc [] cname' (caseBlock fc cname' scr (map (isScr scr) (reverse args')) opts) -- elaborate case updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } ) -- if we haven't got the type yet, hopefully we'll get it later! movelast tyn solve where mkCaseName fc (NS n ns) = NS (mkCaseName fc n) ns mkCaseName fc n = SN (CaseN (FC' fc) n) -- mkCaseName (UN x) = UN (x ++ "_case") -- mkCaseName (MN i x) = MN i (x ++ "_case") mkN n@(NS _ _) = n mkN n = case namespace info of xs@(_:_) -> sNS n xs _ -> n getScrType [] = Nothing getScrType (f : os) = maybe (getScrType os) Just (getAppType f) getAppType (PRef _ _ n) = case lookupTyName n (tt_ctxt ist) of [(n', ty)] | isDConName n' (tt_ctxt ist) -> case unApply (getRetTy ty) of (P _ tyn _, args) -> Just (PApp fc (PRef fc [] tyn) (map pexp (map (const Placeholder) args))) _ -> Nothing _ -> Nothing -- ambiguity is no help to us! getAppType (PApp _ t as) = getAppType t getAppType _ = Nothing inApp (P _ n _) = [n] inApp (App _ f a) = inApp f ++ inApp a inApp (Bind n (Let _ v) sc) = inApp v ++ inApp sc inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc inApp (Bind n b sc) = inApp sc inApp _ = [] isUnique envk n = case lookup n envk of Just u -> u _ -> False getKind env (n, _) = case lookup n env of Nothing -> return (n, False) -- can't happen, actually... Just b -> do ty <- get_type (forget (binderTy b)) case ty of UType UniqueType -> return (n, True) UType AllTypes -> return (n, True) _ -> return (n, False) tcName tm | (P _ n _, _) <- unApply tm = case lookupCtxt n (idris_classes ist) of [_] -> True _ -> False tcName _ = False usedIn ns (n, b) = n `elem` ns || any (\x -> x `elem` ns) (allTTNames (binderTy b)) elab' ina fc (PUnifyLog t) = do unifyLog True elab' ina fc t unifyLog False elab' ina fc (PQuasiquote t goalt) = do -- First extract the unquoted subterms, replacing them with fresh -- names in the quasiquoted term. Claim their reflections to be -- an inferred type (to support polytypic quasiquotes). finalTy <- goal (t, unq) <- extractUnquotes 0 t let unquoteNames = map fst unq mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames -- Save the old state - we need a fresh proof state to avoid -- capturing lexically available variables in the quoted term. ctxt <- get_context datatypes <- get_datatypes g_nextname <- get_global_nextname saveState updatePS (const . newProof (sMN 0 "q") (constraintNS info) ctxt datatypes g_nextname $ P Ref (reflm "TT") Erased) -- Re-add the unquotes, letting Idris infer the (fictional) -- types. Here, they represent the real type rather than the type -- of their reflection. mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy") claim ty RType movelast ty claim n (Var ty) movelast n) unquoteNames -- Determine whether there's an explicit goal type, and act accordingly -- Establish holes for the type and value of the term to be -- quasiquoted qTy <- getNameFrom (sMN 0 "qquoteTy") claim qTy RType movelast qTy qTm <- getNameFrom (sMN 0 "qquoteTm") claim qTm (Var qTy) -- Let-bind the result of elaborating the contained term, so that -- the hole doesn't disappear nTm <- getNameFrom (sMN 0 "quotedTerm") letbind nTm (Var qTy) (Var qTm) -- Fill out the goal type, if relevant case goalt of Nothing -> return () Just gTy -> do focus qTy elabE (ina { e_qq = True }) fc gTy -- Elaborate the quasiquoted term into the hole focus qTm elabE (ina { e_qq = True }) fc t end_unify -- We now have an elaborated term. Reflect it and solve the -- original goal in the original proof state, preserving highlighting env <- get_env EState _ _ _ hs _ _ <- getAux loadState updateAux (\aux -> aux { highlighting = hs }) let quoted = fmap (explicitNames . binderVal) $ lookup nTm env isRaw = case unApply (normaliseAll ctxt env finalTy) of (P _ n _, []) | n == reflm "Raw" -> True _ -> False case quoted of Just q -> do ctxt <- get_context (q', _, _) <- lift $ recheck (constraintNS info) ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q if pattern then if isRaw then reflectRawQuotePattern unquoteNames (forget q') else reflectTTQuotePattern unquoteNames q' else do if isRaw then -- we forget q' instead of using q to ensure rechecking fill $ reflectRawQuote unquoteNames (forget q') else fill $ reflectTTQuote unquoteNames q' solve Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote" -- Finally fill in the terms or patterns from the unquotes. This -- happens last so that their holes still exist while elaborating -- the main quotation. mapM_ elabUnquote unq where elabUnquote (n, tm) = do focus n elabE (ina { e_qq = False }) fc tm elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote" elab' ina fc (PQuoteName n False nfc) = do fill $ reflectName n solve elab' ina fc (PQuoteName n True nfc) = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> do fill $ reflectName n solve highlightSource nfc (AnnBoundName n False) Nothing -> case lookupNameDef n ctxt of [(n', _)] -> do fill $ reflectName n' solve highlightSource nfc (AnnName n' Nothing Nothing Nothing) [] -> lift . tfail . NoSuchVariable $ n more -> lift . tfail . CantResolveAlts $ map fst more elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here" elab' ina fc (PHidden t) | reflection = elab' ina fc t | otherwise = do (h : hs) <- get_holes -- Dotting a hole means that either the hole or any outer -- hole (a hole outside any occurrence of it) -- must be solvable by unification as well as being filled -- in directly. -- Delay dotted things to the end, then when we elaborate them -- we can check the result against what was inferred movelast h delayElab 10 $ do hs <- get_holes when (h `elem` hs) $ do focus h dotterm elab' ina fc t elab' ina fc (PRunElab fc' tm ns) = do attack n <- getNameFrom (sMN 0 "tacticScript") let scriptTy = RApp (Var (sNS (sUN "Elab") ["Elab", "Reflection", "Language"])) (Var unitTy) claim n scriptTy focus n attack -- to get an extra hole elab' ina (Just fc') tm script <- get_guess fullyElaborated script solve -- eliminate the hole. Becuase there are no references, the script is only in the binding env <- get_env runElabAction info ist (maybe fc' id fc) env script ns solve elab' ina fc (PConstSugar constFC tm) = -- Here we elaborate the contained term, then calculate -- highlighting for constFC. The highlighting is the -- highlighting for the outermost constructor of the result of -- evaluating the elaborated term, if one exists (it always -- should, but better to fail gracefully for something silly -- like highlighting info). This is how implicit applications of -- fromInteger get highlighted. do saveState -- so we don't pollute the elaborated term n <- getNameFrom (sMN 0 "cstI") n' <- getNameFrom (sMN 0 "cstIhole") g <- forget <$> goal claim n' g movelast n' -- In order to intercept the elaborated value, we need to -- let-bind it. attack letbind n g (Var n') focus n' elab' ina fc tm env <- get_env ctxt <- get_context let v = fmap (normaliseAll ctxt env . finalise . binderVal) (lookup n env) loadState -- we have the highlighting - re-elaborate the value elab' ina fc tm case v of Just val -> highlightConst constFC val Nothing -> return () where highlightConst fc (P _ n _) = highlightSource fc (AnnName n Nothing Nothing Nothing) highlightConst fc (App _ f _) = highlightConst fc f highlightConst fc (Constant c) = highlightSource fc (AnnConst c) highlightConst _ _ = return () elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x -- delay elaboration of 't', with priority 'pri' until after everything -- else is done. -- The delayed things with lower numbered priority will be elaborated -- first. (In practice, this means delayed alternatives, then PHidden -- things.) delayElab pri t = updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] }) isScr :: PTerm -> (Name, Binder Term) -> (Name, (Bool, Binder Term)) isScr (PRef _ _ n) (n', b) = (n', (n == n', b)) isScr _ (n', b) = (n', (False, b)) caseBlock :: FC -> Name -> PTerm -- original scrutinee -> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause] caseBlock fc n scr env opts = let args' = findScr env args = map mkarg (map getNmScr args') in map (mkClause args) opts where -- Find the variable we want as the scrutinee and mark it as -- 'True'. If the scrutinee is in the environment, match on that -- otherwise match on the new argument we're adding. findScr ((n, (True, t)) : xs) = (n, (True, t)) : scrName n xs findScr [(n, (_, t))] = [(n, (True, t))] findScr (x : xs) = x : findScr xs -- [] can't happen since scrutinee is in the environment! findScr [] = error "The impossible happened - the scrutinee was not in the environment" -- To make sure top level pattern name remains in scope, put -- it at the end of the environment scrName n [] = [] scrName n [(_, t)] = [(n, t)] scrName n (x : xs) = x : scrName n xs getNmScr (n, (s, _)) = (n, s) mkarg (n, s) = (PRef fc [] n, s) -- may be shadowed names in the new pattern - so replace the -- old ones with an _ -- Also, names which don't appear on the rhs should not be -- fixed on the lhs, or this restricts the kind of matching -- we can do to non-dependent types. mkClause args (l, r) = let args' = map (shadowed (allNamesIn l)) args args'' = map (implicitable (allNamesIn r ++ keepscrName scr)) args' lhs = PApp (getFC fc l) (PRef NoFC [] n) (map (mkLHSarg l) args'') in PClause (getFC fc l) n lhs [] r [] -- Keep scrutinee available if it's just a name (this makes -- the names in scope look better when looking at a hole on -- the rhs of a case) keepscrName (PRef _ _ n) = [n] keepscrName _ = [] mkLHSarg l (tm, True) = pexp l mkLHSarg l (tm, False) = pexp tm shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s) shadowed new t = t implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s) implicitable rhs t = t getFC d (PApp fc _ _) = fc getFC d (PRef fc _ _) = fc getFC d (PAlternative _ _ (x:_)) = getFC d x getFC d x = d -- Fail if a term is not yet fully elaborated (e.g. if it contains -- case block functions that don't yet exist) fullyElaborated :: Term -> ElabD () fullyElaborated (P _ n _) = do estate <- getAux case lookup n (case_decls estate) of Nothing -> return () Just _ -> lift . tfail $ ElabScriptStaging n fullyElaborated (Bind n b body) = fullyElaborated body >> for_ b fullyElaborated fullyElaborated (App _ l r) = fullyElaborated l >> fullyElaborated r fullyElaborated (Proj t _) = fullyElaborated t fullyElaborated _ = return () -- If the goal type is a "Lazy", then try elaborating via 'Delay' -- first. We need to do this brute force approach, rather than anything -- more precise, since there may be various other ambiguities to resolve -- first. insertLazy :: PTerm -> ElabD PTerm insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t insertLazy t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t insertLazy (PCoerced t) = return t -- Don't add a delay to pattern variables, since they can be forced -- on the rhs insertLazy t@(PPatvar _ _) | pattern = return t insertLazy t = do ty <- goal env <- get_env let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty) let tries = [mkDelay env t, t] case tyh of P _ (UN l) _ | l == txt "Delayed" -> return (PAlternative [] FirstSuccess tries) _ -> return t where mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs) mkDelay env t = let fc = fileFC "Delay" in addImplBound ist (map fst env) (PApp fc (PRef fc [] (sUN "Delay")) [pexp t]) -- Don't put implicit coercions around applications which are marked -- as '%noImplicit', or around case blocks, otherwise we get exponential -- blowup especially where there are errors deep in large expressions. notImplicitable (PApp _ f _) = notImplicitable f -- TMP HACK no coercing on bind (make this configurable) notImplicitable (PRef _ _ n) | [opts] <- lookupCtxt n (idris_flags ist) = NoImplicit `elem` opts notImplicitable (PAlternative _ _ as) = any notImplicitable as -- case is tricky enough without implicit coercions! If they are needed, -- they can go in the branches separately. notImplicitable (PCase _ _ _) = True notImplicitable _ = False -- Elaboration works more smoothly if we expand function applications -- to their full arity and elaborate it all at once (better error messages -- in particular) expandToArity tm@(PApp fc f a) = do env <- get_env case fullApp tm of -- if f is global, leave it alone because we've already -- expanded it to the right arity PApp fc ftm@(PRef _ _ f) args | Just aty <- lookup f env -> do let a = length (getArgTys (normalise (tt_ctxt ist) env (binderTy aty))) return (mkPApp fc a ftm args) _ -> return tm expandToArity t = return t fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs)) fullApp x = x insertScopedImps fc (Bind n (Pi im@(Just i) _ _) sc) xs | tcinstance i && not (toplevel_imp i) = pimp n (PResolveTC fc) True : insertScopedImps fc sc xs | not (toplevel_imp i) = pimp n Placeholder True : insertScopedImps fc sc xs insertScopedImps fc (Bind n (Pi _ _ _) sc) (x : xs) = x : insertScopedImps fc sc xs insertScopedImps _ _ xs = xs insertImpLam ina t = do ty <- goal env <- get_env let ty' = normalise (tt_ctxt ist) env ty addLam ty' t where -- just one level at a time addLam (Bind n (Pi (Just _) _ _) sc) t = do impn <- unique_hole n -- (sMN 0 "scoped_imp") if e_isfn ina -- apply to an implicit immediately then return (PApp emptyFC (PLam emptyFC impn NoFC Placeholder t) [pexp Placeholder]) else return (PLam emptyFC impn NoFC Placeholder t) addLam _ t = return t insertCoerce ina t@(PCase _ _ _) = return t insertCoerce ina t | notImplicitable t = return t insertCoerce ina t = do ty <- goal -- Check for possible coercions to get to the goal -- and add them as 'alternatives' env <- get_env let ty' = normalise (tt_ctxt ist) env ty let cs = getCoercionsTo ist ty' let t' = case (t, cs) of (PCoerced tm, _) -> tm (_, []) -> t (_, cs) -> PAlternative [] TryImplicit (t : map (mkCoerce env t) cs) return t' where mkCoerce env (PAlternative ms aty tms) n = PAlternative ms aty (map (\t -> mkCoerce env t n) tms) mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in addImplBound ist (map fst env) (PApp fc (PRef fc [] n) [pexp (PCoerced t)]) -- | Elaborate the arguments to a function elabArgs :: IState -- ^ The current Idris state -> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote) -> [Bool] -> FC -- ^ Source location -> Bool -> Name -- ^ Name of the function being applied -> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable) -> Bool -- ^ under a 'force' -> [PTerm] -- ^ argument -> ElabD () elabArgs ist ina failed fc retry f [] force _ = return () elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args) = do hs <- get_holes if holeName `elem` hs then do focus holeName case t of Placeholder -> do movelast holeName elabArgs ist ina failed fc r f ns force args _ -> elabArg t else elabArgs ist ina failed fc r f ns force args where elabArg t = do -- solveAutos ist fn False now_elaborating fc f argName wrapErr f argName $ do hs <- get_holes tm <- get_term -- No coercing under an explicit Force (or it can Force/Delay -- recursively!) let elab = if force then elab' else elabE failed' <- -- trace (show (n, t, hs, tm)) $ -- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $ do focus holeName; g <- goal -- Can't pattern match on polymorphic goals poly <- goal_polymorphic ulog <- getUnifyLog traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $ elab (ina { e_nomatching = unm && poly }) (Just fc) t return failed done_elaborating_arg f argName elabArgs ist ina failed fc r f ns force args wrapErr f argName action = do elabState <- get while <- elaborating_app let while' = map (\(x, y, z)-> (y, z)) while (result, newState) <- case runStateT action elabState of OK (res, newState) -> return (res, newState) Error e -> do done_elaborating_arg f argName lift (tfail (elaboratingArgErr while' e)) put newState return result elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] = fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole addAutoBind :: Plicity -> Name -> ElabD () addAutoBind (Imp _ _ _ _ False) n = updateAux (\est -> est { auto_binds = n : auto_binds est }) addAutoBind _ _ = return () testImplicitWarning :: FC -> Name -> Type -> ElabD () testImplicitWarning fc n goal | implicitable n && emode == ETyDecl = do env <- get_env est <- getAux when (n `elem` auto_binds est) $ tryUnify env (lookupTyName n (tt_ctxt ist)) | otherwise = return () where tryUnify env [] = return () tryUnify env ((nm, ty) : ts) = do inj <- get_inj hs <- get_holes case unify (tt_ctxt ist) env (ty, Nothing) (goal, Nothing) inj hs [] [] of OK _ -> updateAux (\est -> est { implicit_warnings = (fc, nm) : implicit_warnings est }) _ -> tryUnify env ts -- For every alternative, look at the function at the head. Automatically resolve -- any nested alternatives where that function is also at the head pruneAlt :: [PTerm] -> [PTerm] pruneAlt xs = map prune xs where prune (PApp fc1 (PRef fc2 hls f) as) = PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as) prune t = t choose f (PAlternative ms a as) = let as' = fmap (choose f) as fs = filter (headIs f) as' in case fs of [a] -> a _ -> PAlternative ms a as' choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as) choose f t = t headIs f (PApp _ (PRef _ _ f') _) = f == f' headIs f (PApp _ f' _) = headIs f f' headIs f _ = True -- keep if it's not an application -- Rule out alternatives that don't return the same type as the head of the goal -- (If there are none left as a result, do nothing) pruneByType :: Env -> Term -> -- head of the goal Type -> -- goal IState -> [PTerm] -> [PTerm] -- if an alternative has a locally bound name at the head, take it pruneByType env t goalty c as | Just a <- locallyBound as = [a] where locallyBound [] = Nothing locallyBound (t:ts) | Just n <- getName t, n `elem` map fst env = Just t | otherwise = locallyBound ts getName (PRef _ _ n) = Just n getName (PApp _ (PRef _ _ (UN l)) [_, _, arg]) -- ignore Delays | l == txt "Delay" = getName (getTm arg) getName (PApp _ f _) = getName f getName (PHidden t) = getName t getName _ = Nothing -- 'n' is the name at the head of the goal type pruneByType env (P _ n _) goalty ist as -- if the goal type is polymorphic, keep everything | Nothing <- lookupTyExact n ctxt = as -- if the goal type is a ?metavariable, keep everything | Just _ <- lookup n (idris_metavars ist) = as | otherwise = let asV = filter (headIs True n) as as' = filter (headIs False n) as in case as' of [] -> asV _ -> as' where ctxt = tt_ctxt ist -- Get the function at the head of the alternative and see if it's -- a plausible match against the goal type. Keep if so. Also keep if -- there is a possible coercion to the goal type. headIs var f (PRef _ _ f') = typeHead var f f' headIs var f (PApp _ (PRef _ _ (UN l)) [_, _, arg]) | l == txt "Delay" = headIs var f (getTm arg) headIs var f (PApp _ (PRef _ _ f') _) = typeHead var f f' headIs var f (PApp _ f' _) = headIs var f f' headIs var f (PPi _ _ _ _ sc) = headIs var f sc headIs var f (PHidden t) = headIs var f t headIs var f t = True -- keep if it's not an application typeHead var f f' = -- trace ("Trying " ++ show f' ++ " for " ++ show n) $ case lookupTyExact f' ctxt of Just ty -> case unApply (getRetTy ty) of (P _ ctyn _, _) | isTConName ctyn ctxt && not (ctyn == f) -> False _ -> let ty' = normalise ctxt [] ty in -- trace ("Trying " ++ show (getRetTy ty') ++ " for " ++ show goalty) $ case unApply (getRetTy ty') of (V _, _) -> isPlausible ist var env n ty _ -> matching (getRetTy ty') goalty || isCoercion (getRetTy ty') goalty -- May be useful to keep for debugging purposes for a bit: -- let res = matching (getRetTy ty') goalty in -- traceWhen (not res) -- ("Rejecting " ++ show (getRetTy ty', goalty)) res _ -> False -- If the goal is a constructor, it must match the suggested function type matching (P _ ctyn _) (P _ n' _) | isTConName n' ctxt = ctyn == n' | otherwise = True -- Variables match anything matching (V _) _ = True matching _ (V _) = True matching _ (P _ n _) = not (isTConName n ctxt) matching (P _ n _) _ = not (isTConName n ctxt) -- Binders are a plausible match, so keep them matching (Bind n _ sc) _ = True matching _ (Bind n _ sc) = True -- If we hit a function name, it's a plausible match matching (App _ (P _ f _) _) _ | not (isConName f ctxt) = True matching _ (App _ (P _ f _) _) | not (isConName f ctxt) = True -- Otherwise, match the rest of the structure matching (App _ f a) (App _ f' a') = matching f f' && matching a a' matching (TType _) (TType _) = True matching (UType _) (UType _) = True matching l r = l == r -- Return whether there is a possible coercion between the return type -- of an alternative and the goal type isCoercion rty gty | (P _ r _, _) <- unApply rty = not (null (getCoercionsBetween r gty)) isCoercion _ _ = False getCoercionsBetween :: Name -> Type -> [Name] getCoercionsBetween r goal = let cs = getCoercionsTo ist goal in findCoercions r cs where findCoercions t [] = [] findCoercions t (n : ns) = let ps = case lookupTy n (tt_ctxt ist) of [ty'] -> let as = map snd (getArgTys (normalise (tt_ctxt ist) [] ty')) in [n | any useR as] _ -> [] in ps ++ findCoercions t ns useR ty = case unApply (getRetTy ty) of (P _ t _, _) -> t == r _ -> False pruneByType _ t _ _ as = as -- Could the name feasibly be the return type? -- If there is a type class constraint on the return type, and no instance -- in the environment or globally for that name, then no -- Otherwise, yes -- (FIXME: This isn't complete, but I'm leaving it here and coming back -- to it later - just returns 'var' for now. EB) isPlausible :: IState -> Bool -> Env -> Name -> Type -> Bool isPlausible ist var env n ty = let (hvar, classes) = collectConstraints [] [] ty in case hvar of Nothing -> True Just rth -> var -- trace (show (rth, classes)) var where collectConstraints :: [Name] -> [(Term, [Name])] -> Type -> (Maybe Name, [(Term, [Name])]) collectConstraints env tcs (Bind n (Pi _ ty _) sc) = let tcs' = case unApply ty of (P _ c _, _) -> case lookupCtxtExact c (idris_classes ist) of Just tc -> ((ty, map fst (class_instances tc)) : tcs) Nothing -> tcs _ -> tcs in collectConstraints (n : env) tcs' sc collectConstraints env tcs t | (V i, _) <- unApply t = (Just (env !! i), tcs) | otherwise = (Nothing, tcs) -- | Use the local elab context to work out the highlighting for a name findHighlight :: Name -> ElabD OutputAnnotation findHighlight n = do ctxt <- get_context env <- get_env case lookup n env of Just _ -> return $ AnnBoundName n False Nothing -> case lookupTyExact n ctxt of Just _ -> return $ AnnName n Nothing Nothing Nothing Nothing -> lift . tfail . InternalMsg $ "Can't find name " ++ show n -- Try again to solve auto implicits solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD () solveAuto ist fn ambigok (n, failc) = do hs <- get_holes when (not (null hs)) $ do env <- get_env g <- goal handleError cantsolve (when (n `elem` hs) $ do focus n isg <- is_guess -- if it's a guess, we're working on it recursively, so stop when (not isg) $ proofSearch' ist True ambigok 100 True Nothing fn [] []) (lift $ Error (addLoc failc (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env)))) return () where addLoc (FailContext fc f x : prev) err = At fc (ElaboratingArg f x (map (\(FailContext _ f' x') -> (f', x')) prev) err) addLoc _ err = err cantsolve (CantSolveGoal _ _) = True cantsolve (InternalMsg _) = True cantsolve (At _ e) = cantsolve e cantsolve (Elaborating _ _ _ e) = cantsolve e cantsolve (ElaboratingArg _ _ _ e) = cantsolve e cantsolve _ = False solveAutos :: IState -> Name -> Bool -> ElabD () solveAutos ist fn ambigok = do autos <- get_autos mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos) -- Return true if the given error suggests a type class failure is -- recoverable tcRecoverable :: ElabMode -> Err -> Bool tcRecoverable ERHS (CantResolve f g _) = f tcRecoverable ETyDecl (CantResolve f g _) = f tcRecoverable e (ElaboratingArg _ _ _ err) = tcRecoverable e err tcRecoverable e (At _ err) = tcRecoverable e err tcRecoverable _ _ = True trivial' ist = trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist trivialHoles' psn h ist = trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist proofSearch' ist rec ambigok depth prv top n psns hints = do unifyProblems proofSearch rec prv ambigok (not prv) depth (elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist resolveTC' di mv depth tm n ist = resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist collectDeferred :: Maybe Name -> [Name] -> Context -> Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term collectDeferred top casenames ctxt tm = cd [] tm where cd env (Bind n (GHole i psns t) app) = do ds <- get t' <- collectDeferred top casenames ctxt t when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, t', psns))]) cd env app cd env (Bind n b t) = do b' <- cdb b t' <- cd ((n, b) : env) t return (Bind n b' t') where cdb (Let t v) = liftM2 Let (cd env t) (cd env v) cdb (Guess t v) = liftM2 Guess (cd env t) (cd env v) cdb b = do ty' <- cd env (binderTy b) return (b { binderTy = ty' }) cd env (App s f a) = liftM2 (App s) (cd env f) (cd env a) cd env t = return t case_ :: Bool -> Bool -> IState -> Name -> PTerm -> ElabD () case_ ind autoSolve ist fn tm = do attack tyn <- getNameFrom (sMN 0 "ity") claim tyn RType valn <- getNameFrom (sMN 0 "ival") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "irule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm env <- get_env let (Just binding) = lookup letn env let val = binderVal binding if ind then induction (forget val) else casetac (forget val) when autoSolve solveAll -- | Compute the appropriate name for a top-level metavariable metavarName :: [String] -> Name -> Name metavarName _ n@(NS _ _) = n metavarName (ns@(_:_)) n = sNS n ns metavarName _ n = n runElabAction :: ElabInfo -> IState -> FC -> Env -> Term -> [String] -> ElabD Term runElabAction info ist fc env tm ns = do tm' <- eval tm runTacTm tm' where eval tm = do ctxt <- get_context return $ normaliseAll ctxt env (finalise tm) returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased) patvars :: [(Name, Term)] -> Term -> ([(Name, Term)], Term) patvars ns (Bind n (PVar t) sc) = patvars ((n, t) : ns) (instantiate (P Bound n t) sc) patvars ns tm = (ns, tm) pullVars :: (Term, Term) -> ([(Name, Term)], Term, Term) pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs requireError :: Err -> ElabD a -> ElabD () requireError orErr elab = do state <- get case runStateT elab state of OK (_, state') -> lift (tfail orErr) Error e -> return () -- create a fake TT term for the LHS of an impossible case fakeTT :: Raw -> Term fakeTT (Var n) = case lookupNameDef n (tt_ctxt ist) of [(n', TyDecl nt _)] -> P nt n' Erased _ -> P Ref n Erased fakeTT (RBind n b body) = Bind n (fmap fakeTT b) (fakeTT body) fakeTT (RApp f a) = App Complete (fakeTT f) (fakeTT a) fakeTT RType = TType (UVar [] (-1)) fakeTT (RUType u) = UType u fakeTT (RConstant c) = Constant c defineFunction :: RFunDefn Raw -> ElabD () defineFunction (RDefineFun n clauses) = do ctxt <- get_context ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt let info = CaseInfo True True False -- TODO document and figure out clauses' <- forM clauses (\case RMkFunClause lhs rhs -> do (lhs', lty) <- lift $ check ctxt [] lhs (rhs', rty) <- lift $ check ctxt [] rhs lift $ converts ctxt [] lty rty return $ Right (lhs', rhs') RMkImpossibleClause lhs -> do requireError (Msg "Not an impossible case") . lift $ check ctxt [] lhs return $ Left (fakeTT lhs)) let clauses'' = map (\case Right c -> pullVars c Left lhs -> let (ns, lhs') = patvars [] lhs in (ns, lhs', Impossible)) clauses' let clauses''' = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) clauses'' ctxt'<- lift $ addCasedef n (const []) info False (STerm Erased) True False -- TODO what are these? (map snd $ getArgTys ty) [] -- TODO inaccessible types clauses' clauses''' clauses''' clauses''' clauses''' ty ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e} return () checkClosed :: Raw -> Elab' aux (Term, Type) checkClosed tm = do ctxt <- get_context (val, ty) <- lift $ check ctxt [] tm return $! (finalise val, finalise ty) -- | Add another argument to a Pi mkPi :: RFunArg -> Raw -> Raw mkPi arg rTy = RBind (argName arg) (Pi Nothing (argTy arg) (RUType AllTypes)) rTy mustBeType ctxt tm ty = case normaliseAll ctxt [] (finalise ty) of UType _ -> return () TType _ -> return () ty' -> lift . tfail . InternalMsg $ show tm ++ " is not a type: it's " ++ show ty' mustNotBeDefined ctxt n = case lookupDefExact n ctxt of Just _ -> lift . tfail . InternalMsg $ show n ++ " is already defined." Nothing -> return () -- | Prepare a constructor to be added to a datatype being defined here prepareConstructor :: Name -> RConstructorDefn -> ElabD (Name, [PArg], Type) prepareConstructor tyn (RConstructor cn args resTy) = do ctxt <- get_context -- ensure the constructor name is not qualified, and -- construct a qualified one notQualified cn let qcn = qualify cn -- ensure that the constructor name is not defined already mustNotBeDefined ctxt qcn -- construct the actual type for the constructor let cty = foldr mkPi resTy args (checkedTy, ctyTy) <- lift $ check ctxt [] cty mustBeType ctxt checkedTy ctyTy -- ensure that the constructor builds the right family case unApply (getRetTy (normaliseAll ctxt [] (finalise checkedTy))) of (P _ n _, _) | n == tyn -> return () t -> lift . tfail . Msg $ "The constructor " ++ show cn ++ " doesn't construct " ++ show tyn ++ " (return type is " ++ show t ++ ")" -- add temporary type declaration for constructor (so it can -- occur in later constructor types) set_context (addTyDecl qcn (DCon 0 0 False) checkedTy ctxt) -- Save the implicits for high-level Idris let impls = map rFunArgToPArg args return (qcn, impls, checkedTy) where notQualified (NS _ _) = lift . tfail . Msg $ "Constructor names may not be qualified" notQualified _ = return () qualify n = case tyn of (NS _ ns) -> NS n ns _ -> n getRetTy :: Type -> Type getRetTy (Bind _ (Pi _ _ _) sc) = getRetTy sc getRetTy ty = ty -- | Do a step in the reflected elaborator monad. The input is the -- step, the output is the (reflected) term returned. runTacTm :: Term -> ElabD Term runTacTm (unApply -> tac@(P _ n _, args)) | n == tacN "Prim__Solve", [] <- args = do solve returnUnit | n == tacN "Prim__Goal", [] <- args = do hs <- get_holes case hs of (h : _) -> do t <- goal fmap fst . checkClosed $ rawPair (Var (reflm "TTName"), Var (reflm "TT")) (reflectName h, reflect t) [] -> lift . tfail . Msg $ "Elaboration is complete. There are no goals." | n == tacN "Prim__Holes", [] <- args = do hs <- get_holes fmap fst . checkClosed $ mkList (Var $ reflm "TTName") (map reflectName hs) | n == tacN "Prim__Guess", [] <- args = do g <- get_guess fmap fst . checkClosed $ reflect g | n == tacN "Prim__LookupTy", [n] <- args = do n' <- reifyTTName n ctxt <- get_context let getNameTypeAndType = \case Function ty _ -> (Ref, ty) TyDecl nt ty -> (nt, ty) Operator ty _ _ -> (Ref, ty) CaseOp _ ty _ _ _ _ -> (Ref, ty) -- Idris tuples nest to the right reflectTriple (x, y, z) = raw_apply (Var pairCon) [ Var (reflm "TTName") , raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")] , x , raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT") , y, z]] let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty) | (n, def) <- lookupNameDef n' ctxt , let (nt, ty) = getNameTypeAndType def ] fmap fst . checkClosed $ rawList (raw_apply (Var pairTy) [ Var (reflm "TTName") , raw_apply (Var pairTy) [ Var (reflm "NameType") , Var (reflm "TT")]]) defs | n == tacN "Prim__LookupDatatype", [name] <- args = do n' <- reifyTTName name datatypes <- get_datatypes ctxt <- get_context fmap fst . checkClosed $ rawList (Var (tacN "Datatype")) (map reflectDatatype (buildDatatypes ist n')) | n == tacN "Prim__LookupFunDefn", [name] <- args = do n' <- reifyTTName name fmap fst . checkClosed $ rawList (RApp (Var $ tacN "FunDefn") (Var $ reflm "TT")) (map reflectFunDefn (buildFunDefns ist n')) | n == tacN "Prim__LookupArgs", [name] <- args = do n' <- reifyTTName name let listTy = Var (sNS (sUN "List") ["List", "Prelude"]) listFunArg = RApp listTy (Var (tacN "FunArg")) -- Idris tuples nest to the right let reflectTriple (x, y, z) = raw_apply (Var pairCon) [ Var (reflm "TTName") , raw_apply (Var pairTy) [listFunArg, Var (reflm "Raw")] , x , raw_apply (Var pairCon) [listFunArg, Var (reflm "Raw") , y, z]] let out = [ reflectTriple (reflectName fn, reflectList (Var (tacN "FunArg")) (map reflectArg args), reflectRaw res) | (fn, pargs) <- lookupCtxtName n' (idris_implicits ist) , (args, res) <- getArgs pargs . forget <$> maybeToList (lookupTyExact fn (tt_ctxt ist)) ] fmap fst . checkClosed $ rawList (raw_apply (Var pairTy) [Var (reflm "TTName") , raw_apply (Var pairTy) [ RApp listTy (Var (tacN "FunArg")) , Var (reflm "Raw")]]) out | n == tacN "Prim__SourceLocation", [] <- args = fmap fst . checkClosed $ reflectFC fc | n == tacN "Prim__Namespace", [] <- args = fmap fst . checkClosed $ rawList (RConstant StrType) (map (RConstant . Str) ns) | n == tacN "Prim__Env", [] <- args = do env <- get_env fmap fst . checkClosed $ reflectEnv env | n == tacN "Prim__Fail", [_a, errs] <- args = do errs' <- eval errs parts <- reifyReportParts errs' lift . tfail $ ReflectionError [parts] (Msg "") | n == tacN "Prim__PureElab", [_a, tm] <- args = return tm | n == tacN "Prim__BindElab", [_a, _b, first, andThen] <- args = do first' <- eval first res <- eval =<< runTacTm first' next <- eval (App Complete andThen res) runTacTm next | n == tacN "Prim__Try", [_a, first, alt] <- args = do first' <- eval first alt' <- eval alt try' (runTacTm first') (runTacTm alt') True | n == tacN "Prim__Fill", [raw] <- args = do raw' <- reifyRaw =<< eval raw apply raw' [] returnUnit | n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply" , [raw, argSpec] <- args = do raw' <- reifyRaw =<< eval raw argSpec' <- map (\b -> (b, 0)) <$> reifyList reifyBool argSpec let op = if n == tacN "Prim__Apply" then apply else match_apply ns <- op raw' argSpec' fmap fst . checkClosed $ rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName")) [ rawPair (Var $ reflm "TTName", Var $ reflm "TTName") (reflectName n1, reflectName n2) | (n1, n2) <- ns ] | n == tacN "Prim__Gensym", [hint] <- args = do hintStr <- eval hint case hintStr of Constant (Str h) -> do n <- getNameFrom (sMN 0 h) fmap fst $ get_type_val (reflectName n) _ -> fail "no hint" | n == tacN "Prim__Claim", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty claim n' ty' returnUnit | n == tacN "Prim__Check", [env', raw] <- args = do env <- reifyEnv env' raw' <- reifyRaw =<< eval raw ctxt <- get_context (tm, ty) <- lift $ check ctxt env raw' fmap fst . checkClosed $ rawPair (Var (reflm "TT"), Var (reflm "TT")) (reflect tm, reflect ty) | n == tacN "Prim__Attack", [] <- args = do attack returnUnit | n == tacN "Prim__Rewrite", [rule] <- args = do r <- reifyRaw rule rewrite r returnUnit | n == tacN "Prim__Focus", [what] <- args = do n' <- reifyTTName what hs <- get_holes if elem n' hs then focus n' >> returnUnit else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole" | n == tacN "Prim__Unfocus", [what] <- args = do n' <- reifyTTName what movelast n' returnUnit | n == tacN "Prim__Intro", [mn] <- args = do n <- case fromTTMaybe mn of Nothing -> return Nothing Just name -> fmap Just $ reifyTTName name intro n returnUnit | n == tacN "Prim__Forall", [n, ty] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty forall n' Nothing ty' returnUnit | n == tacN "Prim__PatVar", [n] <- args = do n' <- reifyTTName n patvar' n' returnUnit | n == tacN "Prim__PatBind", [n] <- args = do n' <- reifyTTName n patbind n' returnUnit | n == tacN "Prim__LetBind", [n, ty, tm] <- args = do n' <- reifyTTName n ty' <- reifyRaw ty tm' <- reifyRaw tm letbind n' ty' tm' returnUnit | n == tacN "Prim__Compute", [] <- args = do compute ; returnUnit | n == tacN "Prim__Normalise", [env, tm] <- args = do env' <- reifyEnv env tm' <- reifyTT tm ctxt <- get_context let out = normaliseAll ctxt env' (finalise tm') fmap fst . checkClosed $ reflect out | n == tacN "Prim__Whnf", [tm] <- args = do tm' <- reifyTT tm ctxt <- get_context fmap fst . checkClosed . reflect $ whnf ctxt tm' | n == tacN "Prim__Converts", [env, tm1, tm2] <- args = do env' <- reifyEnv env tm1' <- reifyTT tm1 tm2' <- reifyTT tm2 ctxt <- get_context lift $ converts ctxt env' tm1' tm2' returnUnit | n == tacN "Prim__DeclareType", [decl] <- args = do (RDeclare n args res) <- reifyTyDecl decl ctxt <- get_context let rty = foldr mkPi res args (checked, ty') <- lift $ check ctxt [] rty mustBeType ctxt checked ty' mustNotBeDefined ctxt n let decl = TyDecl Ref checked ctxt' = addCtxtDef n decl ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) : new_tyDecls e } returnUnit | n == tacN "Prim__DefineFunction", [decl] <- args = do defn <- reifyFunDefn decl defineFunction defn returnUnit | n == tacN "Prim__DeclareDatatype", [decl] <- args = do RDeclare n args resTy <- reifyTyDecl decl ctxt <- get_context let tcTy = foldr mkPi resTy args (checked, ty') <- lift $ check ctxt [] tcTy mustBeType ctxt checked ty' mustNotBeDefined ctxt n let ctxt' = addTyDecl n (TCon 0 0) checked ctxt set_context ctxt' updateAux $ \e -> e { new_tyDecls = RDatatypeDeclInstrs n (map rFunArgToPArg args) : new_tyDecls e } returnUnit | n == tacN "Prim__DefineDatatype", [defn] <- args = do RDefineDatatype n ctors <- reifyRDataDefn defn ctxt <- get_context tyconTy <- case lookupTyExact n ctxt of Just t -> return t Nothing -> lift . tfail . Msg $ "Type not previously declared" datatypes <- get_datatypes case lookupCtxtName n datatypes of [] -> return () _ -> lift . tfail . Msg $ show n ++ " is already defined as a datatype." -- Prepare the constructors ctors' <- mapM (prepareConstructor n) ctors ttag <- do ES (ps, aux) str prev <- get let i = global_nextname ps put $ ES (ps { global_nextname = global_nextname ps + 1 }, aux) str prev return i let ctxt' = addDatatype (Data n ttag tyconTy False (map (\(cn, _, cty) -> (cn, cty)) ctors')) ctxt set_context ctxt' -- the rest happens in a bit updateAux $ \e -> e { new_tyDecls = RDatatypeDefnInstrs n tyconTy ctors' : new_tyDecls e } returnUnit | n == tacN "Prim__AddInstance", [cls, inst] <- args = do className <- reifyTTName cls instName <- reifyTTName inst updateAux $ \e -> e { new_tyDecls = RAddInstance className instName : new_tyDecls e } returnUnit | n == tacN "Prim__IsTCName", [n] <- args = do n' <- reifyTTName n case lookupCtxtExact n' (idris_classes ist) of Just _ -> fmap fst . checkClosed $ Var (sNS (sUN "True") ["Bool", "Prelude"]) Nothing -> fmap fst . checkClosed $ Var (sNS (sUN "False") ["Bool", "Prelude"]) | n == tacN "Prim__ResolveTC", [fn] <- args = do g <- goal fn <- reifyTTName fn resolveTC' False True 100 g fn ist returnUnit | n == tacN "Prim__Search", [depth, hints] <- args = do d <- eval depth hints' <- eval hints case (d, unList hints') of (Constant (I i), Just hs) -> do actualHints <- mapM reifyTTName hs unifyProblems let psElab = elab ist toplevel ERHS [] (sMN 0 "tac") proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist returnUnit (Constant (I _), Nothing ) -> lift . tfail . InternalMsg $ "Not a list: " ++ show hints' (_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d | n == tacN "Prim__RecursiveElab", [goal, script] <- args = do goal' <- reifyRaw goal ctxt <- get_context script <- eval script (goalTT, goalTy) <- lift $ check ctxt [] goal' lift $ isType ctxt [] goalTy recH <- getNameFrom (sMN 0 "recElabHole") aux <- getAux datatypes <- get_datatypes env <- get_env g_next <- get_global_nextname (ctxt', ES (p, aux') _ _) <- do (ES (current_p, _) _ _) <- get lift $ runElab aux (do runElabAction info ist fc [] script ns ctxt' <- get_context return ctxt') ((newProof recH (constraintNS info) ctxt datatypes g_next goalTT) { nextname = nextname current_p }) set_context ctxt' let tm_out = getProofTerm (pterm p) do (ES (prf, _) s e) <- get let p' = prf { nextname = nextname p , global_nextname = global_nextname p } put (ES (p', aux') s e) env' <- get_env (tm, ty, _) <- lift $ recheck (constraintNS info) ctxt' env (forget tm_out) tm_out let (tm', ty') = (reflect tm, reflect ty) fmap fst . checkClosed $ rawPair (Var $ reflm "TT", Var $ reflm "TT") (tm', ty') | n == tacN "Prim__Metavar", [n] <- args = do n' <- reifyTTName n ctxt <- get_context ptm <- get_term -- See documentation above in the elab case for PMetavar let unique_used = getUniqueUsed ctxt ptm let mvn = metavarName ns n' attack defer unique_used mvn solve returnUnit | n == tacN "Prim__Fixity", [op'] <- args = do opTm <- eval op' case opTm of Constant (Str op) -> let opChars = ":!#$%&*+./<=>?@\\^|-~" invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"] fixities = idris_infixes ist in if not (all (flip elem opChars) op) || elem op invalidOperators then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name." else case nub [f | Fix f someOp <- fixities, someOp == op] of [] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'." [f] -> fmap fst . checkClosed $ reflectFixity f many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many _ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm | n == tacN "Prim__Debug", [ty, msg] <- args = do msg' <- eval msg parts <- reifyReportParts msg debugElaborator parts runTacTm x = lift . tfail $ ElabScriptStuck x -- Running tactics directly -- if a tactic adds unification problems, return an error runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD () runTac autoSolve ist perhapsFC fn tac = do env <- get_env g <- goal let tac' = fmap (addImplBound ist (map fst env)) tac if autoSolve then runT tac' else no_errors (runT tac') (Just (CantSolveGoal g (map (\(n, b) -> (n, binderTy b)) env))) where runT (Intro []) = do g <- goal attack; intro (bname g) where bname (Bind n _ _) = Just n bname _ = Nothing runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs runT Intros = do g <- goal attack; intro (bname g) try' (runT Intros) (return ()) True where bname (Bind n _ _) = Just n bname _ = Nothing runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (MatchRefine fn) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns) let tacs = map (\ (fn', imps) -> (match_apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn []) = do fnimps <- case lookupCtxtName fn (idris_implicits ist) of [] -> do a <- envArgs fn return [(fn, a)] ns -> return (map (\ (n, a) -> (n, map isImp a)) ns) let tacs = map (\ (fn', imps) -> (apply (Var fn') (map (\x -> (x, 0)) imps), fn')) fnimps tryAll tacs when autoSolve solveAll where isImp (PImp _ _ _ _ _) = True isImp _ = False envArgs n = do e <- get_env case lookup n e of Just t -> return $ map (const False) (getArgTys (binderTy t)) _ -> return [] runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps) when autoSolve solveAll runT DoUnify = do unify_all when autoSolve solveAll runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal") claim tmHole RType claim n (Var tmHole) focus tmHole elab ist toplevel ERHS [] (sMN 0 "tac") tm focus n runT (Equiv tm) -- let bind tm, then = do attack tyn <- getNameFrom (sMN 0 "ety") claim tyn RType valn <- getNameFrom (sMN 0 "eqval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "equiv_val") letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") tm focus valn when autoSolve solveAll runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that = do attack; -- (h:_) <- get_holes tyn <- getNameFrom (sMN 0 "rty") -- start_unify h claim tyn RType valn <- getNameFrom (sMN 0 "rval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "rewrite_rule") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm rewrite (Var letn) when autoSolve solveAll runT (Induction tm) -- let bind tm, similar to the others = case_ True autoSolve ist fn tm runT (CaseTac tm) = case_ False autoSolve ist fn tm runT (LetTac n tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT (LetTacTy n ty tm) = do attack tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- unique_hole n letbind letn (Var tyn) (Var valn) focus tyn elab ist toplevel ERHS [] (sMN 0 "tac") ty focus valn elab ist toplevel ERHS [] (sMN 0 "tac") tm when autoSolve solveAll runT Compute = compute runT Trivial = do trivial' ist; when autoSolve solveAll runT TCInstance = runT (Exact (PResolveTC emptyFC)) runT (ProofSearch rec prover depth top psns hints) = do proofSearch' ist rec False depth prover top fn psns hints when autoSolve solveAll runT (Focus n) = focus n runT Unfocus = do hs <- get_holes case hs of [] -> return () (h : _) -> movelast h runT Solve = solve runT (Try l r) = do try' (runT l) (runT r) True runT (TSeq l r) = do runT l; runT r runT (ApplyTactic tm) = do tenv <- get_env -- store the environment tgoal <- goal -- store the goal attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ... script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script elab ist toplevel ERHS [] (sMN 0 "tac") tm (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal and context restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (raw_apply (forget script') [reflectEnv tenv, reflect tgoal]) restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") listTy = Var (sNS (sUN "List") ["List", "Prelude"]) scriptTy = (RBind (sMN 0 "__pi_arg") (Pi Nothing (RApp listTy envTupleType) RType) (RBind (sMN 1 "__pi_arg") (Pi Nothing (Var $ reflm "TT") RType) tacticTy)) runT (ByReflection tm) -- run the reflection function 'tm' on the -- goal, then apply the resulting reflected Tactic = do tgoal <- goal attack script <- getNameFrom (sMN 0 "script") claim script scriptTy scriptvar <- getNameFrom (sMN 0 "scriptvar" ) letbind scriptvar scriptTy (Var script) focus script ptm <- get_term elab ist toplevel ERHS [] (sMN 0 "tac") (PApp emptyFC tm [pexp (delabTy' ist [] tgoal True True)]) (script', _) <- get_type_val (Var scriptvar) -- now that we have the script apply -- it to the reflected goal restac <- getNameFrom (sMN 0 "restac") claim restac tacticTy focus restac fill (forget script') restac' <- get_guess solve -- normalise the result in order to -- reify it ctxt <- get_context env <- get_env let tactic = normalise ctxt env restac' runReflected tactic where tacticTy = Var (reflm "Tactic") scriptTy = tacticTy runT (Reflect v) = do attack -- let x = reflect v in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = hnf ctxt env value runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value')) runT (Fill v) = do attack -- let x = fill x in ... tyn <- getNameFrom (sMN 0 "letty") claim tyn RType valn <- getNameFrom (sMN 0 "letval") claim valn (Var tyn) letn <- getNameFrom (sMN 0 "letvar") letbind letn (Var tyn) (Var valn) focus valn elab ist toplevel ERHS [] (sMN 0 "tac") v (value, _) <- get_type_val (Var letn) ctxt <- get_context env <- get_env let value' = normalise ctxt env value rawValue <- reifyRaw value' runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue) runT (GoalType n tac) = do g <- goal case unApply g of (P _ n' _, _) -> if nsroot n' == sUN n then runT tac else fail "Wrong goal type" _ -> fail "Wrong goal type" runT ProofState = do g <- goal return () runT Skip = return () runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "") runT SourceFC = case perhapsFC of Nothing -> lift . tfail $ Msg "There is no source location available." Just fc -> do fill $ reflectFC fc solve runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover" runT x = fail $ "Not implemented " ++ show x runReflected t = do t' <- reify ist t runTac autoSolve ist perhapsFC fn t' elaboratingArgErr :: [(Name, Name)] -> Err -> Err elaboratingArgErr [] err = err elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err) where rewrite (ElaboratingArg _ _ _ _) = Nothing rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e) rewrite (At fc e) = fmap (At fc) (rewrite e) rewrite err = Just (ElaboratingArg f x during err) withErrorReflection :: Idris a -> Idris a withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror) where handle :: Err -> Idris Err handle e@(ReflectionError _ _) = do logElab 3 "Skipping reflection of error reflection result" return e -- Don't do meta-reflection of errors handle e@(ReflectionFailed _ _) = do logElab 3 "Skipping reflection of reflection failure" return e -- At and Elaborating are just plumbing - error reflection shouldn't rewrite them handle e@(At fc err) = do logElab 3 "Reflecting body of At" err' <- handle err return (At fc err') handle e@(Elaborating what n ty err) = do logElab 3 "Reflecting body of Elaborating" err' <- handle err return (Elaborating what n ty err') handle e@(ElaboratingArg f a prev err) = do logElab 3 "Reflecting body of ElaboratingArg" hs <- getFnHandlers f a err' <- if null hs then handle err else applyHandlers err hs return (ElaboratingArg f a prev err') -- ProofSearchFail is an internal detail - so don't expose it handle (ProofSearchFail e) = handle e -- TODO: argument-specific error handlers go here for ElaboratingArg handle e = do ist <- getIState logElab 2 "Starting error reflection" logElab 5 (show e) let handlers = idris_errorhandlers ist applyHandlers e handlers getFnHandlers :: Name -> Name -> Idris [Name] getFnHandlers f arg = do ist <- getIState let funHandlers = maybe M.empty id . lookupCtxtExact f . idris_function_errorhandlers $ ist return . maybe [] S.toList . M.lookup arg $ funHandlers applyHandlers e handlers = do ist <- getIState let err = fmap (errReverse ist) e logElab 3 $ "Using reflection handlers " ++ concat (intersperse ", " (map show handlers)) let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers -- Typecheck error handlers - if this fails, then something else was wrong earlier! handlers <- case mapM (check (tt_ctxt ist) []) reports of Error e -> ierror $ ReflectionFailed "Type error while constructing reflected error" e OK hs -> return hs -- Normalize error handler terms to produce the new messages -- Need to use 'normaliseAll' since we have to reduce private -- names in error handlers too ctxt <- getContext let results = map (normaliseAll ctxt []) (map fst handlers) logElab 3 $ "New error message info: " ++ concat (intersperse " and " (map show results)) -- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results) errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of Left err -> ierror err Right ok -> return ok return $ case errorparts of [] -> e parts -> ReflectionError errorparts e solveAll = try (do solve; solveAll) (return ()) -- | Do the left-over work after creating declarations in reflected -- elaborator scripts processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris () processTacticDecls info steps = -- The order of steps is important: type declarations might -- establish metavars that later function bodies resolve. forM_ (reverse steps) $ \case RTyDeclInstrs n fc impls ty -> do logElab 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty logElab 3 $ " It has impls " ++ show impls updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) } addIBC (IBCImp n) ds <- checkDef info fc (\_ e -> e) True [(n, (-1, Nothing, ty, []))] addIBC (IBCDef n) ctxt <- getContext case lookupDef n ctxt of (TyDecl _ _ : _) -> -- If the function isn't defined at the end of the elab script, -- then it must be added as a metavariable. This needs guarding -- to prevent overwriting case defs with a metavar, if the case -- defs come after the type decl in the same script! let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True, True))) ds in addDeferred ds' _ -> return () RDatatypeDeclInstrs n impls -> do addIBC (IBCDef n) updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) } addIBC (IBCImp n) RDatatypeDefnInstrs tyn tyconTy ctors -> do let cn (n, _, _) = n cimpls (_, impls, _) = impls cty (_, _, t) = t addIBC (IBCDef tyn) mapM_ (addIBC . IBCDef . cn) ctors ctxt <- getContext let params = findParams tyn (normalise ctxt [] tyconTy) (map cty ctors) let typeInfo = TI (map cn ctors) False [] params [] -- implicit precondition to IBCData is that idris_datatypes on the IState is populated. -- otherwise writing the IBC just fails silently! updateIState $ \i -> i { idris_datatypes = addDef tyn typeInfo (idris_datatypes i) } addIBC (IBCData tyn) ttag <- getName -- from AbsSyntax.hs, really returns a disambiguating Int let metainf = DataMI params addIBC (IBCMetaInformation tyn metainf) updateContext (setMetaInformation tyn metainf) for_ ctors $ \(cn, impls, _) -> do updateIState $ \i -> i { idris_implicits = addDef cn impls (idris_implicits i) } addIBC (IBCImp cn) for_ ctors $ \(ctorN, _, _) -> do totcheck (NoFC, ctorN) ctxt <- tt_ctxt <$> getIState case lookupTyExact ctorN ctxt of Just cty -> do checkPositive (tyn : map cn ctors) (ctorN, cty) return () Nothing -> return () case ctors of [ctor] -> do setDetaggable (cn ctor); setDetaggable tyn addIBC (IBCOpt (cn ctor)); addIBC (IBCOpt tyn) _ -> return () -- TODO: inaccessible RAddInstance className instName -> do -- The type class resolution machinery relies on a special logElab 2 $ "Adding elab script instance " ++ show instName ++ " for " ++ show className addInstance False True className instName addIBC (IBCInstance False True className instName) RClausesInstrs n cs -> do logElab 3 $ "Pattern-matching definition from tactics: " ++ show n solveDeferred emptyFC n let lhss = map (\(_, lhs, _) -> lhs) cs let fc = fileFC "elab_reflected" pmissing <- do ist <- getIState possible <- genClauses fc n lhss (map (\lhs -> delab' ist lhs True True) lhss) missing <- filterM (checkPossible n) possible return (filter (noMatch ist lhss) missing) let tot = if null pmissing then Unchecked -- still need to check recursive calls else Partial NotCovering -- missing cases implies not total setTotality n tot updateIState $ \i -> i { idris_patdefs = addDef n (cs, pmissing) $ idris_patdefs i } addIBC (IBCDef n) ctxt <- getContext case lookupDefExact n ctxt of Just (CaseOp _ _ _ _ _ cd) -> -- Here, we populate the call graph with a list of things -- we refer to, so that if they aren't total, the whole -- thing won't be. let (scargs, sc) = cases_compiletime cd calls = map fst $ findCalls sc scargs in do logElab 2 $ "Called names in reflected elab: " ++ show calls addCalls n calls addIBC $ IBCCG n Just _ -> return () -- TODO throw internal error Nothing -> return () -- checkDeclTotality requires that the call graph be present -- before calling it. -- TODO: reduce code duplication with Idris.Elab.Clause buildSCG (fc, n) -- Actually run the totality checker. In the main clause -- elaborator, this is deferred until after. Here, we run it -- now to get totality information as early as possible. tot' <- checkDeclTotality (fc, n) setTotality n tot' when (tot' /= Unchecked) $ addIBC (IBCTotal n tot') where -- TODO: see if the code duplication with Idris.Elab.Clause can be -- reduced or eliminated. checkPossible :: Name -> PTerm -> Idris Bool checkPossible fname lhs_in = do ctxt <- getContext ist <- getIState let lhs = addImplPat ist lhs_in let fc = fileFC "elab_reflected_totality" let tcgen = False -- TODO: later we may support dictionary generation case elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "refPatLHS") infP initEState (erun fc (buildTC ist info ELHS [] fname (allNamesIn lhs_in) (infTerm lhs))) of OK (ElabResult lhs' _ _ _ _ _ name', _) -> do -- not recursively calling here, because we don't -- want to run infinitely many times let lhs_tm = orderPats (getInferTerm lhs') updateIState $ \i -> i { idris_name = name' } case recheck (constraintNS info) ctxt [] (forget lhs_tm) lhs_tm of OK _ -> return True err -> return False -- if it's a recoverable error, the case may become possible Error err -> if tcgen then return (recoverableCoverage ctxt err) else return (validCoverageCase ctxt err || recoverableCoverage ctxt err) -- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of Right _ -> False Left _ -> True) cs
tpsinnem/Idris-dev
src/Idris/Elab/Term.hs
bsd-3-clause
130,660
1,239
18
56,575
15,570
11,977
3,593
2,302
239
{-# LANGUAGE DeriveDataTypeable, DeriveFoldable, DeriveTraversable, DeriveFunctor #-} module Language.Haskell.AST.Exts.TransformListComp where import Data.Data import Data.Foldable (Foldable) import Data.Traversable (Traversable) import Language.Haskell.AST.Core hiding ( Exp ) -- | Extension of the @GExp@ type with extended list comprehensions data Exp stmt exp id l = EListComp l (exp id l) [QualStmt stmt exp id l] -- ^ an extended list comprehension deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor) -- | A general /transqual/ in a list comprehension, -- which could potentially be a transform of the kind -- enabled by TransformListComp. data QualStmt stmt exp id l = QualStmt l (stmt id l) -- ^ an ordinary statement | ThenTrans l (exp id l) -- ^ @then@ /exp/ | ThenBy l (exp id l) (exp id l) -- ^ @then@ /exp/ @by@ /exp/ | GroupBy l (exp id l) -- ^ @then@ @group@ @by@ /exp/ | GroupUsing l (exp id l) -- ^ @then@ @group@ @using@ /exp/ | GroupByUsing l (exp id l) (exp id l) -- ^ @then@ @group@ @by@ /exp/ @using@ /exp/ deriving (Eq,Ord,Show,Typeable,Data,Foldable,Traversable,Functor) instance Annotated (Exp stmt exp id) where ann (EListComp l _ _) = l instance Annotated (QualStmt stmt exp id) where ann (QualStmt l _) = l ann (ThenTrans l _) = l ann (ThenBy l _ _) = l ann (GroupBy l _) = l ann (GroupUsing l _) = l ann (GroupByUsing l _ _) = l
jcpetruzza/haskell-ast
src/Language/Haskell/AST/Exts/TransformListComp.hs
bsd-3-clause
1,543
0
8
398
438
241
197
26
0
module Tct.Jbc.Config ( parserIO , parser , runJbc , JbcConfig , jbcConfig ) where import qualified Control.Applicative as A (optional) import qualified Jinja.Program as J (ClassId (..), MethodId (..)) import qualified Tct.Core.Common.Pretty as PP import Tct.Core.Common.Options import Tct.Core.Data (deflFun) import Tct.Core.Main import Tct.Core import qualified Tct.Trs as R import qualified Tct.Its as I import Tct.Jbc.Data.Problem import Tct.Jbc.Strategies type JbcConfig = TctConfig Jbc runJbc :: Declared Jbc Jbc => JbcConfig -> IO () runJbc = runTctWithOptions jbcUpdate jbcOptions jbcConfig :: (Declared I.Its I.Its, Declared R.Trs R.Trs) => TctConfig Jbc jbcConfig = defaultTctConfig parserIO `withDefaultStrategy` deflFun jbcDeclaration parserIO :: FilePath -> IO (Either String Jbc) parserIO = fmap parser . readFile parser :: String -> Either String Jbc parser = Right . fromString newtype JbcOptions = JbcOptions (Maybe (String,String)) jbcOptions :: Options JbcOptions jbcOptions = JbcOptions <$> A.optional (option' readEntry (eopt `withArgLong` "entry" `withCropped` 'e' `withHelpDoc` PP.text "CLASS methodname")) where readEntry s = return (takeWhile (/= ' ') s, tail $ dropWhile (/= ' ') s) jbcUpdate :: JbcConfig -> JbcOptions -> JbcConfig jbcUpdate cfg (JbcOptions Nothing) = cfg jbcUpdate cfg (JbcOptions (Just (cn,mn))) = cfg { parseProblem = \fp -> fmap setEntry <$> parseProblem cfg fp } where setEntry jbc = jbc {entry = Just (J.ClassId cn, J.MethodId mn) }
ComputationWithBoundedResources/tct-jbc
src/Tct/Jbc/Config.hs
bsd-3-clause
1,665
0
12
391
514
293
221
-1
-1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE TypeSynonymInstances #-} ----------------------------------------------------------------------------- -- | -- Module : ParserUtils.hs -- Copyright : (c) 2010 David M. Rosenberg -- License : BSD3 -- -- Maintainer : David Rosenberg <rosenbergdm@uchicago.edu> -- Stability : experimental -- Portability : portable -- created : 06/14/10 -- -- Description : -- Utilities for parsing a stream of lexed tokens into an AST. ----------------------------------------------------------------------------- module Language.R.ParserUtils where import qualified Data.Map as Map import Language.R.Token import Language.R.SrcLocation import Data.List sl = Sloc "" 1 1 ss = mkSrcSpan sl sl data AssocDir = LR | RL deriving (Show, Read, Eq, Ord) type OpPrec = (Int, AssocDir) contains :: String -> String -> Bool contains st xs = any (\z -> st `isPrefixOf` z) (tails xs) {- {{{ Operator precedence table - {{{ From R Language Definition 0 :: 1 $ @ 2 ^ 3 - + (unary) 4 : 5 %xyz% 6 * / 7 + - (binary) 8 > >= < <= == != 9 ! 10 & && 11 | || 12 ~ (unary and binary) 13 -> ->> 14 = (as assignment) 15 <- <<- }}} -} class OpToken a where getOpPrecedence :: a -> OpPrec instance OpToken Token where getOpPrecedence a = case a of (ModulusToken _) -> (5, RL) (SlotOperator _) -> (1, RL) (PlusToken _) -> (3, LR) (NegateToken _) -> (3, LR) (AssignLeftToken _) -> (15, RL) (AssignRightToken _) -> (15, LR) (AssignLeftToken' _) -> (15, RL) (EqualsToken _) -> (14, LR) (SliceReplaceToken _) -> (15, LR) (MemberReplaceToken _) -> (15, LR) (MemberReplaceToken' _) -> (15, LR) (MinusToken _) -> (7, LR) (MultiplyToken _) -> (6, LR) (DivideToken _) -> (6, LR) (ExponentToken _) -> (2, RL) (LessToken _) -> (8, LR) (LessEqualToken _) -> (8, LR) (EqualityToken _) -> (8, LR) (InequalityToken _) -> (8, LR) (GreatEqualToken _) -> (8, LR) (GreatToken _) -> (8, LR) (ElementwiseOrToken _) -> (11, LR) (VectorOrToken _) -> (11, LR) (ElementwiseAndToken _) -> (10, LR) (VectorAndToken _) -> (10, LR) (SliceOperator _) -> (0, LR) (MemberOperator _) -> (0, LR) (MemberOperator' _) -> (0, LR) _ -> (-1, LR) -- }}} pop :: [a] -> a pop a = last a popped :: [a] -> [a] popped a = init a push :: [a] -> a -> [a] push xs x = concat [xs, [x]] runShunting :: [Token] -> [Token] runShunting ins = runShunting' (ins, [], []) runShunting' :: ([Token], [Token], [Token]) -> [Token] runShunting' ([], outs, []) = outs runShunting' (ins, outs, ops) = let (ins', outs', ops') = shuntStep ins outs ops in runShunting' (ins', outs', ops') shuntStep :: [Token] -> [Token] -> [Token] -> ([Token], [Token], [Token]) shuntStep [] outs ops = ( [], (concat [outs, [last ops]]), init ops) shuntStep (x:xs) outs ops = let (outs', ops') = case (classifyToken x) of Value -> shuntValue (x, outs, ops) Builtin -> shuntFunction (x, outs, ops) Identifier -> shuntIdentifier (x, outs, ops) Punctuation -> shuntPunct (x, outs, ops) Keyword -> shuntFunction (x, outs, ops) Operator -> shuntOp (x, outs, ops) Assignment -> shuntFunction (x, outs, ops) Replacement -> shuntFunction (x, outs, ops) String -> shuntValue (x, outs, ops) Comment -> (outs, ops) in (xs, outs', ops') shuntOp :: (Token, [Token], [Token]) -> ([Token], [Token]) shuntOp (z, out, []) = (concat [out, [z]], []) shuntOp (z, out, ops@(y:ys)) = if (snd op1, compare op1 op2) `elem` [(LR, LT), (LR, EQ), (RL, LT)] then (shuntOp (z, (concat [out, [y]]), ys)) else (concat [out, [z]], ys) where op1 = getOpPrecedence z op2 = getOpPrecedence y shuntPunct :: (Token, [Token], [Token]) -> ([Token], [Token]) shuntPunct (p, out, ops) = case p of -- □ If the token is a left parenthesis, then push it onto the stack. (ParenLeftToken _) -> (out, concat [ops, [p]]) -- □ If the token is a right parenthesis: -- ☆ Until the token at the top of the stack is a left parenthesis, pop -- operators off the stack onto the output queue. -- ☆ Pop the left parenthesis from the stack, but not onto the output -- queue. -- ☆ If the token at the top of the stack is a function token, pop it -- onto the output queue. -- ☆ If the stack runs out without finding a left parenthesis, then -- there are mismatched parentheses. (ParenRightToken _) -> let out1 = concat [out, takeWhile (\z -> tokenString z /= "(") (reverse ops)] ops1 = (reverse . (dropWhile (\z -> tokenString z /= "(")) . reverse) ops (out2, ops2) = case (isFunction $ last ops1) of True -> (concat [out1, [last ops1]], (init ops1)) False -> (out1, ops1) in (out2, ops2) -- □ If the token is a function argument separator (e.g., a comma): -- ☆ Until the token at the top of the stack is a left parenthesis, pop -- operators off the stack onto the output queue. If no left -- parentheses are encountered, either the separator was misplaced or -- parentheses were mismatched. (CommaToken _) -> let out1 = concat [out, takeWhile (\z -> tokenString z /= "(") (reverse ops)] ops1 = (reverse . (dropWhile (\z -> tokenString z /= "(")) . reverse) ops in (out1, ops1) otherwise -> (out, ops) isFunction :: Token -> Bool isFunction a = (classifyToken a) `elem` [Builtin, Replacement, Assignment] data IdentifierType = FunctionID | ValueID deriving (Read, Show, Eq, Ord) classifyIdentifier :: Token -> IdentifierType classifyIdentifier a = case (contains "()" $ tokenString a) of True -> FunctionID False -> ValueID shuntFunction :: (Token, [Token], [Token]) -> ([Token], [Token]) shuntFunction (z, out, ops) = (out, concat [ops, [z]]) shuntValue :: (Token, [Token], [Token]) -> ([Token], [Token]) shuntValue (z, out, ops) = (concat [out, [z]], ops) shuntIdentifier :: (Token, [Token], [Token]) -> ([Token], [Token]) shuntIdentifier (z, out, ops) = case z' of FunctionID -> shuntValue (z, out, ops) ValueID -> shuntFunction (z, out, ops) -- ************************************************************ -- TODO: What to do here -- ************************************************************ otherwise -> (out, ops) where z' = classifyIdentifier z {- {{{ Shunting yard pseudocode • While there are tokens to be read: □ Read a token. □ If the token is a number, then add it to the output queue. X If the token is a function token, then push it onto the stack. X If the token is a function argument separator (e.g., a comma): ☆ Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. If no left parentheses are encountered, either the separator was misplaced or parentheses were mismatched. X If the token is an operator, o[1], then: ☆ while there is an operator token, o[2], at the top of the stack, and either o[1] is left-associative and its precedence is less than or equal to that of o[2], or o[1] is right-associative and its precedence is less than that of o[2], pop o[2] off the stack, onto the output queue; ☆ push o[1] onto the stack. X If the token is a left parenthesis, then push it onto the stack. X If the token is a right parenthesis: ☆ Until the token at the top of the stack is a left parenthesis, pop operators off the stack onto the output queue. ☆ Pop the left parenthesis from the stack, but not onto the output queue. ☆ If the token at the top of the stack is a function token, pop it onto the output queue. ☆ If the stack runs out without finding a left parenthesis, then there are mismatched parentheses. • When there are no more tokens to read: □ While there are still operator tokens in the stack: ☆ If the operator token on the top of the stack is a parenthesis, then there are mismatched parentheses. ☆ Pop the operator onto the output queue. • Exit. }}} -} myvals :: [Token] myvals = [NumericToken ss "3.3" 3.3, PlusToken ss, NumericToken ss "5.1" 5.1, MultiplyToken ss, NumericToken ss "2.2" 2.2]
rosenbergdm/language-r
src/Language/R/ParserUtils.hs
bsd-3-clause
9,645
0
21
2,977
2,329
1,334
995
129
10
{-# LANGUAGE OverloadedStrings, TypeFamilies, TupleSections, FlexibleContexts, PackageImports #-} import Data.UUID import System.Random import Control.Applicative import Control.Monad import "monads-tf" Control.Monad.State import Control.Concurrent (forkIO) import Data.Maybe import Data.Pipe import Data.Pipe.List import Data.HandleLike import Text.XML.Pipe import Network import Network.PeyoTLS.Server import Network.PeyoTLS.ReadFile import "crypto-random" Crypto.Random import XmppServer import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BSC data SHandle s h = SHandle h instance HandleLike h => HandleLike (SHandle s h) where type HandleMonad (SHandle s h) = StateT s (HandleMonad h) type DebugLevel (SHandle s h) = DebugLevel h hlPut (SHandle h) = lift . hlPut h hlGet (SHandle h) = lift . hlGet h hlClose (SHandle h) = lift $ hlClose h hlDebug (SHandle h) = (lift .) . hlDebug h main :: IO () main = do ca <- readCertificateStore ["cacert.sample_pem"] k <- readKey "localhost.sample_key" c <- readCertificateChain ["localhost.sample_crt"] soc <- listenOn $ PortNumber 5222 g0 <- cprgCreate <$> createEntropyPool :: IO SystemRNG forever $ do (h, _, _) <- accept soc voidM . forkIO . (`evalStateT` g0) $ do uuids <- randoms <$> lift getStdGen g <- StateT $ return . cprgFork liftIO . hlPut h . xmlString $ begin ++ tlsFeatures voidM . liftIO . runPipe $ handleP h =$= xmlEvent =$= convert fromJust =$= (xmlBegin >>= xmlNodeUntil isStarttls) =$= checkP h =$= toList liftIO . hlPut h $ xmlString proceed liftIO . (`run` g) $ do p <- open h ["TLS_RSA_WITH_AES_128_CBC_SHA"] [(k, c)] (Just ca) uns <- getNames p let e = case uns of [n] -> Just . BSC.pack $ takeWhile (/= '@') n _ -> Nothing (`evalStateT` initXmppState uuids) $ xmpp (SHandle p) e xmpp :: (MonadState (HandleMonad h), StateType (HandleMonad h) ~ XmppState, HandleLike h) => h -> Maybe BS.ByteString -> HandleMonad h () xmpp h e = do voidM . runPipe $ input h =$= makeP e =$= output h hlPut h $ xmlString [XmlEnd (("stream", Nothing), "stream")] hlClose h makeP :: (MonadState m, StateType m ~ XmppState) => Maybe BS.ByteString -> Pipe Common Common m () makeP e = (,) `liftM` await `ap` lift (gets receiver) >>= \p -> case p of (Just (SRStream _), Nothing) -> do yield SRXmlDecl lift nextUuid >>= \u -> yield $ SRStream [ (Id, toASCIIBytes u), (From, "localhost"), (Version, "1.0"), (Lang, "en") ] lift nextUuid >>= digestMd5 e >>= \un -> lift . modify . setReceiver $ Jid un "localhost" Nothing makeP e (Just (SRStream _), _) -> do yield SRXmlDecl lift nextUuid >>= \u -> yield $ SRStream [ (Id, toASCIIBytes u), (From, "localhost"), (Version, "1.0"), (Lang, "en") ] yield $ SRFeatures [Rosterver Optional, Bind Required, Session Optional] makeP e (Just (SRIq Set i Nothing Nothing (IqBind (Just Required) (Resource n))), _) -> do lift $ modify (setResource n) Just j <- lift $ gets receiver yield . SRIq Result i Nothing Nothing . IqBind Nothing $ BJid j makeP e (Just (SRIq Set i Nothing Nothing IqSession), mrcv) -> yield (SRIq Result i Nothing mrcv IqSessionNull) >> makeP e (Just (SRIq Get i Nothing Nothing (IqRoster Nothing)), mrcv) -> do yield . SRIq Result i Nothing mrcv . IqRoster . Just $ Roster (Just "1") [] makeP e (Just (SRPresence _ _), Just rcv) -> yield (SRMessage Chat "hoge" (Just sender) rcv . MBody $ MessageBody "Hi, TLS!") >> makeP e _ -> return () voidM :: Monad m => m a -> m () voidM = (>> return ()) sender :: Jid sender = Jid "yoshio" "localhost" (Just "profanity") isStarttls :: XmlNode -> Bool isStarttls (XmlNode ((_, Just "urn:ietf:params:xml:ns:xmpp-tls"), "starttls") _ [] []) = True isStarttls _ = False begin :: [XmlNode] begin = [ XmlDecl (1, 0), XmlStart (("stream", Nothing), "stream") [ ("", "jabber:client"), ("stream", "http://etherx.jabber.org/streams") ] [ (nullQ "id", "83e074ac-c014-432e9f21-d06e73f5777e"), (nullQ "from", "localhost"), (nullQ "version", "1.0"), ((("xml", Nothing), "lang"), "en") ] ] tlsFeatures :: [XmlNode] tlsFeatures = [XmlNode (("stream", Nothing), "features") [] [] [mechanisms, starttls]] mechanisms :: XmlNode mechanisms = XmlNode (nullQ "mechanisms") [("", "urn:ietf:params:xml:ns:xmpp-sasl")] [] [ XmlNode (nullQ "mechanism") [] [] [XmlCharData "SCRAM-SHA-1"], XmlNode (nullQ "mechanism") [] [] [XmlCharData "DIGEST-MD5"] ] starttls :: XmlNode starttls = XmlNode (nullQ "starttls") [("", "urn:ietf:params:xml:ns:xmpp-tls")] [] [] proceed :: [XmlNode] proceed = (: []) $ XmlNode (nullQ "proceed") [("", "urn:ietf:params:xml:ns:xmpp-tls")] [] []
YoshikuniJujo/xmpipe
old/external/tlssv_pipe.hs
bsd-3-clause
4,729
62
24
909
2,077
1,046
1,031
131
7
module Main (main) where import Keepass ( KDBUnlocked(..), KDBLocked(..), loadKdb, decode ) import Format ( entryContains, isMetaEntry, displayEntry ) import Data.ByteString as BS ( readFile ) import Control.Applicative ( liftA2 ) import Control.Monad ( when, replicateM_, forM_ ) import Control.Exception ( bracket_ ) import System.Environment ( getArgs ) import System.IO ( stdout, stdin, hSetEcho, hFlush ) main :: IO () main = do args <- getArgs when (length args /= 1) $ fail "usage: hkeepass <filename>" contents <- BS.readFile $ head args let db = loadKdb contents case db of (Left msg) -> putStrLn ("loadKdb error: " ++ msg) (Right kdb) -> do putStrLn $ "read " ++ show (kdbLength kdb) ++ " bytes" unlockAndSearch kdb unlockAndSearch :: KDBLocked -> IO () unlockAndSearch kdb = do pw <- promptWith noEcho "password: " case decode kdb pw of (Left msg) -> putStrLn ("decode error: " ++ msg) >> unlockAndSearch kdb (Right kdb') -> putStrLn "\ndecoding successful" >> search kdb' search :: KDBUnlocked -> IO () search kdb = do searchTerm <- prompt "search> " showSearch searchTerm kdb done <- prompt "done? " case done of ('q':_) -> return () _ -> replicateM_ 50 (putStrLn "") >> search kdb showSearch :: String -> KDBUnlocked -> IO () showSearch searchTerm (KDBUnlocked groups entries) = do let matches = filter (liftA2 (&&) (not.isMetaEntry) (`entryContains` searchTerm)) entries forM_ matches (putStr . displayEntry groups) noEcho :: IO a -> IO a noEcho = bracket_ (hSetEcho stdin False) (hSetEcho stdin True) promptWith :: (IO String -> IO String) -> String -> IO String promptWith f str = putStr str >> hFlush stdout >> f getLine prompt :: String -> IO String prompt = promptWith id
bjornars/HKeePass
src/Main.hs
bsd-3-clause
1,946
0
16
532
673
339
334
50
2
{-# language DeriveGeneric, DeriveAnyClass #-} ---------------------------------------------------------------------- -- | -- Module : XMonad.Actions.GroupNavigation -- Description : Cycle through groups of windows across workspaces. -- Copyright : (c) nzeh@cs.dal.ca -- License : BSD3-style (see LICENSE) -- -- Maintainer : nzeh@cs.dal.ca -- Stability : unstable -- Portability : unportable -- -- Provides methods for cycling through groups of windows across -- workspaces, ignoring windows that do not belong to this group. A -- group consists of all windows matching a user-provided boolean -- query. -- -- Also provides a method for jumping back to the most recently used -- window in any given group, and predefined groups. -- ---------------------------------------------------------------------- module XMonad.Actions.GroupNavigation ( -- * Usage -- $usage Direction (..) , nextMatch , nextMatchOrDo , nextMatchWithThis , historyHook -- * Utilities -- $utilities , isOnAnyVisibleWS ) where import Control.Monad.Reader import Control.Monad.State import Control.DeepSeq import Data.Map ((!)) import qualified Data.Map as Map import Data.Sequence (Seq, ViewL (EmptyL, (:<)), viewl, (<|), (><), (|>)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import Graphics.X11.Types import GHC.Generics import Prelude hiding (concatMap, drop, elem, filter, null, reverse) import XMonad.Core import XMonad.ManageHook import XMonad.Operations (windows, withFocused) import XMonad.Prelude (elem, foldl') import qualified XMonad.StackSet as SS import qualified XMonad.Util.ExtensibleState as XS {- $usage Import the module into your @~\/.xmonad\/xmonad.hs@: > import XMonad.Actions.GroupNavigation To support cycling forward and backward through all xterm windows, add something like this to your keybindings: > , ((modm , xK_t), nextMatch Forward (className =? "XTerm")) > , ((modm .|. shiftMask, xK_t), nextMatch Backward (className =? "XTerm")) These key combinations do nothing if there is no xterm window open. If you rather want to open a new xterm window if there is no open xterm window, use 'nextMatchOrDo' instead: > , ((modm , xK_t), nextMatchOrDo Forward (className =? "XTerm") (spawn "xterm")) > , ((modm .|. shiftMask, xK_t), nextMatchOrDo Backward (className =? "XTerm") (spawn "xterm")) You can use 'nextMatchWithThis' with an arbitrary query to cycle through all windows for which this query returns the same value as the current window. For example, to cycle through all windows in the same window class as the current window use: > , ((modm , xK_f), nextMatchWithThis Forward className) > , ((modm , xK_b), nextMatchWithThis Backward className) Finally, you can define keybindings to jump to the most recent window matching a certain Boolean query. To do this, you need to add 'historyHook' to your logHook: > main = xmonad $ def { logHook = historyHook } Then the following keybindings, for example, allow you to return to the most recent xterm or emacs window or to simply to the most recent window: > , ((modm .|. controlMask, xK_e), nextMatch History (className =? "Emacs")) > , ((modm .|. controlMask, xK_t), nextMatch History (className =? "XTerm")) > , ((modm , xK_BackSpace), nextMatch History (return True)) Again, you can use 'nextMatchOrDo' instead of 'nextMatch' if you want to execute an action if no window matching the query exists. -} --- Basic cyclic navigation based on queries ------------------------- -- | The direction in which to look for the next match data Direction = Forward -- ^ Forward from current window or workspace | Backward -- ^ Backward from current window or workspace | History -- ^ Backward in history -- | Focuses the next window for which the given query produces the -- same result as the currently focused window. Does nothing if there -- is no focused window (i.e., the current workspace is empty). nextMatchWithThis :: Eq a => Direction -> Query a -> X () nextMatchWithThis dir qry = withFocused $ \win -> do prop <- runQuery qry win nextMatch dir (qry =? prop) -- | Focuses the next window that matches the given boolean query. -- Does nothing if there is no such window. This is the same as -- 'nextMatchOrDo' with alternate action @return ()@. nextMatch :: Direction -> Query Bool -> X () nextMatch dir qry = nextMatchOrDo dir qry (return ()) -- | Focuses the next window that matches the given boolean query. If -- there is no such window, perform the given action instead. nextMatchOrDo :: Direction -> Query Bool -> X () -> X () nextMatchOrDo dir qry act = orderedWindowList dir >>= focusNextMatchOrDo qry act -- Produces the action to perform depending on whether there's a -- matching window focusNextMatchOrDo :: Query Bool -> X () -> Seq Window -> X () focusNextMatchOrDo qry act = findM (runQuery qry) >=> maybe act (windows . SS.focusWindow) -- Returns the list of windows ordered by workspace as specified in -- ~/.xmonad/xmonad.hs orderedWindowList :: Direction -> X (Seq Window) orderedWindowList History = fmap (\(HistoryDB w ws) -> maybe ws (ws |>) w) XS.get orderedWindowList dir = withWindowSet $ \ss -> do wsids <- asks (Seq.fromList . workspaces . config) let wspcs = orderedWorkspaceList ss wsids wins = dirfun dir $ foldl' (><) Seq.empty $ fmap (Seq.fromList . SS.integrate' . SS.stack) wspcs cur = SS.peek ss return $ maybe wins (rotfun wins) cur where dirfun Backward = Seq.reverse dirfun _ = id rotfun wins x = rotate $ rotateTo (== x) wins -- Returns the ordered workspace list as specified in ~/.xmonad/xmonad.hs orderedWorkspaceList :: WindowSet -> Seq String -> Seq WindowSpace orderedWorkspaceList ss wsids = rotateTo isCurWS wspcs' where wspcs = SS.workspaces ss wspcsMap = foldl' (\m ws -> Map.insert (SS.tag ws) ws m) Map.empty wspcs wspcs' = fmap (wspcsMap !) wsids isCurWS ws = SS.tag ws == SS.tag (SS.workspace $ SS.current ss) --- History navigation, requires a layout modifier ------------------- -- The state extension that holds the history information data HistoryDB = HistoryDB (Maybe Window) -- currently focused window (Seq Window) -- previously focused windows deriving (Read, Show, Generic, NFData) instance ExtensionClass HistoryDB where initialValue = HistoryDB Nothing Seq.empty extensionType = PersistentExtension -- | Action that needs to be executed as a logHook to maintain the -- focus history of all windows as the WindowSet changes. historyHook :: X () historyHook = (XS.put $!) . force =<< updateHistory =<< XS.get -- Updates the history in response to a WindowSet change updateHistory :: HistoryDB -> X HistoryDB updateHistory (HistoryDB oldcur oldhist) = withWindowSet $ \ss -> let newcur = SS.peek ss wins = Set.fromList $ SS.allWindows ss newhist = Seq.filter (`Set.member` wins) (ins oldcur oldhist) in pure $ HistoryDB newcur (del newcur newhist) where ins x xs = maybe xs (<| xs) x del x xs = maybe xs (\x' -> Seq.filter (/= x') xs) x --- Some sequence helpers -------------------------------------------- -- Rotates the sequence by one position rotate :: Seq a -> Seq a rotate xs = rotate' (viewl xs) where rotate' EmptyL = Seq.empty rotate' (x' :< xs') = xs' |> x' -- Rotates the sequence until an element matching the given condition -- is at the beginning of the sequence. rotateTo :: (a -> Bool) -> Seq a -> Seq a rotateTo cond xs = let (lxs, rxs) = Seq.breakl cond xs in rxs >< lxs --- A monadic find --------------------------------------------------- -- Applies the given action to every sequence element in turn until -- the first element is found for which the action returns true. The -- remaining elements in the sequence are ignored. findM :: Monad m => (a -> m Bool) -> Seq a -> m (Maybe a) findM cond xs = findM' cond (viewl xs) where findM' _ EmptyL = return Nothing findM' qry (x' :< xs') = do isMatch <- qry x' if isMatch then return (Just x') else findM qry xs' -- $utilities -- #utilities# -- Below are handy queries for use with 'nextMatch', 'nextMatchOrDo', -- and 'nextMatchWithThis'. -- | A query that matches all windows on visible workspaces. This is -- useful for configurations with multiple screens, and matches even -- invisible windows. isOnAnyVisibleWS :: Query Bool isOnAnyVisibleWS = do w <- ask ws <- liftX $ gets windowset let allVisible = concat $ maybe [] SS.integrate . SS.stack . SS.workspace <$> SS.current ws:SS.visible ws visibleWs = w `elem` allVisible unfocused = Just w /= SS.peek ws return $ visibleWs && unfocused
xmonad/xmonad-contrib
XMonad/Actions/GroupNavigation.hs
bsd-3-clause
9,287
0
17
2,213
1,563
847
716
97
3
{-# LANGUAGE OverloadedStrings #-} {-| The Read type class is very useful for building data types from String representations. But String has high overhead, so sometimes it isn't suitable for applications where space usage and performance are important. This library provides a simpler version of Read's functionality for Text and ByteStrings. -} module Data.Readable ( Readable(..) ) where ------------------------------------------------------------------------------ import Control.Monad import Data.ByteString.Char8 (ByteString) import Data.Int import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding import Data.Text.Read import Data.Word ------------------------------------------------------------------------------ -- | ByteString and Text reading using MonadPlus to handle parse failure. On -- error, fromText and fromBS will return mzero. You can use mplus to provide -- fallback defaults. class Readable a where -- | Reads data from a Text representation. fromText :: MonadPlus m => Text -> m a -- | Reads data from a UTF8 encoded ByteString. The default -- implementation of this function simply decodes with UTF-8 and then -- calls the fromText function. If decoding fails, mzero will be -- returned. You can provide your own implementation if you need -- different behavior such as not decoding to UTF8. fromBS :: MonadPlus m => ByteString -> m a fromBS = fromText <=< hushPlus . decodeUtf8' hushPlus :: MonadPlus m => Either a b -> m b hushPlus (Left _) = mzero hushPlus (Right b) = return b ------------------------------------------------------------------------------ -- | Fails if the input wasn't parsed completely. checkComplete :: MonadPlus m => (t, Text) -> m t checkComplete (a,rest) | T.null rest = return a | otherwise = mzero -- Leaving out these instances breaks users who depend on having a unified -- constraint for parsing, so we need to keep them around. instance Readable ByteString where fromText = return . encodeUtf8 fromBS = return instance Readable Text where fromText = return instance Readable Int where fromText = either (const mzero) checkComplete . signed decimal instance Readable Integer where fromText = either (const mzero) checkComplete . signed decimal instance Readable Float where fromText = either (const mzero) checkComplete . rational instance Readable Double where fromText = either (const mzero) checkComplete . double instance Readable Bool where fromText t = case T.toLower t of "1" -> return True "0" -> return False "t" -> return True "f" -> return False "true" -> return True "false" -> return False "y" -> return True "n" -> return False "yes" -> return True "no" -> return False _ -> mzero instance Readable Int8 where fromText = either (const mzero) checkComplete . signed decimal instance Readable Int16 where fromText = either (const mzero) checkComplete . signed decimal instance Readable Int32 where fromText = either (const mzero) checkComplete . signed decimal instance Readable Int64 where fromText = either (const mzero) checkComplete . signed decimal instance Readable Word8 where fromText = either (const mzero) checkComplete . decimal instance Readable Word16 where fromText = either (const mzero) checkComplete . decimal instance Readable Word32 where fromText = either (const mzero) checkComplete . decimal instance Readable Word64 where fromText = either (const mzero) checkComplete . decimal
mightybyte/readable
src/Data/Readable.hs
bsd-3-clause
3,811
0
9
916
775
396
379
-1
-1
module HTIG.Database ( openDatabase , getTLLastStatusId , getMentionLastStatusId , addToTimeline , addToMention , getStatusFromId , Connection -- re-export , commit ) where import Control.Applicative ((<$>)) import Control.Monad (when) import Data.Maybe (isJust, fromJust) import Database.HDBC (run, runRaw, commit, quickQuery', fromSql, toSql) import Database.HDBC.Sqlite3 (Connection, connectSqlite3) import HTIG.TwitterAPI (Status(..), TwitterUser(..)) databaseSchema :: String databaseSchema = unlines -- TODO: CREATE INDEX [ "CREATE TABLE IF NOT EXISTS user (" , " id INTEGER NOT NULL PRIMARY KEY," , " name VARCHAR(255) NOT NULL," --, " screen_name VARCHAR(255) NOT NULL UNIQUE" , " screen_name VARCHAR(255) NOT NULL" , ");" , "CREATE TABLE IF NOT EXISTS status (" , " id INTEGER NOT NULL UNIQUE," , " created_at INTEGER NOT NULL," , " text VARCHAR(140) NOT NULL," , " source TEXT NOT NULL," , " truncated BOOL NOT NULL," , " in_reply_to_status_id INTEGER," , " in_reply_to_user_id INTEGER," , " favorited BOOL NOT NULL," , " in_reply_to_screen_name," , " user_id INTEGER NOT NULL," , " retweeted_status_id INTEGER REFERENCES status (id)" , ");" , "CREATE TABLE IF NOT EXISTS timeline (" , " status_id INTEGER NOT NULL UNIQUE REFERENCES status (id)" , ");" , "CREATE TABLE IF NOT EXISTS mention (" , " status_id INTEGER NOT NULL UNIQUE REFERENCES status (id)" , ");" ] openDatabase :: FilePath -> IO Connection openDatabase fpath = do conn <- connectSqlite3 fpath runRaw conn databaseSchema commit conn return conn getTLLastStatusId :: String -> Connection -> IO (Maybe Integer) getTLLastStatusId = getLastStatusId "timeline" getMentionLastStatusId :: String -> Connection -> IO (Maybe Integer) getMentionLastStatusId = getLastStatusId "mention" getLastStatusId :: String -> String -> Connection -> IO (Maybe Integer) getLastStatusId tbl sname conn = do result <- quickQuery' conn ("SELECT status_id FROM " ++ tbl ++ " \ \ ORDER BY status_id DESC LIMIT 1") [] case result of [val]:_ -> return $ Just $ fromSql val [] -> return Nothing x -> fail $ "unexpexted result: " ++ show x -- TODO: addToTimeline, addToMention をうまいことまとめる addToTimeline :: String -> Status -> Connection -> IO () addToTimeline sname st conn = do addStatusIfNotExists st conn run conn "INSERT INTO timeline (status_id) VALUES (?)" [toSql $ stId st] return () addToMention :: String -> Status -> Connection -> IO () addToMention sname st conn = do addStatusIfNotExists st conn run conn "INSERT INTO mention (status_id) VALUES (?)" [toSql $ stId st] return () addStatusIfNotExists :: Status -> Connection -> IO () addStatusIfNotExists st conn = do [val]:_ <- quickQuery' conn "SELECT COUNT(*) FROM user where id = ?" [toSql $ usId . stUser $ st] when ((fromSql val :: Int) == 0) $ do run conn "INSERT INTO user (id, name, screen_name) VALUES (?, ?, ?)" [ toSql $ usId . stUser $ st , toSql $ usName . stUser $ st , toSql $ usScreenName . stUser $ st ] return () when (isJust $ stRetweetedStatus st) $ addStatusIfNotExists (fromJust $ stRetweetedStatus st) conn [val']:_ <- quickQuery' conn "SELECT COUNT(*) FROM status WHERE id = ?" [toSql $ stId st] when ((fromSql val' :: Int) == 0) $ do run conn "INSERT INTO status (id, created_at, text, source, truncated, in_reply_to_status_id, \ \ in_reply_to_user_id, favorited, in_reply_to_screen_name, user_id, retweeted_status_id) \ \ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" [ toSql $ stId st , toSql $ stCreatedAt st , toSql $ stText st , toSql $ stSource st , toSql $ stTruncated st , toSql $ stInReplyToStatusId st , toSql $ stInReplyToUserId st , toSql $ stFavorited st , toSql $ stInReplyToScreenName st , toSql $ (usId . stUser) st , toSql $ stId <$> stRetweetedStatus st ] return () getStatusFromId :: Integer -> Connection -> IO (Maybe Status) getStatusFromId stid conn = do result <- quickQuery' conn "SELECT status.id, created_at, text, source, truncated, in_reply_to_status_id, in_reply_to_user_id, \ \ favorited, in_reply_to_screen_name, user.id, user.name, user.screen_name, retweeted_status_id \ \ FROM status LEFT JOIN user ON (status.user_id = user.id) \ \ WHERE status.id = ? LIMIT 1" [toSql stid] case result of [] -> return Nothing [vId, vCreatedAt, vText, vSource, vTruncated, vInReplyToStatusId, vInReplyToUserId, vFavorited, vInReplyToScreenName, vUserId, vUserName, vUserScreenName, vRetweetedStatusId]:_ -> do retweetedStatus <- case fromSql vRetweetedStatusId of Just rsid -> getStatusFromId rsid conn Nothing -> return Nothing return $ Just $ Status (fromSql vCreatedAt) (fromSql vId) (fromSql vText) (fromSql vSource) (fromSql vTruncated) (fromSql vInReplyToStatusId) (fromSql vInReplyToUserId) (fromSql vFavorited) (fromSql vInReplyToScreenName) (TwitterUser (fromSql vUserId) (fromSql vUserName) (fromSql vUserScreenName)) retweetedStatus x -> fail $ "unexpexted result: " ++ show x -- TODO: export these functions garbageCollect :: Connection -> IO () garbageCollect conn = do clearOldTimeline conn clearOldMentions conn clearUnreferencedStatuses conn clearOldTimeline :: Connection -> IO () clearOldTimeline conn = do c <- run conn "DELETE FROM timeline WHERE status_id <= (SELECT status_id FROM timeline ORDER BY status_id LIMIT 1 OFFSET 100)" [] print ("delete", c, "old timeline") -- debug print clearOldMentions :: Connection -> IO () clearOldMentions conn = do c <- run conn "DELETE FROM mention WHERE status_id <= (SELECT status_id FROM mention ORDER BY status_id LIMIT 1 OFFSET 100)" [] print ("delete", c, "old mentions") -- debug print clearUnreferencedStatuses :: Connection -> IO () clearUnreferencedStatuses conn = do c <- run conn "DELETE FROM status \ \ WHERE (SELECT COUNT(*) FROM timeline WHERE status_id = id) = 0 \ \ AND (SELECT COUNT(*) FROM mention WHERE status_id = id) = 0 \ \ AND (SELECT COUNT(*) FROM status as s WHERE s.retweeted_status_id = status.id) = 0" [] print ("delete", c, "unreferenced statuses") -- debug print
nakamuray/htig
HTIG/Database.hs
bsd-3-clause
7,306
0
17
2,290
1,466
748
718
137
4
module Homework6.Fibonacci where import Data.List --Exercise 1 fib :: Integer -> Integer fib 0 = 0 fib 1 = 1 fib n = fib(n-1) + fib(n-2) fibs1 :: [Integer] fibs1 = map fib [0..] --Exercise 2 fibonacci :: Integer -> Integer fibonacci n | n >= 0 = fst $ fib' n fib' :: Integer -> (Integer, Integer) fib' 0 = (0, 1) fib' n = let (a, b) = fib' (div n 2) c = a * (b * 2 - a) d = a * a + b * b in if mod n 2 == 0 then (c, d) else (d, c + d) fibs2 :: [Integer] fibs2 = map fibonacci [0..] --Exercise 3 data Stream a = Cons a (Stream a) instance Show a => Show (Stream a) where show st = let sh 0 (Cons x xs) = show x ++ "" sh n (Cons x xs) = show x ++ ", " ++ sh (n-1) xs in sh 30 st --Exercise 4 streamRepeat :: a -> Stream a streamRepeat n = Cons n $ streamRepeat n streamMap :: (a -> b) -> Stream a -> Stream b streamMap f (Cons x xs) = Cons (f x) (streamMap f xs) streamFromSeed :: (a -> a) -> a -> Stream a streamFromSeed f n = Cons (n) (streamFromSeed f (f n)) --Exercise 5 nats :: Stream Integer nats = streamFromSeed (\x -> x + 1) 0 {- THIS SAVED ME: https://mail.haskell.org/pipermail/beginners/2014-February/013160.html In this situation, if interleaveStreams evaluates its second argument before returning any work, it will never be able to return. Happily, the outer Cons of the result does not depend on the second argument. I can fix the issue just by making the second argument be pattern-matched lazily (with ~, i.e. only as soon as any uses of the argument in the function are evaluated): -} interleaveStreams :: Stream a -> Stream a -> Stream a interleaveStreams (Cons x xs) ~(Cons y ys) = Cons x (Cons y (interleaveStreams xs ys)) ruler :: Stream Integer ruler = foldr1 interleaveStreams $ map streamRepeat [0..]
gabluc/CIS194-Solutions
src/Homework6/Fibonacci.hs
bsd-3-clause
1,864
0
13
487
686
352
334
38
2
{-# LANGUAGE DeriveDataTypeable #-} -- | ABS extension to support write-once promises -- (used by the PA case study). module ABS.Runtime.Extension.Promise ( pro_new , pro_try , pro_give , PromiseRewriteException (..) ) where import ABS.Runtime.Base (Fut) import Control.Concurrent.MVar (newEmptyMVar, tryReadMVar, tryPutMVar) import ABS.Runtime.Extension.Exception import Data.Typeable -- exceptions must support Show and Typeable import Control.Monad (unless) import qualified Control.Exception (Exception (..)) {-# INLINE pro_new #-} -- | Newly-allocated promise with empty contents pro_new :: IO (Fut a) pro_new = newEmptyMVar {-# INLINE pro_try #-} -- | Try to extract the value inside the promise. -- -- Does not block. pro_try :: Fut b -> IO (Maybe b) pro_try = tryReadMVar {-# INLINE pro_give #-} -- | Writes (once) the value to the given promise, essentially resolving it. -- -- Will throw a 'PromiseRewriteException' when to write more than once. pro_give :: Fut b -> b -> IO () pro_give fut = (>>= (`unless` throw PromiseRewriteException)) . tryPutMVar fut -- | Trying to write to an already-resolved promise data PromiseRewriteException = PromiseRewriteException deriving (Show, Typeable) instance Control.Exception.Exception PromiseRewriteException where toException = absExceptionToException' fromException = absExceptionFromException'
abstools/habs-runtime
src/ABS/Runtime/Extension/Promise.hs
bsd-3-clause
1,373
0
8
206
239
146
93
25
1
{-# OPTIONS_GHC -fno-warn-orphans #-} -- | A re-export of the prettyprinting library, along with some convenience functions. module Futhark.Util.Pretty ( module Text.PrettyPrint.Mainland, module Text.PrettyPrint.Mainland.Class, pretty, prettyDoc, prettyTuple, prettyTupleLines, prettyText, prettyTextOneLine, prettyOneLine, apply, oneLine, annot, nestedBlock, textwrap, shorten, commastack, ) where import Data.Text (Text) import qualified Data.Text.Lazy as LT import Numeric.Half import Text.PrettyPrint.Mainland hiding (pretty) import qualified Text.PrettyPrint.Mainland as PP import Text.PrettyPrint.Mainland.Class -- | Prettyprint a value, wrapped to 80 characters. pretty :: Pretty a => a -> String pretty = PP.pretty 80 . ppr -- | Prettyprint a value to a 'Text', wrapped to 80 characters. prettyText :: Pretty a => a -> Text prettyText = LT.toStrict . PP.prettyLazyText 80 . ppr -- | Prettyprint a value to a 'Text' without any width restriction. prettyTextOneLine :: Pretty a => a -> Text prettyTextOneLine = LT.toStrict . PP.prettyLazyText 80 . oneLine . ppr -- | Prettyprint a value without any width restriction. prettyOneLine :: Pretty a => a -> String prettyOneLine = ($ "") . displayS . renderCompact . oneLine . ppr -- | Re-export of 'PP.pretty'. prettyDoc :: Int -> Doc -> String prettyDoc = PP.pretty ppTuple' :: Pretty a => [a] -> Doc ppTuple' ets = braces $ commasep $ map (align . ppr) ets -- | Prettyprint a list enclosed in curly braces. prettyTuple :: Pretty a => [a] -> String prettyTuple = PP.pretty 80 . ppTuple' -- | Like 'prettyTuple', but put a linebreak after every element. prettyTupleLines :: Pretty a => [a] -> String prettyTupleLines = PP.pretty 80 . ppTupleLines' where ppTupleLines' ets = braces $ stack $ punctuate comma $ map (align . ppr) ets -- | The document @'apply' ds@ separates @ds@ with commas and encloses them with -- parentheses. apply :: [Doc] -> Doc apply = parens . commasep . map align -- | Make sure that the given document is printed on just a single line. oneLine :: PP.Doc -> PP.Doc oneLine s = PP.text $ PP.displayS (PP.renderCompact s) "" -- | Like 'text', but splits the string into words and permits line breaks between all of them. textwrap :: String -> Doc textwrap = folddoc (<+/>) . map text . words -- | Stack and prepend a list of 'Doc's to another 'Doc', separated by -- a linebreak. If the list is empty, the second 'Doc' will be -- returned without a preceding linebreak. annot :: [Doc] -> Doc -> Doc annot [] s = s annot l s = stack l </> s -- | Surround the given document with enclosers and add linebreaks and -- indents. nestedBlock :: String -> String -> Doc -> Doc nestedBlock pre post body = text pre </> PP.indent 2 body </> text post -- | Prettyprint on a single line up to at most some appropriate -- number of characters, with trailing ... if necessary. Used for -- error messages. shorten :: Pretty a => a -> Doc shorten a | length s > 70 = text (take 70 s) <> text "..." | otherwise = text s where s = pretty a -- | Like 'commasep', but a newline after every comma. commastack :: [Doc] -> Doc commastack = align . stack . punctuate comma instance Pretty Half where ppr = text . show
HIPERFIT/futhark
src/Futhark/Util/Pretty.hs
isc
3,278
0
10
654
775
424
351
64
1
import Distribution.Simple(defaultMain) main :: IO () main = defaultMain
jokusi/Astview
Setup.hs
mit
74
0
7
10
31
15
16
3
1
{-# LANGUAGE LambdaCase #-} module Test.DocTest.Discover where import CabalLenses.PackageDescription import Control.Lens import Distribution.InstalledPackageInfo (PError) import Distribution.ModuleName import Distribution.PackageDescription import Distribution.PackageDescription.Parse (ParseResult (..), parsePackageDescription) import Data.List (intercalate,nub) loadPackageDescription :: FilePath -> IO (Either PError GenericPackageDescription) loadPackageDescription cabalFile = do projectDirectory <- return cabalFile --TODO discover cabalFile <- readFile projectDirectory return$ case parsePackageDescription cabalFile of ParseFailed e -> Left e ParseOk _ pkg -> Right pkg -- | when `hs-source-dirs` is not singleton, includes nonexistent files. -- Removes duplicates, as stripping ".hs" extension often collides into a directory. modulePaths :: GenericPackageDescription -> [FilePath] modulePaths pkg = do d <- pkg^..packageHsSourcesDirs m <- pkg^..packageExposedModules return$ (intercalate "/" . nub) (d : components m) -- e.g. ("sources/sources" : ["Commands","Core"]) -- packageLibrary :: Traversal' GenericPackageDescription Library -- packageLibrary = packageDescriptionL.libraryL.each -- | ignores 'condTreeComponentsL' packageCondLibrary :: Traversal' GenericPackageDescription Library packageCondLibrary = condLibraryL.each.condTreeDataL packageExposedModules :: Traversal' GenericPackageDescription ModuleName packageExposedModules = packageCondLibrary.exposedModulesL.each packageHsSourcesDirs :: Traversal' GenericPackageDescription FilePath packageHsSourcesDirs = packageCondLibrary.libBuildInfoL.hsSourceDirsL.each
sboosali/commands-core
tests/Test/DocTest/Discover.hs
mit
1,735
0
11
252
295
156
139
28
2
{- | Module : ./CspCASL/LocalTop.hs Description : Local top element analysis for CspCASL specifications Copyright : (c) Andy Gimblett, Swansea University 2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : a.m.gimblett@swan.ac.uk Stability : provisional Portability : portable Analysis of relations for presence of local top elements. Used by CspCASL static analysis. -} module CspCASL.LocalTop ( checkLocalTops, cartesian ) where import CASL.AS_Basic_CASL (SORT) import qualified Common.Lib.Rel as Rel import Common.Result (Diagnosis (..), mkDiag, DiagKind (..)) import qualified Data.Set as S import Data.Maybe -- | A relation is a set of pairs. type Relation a b = S.Set (a, b) type BinaryRelation a = Relation a a {- | We're interested in triples where two elements are both in relation with some third object. We represent this as a Obligation, where the first element is the shared one. It's important to note that (Obligation x y z) == (Obligation x z y), which we encode here. For every obligation, we look for any corresponding top elements. -} data Obligation a = Obligation a a a instance Eq a => Eq (Obligation a) where (Obligation n m o) == (Obligation x y z) = (n == x) && ((m, o) == (y, z) || (m, o) == (z, y)) instance Ord a => Ord (Obligation a) where compare (Obligation n m o) (Obligation x y z) | Obligation n m o == Obligation x y z = EQ | otherwise = compare (n, m, o) (x, y, z) instance Show a => Show (Obligation a) where show (Obligation x y z) = show [x, y, z] {- | Turn a binary relation into a set mapping its obligation elements to their corresponding local top elements (if any). -} localTops :: Ord a => BinaryRelation a -> S.Set (Obligation a, S.Set a) localTops r = S.map (\ x -> (x, m x)) (obligations r) where m = findTops $ cartesian r {- | Find all the obligations in a binary relation, by searching its cartesian product for elements of the right form. -} obligations :: Ord a => BinaryRelation a -> S.Set (Obligation a) obligations r = stripMaybe $ S.map isObligation (cartesian r) where isObligation ((w, x), (y, z)) = if (w == y) && (x /= z) && (w /= z) && (w /= x) then Just (Obligation w x z) else Nothing {- | Given a binary relation's cartesian product and a obligation, look for corresponding top elements in that product. -} findTops :: Ord a => BinaryRelation (a, a) -> Obligation a -> S.Set a findTops c cand = S.map get_top (S.filter (is_top cand) c) where is_top (Obligation _ y z) ((m, n), (o, p)) = (m == y && o == z) && (n == p) get_top ((_, _), (_, p)) = p -- Utility functions. -- | Cartesian product of a set. cartesian :: Ord a => S.Set a -> S.Set (a, a) cartesian x = S.fromDistinctAscList [(i, j) | i <- xs, j <- xs] where xs = S.toAscList x -- fromDistinctAscList sorted precondition satisfied by construction -- | Given a set of Maybes, filter to keep only the Justs stripMaybe :: Ord a => S.Set (Maybe a) -> S.Set a stripMaybe x = S.fromList $ catMaybes $ S.toList x -- | Given a binary relation, compute its reflexive closure. reflexiveClosure :: Ord a => BinaryRelation a -> BinaryRelation a reflexiveClosure r = S.fold add_refl r r where add_refl (x, y) r' = (x, x) `S.insert` ((y, y) `S.insert` r') {- | Main function for CspCASL LTE checks: given a transitively-closed subsort relation as a list of pairs, return a list of unfulfilled LTE obligations. -} unmetObs :: Ord a => [(a, a)] -> [Obligation a] unmetObs r = unmets where l = S.toList $ localTops $ reflexiveClosure $ S.fromList r unmets = map fst $ filter (S.null . snd) l {- Wrapper functions follow that allow easy calling for various situations (static analysis and signature union). -} {- | Add diagnostic error message for every unmet local top element obligation. -} lteError :: Obligation SORT -> Diagnosis lteError (Obligation x y z) = mkDiag Error msg () where msg = "local top element obligation (" ++ show x ++ " < " ++ show y ++ ", " ++ show z ++ ") unfulfilled" {- | This is the main interface for the LTE check. Check a CspCASL signature (actually just the sort relation) for local top elements in its subsort relation. Returns empty list for sucess or a list of diags for failure where diags is a list of diagnostic errors resulting from the check. -} checkLocalTops :: Rel.Rel SORT -> [Diagnosis] checkLocalTops sr = let obs = unmetObs (Rel.toList (Rel.transClosure sr)) in map lteError obs
spechub/Hets
CspCASL/LocalTop.hs
gpl-2.0
4,565
0
14
1,014
1,241
661
580
54
2
{-# LANGUAGE CPP #-} {- | Module : $Header$ Description : Datatypes and functions for options that hets understands. Copyright : (c) Martin Kuehl, Christian Maeder, Uni Bremen 2002-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Datatypes for options that hets understands. Useful functions to parse and check user-provided values. -} module Driver.Options ( HetcatsOpts (..) , Flag , optionArgs , optionFlags , accessTokenS , makeOpts , AnaType (..) , GuiType (..) , InType (..) , OWLFormat (..) , plainOwlFormats , OutType (..) , PrettyType (..) , prettyList , GraphType (..) , SPFType (..) , ATType , Delta , hetcatsOpts , isStructured , guess , rmSuffix , envSuffix , prfSuffix , removePrfOut , hasEnvOut , hasPrfOut , getFileNames , existsAnSource , getExtensions , checkRecentEnv , downloadExtensions , defaultHetcatsOpts , hetsVersion , showDiags , showDiags1 , putIfVerbose , doDump , checkUri , defLogicIsDMU , useCatalogURL , hetsIOError ) where import Driver.Version import Common.Utils import Common.IO import Common.Id import Common.Result import Common.ResultT import Common.Amalgamate import Common.Keywords import System.Directory import System.Console.GetOpt import System.Exit import System.IO import Control.Monad import Control.Monad.Trans import Data.Char import Data.List import Data.Maybe -- | short version without date for ATC files hetsVersion :: String hetsVersion = takeWhile (/= ',') hetcats_version -- | translate a given http reference using the URL catalog useCatalogURL :: HetcatsOpts -> FilePath -> FilePath useCatalogURL opts fname = case mapMaybe (\ (a, b) -> fmap (b ++) $ stripPrefix a fname) $ urlCatalog opts of m : _ -> m _ -> fname bracket :: String -> String bracket s = "[" ++ s ++ "]" -- use the same strings for parsing and printing! verboseS, intypeS, outtypesS, skipS, justStructuredS, transS, guiS, libdirsS, outdirS, amalgS, recursiveS, namedSpecsS, interactiveS, modelSparQS, counterSparQS, connectS, xmlS, listenS, applyAutomaticRuleS, normalFormS, unlitS :: String modelSparQS = "modelSparQ" counterSparQS = "counterSparQ" verboseS = "verbose" intypeS = "input-type" outtypesS = "output-types" skipS = "just-parse" justStructuredS = "just-structured" guiS = "gui" libdirsS = "hets-libdirs" outdirS = "output-dir" amalgS = "casl-amalg" namedSpecsS = "named-specs" transS = "translation" recursiveS = "recursive" interactiveS = "interactive" connectS = "connect" xmlS = "xml" listenS = "listen" applyAutomaticRuleS = "apply-automatic-rule" normalFormS = "normal-form" unlitS = "unlit" urlCatalogS :: String urlCatalogS = "url-catalog" relposS :: String relposS = "relative-positions" fullSignS :: String fullSignS = "full-signatures" fullTheoriesS :: String fullTheoriesS = "full-theories" logicGraphS :: String logicGraphS = "logic-graph" fileTypeS :: String fileTypeS = "file-type" blacklistS :: String blacklistS = "blacklist" whitelistS :: String whitelistS = "whitelist" accessTokenS :: String accessTokenS = "access-token" genTermS, treeS, bafS :: String genTermS = "gen_trm" treeS = "tree." bafS = ".baf" graphE, ppS, envS, deltaS, prfS, omdocS, hsS, experimentalS :: String graphE = "graph." ppS = "pp." envS = "env" deltaS = ".delta" prfS = "prf" omdocS = "omdoc" hsS = "hs" experimentalS = "exp" tptpS, dfgS, cS :: String tptpS = "tptp" dfgS = "dfg" cS = ".c" showOpt :: String -> String showOpt s = if null s then "" else " --" ++ s showEqOpt :: String -> String -> String showEqOpt k s = if null s then "" else showOpt k ++ "=" ++ s -- main Datatypes -- -- | 'HetcatsOpts' is a record of all options received from the command line data HetcatsOpts = HcOpt -- for comments see usage info { analysis :: AnaType , guiType :: GuiType , urlCatalog :: [(String, String)] , infiles :: [FilePath] -- ^ files to be read , specNames :: [SIMPLE_ID] -- ^ specs to be processed , transNames :: [SIMPLE_ID] -- ^ comorphism to be processed , viewNames :: [SIMPLE_ID] -- ^ views to be processed , intype :: InType , libdirs :: [FilePath] , modelSparQ :: FilePath , counterSparQ :: Int , outdir :: FilePath , outtypes :: [OutType] , xupdate :: FilePath , recurse :: Bool , verbose :: Int , defLogic :: String , defSyntax :: String , outputToStdout :: Bool -- ^ send messages to stdout? , caslAmalg :: [CASLAmalgOpt] , interactive :: Bool , connectP :: Int , connectH :: String , uncolored :: Bool , xmlFlag :: Bool , applyAutomatic :: Bool , computeNormalForm :: Bool , dumpOpts :: [String] , ioEncoding :: Enc -- | use the library name in positions to avoid differences after uploads , useLibPos :: Bool , unlit :: Bool , serve :: Bool , listen :: Int , whitelist :: [[String]] , blacklist :: [[String]] , runMMT :: Bool , fullTheories :: Bool , outputLogicGraph :: Bool , fileType :: Bool , accessToken :: String , fullSign :: Bool } {- | 'defaultHetcatsOpts' defines the default HetcatsOpts, which are used as basic values when the user specifies nothing else -} defaultHetcatsOpts :: HetcatsOpts defaultHetcatsOpts = HcOpt { analysis = Basic , guiType = NoGui , urlCatalog = [] , infiles = [] , specNames = [] , transNames = [] , viewNames = [] , intype = GuessIn , libdirs = [] , modelSparQ = "" , counterSparQ = 3 , outdir = "" , outtypes = [] -- no default , xupdate = "" , recurse = False , defLogic = "CASL" , defSyntax = "" , verbose = 1 , outputToStdout = True , caslAmalg = [Cell] , interactive = False , connectP = -1 , connectH = "" , uncolored = False , xmlFlag = False , applyAutomatic = False , computeNormalForm = False , dumpOpts = [] , ioEncoding = Utf8 , useLibPos = False , unlit = False , serve = False , listen = -1 , whitelist = [] , blacklist = [] , runMMT = False , fullTheories = False , outputLogicGraph = False , fileType = False , accessToken = "" , fullSign = False } instance Show HetcatsOpts where show opts = let showFlag p o = if p opts then showOpt o else "" showIPLists p s = let ll = p opts in if null ll then "" else showEqOpt s . intercalate "," $ map (intercalate ".") ll in showEqOpt verboseS (show $ verbose opts) ++ show (guiType opts) ++ showFlag outputLogicGraph logicGraphS ++ showFlag fileType fileTypeS ++ showFlag interactive interactiveS ++ show (analysis opts) ++ case defLogic opts of s | s /= defLogic defaultHetcatsOpts -> showEqOpt logicS s _ -> "" ++ case defSyntax opts of s | s /= defSyntax defaultHetcatsOpts -> showEqOpt serializationS s _ -> "" ++ case accessToken opts of "" -> "" t -> showEqOpt accessTokenS t ++ showEqOpt libdirsS (intercalate ":" $ libdirs opts) ++ case modelSparQ opts of "" -> "" f -> showEqOpt modelSparQS f ++ case counterSparQ opts of n | n /= counterSparQ defaultHetcatsOpts -> showEqOpt counterSparQS $ show n _ -> "" ++ showFlag xmlFlag xmlS ++ showFlag ((/= -1) . connectP) connectS ++ showFlag ((/= -1) . listen) listenS ++ showIPLists whitelist whitelistS ++ showIPLists blacklist blacklistS ++ concatMap (showEqOpt "dump") (dumpOpts opts) ++ showEqOpt "encoding" (map toLower $ show $ ioEncoding opts) ++ showFlag unlit unlitS ++ showFlag useLibPos relposS ++ showFlag fullSign fullSignS ++ showFlag fullTheories fullTheoriesS ++ case urlCatalog opts of [] -> "" cs -> showEqOpt urlCatalogS $ intercalate "," $ map (\ (a, b) -> a ++ '=' : b) cs ++ showEqOpt intypeS (show $ intype opts) ++ showEqOpt outdirS (outdir opts) ++ showEqOpt outtypesS (intercalate "," $ map show $ outtypes opts) ++ showFlag recurse recursiveS ++ showFlag applyAutomatic applyAutomaticRuleS ++ showFlag computeNormalForm normalFormS ++ showEqOpt namedSpecsS (intercalate "," $ map show $ specNames opts) ++ showEqOpt transS (intercalate ":" $ map show $ transNames opts) ++ showEqOpt viewS (intercalate "," $ map show $ viewNames opts) ++ showEqOpt amalgS (tail $ init $ show $ case caslAmalg opts of [] -> [NoAnalysis] l -> l) ++ " " ++ unwords (infiles opts) -- | every 'Flag' describes an option (see usage info) data Flag = Verbose Int | Quiet | Uncolored | Version | Recurse | ApplyAutomatic | NormalForm | Help | Gui GuiType | Analysis AnaType | DefaultLogic String | DefaultSyntax String | InType InType | LibDirs String | OutDir FilePath | XUpdate FilePath | ModelSparQ FilePath | CounterSparQ Int | OutTypes [OutType] | Specs [SIMPLE_ID] | Trans [SIMPLE_ID] | Views [SIMPLE_ID] | CASLAmalg [CASLAmalgOpt] | Interactive | Connect Int String | XML | Dump String | IOEncoding Enc | Unlit | RelPos | Serve | Listen Int | Whitelist String | Blacklist String | UseMMT | FullTheories | FullSign | OutputLogicGraph | FileType | AccessToken String | UrlCatalog [(String, String)] -- | 'makeOpts' includes a parsed Flag in a set of HetcatsOpts makeOpts :: HetcatsOpts -> Flag -> HetcatsOpts makeOpts opts flg = let splitIPs = map (splitBy '.') . splitOn ',' in case flg of Interactive -> opts { interactive = True } XML -> opts { xmlFlag = True } Listen x -> opts { listen = x } Blacklist x -> opts { blacklist = splitIPs x } Whitelist x -> opts { whitelist = splitIPs x } Connect x y -> opts { connectP = x, connectH = y } Analysis x -> opts { analysis = x } Gui x -> opts { guiType = x } InType x -> opts { intype = x } LibDirs x -> opts { libdirs = joinHttpLibPath $ splitPaths x } ModelSparQ x -> opts { modelSparQ = x } CounterSparQ x -> opts { counterSparQ = x } OutDir x -> opts { outdir = x } OutTypes x -> opts { outtypes = x } XUpdate x -> opts { xupdate = x } Recurse -> opts { recurse = True } ApplyAutomatic -> opts { applyAutomatic = True } NormalForm -> opts { computeNormalForm = True } Specs x -> opts { specNames = x } Trans x -> opts { transNames = x } Views x -> opts { viewNames = x } Verbose x -> opts { verbose = x } DefaultLogic x -> opts { defLogic = x } DefaultSyntax x -> opts { defSyntax = x } CASLAmalg x -> opts { caslAmalg = x } Quiet -> opts { verbose = 0 } Uncolored -> opts { uncolored = True } Dump s -> opts { dumpOpts = s : dumpOpts opts } IOEncoding e -> opts { ioEncoding = e } Serve -> opts { serve = True } Unlit -> opts { unlit = True } RelPos -> opts { useLibPos = True } UseMMT -> opts { runMMT = True } FullTheories -> opts { fullTheories = True } OutputLogicGraph -> opts { outputLogicGraph = True } FileType -> opts { fileType = True } FullSign -> opts { fullSign = True } UrlCatalog m -> opts { urlCatalog = m ++ urlCatalog opts } AccessToken s -> opts { accessToken = s } Help -> opts -- skipped Version -> opts -- skipped -- | 'AnaType' describes the type of analysis to be performed data AnaType = Basic | Structured | Skip instance Show AnaType where show a = case a of Basic -> "" Structured -> showOpt justStructuredS Skip -> showOpt skipS -- | check if structured analysis should be performed isStructured :: HetcatsOpts -> Bool isStructured a = case analysis a of Structured -> True _ -> False -- | 'GuiType' determines if we want the GUI shown data GuiType = UseGui | NoGui deriving Eq instance Show GuiType where show g = case g of UseGui -> showOpt guiS NoGui -> "" -- | 'InType' describes the type of input the infile contains data InType = ATermIn ATType | CASLIn | HetCASLIn | DOLIn | OWLIn OWLFormat | HaskellIn | MaudeIn | TwelfIn | HolLightIn | IsaIn | ThyIn | PrfIn | OmdocIn | ExperimentalIn -- ^ for testing new functionality | ProofCommand | GuessIn | RDFIn | FreeCADIn | CommonLogicIn Bool -- ^ "clf" or "clif" ('True' is long version) | DgXml | Xmi | Qvt | TPTPIn | HtmlIn -- just to complain deriving Eq instance Show InType where show i = case i of ATermIn at -> genTermS ++ show at CASLIn -> "casl" HetCASLIn -> "het" DOLIn -> "dol" OWLIn oty -> show oty HaskellIn -> hsS ExperimentalIn -> "exp" MaudeIn -> "maude" TwelfIn -> "elf" HolLightIn -> "hol" IsaIn -> "isa" ThyIn -> "thy" TPTPIn -> "tptp" PrfIn -> prfS OmdocIn -> omdocS ProofCommand -> "hpf" GuessIn -> "" RDFIn -> "rdf" FreeCADIn -> "fcstd" CommonLogicIn isLong -> if isLong then "clif" else "clf" DgXml -> xmlS Xmi -> "xmi" Qvt -> "qvt" HtmlIn -> "html" -- maybe this optional tree prefix can be omitted instance Read InType where readsPrec _ = readShowAux $ concatMap showAll (plainInTypes ++ aInTypes) where showAll i@(ATermIn _) = [(show i, i), (treeS ++ show i, i)] showAll i = [(show i, i)] -- | 'ATType' describes distinct types of ATerms data ATType = BAF | NonBAF deriving Eq instance Show ATType where show a = case a of BAF -> bafS NonBAF -> "" -- RDFIn is on purpose not listed; must be added manually if neccessary plainInTypes :: [InType] plainInTypes = [ CASLIn, HetCASLIn, DOLIn ] ++ map OWLIn plainOwlFormats ++ [ HaskellIn, ExperimentalIn , MaudeIn, TwelfIn , HolLightIn, IsaIn, ThyIn, PrfIn, OmdocIn, ProofCommand , CommonLogicIn False, CommonLogicIn True , DgXml, FreeCADIn, Xmi, Qvt, TPTPIn ] aInTypes :: [InType] aInTypes = [ ATermIn x | x <- [BAF, NonBAF] ] -- | 'OWLFormat' lists possibilities for OWL syntax (in + out) data OWLFormat = Manchester | OwlXml | RdfXml | OBO | Turtle deriving Eq plainOwlFormats :: [OWLFormat] plainOwlFormats = [ Manchester, OwlXml, RdfXml, OBO, Turtle ] instance Show OWLFormat where show ty = case ty of Manchester -> "omn" OwlXml -> "owl" -- "owl.xml" ?? might occur but conflicts with dgxml RdfXml -> "rdf" OBO -> "obo" Turtle -> "ttl" data SPFType = ConsistencyCheck | ProveTheory deriving Eq instance Show SPFType where show x = case x of ConsistencyCheck -> cS ProveTheory -> "" spfTypes :: [SPFType] spfTypes = [ConsistencyCheck, ProveTheory] -- | 'OutType' describes the type of outputs that we want to generate data OutType = PrettyOut PrettyType | GraphOut GraphType | Prf | EnvOut | OWLOut OWLFormat | CLIFOut | KIFOut | OmdocOut | XmlOut -- ^ development graph xml output | JsonOut -- ^ development graph json output | ExperimentalOut -- ^ for testing new functionality | HaskellOut | FreeCADOut | ThyFile -- ^ isabelle theory file | DfgFile SPFType -- ^ SPASS input file | TPTPFile SPFType | ComptableXml | RDFOut | SigFile Delta -- ^ signature as text | TheoryFile Delta -- ^ signature with sentences as text | SymXml | SymsXml deriving Eq instance Show OutType where show o = case o of PrettyOut p -> ppS ++ show p GraphOut f -> graphE ++ show f Prf -> prfS EnvOut -> envS OWLOut oty -> show oty CLIFOut -> "clif" KIFOut -> "kif" OmdocOut -> omdocS XmlOut -> xmlS JsonOut -> "json" ExperimentalOut -> experimentalS HaskellOut -> hsS FreeCADOut -> "fcxml" ThyFile -> "thy" DfgFile t -> dfgS ++ show t TPTPFile t -> tptpS ++ show t ComptableXml -> "comptable.xml" RDFOut -> "nt" SigFile d -> "sig" ++ show d TheoryFile d -> "th" ++ show d SymXml -> "sym.xml" SymsXml -> "syms.xml" plainOutTypeList :: [OutType] plainOutTypeList = [ Prf, EnvOut ] ++ map OWLOut plainOwlFormats ++ [ RDFOut, CLIFOut, KIFOut, OmdocOut, XmlOut, JsonOut, ExperimentalOut , HaskellOut, ThyFile, ComptableXml, FreeCADOut, SymXml, SymsXml] outTypeList :: [OutType] outTypeList = let dl = [Delta, Fully] in plainOutTypeList ++ [ PrettyOut p | p <- prettyList ++ prettyList2] ++ [ SigFile d | d <- dl ] ++ [ TheoryFile d | d <- dl ] ++ [ DfgFile x | x <- spfTypes] ++ [ TPTPFile x | x <- spfTypes] ++ [ GraphOut f | f <- graphList ] instance Read OutType where readsPrec _ = readShow outTypeList data Delta = Delta | Fully deriving Eq instance Show Delta where show d = case d of Delta -> deltaS Fully -> "" {- | 'PrettyType' describes the type of output we want the pretty-printer to generate -} data PrettyType = PrettyAscii Bool | PrettyLatex Bool | PrettyXml | PrettyHtml deriving Eq instance Show PrettyType where show p = case p of PrettyAscii b -> (if b then "stripped." else "") ++ "het" PrettyLatex b -> (if b then "labelled." else "") ++ "tex" PrettyXml -> xmlS PrettyHtml -> "html" prettyList :: [PrettyType] prettyList = [PrettyAscii False, PrettyLatex False, PrettyXml, PrettyHtml] prettyList2 :: [PrettyType] prettyList2 = [PrettyAscii True, PrettyLatex True] -- | 'GraphType' describes the type of Graph that we want generated data GraphType = Dot Bool -- ^ True means show internal node labels deriving Eq instance Show GraphType where show g = case g of Dot si -> (if si then "exp." else "") ++ "dot" graphList :: [GraphType] graphList = [Dot True, Dot False] {- | 'options' describes all available options and is used to generate usage information -} options :: [OptDescr Flag] options = let cslst = "is a comma-separated list" ++ crS ++ "of one or more from:" crS = "\n " bS = "| " joinBar l = "(" ++ intercalate "|" l ++ ")" in [ Option "v" [verboseS] (OptArg parseVerbosity "0-5") "verbosity, default is -v1" , Option "q" ["quiet"] (NoArg Quiet) "same as -v0, no output to stdout" , Option "V" ["version"] (NoArg Version) "print version number and exit" , Option "h" ["help", "usage"] (NoArg Help) "print usage information and exit" #ifdef UNI_PACKAGE , Option "g" [guiS] (NoArg (Gui UseGui)) "show graphs in windows" , Option "u" ["uncolored"] (NoArg Uncolored) "no colors in shown graphs" #endif , Option "x" [xmlS] (NoArg XML) "use xml packets to communicate" #ifdef SERVER , Option "X" ["server"] (NoArg Serve) "start hets as web-server" #endif , Option "G" [logicGraphS] (NoArg OutputLogicGraph) "output logic graph (as xml) or as graph (-g)" , Option "I" [interactiveS] (NoArg Interactive) "run in interactive (console) mode" , Option "F" [fileTypeS] (NoArg FileType) "only display file type" , Option "p" [skipS] (NoArg $ Analysis Skip) "skip static analysis, only parse" , Option "s" [justStructuredS] (NoArg $ Analysis Structured) "skip basic, just do structured analysis" , Option "l" [logicS] (ReqArg DefaultLogic "LOGIC") "choose logic, default is CASL" , Option "y" [serializationS] (ReqArg DefaultSyntax "SER") "choose different logic syntax" , Option "L" [libdirsS] (ReqArg LibDirs "DIR") ("colon-separated list of directories" ++ crS ++ "containing HetCASL libraries") , Option "m" [modelSparQS] (ReqArg ModelSparQ "FILE") "lisp file for SparQ definitions" , Option "" [counterSparQS] (ReqArg parseCounter "0-99") "maximal number of counter examples" , Option "c" [connectS] (ReqArg parseConnect "HOST:PORT") ("run (console) interface via connection" ++ crS ++ "to given host and port") , Option "S" [listenS] (ReqArg parseListen "PORT") "run interface/server by listening to the port" , Option "" [whitelistS] (ReqArg Whitelist "IP4s") $ "comma-separated list of IP4 addresses" ++ crS ++ "(missing numbers at dots are wildcards)" , Option "" [blacklistS] (ReqArg Blacklist "IP4s") $ "comma-separated list of IP4 addresses" ++ crS ++ "(example: 77.75.77.)" , Option "C" [urlCatalogS] (ReqArg parseCatalog "URLS") "comma-separated list of URL pairs: srcURL=tarURL" , Option "i" [intypeS] (ReqArg parseInType "ITYPE") ("input file type can be one of:" ++ concatMap (\ t -> crS ++ bS ++ t) (map show plainInTypes ++ map (++ bracket bafS) [bracket treeS ++ genTermS])) , Option "d" ["dump"] (ReqArg Dump "STRING") "dump various strings" , Option "e" ["encoding"] (ReqArg parseEncoding "ENCODING") "latin1 or utf8 (default) encoding" , Option "" [unlitS] (NoArg Unlit) "unlit input source" , Option "" [relposS] (NoArg RelPos) "use relative file positions" , Option "" [fullSignS] (NoArg FullSign) "xml output full signatures" , Option "" [fullTheoriesS] (NoArg FullTheories) "xml output full theories" , Option "" [accessTokenS] (ReqArg AccessToken "TOKEN") "add access token to URLs (for ontohub)" , Option "O" [outdirS] (ReqArg OutDir "DIR") "destination directory for output files" , Option "o" [outtypesS] (ReqArg parseOutTypes "OTYPES") ("output file types, default nothing," ++ crS ++ cslst ++ crS ++ concatMap ( \ t -> bS ++ show t ++ crS) plainOutTypeList ++ bS ++ joinBar (map show [SigFile Fully, TheoryFile Fully]) ++ bracket deltaS ++ crS ++ bS ++ ppS ++ joinBar (map show prettyList) ++ crS ++ bS ++ ppS ++ joinBar (map show prettyList2) ++ crS ++ bS ++ graphE ++ joinBar (map show graphList) ++ crS ++ bS ++ dfgS ++ bracket cS ++ crS ++ bS ++ tptpS ++ bracket cS) , Option "U" ["xupdate"] (ReqArg XUpdate "FILE") "apply additional xupdates from file" , Option "R" [recursiveS] (NoArg Recurse) "output also imported libraries" , Option "A" [applyAutomaticRuleS] (NoArg ApplyAutomatic) "apply automatic dev-graph strategy" , Option "N" [normalFormS] (NoArg NormalForm) "compute normal forms (takes long)" , Option "n" [namedSpecsS] (ReqArg (Specs . parseSIdOpts) "NSPECS") ("process specs option " ++ crS ++ cslst ++ " SIMPLE-ID") , Option "w" [viewS] (ReqArg (Views . parseSIdOpts) "NVIEWS") ("process views option " ++ crS ++ cslst ++ " SIMPLE-ID") , Option "t" [transS] (ReqArg parseTransOpt "TRANS") ("translation option " ++ crS ++ "is a colon-separated list" ++ crS ++ "of one or more from: SIMPLE-ID") , Option "a" [amalgS] (ReqArg parseCASLAmalg "ANALYSIS") ("CASL amalgamability analysis options" ++ crS ++ cslst ++ crS ++ joinBar (map show caslAmalgOpts)), Option "M" ["MMT"] (NoArg UseMMT) "use MMT" ] -- | options that require arguments for the wep-api excluding \"translation\" optionArgs :: [(String, String -> Flag)] optionArgs = foldr (\ o l -> case o of Option _ (s : _) (ReqArg f _) _ | s /= transS -> (s, f) : l _ -> l) [] options -- | command line switches for the wep-api excluding non-dev-graph related ones optionFlags :: [(String, Flag)] optionFlags = drop 11 $ foldr (\ o l -> case o of Option _ (s : _) (NoArg f) _ -> (s, f) : l _ -> l) [] options -- parser functions returning Flags -- -- | 'parseVerbosity' parses a 'Verbose' Flag from user input parseVerbosity :: Maybe String -> Flag parseVerbosity ms = case ms of Nothing -> Verbose 2 Just s -> Verbose $ parseInt s parseInt :: String -> Int parseInt s = fromMaybe (hetsError $ s ++ " is not a valid INT") $ readMaybe s parseCounter :: String -> Flag parseCounter = CounterSparQ . parseInt divideIntoPortHost :: String -> Bool -> (String, String) -> (String, String) divideIntoPortHost s sw (accP, accH) = case s of ':' : ll -> divideIntoPortHost ll True (accP, accH) c : ll -> if sw then divideIntoPortHost ll True (accP, c : accH) else divideIntoPortHost ll False (c : accP, accH) [] -> (accP, accH) -- | 'parseConnect' parses a port Flag from user input parseConnect :: String -> Flag parseConnect s = let (sP, sH) = divideIntoPortHost s False ([], []) in case reads sP of [(i, "")] -> Connect i sH _ -> Connect (-1) sH parseListen :: String -> Flag parseListen s = case reads s of [(i, "")] -> Listen i _ -> Listen (-1) parseEncoding :: String -> Flag parseEncoding s = case map toLower $ trim s of "latin1" -> IOEncoding Latin1 "utf8" -> IOEncoding Utf8 r -> hetsError (r ++ " is not a valid encoding") -- | intypes useable for downloads downloadExtensions :: [String] downloadExtensions = map ('.' :) $ map show plainInTypes ++ map ((treeS ++) . show) [ATermIn BAF, ATermIn NonBAF] ++ map show aInTypes -- | remove the extension from a file rmSuffix :: FilePath -> FilePath rmSuffix = fst . stripSuffix (envSuffix : downloadExtensions) -- | the suffix of env files envSuffix :: String envSuffix = '.' : envS -- | the suffix of env files prfSuffix :: String prfSuffix = '.' : prfS isDefLogic :: String -> HetcatsOpts -> Bool isDefLogic s = (s ==) . defLogic defLogicIsDMU :: HetcatsOpts -> Bool defLogicIsDMU = isDefLogic "DMU" getExtensions :: HetcatsOpts -> [String] getExtensions opts = case intype opts of GuessIn | defLogicIsDMU opts -> [".xml"] | isDefLogic "Framework" opts -> [".elf", ".thy", ".maude", ".het"] GuessIn -> downloadExtensions e@(ATermIn _) -> ['.' : show e, '.' : treeS ++ show e] e -> ['.' : show e] ++ [envSuffix] getFileNames :: [String] -> FilePath -> [FilePath] getFileNames exts file = file : map (rmSuffix file ++) exts -- | checks if a source file for the given file name exists existsAnSource :: HetcatsOpts -> FilePath -> IO (Maybe FilePath) existsAnSource opts file = do let names = getFileNames (getExtensions opts) file -- look for the first existing file validFlags <- mapM doesFileExist names return . fmap snd . find fst $ zip validFlags names -- | should env be written hasEnvOut :: HetcatsOpts -> Bool hasEnvOut = any ( \ o -> case o of EnvOut -> True _ -> False) . outtypes -- | should prf be written isPrfOut :: OutType -> Bool isPrfOut o = case o of Prf -> True _ -> False -- | should prf be written hasPrfOut :: HetcatsOpts -> Bool hasPrfOut = any isPrfOut . outtypes -- | remove prf writing removePrfOut :: HetcatsOpts -> HetcatsOpts removePrfOut opts = opts { outtypes = filter (not . isPrfOut) $ outtypes opts } {- | gets two Paths and checks if the first file is not older than the second one and should return True for two identical files -} checkRecentEnv :: HetcatsOpts -> FilePath -> FilePath -> IO Bool checkRecentEnv opts fp1 base2 = catchIOException False $ do fp1_time <- getModificationTime fp1 maybe_source_file <- existsAnSource opts {intype = GuessIn} base2 maybe (return False) ( \ fp2 -> do fp2_time <- getModificationTime fp2 return (fp1_time >= fp2_time)) maybe_source_file parseCatalog :: String -> Flag parseCatalog str = UrlCatalog $ map ((\ l -> case l of [a, b] -> (a, b) _ -> hetsError (str ++ " is not a valid URL catalog")) . splitOn '=') $ splitOn ',' str -- | 'parseInType' parses an 'InType' Flag from user input parseInType :: String -> Flag parseInType = InType . parseInType1 -- | 'parseInType1' parses an 'InType' Flag from a String parseInType1 :: String -> InType parseInType1 str = case reads str of [(t, "")] -> t _ -> hetsError (str ++ " is not a valid ITYPE") {- the mere typo read instead of reads caused the runtime error: Fail: Prelude.read: no parse -} -- 'parseOutTypes' parses an 'OutTypes' Flag from user input parseOutTypes :: String -> Flag parseOutTypes str = case reads $ bracket str of [(l, "")] -> OutTypes l _ -> hetsError (str ++ " is not a valid OTYPES") -- | parses a comma separated list from user input parseSIdOpts :: String -> [SIMPLE_ID] parseSIdOpts = map mkSimpleId . splitOn ',' -- | 'parseTransOpt' parses a 'Trans' Flag from user input parseTransOpt :: String -> Flag parseTransOpt = Trans . map mkSimpleId . splitPaths -- | guesses the InType guess :: String -> InType -> InType guess file itype = case itype of GuessIn -> guessInType file _ -> itype -- | 'guessInType' parses an 'InType' from the FilePath guessInType :: FilePath -> InType guessInType file = case fileparse downloadExtensions file of (_, _, Just ('.' : suf)) -> parseInType1 suf (_, _, _) -> GuessIn -- | 'parseCASLAmalg' parses CASL amalgamability options parseCASLAmalg :: String -> Flag parseCASLAmalg str = case reads $ bracket str of [(l, "")] -> CASLAmalg $ filter ( \ o -> case o of NoAnalysis -> False _ -> True ) l _ -> hetsError $ str ++ " is not a valid CASL amalgamability analysis option list" -- main functions -- -- | 'hetcatsOpts' parses sensible HetcatsOpts from ARGV hetcatsOpts :: [String] -> IO HetcatsOpts hetcatsOpts argv = let argv' = filter (not . isUni) argv isUni = isPrefixOf "--uni" in case getOpt Permute options argv' of (opts, nonOpts, []) -> do flags <- checkFlags opts return (foldr (flip makeOpts) defaultHetcatsOpts flags) { infiles = nonOpts } (_, _, errs) -> hetsIOError (concat errs) -- | 'checkFlags' checks all parsed Flags for sanity checkFlags :: [Flag] -> IO [Flag] checkFlags fs = do let collectFlags = collectDirs . collectOutTypes . collectVerbosity . collectSpecOpts -- collect some more here? h = null [ () | Help <- fs] v = null [ () | Version <- fs] unless h $ putStr hetsUsage unless v $ putStrLn ("version of hets: " ++ hetcats_version) unless (v && h) exitSuccess collectFlags fs -- auxiliary functions: FileSystem interaction -- -- | check if infile is uri checkUri :: FilePath -> Bool checkUri file = "://" `isPrefixOf` dropWhile isAlpha file -- (http://, https://, ftp://, file://, etc.) -- | 'checkOutDirs' checks a list of OutDir for sanity checkOutDirs :: [Flag] -> IO [Flag] checkOutDirs fs = do case fs of [] -> return () [f] -> checkOutDir f _ -> hetsIOError "Only one output directory may be specified on the command line" return fs -- | 'checkLibDirs' checks a list of LibDir for sanity checkLibDirs :: [Flag] -> IO [Flag] checkLibDirs fs = case fs of [] -> do s <- getEnvDef "HETS_LIB" "" if null s then return [] else do let d = LibDirs s checkLibDirs [d] return [d] [LibDirs f] -> mapM_ checkLibDir (joinHttpLibPath $ splitPaths f) >> return fs _ -> hetsIOError "Only one library path may be specified on the command line" joinHttpLibPath :: [String] -> [String] joinHttpLibPath l = case l of p : f : r | elem p ["http", "https"] -> (p ++ ':' : f) : joinHttpLibPath r f : r -> f : joinHttpLibPath r [] -> [] -- | 'checkLibDir' checks a single LibDir for sanity checkLibDir :: FilePath -> IO () checkLibDir file = do exists <- if checkUri file then return True else doesDirectoryExist file unless exists . hetsIOError $ "Not a valid library directory: " ++ file -- | 'checkOutDir' checks a single OutDir for sanity checkOutDir :: Flag -> IO () checkOutDir (OutDir file) = do exists <- doesDirectoryExist file unless exists . hetsIOError $ "Not a valid output directory: " ++ file checkOutDir _ = return () -- auxiliary functions: collect flags -- collectDirs :: [Flag] -> IO [Flag] collectDirs fs = do let (ods, fs1) = partition isOutDir fs (lds, fs2) = partition isLibDir fs1 isOutDir (OutDir _) = True isOutDir _ = False isLibDir (LibDirs _) = True isLibDir _ = False ods' <- checkOutDirs ods lds' <- checkLibDirs lds return $ ods' ++ lds' ++ fs2 collectVerbosity :: [Flag] -> [Flag] collectVerbosity fs = let (v, fs') = foldr (\ f (n, rs) -> case f of Verbose x -> (if n < 0 then x else n + x, rs) _ -> (n, f : rs)) (-1, []) fs in if v < 0 || not (null [() | Quiet <- fs']) then fs' else Verbose v : fs' collectOutTypes :: [Flag] -> [Flag] collectOutTypes fs = let (ots, fs') = foldr (\ f (os, rs) -> case f of OutTypes ot -> (ot ++ os, rs) _ -> (os, f : rs)) ([], []) fs in if null ots then fs' else OutTypes ots : fs' collectSpecOpts :: [Flag] -> [Flag] collectSpecOpts fs = let (specs, fs') = foldr (\ f (os, rs) -> case f of Specs ot -> (ot ++ os, rs) _ -> (os, f : rs)) ([], []) fs in if null specs then fs' else Specs specs : fs' -- auxiliary functions: error messages -- -- | only print the error (and no usage info) hetsError :: String -> a hetsError = error . ("command line usage error (see 'hets -h')\n" ++) -- | print error and usage and exit with code 2 hetsIOError :: String -> IO a hetsIOError s = do hPutStrLn stderr s putStr hetsUsage exitWith $ ExitFailure 2 -- | 'hetsUsage' generates usage information for the commandline hetsUsage :: String hetsUsage = let header = "Usage: hets [OPTION ...] [FILE ...] [+RTS -?]" in usageInfo header options {- | 'putIfVerbose' prints a given String to StdOut when the given HetcatsOpts' Verbosity exceeds the given level -} putIfVerbose :: HetcatsOpts -> Int -> String -> IO () putIfVerbose opts level = when (outputToStdout opts) . when (verbose opts >= level) . putStrLn doDump :: HetcatsOpts -> String -> IO () -> IO () doDump opts str = when (elem str $ dumpOpts opts) -- | show diagnostic messages (see Result.hs), according to verbosity level showDiags :: HetcatsOpts -> [Diagnosis] -> IO () showDiags opts ds = runResultT (showDiags1 opts $ liftR $ Result ds Nothing) >> return () -- | show diagnostic messages (see Result.hs), according to verbosity level showDiags1 :: HetcatsOpts -> ResultT IO a -> ResultT IO a showDiags1 opts res = if outputToStdout opts then do Result ds res' <- lift $ runResultT res lift $ printDiags (verbose opts) ds case res' of Just res'' -> return res'' Nothing -> liftR $ Result [] Nothing else res
mariefarrell/Hets
Driver/Options.hs
gpl-2.0
34,635
0
46
8,753
9,890
5,330
4,560
907
41
{-# OPTIONS_GHC -fno-warn-orphans #-} {-| Common functionality for htools-related unittests. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Test.Ganeti.TestHTools ( nullIPolicy , defGroup , defGroupList , defGroupAssoc , createInstance , makeSmallCluster , setInstanceSmallerThanNode ) where import qualified Data.Map as Map import Test.Ganeti.TestCommon import qualified Ganeti.Constants as C import qualified Ganeti.HTools.Container as Container import qualified Ganeti.HTools.Group as Group import qualified Ganeti.HTools.Instance as Instance import qualified Ganeti.HTools.Loader as Loader import qualified Ganeti.HTools.Node as Node import qualified Ganeti.HTools.Types as Types -- * Helpers -- | Null iPolicy, and by null we mean very liberal. nullIPolicy :: Types.IPolicy nullIPolicy = Types.IPolicy { Types.iPolicyMinMaxISpecs = [Types.MinMaxISpecs { Types.minMaxISpecsMinSpec = Types.ISpec { Types.iSpecMemorySize = 0 , Types.iSpecCpuCount = 0 , Types.iSpecDiskSize = 0 , Types.iSpecDiskCount = 0 , Types.iSpecNicCount = 0 , Types.iSpecSpindleUse = 0 } , Types.minMaxISpecsMaxSpec = Types.ISpec { Types.iSpecMemorySize = maxBound , Types.iSpecCpuCount = maxBound , Types.iSpecDiskSize = maxBound , Types.iSpecDiskCount = C.maxDisks , Types.iSpecNicCount = C.maxNics , Types.iSpecSpindleUse = maxBound } }] , Types.iPolicyStdSpec = Types.ISpec { Types.iSpecMemorySize = Types.unitMem , Types.iSpecCpuCount = Types.unitCpu , Types.iSpecDiskSize = Types.unitDsk , Types.iSpecDiskCount = 1 , Types.iSpecNicCount = 1 , Types.iSpecSpindleUse = 1 } , Types.iPolicyDiskTemplates = [minBound..maxBound] , Types.iPolicyVcpuRatio = maxVcpuRatio -- somewhat random value, high -- enough to not impact us , Types.iPolicySpindleRatio = maxSpindleRatio } -- | Default group definition. defGroup :: Group.Group defGroup = flip Group.setIdx 0 $ Group.create "default" Types.defaultGroupID Types.AllocPreferred [] nullIPolicy [] -- | Default group, as a (singleton) 'Group.List'. defGroupList :: Group.List defGroupList = Container.fromList [(Group.idx defGroup, defGroup)] -- | Default group, as a string map. defGroupAssoc :: Map.Map String Types.Gdx defGroupAssoc = Map.singleton (Group.uuid defGroup) (Group.idx defGroup) -- | Create an instance given its spec. createInstance :: Int -> Int -> Int -> Instance.Instance createInstance mem dsk vcpus = Instance.create "inst-unnamed" mem dsk [Instance.Disk dsk Nothing] vcpus Types.Running [] True (-1) (-1) Types.DTDrbd8 1 [] -- | Create a small cluster by repeating a node spec. makeSmallCluster :: Node.Node -> Int -> Node.List makeSmallCluster node count = let origname = Node.name node origalias = Node.alias node nodes = map (\idx -> node { Node.name = origname ++ "-" ++ show idx , Node.alias = origalias ++ "-" ++ show idx }) [1..count] fn = flip Node.buildPeers Container.empty namelst = map (\n -> (Node.name n, fn n)) nodes (_, nlst) = Loader.assignIndices namelst in nlst -- | Update an instance to be smaller than a node. setInstanceSmallerThanNode :: Node.Node -> Instance.Instance -> Instance.Instance setInstanceSmallerThanNode node inst = let new_dsk = Node.availDisk node `div` 2 in inst { Instance.mem = Node.availMem node `div` 2 , Instance.dsk = new_dsk , Instance.vcpus = Node.availCpu node `div` 2 , Instance.disks = [Instance.Disk new_dsk (if Node.exclStorage node then Just $ Node.fSpindles node `div` 2 else Nothing)] }
apyrgio/snf-ganeti
test/hs/Test/Ganeti/TestHTools.hs
bsd-2-clause
5,622
0
16
1,604
903
523
380
77
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | Generate HPC (Haskell Program Coverage) reports module Stack.Build.Coverage ( generateHpcReport , generateHpcMarkupIndex ) where import Control.Applicative ((<$>)) import Control.Exception.Lifted import Control.Monad (liftM) import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Resource import qualified Data.ByteString.Char8 as S8 import Data.Foldable (forM_) import Data.Function import Data.List import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid ((<>)) 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 qualified Data.Text.Lazy as LT import Data.Traversable (forM) import Path import Path.IO import Prelude hiding (FilePath, writeFile) import Stack.Constants import Stack.Types import System.Process.Read import Text.Hastache (htmlEscape) -- | Generates the HTML coverage report and shows a textual coverage -- summary. generateHpcReport :: (MonadIO m,MonadReader env m,HasConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,HasEnvConfig env) => Path Abs Dir -> Text -> Text -> Text -> m () generateHpcReport pkgDir pkgName pkgId testName = do let whichTest = pkgName <> "'s test-suite \"" <> testName <> "\"" -- Compute destination directory. installDir <- installationRootLocal testNamePath <- parseRelDir (T.unpack testName) pkgIdPath <- parseRelDir (T.unpack pkgId) let destDir = installDir </> hpcDirSuffix </> pkgIdPath </> testNamePath -- Directories for .mix files. hpcDir <- hpcDirFromDir pkgDir hpcRelDir <- (</> dotHpc) <$> hpcRelativeDir -- Compute arguments used for both "hpc markup" and "hpc report". pkgDirs <- Map.keys . envConfigPackages <$> asks getEnvConfig let args = -- Use index files from all packages (allows cross-package -- coverage results). concatMap (\x -> ["--srcdir", toFilePath x]) pkgDirs ++ -- Look for index files in the correct dir (relative to -- each pkgdir). ["--hpcdir", toFilePath hpcRelDir, "--reset-hpcdirs" -- Restrict to just the current library code (see #634 - -- this will likely be customizable in the future) ,"--include", T.unpack (pkgId <> ":")] -- If a .tix file exists, generate an HPC report for it. tixFile <- parseRelFile (T.unpack testName ++ ".tix") let tixFileAbs = hpcDir </> tixFile tixFileExists <- fileExists tixFileAbs if not tixFileExists then $logError $ T.concat [ "Didn't find .tix coverage file for " , whichTest , " - expected to find it at " , T.pack (toFilePath tixFileAbs) , "." ] else (`onException` $logError ("Error occurred while producing coverage report for " <> whichTest)) $ do menv <- getMinimalEnvOverride $logInfo $ "Generating HTML coverage report for " <> whichTest _ <- readProcessStdout (Just hpcDir) menv "hpc" ("markup" : toFilePath tixFileAbs : ("--destdir=" ++ toFilePath destDir) : args) output <- readProcessStdout (Just hpcDir) menv "hpc" ("report" : toFilePath tixFileAbs : args) -- Print output, stripping @\r@ characters because -- Windows. forM_ (S8.lines output) ($logInfo . T.decodeUtf8 . S8.filter (not . (=='\r'))) $logInfo ("The HTML coverage report for " <> whichTest <> " is available at " <> T.pack (toFilePath (destDir </> $(mkRelFile "hpc_index.html")))) generateHpcMarkupIndex :: (MonadIO m,MonadReader env m,MonadLogger m,MonadCatch m,HasEnvConfig env) => m () generateHpcMarkupIndex = do installDir <- installationRootLocal let markupDir = installDir </> hpcDirSuffix outputFile = markupDir </> $(mkRelFile "index.html") (dirs, _) <- listDirectory markupDir rows <- liftM (catMaybes . concat) $ forM dirs $ \dir -> do (subdirs, _) <- listDirectory dir forM subdirs $ \subdir -> do let indexPath = subdir </> $(mkRelFile "hpc_index.html") exists <- fileExists indexPath if not exists then return Nothing else do relPath <- stripDir markupDir indexPath let package = dirname dir testsuite = dirname subdir return $ Just $ T.concat [ "<tr><td>" , pathToHtml package , "</td><td><a href=\"" , pathToHtml relPath , "\">" , pathToHtml testsuite , "</a></td></tr>" ] liftIO $ T.writeFile (toFilePath outputFile) $ T.concat $ [ "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" -- Part of the css from HPC's output HTML , "<style type=\"text/css\">" , "table.dashboard { border-collapse: collapse; border: solid 1px black }" , ".dashboard td { border: solid 1px black }" , ".dashboard th { border: solid 1px black }" , "</style>" , "</head>" , "<body>" ] ++ (if null rows then [ "<b>No hpc_index.html files found in \"" , pathToHtml markupDir , "\".</b>" ] else [ "<table class=\"dashboard\" width=\"100%\" boder=\"1\"><tbody>" , "<p><b>NOTE: This is merely a listing of the html files found in the coverage reports directory. Some of these reports may be old.</b></p>" , "<tr><th>Package</th><th>TestSuite</th></tr>" ] ++ rows ++ ["</tbody></table>"]) ++ ["</body></html>"] $logInfo $ "\nAn index of the generated HTML coverage reports is available at " <> T.pack (toFilePath outputFile) pathToHtml :: Path b t -> Text pathToHtml = T.dropWhileEnd (=='/') . LT.toStrict . htmlEscape . LT.pack . toFilePath
duplode/stack
src/Stack/Build/Coverage.hs
bsd-3-clause
6,933
0
22
2,300
1,339
716
623
121
3
{-# LANGUAGE RecursiveDo #-} -- From https://ocharles.org.uk/blog/posts/2014-12-09-recursive-do.html import Control.Monad.Fix data RoseTree a = RoseTree a [RoseTree a] deriving (Show) exampleTree :: RoseTree Int exampleTree = RoseTree 5 [RoseTree 4 [], RoseTree 6 []] pureMax :: Ord a => RoseTree a -> RoseTree (a, a) pureMax tree = let (t, largest) = go largest tree in t where go :: Ord a => a -> RoseTree a -> (RoseTree (a, a), a) go biggest (RoseTree x []) = (RoseTree (x, biggest) [], x) go biggest (RoseTree x xs) = let sub = map (go biggest) xs (xs', largests) = unzip sub in (RoseTree (x, biggest) xs', max x (maximum largests)) t = pureMax exampleTree -- --------------------------------------------------------------------- impureMin :: (MonadFix m, Ord b) => (a -> m b) -> RoseTree a -> m (RoseTree (a, b)) impureMin f tree = do rec (t, largest) <- go largest tree return t where go smallest (RoseTree x []) = do b <- f x return (RoseTree (x, smallest) [], b) go smallest (RoseTree x xs) = do sub <- mapM (go smallest) xs b <- f x let (xs', bs) = unzip sub return (RoseTree (x, smallest) xs', min b (minimum bs)) budget :: String -> IO Int budget "Ada" = return 10 -- A struggling startup programmer budget "Curry" = return 50 -- A big-earner in finance budget "Dijkstra" = return 20 -- Teaching is the real reward budget "Howard" = return 5 -- An frugile undergraduate! inviteTree = RoseTree "Ada" [ RoseTree "Dijkstra" [] , RoseTree "Curry" [ RoseTree "Howard" []] ] ti = impureMin budget inviteTree simplemdo = mdo return 5
mpickering/ghc-exactprint
tests/examples/ghc710/RecursiveDo.hs
bsd-3-clause
1,688
5
12
420
709
341
368
39
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} -- | This module provides styles for borders as used in terminal -- applications. Your mileage may vary on some of the fancier styles -- due to varying support for some border characters in the fonts your -- users may be using. Because of this, we provide the 'ascii' style in -- addition to the Unicode styles. The 'unicode' style is also a safe -- bet. -- -- To use these in your widgets, see -- 'Brick.Widgets.Core.withBorderStyle'. By default, widgets rendered -- without a specified border style use 'unicode' style. module Brick.Widgets.Border.Style ( BorderStyle(..) , borderStyleFromChar , ascii , unicode , unicodeBold , unicodeRounded , defaultBorderStyle ) where import GHC.Generics import Control.DeepSeq -- | A border style for use in any widget that needs to render borders -- in a consistent style. data BorderStyle = BorderStyle { bsCornerTL :: Char -- ^ Top-left corner character , bsCornerTR :: Char -- ^ Top-right corner character , bsCornerBR :: Char -- ^ Bottom-right corner character , bsCornerBL :: Char -- ^ Bottom-left corner character , bsIntersectFull :: Char -- ^ Full intersection (cross) , bsIntersectL :: Char -- ^ Left side of a horizontal border intersecting a vertical one , bsIntersectR :: Char -- ^ Right side of a horizontal border intersecting a vertical one , bsIntersectT :: Char -- ^ Top of a vertical border intersecting a horizontal one , bsIntersectB :: Char -- ^ Bottom of a vertical border intersecting a horizontal one , bsHorizontal :: Char -- ^ Horizontal border character , bsVertical :: Char -- ^ Vertical border character } deriving (Show, Read, Eq, Generic, NFData) defaultBorderStyle :: BorderStyle defaultBorderStyle = unicode -- | Make a border style using the specified character everywhere. borderStyleFromChar :: Char -> BorderStyle borderStyleFromChar c = BorderStyle c c c c c c c c c c c -- |An ASCII border style which will work in any terminal. ascii :: BorderStyle ascii = BorderStyle { bsCornerTL = '+' , bsCornerTR = '+' , bsCornerBR = '+' , bsCornerBL = '+' , bsIntersectFull = '+' , bsIntersectL = '+' , bsIntersectR = '+' , bsIntersectT = '+' , bsIntersectB = '+' , bsHorizontal = '-' , bsVertical = '|' } -- |A unicode border style with real corner and intersection characters. unicode :: BorderStyle unicode = BorderStyle { bsCornerTL = '┌' , bsCornerTR = '┐' , bsCornerBR = '┘' , bsCornerBL = '└' , bsIntersectFull = '┼' , bsIntersectL = '├' , bsIntersectR = '┤' , bsIntersectT = '┬' , bsIntersectB = '┴' , bsHorizontal = '─' , bsVertical = '│' } -- |A unicode border style in a bold typeface. unicodeBold :: BorderStyle unicodeBold = BorderStyle { bsCornerTL = '┏' , bsCornerTR = '┓' , bsCornerBR = '┛' , bsCornerBL = '┗' , bsIntersectFull = '╋' , bsIntersectL = '┣' , bsIntersectR = '┫' , bsIntersectT = '┳' , bsIntersectB = '┻' , bsHorizontal = '━' , bsVertical = '┃' } -- |A unicode border style with rounded corners. unicodeRounded :: BorderStyle unicodeRounded = BorderStyle { bsCornerTL = '╭' , bsCornerTR = '╮' , bsCornerBR = '╯' , bsCornerBL = '╰' , bsIntersectFull = '┼' , bsIntersectL = '├' , bsIntersectR = '┤' , bsIntersectT = '┬' , bsIntersectB = '┴' , bsHorizontal = '─' , bsVertical = '│' }
sjakobi/brick
src/Brick/Widgets/Border/Style.hs
bsd-3-clause
4,464
0
8
1,680
536
352
184
83
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Text/Internal/Encoding/Utf16.hs" #-} {-# LANGUAGE MagicHash, BangPatterns #-} -- | -- Module : Data.Text.Internal.Encoding.Utf16 -- Copyright : (c) 2008, 2009 Tom Harper, -- (c) 2009 Bryan O'Sullivan, -- (c) 2009 Duncan Coutts -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : GHC -- -- /Warning/: this is an internal module, and does not have a stable -- API or name. Functions in this module may not check or enforce -- preconditions expected by public modules. Use at your own risk! -- -- Basic UTF-16 validation and character manipulation. module Data.Text.Internal.Encoding.Utf16 ( chr2 , validate1 , validate2 ) where import GHC.Exts import GHC.Word (Word16(..)) chr2 :: Word16 -> Word16 -> Char chr2 (W16# a#) (W16# b#) = C# (chr# (upper# +# lower# +# 0x10000#)) where !x# = word2Int# a# !y# = word2Int# b# !upper# = uncheckedIShiftL# (x# -# 0xD800#) 10# !lower# = y# -# 0xDC00# {-# INLINE chr2 #-} validate1 :: Word16 -> Bool validate1 x1 = x1 < 0xD800 || x1 > 0xDFFF {-# INLINE validate1 #-} validate2 :: Word16 -> Word16 -> Bool validate2 x1 x2 = x1 >= 0xD800 && x1 <= 0xDBFF && x2 >= 0xDC00 && x2 <= 0xDFFF {-# INLINE validate2 #-}
phischu/fragnix
tests/packages/scotty/Data.Text.Internal.Encoding.Utf16.hs
bsd-3-clause
1,368
0
11
335
248
140
108
24
1
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0"> <title>Deimos IO Help</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data> </view> </helpset>
oscarpicas/s2tbx
s2tbx-rapideye-reader/src/main/resources/org/esa/s2tbx/dataio/rapideye/docs/help.hs
gpl-3.0
770
68
18
165
281
143
138
-1
-1
import System.Posix.IO import System.IO showNBR = do v <- System.Posix.IO.queryFdOption 0 System.Posix.IO.NonBlockingRead putStr $ "NonBlockingRead = " ++ (show v) ++ "\n" main = do showNBR System.Posix.IO.setFdOption 0 System.Posix.IO.NonBlockingRead True showNBR
jimenezrick/unix
tests/queryfdoption01.hs
bsd-3-clause
272
2
10
38
93
46
47
9
1
import Primes import Data.Map (assocs) import Data.Array.ST import qualified Data.Array as A import Control.Monad import qualified Data.List as L import Data.List (permutations) import Data.List.Ordered (nub, sort) f = makeFactorizer 500000 primeFactorize n = runFactorization f n --solution n = -- where factors = getFactors $ factorize n replicateFactors :: Factorization -> [[Integer]] replicateFactors fact = L.nub $ permutations $ concatMap (\(p, k) -> replicate (fromIntegral k) (fromIntegral p)) asss where asss = assocs $ getFactors fact allSplits :: [Integer] -> [[[Integer]]] allSplits [f] = [[[f]]] allSplits (f:fs) = let rest = allSplits fs in (map ([f] :) rest) ++ (map (aggregate f) rest) where aggregate x ((l:ls):lss) = (x:l:ls) : lss -- aggregate _ [] = [] allFactorizations :: Integer -> [[Integer]] allFactorizations n = map (map product) splits where splits = concatMap allSplits $ replicateFactors fact fact = primeFactorize n newtype SumAndLength = SL { getSumAndLength :: (Integer, Integer) } deriving (Eq, Ord) instance Show SumAndLength where show (SL sl) = show sl getSum :: SumAndLength -> Integer getSum (SL (s, _)) = s getLength :: SumAndLength -> Integer getLength (SL (_, l)) = l sums :: Integer -> [SumAndLength] sums n = filter (\(SL (_, l)) -> l>1) all where all = map (\l -> SL (sum l, n - sum l + fromIntegral (length l))) $ allFactorizations n solutionsArr :: Int -> A.Array Int Int solutionsArr n = let n' = 2*n in runSTArray $ do sols <- newArray (2, n') maxBound forM_ [n',n'-1..2] $ \k -> do let ss = sums (fromIntegral k) forM_ ss $ \(SL (_, l)) -> do let l' = fromInteger l writeArray sols (fromInteger l) k return sols solutions :: Int -> [Int] solutions n = nub $ sort $ take (n-1) $ A.elems $ solutionsArr n answer n = sum $ solutions n main = print $ answer 12000
arekfu/project_euler
p0088/p0088_2.hs
mit
1,970
12
21
468
900
453
447
45
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE CPP #-} -- | Module to be shared between server and client. -- -- This module must be valid for both GHC and Fay. module Fay.Yesod where import Prelude #ifdef FAY import FFI #else import Fay.FFI #endif import Data.Data -- | A proxy type for specifying what type a command should return. The final -- field for each data constructor in a command datatype should be @Returns@. data Returns a = Returns deriving (Eq, Show, Read, Data, Typeable) -- | Call a command. call :: (Returns a -> command) -> (a -> Fay ()) -- ^ Success Handler -> Fay () call f g = ajaxCommand (f Returns) g -- ! Call a command, handling errors as well callWithErrorHandling :: (Returns a -> command) -> (a -> Fay ()) -- ^ Success Handler -> (Fay ()) -- ^ Failure Handler -> Fay () callWithErrorHandling f g h = ajaxCommandWithErrorHandling (f Returns) g h -- | Run the AJAX command. ajaxCommand :: Automatic command -> (Automatic a -> Fay ()) -- ^ Success Handler -> Fay () ajaxCommand = ffi "jQuery['ajax']({ url: window['yesodFayCommandPath'], type: 'POST', data: { json: JSON.stringify(%1) }, dataType: 'json', success : %2})" -- | Run the AJAX command, handling errors as well ajaxCommandWithErrorHandling :: Automatic command -> (Automatic a -> Fay ()) -- ^ Success Handler -> (Fay ()) -- ^ Failure Handler -> Fay () ajaxCommandWithErrorHandling = ffi "jQuery['ajax']({ url: window['yesodFayCommandPath'], type: 'POST', data: { json: JSON.stringify(%1) }, dataType: 'json', success : %2, error: %3})"
fpco/yesod-fay
Fay/Yesod.hs
mit
1,704
0
10
431
306
164
142
28
1
elementAt :: [a] -> Int -> a elementAt li i = li !! (i - 1)
mtnmts/Haskell99
src/99-problems/problem-3.hs
mit
60
0
8
16
43
21
22
2
1
module AvlMap ( TreeMap(), empty, getSize, insert, containsKey, getValueByKey, setValueByKey, deleteByKey, getValueByIndex, setValueByIndex, deleteByIndex, tryInsert, tryGetValueByKey, trySetValueByKey, tryDeleteByKey, tryGetValueByIndex, trySetValueByIndex, tryDeleteByIndex, toList ) where data TreeMap tKey tValue = Empty | Node { key :: tKey, value :: tValue, size :: Int, height :: Int, left :: TreeMap tKey tValue, right :: TreeMap tKey tValue} empty :: TreeMap tKey tValue empty = Empty getHeight :: TreeMap tKey tValue -> Int getHeight Empty = 0 getHeight Node { height = height } = height getSize :: TreeMap tKey tValue -> Int getSize Empty = 0 getSize Node { size = size } = size buildTree :: TreeMap tKey tValue -> tKey -> tValue -> TreeMap tKey tValue -> TreeMap tKey tValue buildTree left key value right = Node {key = key, value = value, size = (getSize left) + (getSize right) + 1, height = (max (getHeight left) (getHeight right)) + 1, left = left, right = right} balance :: TreeMap tKey tValue -> TreeMap tKey tValue balance Empty = Empty balance x = let getBalance :: TreeMap tKey tValue -> Int getBalance x = (getHeight (right x)) - (getHeight (left x)) in case (getBalance x) of 1 -> x 0 -> x -1 -> x 2 -> if (getBalance (right x)) == (-1) then rotateLeft (buildTree (left x) (key x) (value x) (rotateRight (right x))) else rotateLeft x -2 -> if (getBalance (left x)) == 1 then rotateRight (buildTree (rotateLeft (left x)) (key x) (value x) (right x)) else rotateRight x otherwise -> error "This is impossible" rotateLeft :: TreeMap tKey tValue -> TreeMap tKey tValue rotateLeft oldTop = let Node { key = oldTopKey , value = oldTopValue , left = oldTopLeft , right = oldTopRight } = oldTop -- to rotate left, top must be non empty Node { key = oldRightKey, value = oldRightValue, left = oldRightLeft, right = oldRightRight } = right oldTop -- to rotate left, right must be non empty newLeft = buildTree oldTopLeft oldTopKey oldTopValue oldRightLeft in buildTree newLeft oldRightKey oldRightValue oldRightRight rotateRight :: TreeMap tKey tValue -> TreeMap tKey tValue rotateRight oldTop = let Node { key = oldTopKey , value = oldTopValue , left = oldTopLeft , right = oldTopRight } = oldTop -- to rotate right, top must be non empty Node { key = oldLeftKey, value = oldLeftValue, left = oldLeftLeft, right = oldLeftRight } = left oldTop -- to rotate right, left must be non empty newRight = buildTree oldLeftRight oldTopKey oldTopValue oldTopRight in buildTree oldLeftLeft oldLeftKey oldLeftValue newRight insert :: (Ord tKey) => TreeMap tKey tValue -> tKey -> tValue -> TreeMap tKey tValue insert node key value = case (tryInsert node key value) of Just result -> result Nothing -> error "Cannot insert - key duplicated" tryInsert :: (Ord tKey) => TreeMap tKey tValue -> tKey -> tValue -> Maybe (TreeMap tKey tValue) tryInsert Empty key value = Just Node { key = key, value = value, size = 1, height = 1, left = Empty, right = Empty } tryInsert Node { key = nodeKey, value = nodeValue, left = left, right = right } insertKey insertValue = if insertKey > nodeKey then case tryInsert right insertKey insertValue of Just insertedRight -> Just (balance (buildTree left nodeKey nodeValue insertedRight)) Nothing -> Nothing else if insertKey == nodeKey then Nothing else case tryInsert left insertKey insertValue of Just insertedLeft -> Just (balance (buildTree insertedLeft nodeKey nodeValue right)) Nothing -> Nothing byKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> (TreeMap tKey tValue -> (b, TreeMap tKey tValue)) -> Maybe (b, TreeMap tKey tValue) byKey Empty _ _ = Nothing byKey node searchKey processFunction | searchKey < nodeKey = case (byKey nodeLeft searchKey processFunction) of (Just (processResult, processedLeft )) -> Just (processResult, balance (buildTree processedLeft nodeKey nodeValue nodeRight)) Nothing -> Nothing | searchKey > nodeKey = case (byKey nodeRight searchKey processFunction) of (Just (processResult, processedRight)) -> Just (processResult, balance (buildTree nodeLeft nodeKey nodeValue processedRight)) Nothing -> Nothing | searchKey == nodeKey = Just (processFunction node) | otherwise = error "This is impossible" where nodeKey = key node nodeValue = value node nodeLeft = left node nodeRight = right node tryGetValueByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> Maybe tValue tryGetValueByKey node searchKey = case (byKey node searchKey (\foundNode -> (value foundNode, foundNode))) of Just (foundValue, _) -> Just foundValue Nothing -> Nothing getValueByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> tValue getValueByKey node searchKey = case (tryGetValueByKey node searchKey) of Just result -> result Nothing -> error "Key not found" containsKey:: (Ord tKey) => TreeMap tKey tValue -> tKey -> Bool containsKey node searchKey = case (tryGetValueByKey node searchKey) of Just _ -> True Nothing -> False trySetValueByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> tValue -> Maybe (TreeMap tKey tValue) trySetValueByKey node searchKey replaceValue = case (byKey node searchKey (\foundNode -> ((), buildTree (left foundNode) (key foundNode) replaceValue (right foundNode)))) of Just (_,result) -> Just result Nothing -> Nothing setValueByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> tValue -> TreeMap tKey tValue setValueByKey node searchKey replaceValue = case (trySetValueByKey node searchKey replaceValue) of Just result -> result Nothing -> error "Key not found" deleteByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> ((tKey, tValue), TreeMap tKey tValue) deleteByKey node deleteKey = case (tryDeleteByKey node deleteKey) of Just result -> result Nothing -> error "Key not found" tryDeleteByKey :: (Ord tKey) => TreeMap tKey tValue -> tKey -> Maybe ((tKey, tValue), TreeMap tKey tValue) tryDeleteByKey node deleteKey = byKey node deleteKey (\foundNode -> ((key foundNode, value foundNode), deleteRootNode foundNode)) byIndex :: TreeMap tKey tValue -> Int -> (TreeMap tKey tValue -> (b, TreeMap tKey tValue)) -> Maybe (b, TreeMap tKey tValue) byIndex Empty _ _ = Nothing byIndex node index processFunction | index < split = case (byIndex nodeLeft index processFunction) of Just (processedResult, processedLeft ) -> Just (processedResult, balance (buildTree processedLeft nodeKey nodeValue nodeRight)) Nothing -> Nothing | index > split = case (byIndex nodeRight (index - split) processFunction) of Just (processedResult, processedRight) -> Just (processedResult, balance (buildTree nodeLeft nodeKey nodeValue processedRight)) Nothing -> Nothing | index == split = Just (processFunction node) where nodeKey = key node nodeValue = value node nodeLeft = left node nodeRight = right node split = (getSize nodeLeft) + 1 deleteByIndex :: TreeMap tKey tValue -> Int -> ((tKey, tValue), TreeMap tKey tValue) deleteByIndex node deleteIndex = case (tryDeleteByIndex node deleteIndex) of Just result -> result Nothing -> error "Index not found" tryDeleteByIndex :: TreeMap tKey tValue -> Int -> Maybe ((tKey, tValue), TreeMap tKey tValue) tryDeleteByIndex node deleteIndex = byIndex node deleteIndex (\foundNode -> ((key foundNode, value foundNode), deleteRootNode foundNode)) tryGetValueByIndex :: TreeMap tKey tValue -> Int -> Maybe tValue tryGetValueByIndex node searchIndex = case (byIndex node searchIndex (\foundNode -> (value foundNode, foundNode))) of Just (result, _) -> Just result Nothing -> Nothing getValueByIndex :: TreeMap tKey tValue -> Int -> tValue getValueByIndex node searchIndex = case (tryGetValueByIndex node searchIndex) of Just result -> result Nothing -> error "Index not found" trySetValueByIndex :: TreeMap Int tValue -> Int -> tValue -> Maybe (TreeMap Int tValue) trySetValueByIndex node searchIndex replaceValue = case (byIndex node searchIndex (\foundNode -> ((), buildTree (left foundNode) (key foundNode) replaceValue (right foundNode)))) of Just (_,result) -> Just result Nothing -> Nothing setValueByIndex :: TreeMap Int tValue -> Int -> tValue -> TreeMap Int tValue setValueByIndex node searchIndex replaceValue = case (trySetValueByIndex node searchIndex replaceValue) of Just result -> result Nothing -> error "Index not found" deleteRootNode :: TreeMap tKey tValue -> TreeMap tKey tValue deleteRootNode Empty = error "Unexpected 2" deleteRootNode Node {left = Empty, right = right} = right deleteRootNode Node {left = left, right = Empty} = left deleteRootNode node = balance (buildTree (left node) firstKey firstValue tree) where (firstKey, firstValue, tree) = deleteFirst (right node) deleteFirst :: TreeMap tKey tValue -> (tKey, tValue, TreeMap tKey tValue) deleteFirst Node {left = Empty, key = key, value = value, right = right} = (key, value, right) deleteFirst Node {left = left, key = key, value = value, right = right} = (resultKey, resultValue, balance (buildTree resultTreeMap key value right)) where (resultKey, resultValue, resultTreeMap) = (deleteFirst left) toList :: TreeMap tKey tValue -> [(tKey, tValue)] toList Empty = [] toList Node {left = left, key = key, value = value, right = right} = (toList left) ++ ((key, value): (toList right))
cshung/MiscLab
Haskell99/AvlMap.hs
mit
11,369
0
17
3,696
3,339
1,738
1,601
152
8
{-# htermination intersectFM_C :: (Ord a, Ord k) => (b1 -> b2 -> b3) -> FiniteMap (a,k) b1 -> FiniteMap (a,k) b2 -> FiniteMap (a,k) b3 #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_intersectFM_C_12.hs
mit
156
0
3
29
5
3
2
1
0
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified Graphics.UI.FLTK.LowLevel.FL as FL import Graphics.UI.FLTK.LowLevel.Fl_Types import Graphics.UI.FLTK.LowLevel.Fl_Enumerations import Graphics.UI.FLTK.LowLevel.FLTKHS import Data.IORef import qualified Data.Text as T import Control.Monad name :: [T.Text] name = ["X", "Y", "R", "start", "end", "rotate"] drawArc :: IORef [Double] -> Ref Widget -> IO () drawArc myArgsRef widget = do myArgs <- readIORef myArgsRef rectangle' <- getRectangle widget let (x',y',w',h') = fromRectangle rectangle' flcPushClip rectangle' flcSetColor dark3Color flcRectf rectangle' flcPushMatrix if (myArgs !! 5 > 0) then do flcTranslate (ByXY (ByX ((fromIntegral x') + (fromIntegral w')/2)) (ByY ((fromIntegral y') + (fromIntegral h')/2))) flcRotate (PreciseAngle (myArgs !! 5)) flcTranslate (ByXY (ByX (-((fromIntegral x') + (fromIntegral w')/2))) (ByY (-((fromIntegral y') + (fromIntegral h')/2)))) else return () flcSetColor whiteColor flcTranslate (ByXY (ByX (fromIntegral x')) (ByY (fromIntegral $ y'))) flcBeginComplexPolygon flcArcByRadius (PrecisePosition (PreciseX $ myArgs !! 0) (PreciseY $ myArgs !! 1)) (myArgs !! 2) (PreciseAngle (myArgs !! 3)) (PreciseAngle (myArgs !! 4)) flcGap flcArcByRadius (PrecisePosition (PreciseX 140) (PreciseY 140)) 20 (PreciseAngle 0) (PreciseAngle (-360)) flcEndComplexPolygon flcSetColor redColor flcBeginLine flcArcByRadius (PrecisePosition (PreciseX $ myArgs !! 0) (PreciseY $ myArgs !! 1)) (myArgs !! 2) (PreciseAngle (myArgs !! 3)) (PreciseAngle (myArgs !! 4)) flcEndLine flcPopMatrix flcPopClip setIndex :: Int -> [a] -> a -> [a] setIndex idx' xs x = map ( \(i,e) -> if (i == idx') then x else e ) (zip [0..] xs) sliderCb :: Ref Widget -> Int -> IORef [Double] -> Ref HorValueSlider -> IO () sliderCb widget sliderNumber myArgsRef slider' = do v' <- getValue slider' modifyIORef myArgsRef (\myArgs' -> setIndex sliderNumber myArgs' v') redraw widget main :: IO () main = do myArgs' <- newIORef [140, 140, 50, 0, 360,0] window' <- doubleWindowNew (Size (Width 300) (Height 500)) Nothing Nothing begin window' widget <- widgetCustom (Rectangle (Position (X 10) (Y 10)) (Size (Width 280) (Height 280))) Nothing (drawArc myArgs') defaultCustomWidgetFuncs forM_ (take 6 (zip (iterate ((+) 25) 300) [0..])) $ \(y, sliderNumber') -> do s <- horValueSliderNew (toRectangle $ (50, y, 240, 25)) (Just $ name !! sliderNumber') case sliderNumber' of sliderNumber'' | sliderNumber'' < 3 -> setMinimum s 0 >> setMaximum s 300 | sliderNumber'' == 5 -> setMinimum s 0 >> setMaximum s 360 _ -> setMinimum s (-360) >> setMaximum s 360 setStep s 1 _ <- readIORef myArgs' >>= \args' -> setValue s (args' !! sliderNumber') setAlign s alignLeft setCallback s (sliderCb widget sliderNumber' myArgs') end window' showWidget window' _ <- FL.run return ()
deech/fltkhs-demos
src/Examples/arc.hs
mit
3,179
0
21
757
1,270
639
631
94
2
import Network import System.Exit import System.IO import System.Environment import System.Directory import Numeric import Control.Concurrent import Data.String import Data.List main = do xs <- getArgs let seasonName = xs !! 1 currentPath <- getCurrentDirectory threadDelay 50000 -- Give the web server some time to download all files (?? Not sure how to make this work all the time) let path = (fixFullPath currentPath) ++ seasonName seasons <- listDirectory path files <- discoverFiles seasons path let arguments = map (show . verifiedLengths) files sendOrder 4445 (xs ++ arguments) -- |Function exists only to solve the strange pathing problems as a result of getCurrentDirectory function. fixFullPath :: FilePath -- ^ Result of getCurrentDirectory -> String -- ^ Complete path up until public directory fixFullPath p = do if last p == 'b' then p ++ "\\public\\" else p ++ "\\Web\\public\\" -- |Discovers files recently downloaded by web server. discoverFiles :: [FilePath] -- ^ List of season numbers -> String -- ^ Path of season folder -> IO [[FilePath]] -- ^ List of episode numbers organised by season discoverFiles seasons path = do let paths = sort seasons let paths' = map ((path ++ "/") ++) paths mapM listDirectory paths' -- |Counts episodes for all seasons. This mitigates the possibility of missing episodes after the api call has finished which could potentially corrupt the work of Slaves. verifiedLengths :: [FilePath] -- ^ List of episode numbers -> Int -- ^ Number of episodes actually downloadable verifiedLengths seasonEpisodes = do let episodeCount = length seasonEpisodes let verifiedEpisodes = takeWhile (\n -> elem (show n) seasonEpisodes) [1..episodeCount] length verifiedEpisodes {-| Sends the order received from web server to Master haskell process. -} sendOrder :: PortNumber -- ^ The port number used for communicating with master haskell process -> [String] -- ^ Arguments received in main from web server -> IO () sendOrder port xs = withSocketsDo $ do print $ "Connecting to Master @localhost:" ++ (show port) handle <- connectTo "localhost" (PortNumber port) hSetBuffering handle LineBuffering hPutStrLn handle (show xs) response <- hGetLine handle if response == "KO" then die "Master was unable to process request" else if response == "OK" then exitSuccess else die "Unexpected failure"
thomaslecointre/Distributed-Haskell
web/haskell/Messenger.hs
mit
2,606
1
15
642
526
258
268
52
3
module Sudoku where import Control.Arrow ((&&&)) import Data.Char (digitToInt) import Data.List (group, lines, minimumBy, nub, sort, splitAt, transpose) import System.IO -- basic function groupCnt xs = map (head &&& length) $ group $ sort xs minimumOn f xs = minimumBy (\x y -> compare (f x) (f y)) xs toSnd0 f a = (a, f a) toSnd f = map (toSnd0 f) -- 按段划分,类似于Python中的xs[::9] --splitSeg :: Int -> [Int] -> Mat splitSeg n [] = [] splitSeg n xs = h: splitSeg n t where (h, t) = splitAt n xs -- problem related type Mat = [[Int]] puzzle0 = [[5,3,0,0,7,0,0,0,0] ,[6,0,0,1,9,5,0,0,0] ,[0,9,8,0,0,0,0,6,0] ,[8,0,0,0,6,0,0,0,3] ,[4,0,0,8,0,3,0,0,1] ,[7,0,0,0,2,0,0,0,6] ,[0,6,0,0,0,0,2,8,0] ,[0,0,0,4,1,9,0,0,5] ,[0,0,0,0,8,0,0,7,9]] :: Mat puzzle3 = [[2,0,0,0,8,0,3,0,0] ,[0,6,0,0,7,0,0,8,4] ,[0,3,0,5,0,0,2,0,9] ,[0,0,0,1,0,5,4,0,8] ,[0,0,0,0,0,0,0,0,0] ,[4,0,2,7,0,6,0,0,0] ,[3,0,1,0,0,7,0,4,0] ,[7,2,0,0,4,0,0,6,0] ,[0,0,4,0,1,0,0,0,3]] :: Mat cands = [1..9] boxSize = 3 matSize = 9 rs = [0..8] mat2 = matSize * matSize -- 所有的位置坐标 poss = sequence [[0..(matSize - 1)], [0..(matSize - 1)]] -- 返回棋盘中对应的行或者列,或者所处的3x3的小方格 row, col :: Mat -> Int -> [Int] row m x = m !! x col m y = transpose m !! y regionN n x = take n [(roundN n x)..] where roundN n x = (x `div` n) * n box :: Mat -> Int -> Int -> [Int] box m x y = map (\(i:j:_) -> (m !! i) !! j) $ boxPos x y where boxPos x y = sequence [regionN boxSize x, regionN boxSize y] -- 找到所有的备选项 fcand :: Mat -> Int -> Int -> [Int] fcand m x y = filter (`notElem` c) cands where c = row m x ++ col m y ++ box m x y valid0 xs = all (\(x,c)->x==0||c<=1) $ groupCnt xs valid :: Mat -> Bool valid m = all valid0 (map (row m) rs ++ map (col m) rs) -- valid should check box type, too. But it works now, so no further improve updateCell :: Mat -> Int -> Int -> Int updateCell m x y | v /= 0 = v | v == 0 && length vs == 1 = head vs -- 只有在一个可选择结果的时候,直接选择 | otherwise = 0 where v = m !! x !! y vs = fcand m x y possCell :: Mat -> Int -> Int -> [Int] possCell m x y | v /= 0 = [v] | v == 0 = vs where v = m !! x !! y vs = fcand m x y rebuildMat :: [Int] -> Mat rebuildMat = splitSeg matSize -- 策略非常简单 -- 采用直接推断的方式: 同行同列同小格的元素不再出现,如果剩余备选项只有一个,则固定选择。 -- 否则,进入到下一个推测中 infer0 :: Mat -> Mat infer0 m = if nm == m then m else infer0 nm where nm = updateCand m updateCand m = rebuildMat . map (\(i:j:_) -> updateCell m i j) $ poss pgs mat = sum $ map (length . filter (/= 0)) mat -- given mat, return index and its candidates (its candidates is minimal) -- WARNING: minimum is fold1 function ,so it doesn't work on empty list minBranch :: Mat -> ([Int], [Int]) minBranch m = if null mc then ([],[]) else minimumOn (\(_,c) -> length c) mc where mc = filter (\(_,c) -> length c > 1) $ toSnd (\(i:j:_) -> possCell m i j) poss update xs n a = take n xs ++ [a] ++ drop (n + 1) xs update2 mat n m a = take n mat ++ [update (mat !! n) m a] ++ drop (n+1) mat possM m = if t == ([],[]) then [] else possMat m t where t = minBranch m possMat m (x:y:_, cs) = map (update2 m x y) cs sudoku :: Mat -> [Mat] sudoku m | pgs m0 == mat2 = [m0] | otherwise = filter valid $ concatMap sudoku $ possM m0 where m0 = infer0 m showMat m = do print "mat:" mapM_ print m test puzzle = do print "orignal puzzle" showMat puzzle print $ pgs puzzle print "solution" showMat $ head $ sudoku puzzle proc s = map (map (map digitToInt) . tail) $ splitSeg (matSize + 1) $ lines s topLeft3 m = (\(x:y:z:_) -> x * 100 + y * 10 + z) $ take 3 $ head m main = do s <- readFile "p096_sudoku.txt" --test $ (!! 0) $ proc s mapM_ showMat $ sudoku $ (!! 48) $ proc s --print $ topLeft3 $ head $ sudoku $ (!! 48) $ proc s print $ toSnd0 sum $ map (sum . map topLeft3 . sudoku) $ proc s
liuyang1/euler
Sudoku.hs
mit
4,356
0
14
1,192
2,230
1,236
994
100
2
{-# LANGUAGE CPP, DeriveDataTypeable, FlexibleContexts,OverloadedStrings, GeneralizedNewtypeDeriving, MultiParamTypeClasses , TemplateHaskell, TypeFamilies, RecordWildCards, DeriveGeneric, DeriveDataTypeable #-} module Tach.Migration.Acidic where
smurphy8/tach
core-types/tach-migration-acidic/src/Tach/Migration/Acidic.hs
mit
253
0
3
23
8
6
2
4
0
-- -- __ -- |__) _ _ | _ _ _ -- |__) (_) | ) | (_| | ) (_) -- _/ -- module Bonlang (module B) where import Bonlang.Lang as B import Bonlang.Lang.Numeric as B import Bonlang.Lang.Bool as B import Bonlang.Lang.Strings as B import Bonlang.Lang.Types as B import Bonlang.Lexer as B import Bonlang.Runtime as B import Bonlang.Runtime.Numeric as B import Bonlang.Runtime.Primitives as B import Bonlang.Runtime.Strings as B import Bonlang.Runtime.Types as B
charlydagos/bonlang
src/Bonlang.hs
mit
674
0
4
296
101
76
25
12
0
import Graphics.Gloss main = animate (InWindow "Dragon" (500, 500) (0, 0)) white (dragonAnime (0,0) (500,450)) dragonAnime a b t = Line (dragon a b !! (round t `mod` 20)) alterne :: [a] -> [a] alterne [] = [] alterne [a] = [a] alterne (y:x:xs) = alterne [y] ++ alterne xs combine :: (a -> b -> c) -> [a] -> [b] -> [c] combine f x [] = [] combine f [] y = [] combine f (x:xs) (y:ys) = [x `f` y] ++ combine f xs ys pasPascal :: [Integer] -> [Integer] pasPascal [] = [] pasPascal [x] = [x] ++ [x] pasPascal xs = zipWith (+) ([0] ++ xs) (xs ++ [0]) pascal :: [[Integer]] pascal = iterate pasPascal [1] --type Point = (Float, Float) --type Path = [Point] pointAIntercaler :: Point -> Point -> Point pointAIntercaler (xa,ya) (xb,yb) = ((xa + xb)/2 + (yb - ya)/2, (ya + yb)/2 + (xa-xb)/2) pasDragon :: Path -> Path pasDragon [] = [] pasDragon [x] = [x] pasDragon (x:y:z:xs) = x : pointAIntercaler x y : y : pointAIntercaler z y : pasDragon ([z] ++ xs) pasDragon (x:y:xs) = x : pointAIntercaler x y : pasDragon ([y] ++ xs) dragon :: Point -> Point -> [Path] dragon x y = iterate pasDragon ([x] ++ [y])
Debaerdm/L3-MIAGE
Programmation Fonctionnel/TP/TP2/alterne.hs
mit
1,108
4
10
229
740
375
365
26
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html module Stratosphere.ResourceProperties.IoTAnalyticsPipelineDeviceShadowEnrich where import Stratosphere.ResourceImports -- | Full data type definition for IoTAnalyticsPipelineDeviceShadowEnrich. See -- 'ioTAnalyticsPipelineDeviceShadowEnrich' for a more convenient -- constructor. data IoTAnalyticsPipelineDeviceShadowEnrich = IoTAnalyticsPipelineDeviceShadowEnrich { _ioTAnalyticsPipelineDeviceShadowEnrichAttribute :: Maybe (Val Text) , _ioTAnalyticsPipelineDeviceShadowEnrichName :: Maybe (Val Text) , _ioTAnalyticsPipelineDeviceShadowEnrichNext :: Maybe (Val Text) , _ioTAnalyticsPipelineDeviceShadowEnrichRoleArn :: Maybe (Val Text) , _ioTAnalyticsPipelineDeviceShadowEnrichThingName :: Maybe (Val Text) } deriving (Show, Eq) instance ToJSON IoTAnalyticsPipelineDeviceShadowEnrich where toJSON IoTAnalyticsPipelineDeviceShadowEnrich{..} = object $ catMaybes [ fmap (("Attribute",) . toJSON) _ioTAnalyticsPipelineDeviceShadowEnrichAttribute , fmap (("Name",) . toJSON) _ioTAnalyticsPipelineDeviceShadowEnrichName , fmap (("Next",) . toJSON) _ioTAnalyticsPipelineDeviceShadowEnrichNext , fmap (("RoleArn",) . toJSON) _ioTAnalyticsPipelineDeviceShadowEnrichRoleArn , fmap (("ThingName",) . toJSON) _ioTAnalyticsPipelineDeviceShadowEnrichThingName ] -- | Constructor for 'IoTAnalyticsPipelineDeviceShadowEnrich' containing -- required fields as arguments. ioTAnalyticsPipelineDeviceShadowEnrich :: IoTAnalyticsPipelineDeviceShadowEnrich ioTAnalyticsPipelineDeviceShadowEnrich = IoTAnalyticsPipelineDeviceShadowEnrich { _ioTAnalyticsPipelineDeviceShadowEnrichAttribute = Nothing , _ioTAnalyticsPipelineDeviceShadowEnrichName = Nothing , _ioTAnalyticsPipelineDeviceShadowEnrichNext = Nothing , _ioTAnalyticsPipelineDeviceShadowEnrichRoleArn = Nothing , _ioTAnalyticsPipelineDeviceShadowEnrichThingName = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-attribute itapdseAttribute :: Lens' IoTAnalyticsPipelineDeviceShadowEnrich (Maybe (Val Text)) itapdseAttribute = lens _ioTAnalyticsPipelineDeviceShadowEnrichAttribute (\s a -> s { _ioTAnalyticsPipelineDeviceShadowEnrichAttribute = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-name itapdseName :: Lens' IoTAnalyticsPipelineDeviceShadowEnrich (Maybe (Val Text)) itapdseName = lens _ioTAnalyticsPipelineDeviceShadowEnrichName (\s a -> s { _ioTAnalyticsPipelineDeviceShadowEnrichName = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-next itapdseNext :: Lens' IoTAnalyticsPipelineDeviceShadowEnrich (Maybe (Val Text)) itapdseNext = lens _ioTAnalyticsPipelineDeviceShadowEnrichNext (\s a -> s { _ioTAnalyticsPipelineDeviceShadowEnrichNext = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-rolearn itapdseRoleArn :: Lens' IoTAnalyticsPipelineDeviceShadowEnrich (Maybe (Val Text)) itapdseRoleArn = lens _ioTAnalyticsPipelineDeviceShadowEnrichRoleArn (\s a -> s { _ioTAnalyticsPipelineDeviceShadowEnrichRoleArn = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iotanalytics-pipeline-deviceshadowenrich.html#cfn-iotanalytics-pipeline-deviceshadowenrich-thingname itapdseThingName :: Lens' IoTAnalyticsPipelineDeviceShadowEnrich (Maybe (Val Text)) itapdseThingName = lens _ioTAnalyticsPipelineDeviceShadowEnrichThingName (\s a -> s { _ioTAnalyticsPipelineDeviceShadowEnrichThingName = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/IoTAnalyticsPipelineDeviceShadowEnrich.hs
mit
4,130
0
12
350
538
305
233
42
1
{-# LANGUAGE MultiParamTypeClasses #-} module HeapSort.Quiz where import Control.Applicative import Inter.Quiz import Inter.Types import HeapSort.Central import HeapSort.Tree import HeapSort.Data import HeapSort.Generator import Data.Typeable instance Generator HeapSort QuizConfig Config where generator p (QuizConfig fb k n min max) key = do -- IO Config fb <$> HeapSort.Generator.generate k n (min,max) instance Project HeapSort Config Config where project p = id make :: Make make = quiz HeapSort (QuizConfig OnFailure 3 7 1 100)
Erdwolf/autotool-bonn
src/HeapSort/Quiz.hs
gpl-2.0
560
0
10
98
161
87
74
17
1
{- | Module : $Id: h2hf.hs 13959 2010-08-31 22:15:26Z cprodescu $ Description : a test driver for Haskell to Isabelle HOLCF translations Copyright : (c) Christian Maeder, Uni Bremen 2002-2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : experimental Portability : non-portable(uses programatica) test translation from Haskell to Isabelle -} module Main where import System.Environment import Data.Char import Text.ParserCombinators.Parsec import Common.Result import Common.AnnoState import Common.AS_Annotation import Common.GlobalAnnotations import Common.ExtSign import Comorphisms.Hs2HOLCF import Isabelle.IsaPrint import Isabelle.IsaSign as IsaSign import Haskell.HatAna as HatAna import Haskell.HatParser pickParser :: (Continuity, Bool) -> AParser () (IsaSign.Sign, [Named IsaSign.Sentence]) pickParser c = do b <- hatParser let res@(Result _ m) = do (_, ExtSign sig _, sens) <- hatAna (b, HatAna.emptySign, emptyGlobalAnnos) transTheory (fst c) (snd c) sig sens case m of Nothing -> fail $ show res Just x -> return x main :: IO () main = do let err = "command line input error: first argument must be" ++ " either h (HOL), hc (HOLCF), mh (HOL with theory morphisms)," ++ " mhc (HOLCF with theory morphisms)." l <- getArgs case l of [] -> putStrLn err c : fs -> let elm = elem $ map toLower c in mapM_ (process (if elm ["h", "hol"] then (NotCont,False) else if elm ["hc", "holcf"] then (IsCont True,False) else if elm ["mh", "mhol"] then (NotCont,True) else if elm ["mhc", "mholcf"] then (IsCont True,True) else error err)) fs process :: (Continuity,Bool) -> FilePath -> IO () process c fn = do putStrLn $ "translating " ++ show fn ++ " to " ++ case c of (IsCont _,False) -> "HOLCF" (NotCont,False) -> "HOL" (IsCont _,True) -> "HOLCF with theory morphisms" (NotCont,True) -> "HOL with theory morphisms" s <- readFile fn case runParser (pickParser c) (emptyAnnos ()) fn s of Right (sig, hs) -> do let tn = takeWhile (/= '.') (reverse . takeWhile ( \ x -> x /= '/') $ reverse fn) ++ "_" ++ case c of (IsCont _,False) -> "hc" (NotCont,False) -> "h" (IsCont _,True) -> "mhc" (NotCont,True) -> "mh" nsig = sig {theoryName = tn} doc = printIsaTheory tn nsig hs thyFile = tn ++ ".thy" putStrLn $ "writing " ++ show thyFile writeFile thyFile (shows doc "\n") Left err -> putStrLn $ show err
nevrenato/Hets_Fork
Haskell/h2hf.hs
gpl-2.0
2,788
0
24
826
804
422
382
62
8
module VCGenerator where import SLParser import Z3.Monad import qualified Data.Map.Strict as Map import Control.Concurrent.STM.TVar import Control.Monad.IO.Class (liftIO) import Control.Monad.STM (atomically) -- | Data structure that keeps track of variables' AST nodes. type Identifiers = TVar (Map.Map String AST) -- | Function that generates VCs from SL annotations with an AST traversal. vcGen :: MonadZ3 z3 => SL -- ^ AST that resulted from Parse -> z3 ([AST],[AST]) -- ^ Declarations and Assertions resulting from annotation parse, in Z3 compatible format (Also SMT-Lib compatible) vcGen (WithBoth l prec posc pose) = do (iMap,attribs,sl') <- genericGen l res <- vcGen' iMap (WithBoth sl' prec posc pose) decls <- liftIO $ readTVarIO iMap return ((Map.elems decls),attribs++res) vcGen (WithPre l prec) = do (iMap,attribs,sl') <- genericGen l res <- vcGen' iMap (WithPre sl' prec) decls <- liftIO $ readTVarIO iMap return ((Map.elems decls),attribs++res) vcGen (WithPost l posc pose) = do (iMap,attribs,sl') <- genericGen l res <- vcGen' iMap (WithPost sl' posc pose) decls <- liftIO $ readTVarIO iMap return ((Map.elems decls),attribs++res) vcGen (Without l) = do (iMap,attribs,sl') <- genericGen l res <- vcGen' iMap (Without sl') decls <- liftIO $ readTVarIO iMap return ((Map.elems decls),attribs++res) -- | vcGen helper function that parses inner expressions and returns categorized structures. genericGen :: MonadZ3 z3 => [Expression] -- ^ List of expressions to be parsed -> z3 (Identifiers,[AST],[Expression]) -- ^ Tuple with `Identifiers` data structure, list of var attributions in Z3 compatible format and expressions to be parsed for VCs genericGen sl = do let (sls,decls) = foldr foldAux ([],[]) sl kvs <- foldr yafa (return []) decls imap <- liftIO $ newTVarIO (Map.fromList kvs) attribs <- mapM (\((DeclarationStatement _ val),ast) -> do { _val <- expression2VC imap val ;mkEq ast _val} ) $ zip decls (map snd kvs) return (imap,attribs,sls) where yafa (DeclarationStatement i val) acc = do accc <- acc newVar <- mkFreshIntVar i return $ (i,newVar):accc foldAux x@(DeclarationStatement a b) (s,d) = (s,x:d) foldAux x (s,d) = (x:s,d) -- | vcGen helper function that parses SL to generate VCs. vcGen' :: MonadZ3 z3 => Identifiers -- ^ Data structure with declared variables in SMT-Lib/Z3 format -> SL -- ^ SL AST tree to be parsed -> z3 [AST] -- ^ Resulting VCs in SMT-Lib/Z3 format vcGen' idents (WithBoth l prec posc _) = do x <- condition2VC idents prec y <- wp idents l posc ys <- vcAux idents l posc res <- mkImplies x y return (res:ys) vcGen' idents (Without l) = do x <- mkTrue y <- wp idents l (Boolean True) ys <- vcAux idents l (Boolean True) res <- mkImplies x y return (res:ys) vcGen' idents (WithPre l prec) = do x <- condition2VC idents prec y <- wp idents l (Boolean True) ys <- vcAux idents l (Boolean True) res <- mkImplies x y return (res:ys) vcGen' idents (WithPost l posc _) = do x <- mkTrue y <- wp idents l posc ys <- vcAux idents l posc res <- mkImplies x y return (res:ys) -- | `vcGen` helper function. vcAux :: MonadZ3 z3 => Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> [Expression] -- ^ List of Expressions to parse -> Condition -- ^ Q condition -> z3 [AST] -- ^ resulting list of VCs vcAux idents [] c = return [] vcAux idents ((AssignmentStatement _ _):[]) c = return [] vcAux idents ((Conditional b ct cf):[]) c = do x <- vcAux idents ct c y <- vcAux idents cf c return (x++y) vcAux idents ((Cycle b cc):[]) c = do inv <- mkTrue b' <- condition2VC idents b vc1esq <- mkAnd [inv,b'] vc1dir <- wp idents cc (Boolean True) vc1 <- mkImplies vc1esq vc1dir b'' <- condition2VC idents (Not b) vc2esq <- mkAnd [inv,b''] vc2dir <- condition2VC idents c vc2 <- mkImplies vc2esq vc2dir y <- vcAux idents cc (Boolean True) return ([vc1,vc2]++y) vcAux idents ((CycleInv b inv cc):[]) c = do inv' <- condition2VC idents inv b' <- condition2VC idents b vc1esq <- mkAnd [inv',b'] vc1dir <- wp idents cc inv vc1 <- mkImplies vc1esq vc1dir b'' <- condition2VC idents (Not b) vc2esq <- mkAnd [inv',b''] vc2dir <- condition2VC idents c vc2 <- mkImplies vc2esq vc2dir y <- vcAux idents cc inv return ([vc1,vc2]++y) vcAux idents (_:[]) _ = error "Not Implemented." vcAux idents (l:ls) c = do x <- vcAux idents [l] (wpcond idents ls c) y <- vcAux idents ls c return (x++y) -- | VCGen inner function that resembles one in the subject's slides with the same name. wp :: MonadZ3 z3 => Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> [Expression] -- ^ List of expressions to be parsed -> Condition -- ^ Q condition -> z3 AST -- ^ resulting VC wp idents a b = condition2VC idents $ wpcond idents a b -- | `wp` inner function that is responsible for the logic of the WP function, as described in the subject's slides. wpcond :: Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> [Expression] -- ^ Expressions to be parsed -> Condition -- ^ Q Condition -> Condition -- ^ Resulting Condition wpcond idents [] c = c wpcond idents ((AssignmentStatement s expr):[]) c = replaceQ idents s expr c wpcond idents ((Conditional b ct cf):[]) q = And (Or (Not b) (wpcond idents ct q)) (Or (Not (Not b)) (wpcond idents cf q)) wpcond idents ((Cycle b c):[]) q = Boolean True wpcond idents ((CycleInv b i c):[]) q = i wpcond idents (_:[]) q = error "Not implemented." wpcond idents (l:ls) q = wpcond idents [l] (wpcond idents ls q) -- | Function responsible for Q[x->e] action as described in `wp` definition replaceQ :: Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> String -- ^ Variable x to be replaced -> Expression -- ^ Value e to replace on x -> Condition -- ^ Q -> Condition -- ^ Resulting Q replaceQ idents s expr (And c1 c2) = And (replaceQ idents s expr c1) (replaceQ idents s expr c2) replaceQ idents s expr (Or c1 c2) = Or (replaceQ idents s expr c1) (replaceQ idents s expr c2) replaceQ idents s expr (Not c) = Not (replaceQ idents s expr c) replaceQ idents s expr (Equal exp1 exp2) = Equal (replaceExp idents s expr exp1) (replaceExp idents s expr exp2) replaceQ idents s expr (LessThan exp1 exp2) = LessThan (replaceExp idents s expr exp1) (replaceExp idents s expr exp2) replaceQ idents s expr (LessThanEqual exp1 exp2) = LessThanEqual (replaceExp idents s expr exp1) (replaceExp idents s expr exp2) replaceQ idents s expr (Boolean b) = Boolean b -- | `replaceQ` helper function that does Q[x->e] action on SL Expressions replaceExp :: Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> String -- ^ Variable x to be replaced -> Expression -- ^ Value e to replace on x -> Expression -- ^ Q -> Expression -- ^ Resulting Q replaceExp idents s expr (Constant i) = Constant i replaceExp idents s expr (Identifier ss) = if ss==s then expr else (Identifier ss) replaceExp idents s expr (Addition e1 e2) = Addition (replaceExp idents s expr e1) (replaceExp idents s expr e2) replaceExp idents s expr (Subtraction e1 e2) = Subtraction (replaceExp idents s expr e1) (replaceExp idents s expr e2) replaceExp idents s expr (Multiplication e1 e2) = Multiplication (replaceExp idents s expr e1) (replaceExp idents s expr e2) replaceExp idents s expr (Division e1 e2) = Division (replaceExp idents s expr e1) (replaceExp idents s expr e2) replaceExp idents s expr (Modulus e1 e2) = Modulus (replaceExp idents s expr e1) (replaceExp idents s expr e2) replaceExp idents s expr (Negation e) = Negation (replaceExp idents s expr e) replaceExp idents s expr (AssignmentStatement ss ex) = if ss==s then AssignmentStatement ss expr else AssignmentStatement ss ex replaceExp idents s expr (Cycle c ex) = Cycle (replaceQ idents s expr c) (map (\x -> (replaceExp idents s expr x)) ex) replaceExp idents s expr (CycleInv c1 c2 ex) = CycleInv (replaceQ idents s expr c1) (replaceQ idents s expr c2) (map (\x -> (replaceExp idents s expr x)) ex) replaceExp idents s expr (Conditional c ex1 ex2) = Conditional (replaceQ idents s expr c) (map (\x -> (replaceExp idents s expr x)) ex1) (map (\x -> (replaceExp idents s expr x)) ex2) replaceExp idents s expr _ = error "Not implemented." -- | Function that converts SL Condition to SMT-Lib/Z3 compatible AST node. condition2VC :: MonadZ3 z3 => Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> Condition -- ^ SL Condition to be parsed -> z3 AST -- ^ Resulting node condition2VC idents (And c1 c2) = do x <- condition2VC idents c1 y <- condition2VC idents c2 mkAnd [x,y] condition2VC idents (Or c1 c2) = do x <- condition2VC idents c1 y <- condition2VC idents c2 mkOr [x,y] condition2VC idents (Not c) = do x <- condition2VC idents c mkNot x condition2VC idents (Equal c1 c2) = do x <- expression2VC idents c1 y <- expression2VC idents c2 mkEq x y condition2VC idents (LessThan c1 c2) = do x <- expression2VC idents c1 y <- expression2VC idents c2 mkLt x y condition2VC idents (LessThanEqual c1 c2) = do x <- expression2VC idents c1 y <- expression2VC idents c2 mkLe x y condition2VC idents (Boolean True) = mkTrue condition2VC idents (Boolean False) = mkFalse -- | Function that converts SL Expression to SMT-Lib/Z3 compatible AST node. expression2VC :: MonadZ3 z3 => Identifiers -- ^ Auxiliary data structure that keeps track of variable declarations -> Expression -- ^ SL Expression to be parsed -> z3 AST -- ^ Resulting node expression2VC idents (Constant i) = mkInteger i expression2VC idents (Identifier s) = do iMap <- liftIO $ readTVarIO idents case (Map.lookup s iMap) of Nothing -> do x <- mkFreshIntVar s let newMap = Map.insert s x iMap liftIO $ atomically $ writeTVar idents newMap return x Just x -> return x expression2VC idents (Addition e1 e2) = do x <- expression2VC idents e1 y <- expression2VC idents e2 mkAdd [x,y] expression2VC idents (Subtraction e1 e2) = do x <- expression2VC idents e1 y <- expression2VC idents e2 mkSub [x,y] expression2VC idents (Multiplication e1 e2) = do x <- expression2VC idents e1 y <- expression2VC idents e2 mkMul [x,y] expression2VC idents (Division e1 e2) = do x <- expression2VC idents e1 y <- expression2VC idents e2 mkDiv x y expression2VC idents (Modulus e1 e2) = do x <- expression2VC idents e1 y <- expression2VC idents e2 mkMod x y expression2VC idents (Negation e) = do x <- expression2VC idents e mkUnaryMinus x expression2VC idents Throw = error "Throw not implemented."
jbddc/vf-verifier
src/VCGenerator.hs
gpl-3.0
11,349
0
16
2,744
4,038
1,979
2,059
228
3
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-} -- | -- Module : HSParedit -- Copyright : (c) Mateusz Kowalczyk 2013 -- License : GPL-3 -- -- Maintainer : fuuzetsu@fuuzetsu.co.uk -- Stability : experimental -- Portability : portable module HSParedit where import Data.Functor import Data.Monoid import Data.Tree import Data.Tree.Zipper import Data.Tree.Pretty import HSParedit.Types import HSParedit.Printer (toScheme) onTree :: (TreePos Full a -> TreePos Full b) -> Tree a -> Tree b onTree f = toTree . f . fromTree sc :: String -> Tree Code sc xs = Node CodeSymbol (map (\x -> Node (SymbolChar x) []) xs) basicTree :: Tree Code basicTree = Node { rootLabel = TopLevel , subForest = [ Node { rootLabel = RoundNode , subForest = [ sc "foo" , sc "bar" ] } , Node { rootLabel = RoundNode , subForest = [ sc "qux" , sc "quux" ] } ] } type EC = TreePos Empty Code type FC = TreePos Full Code zipTree :: TreePos Full Code zipTree = fromTree basicTree leftNodes :: TreePos Full a -> [Tree a] leftNodes = gatherSiblings prev . prev rightNodes :: TreePos Full a -> [Tree a] rightNodes = gatherSiblings next . next deleteRightNodes :: TreePos Full a -> TreePos Full a deleteRightNodes = deleteNodes next prevTree deleteLeftNodes :: TreePos Full a -> TreePos Full a deleteLeftNodes = deleteNodes prev nextTree -- | This function keeps deleting the neighbours picked with @f@ and @g@ -- one by one, refocusing on our original node at each deletion. -- Terminates when there are no more neigbours to remove. -- See 'deleteLeftNodes' and 'deleteRightNodes' for example usage. deleteNodes :: (TreePos Full a -> Maybe (TreePos Full a)) -- ^ Advance to next neighbour -> (TreePos Empty a -> Maybe (TreePos Full a)) -- ^ Move back to original node after deletion -> TreePos Full a -> TreePos Full a deleteNodes f g n = case f n of Nothing -> n -- no siblings left Just n' -> case g $ delete n' of Nothing -> n -- something went pretty damn wrong, return original Just n'' -> deleteNodes f g n'' gatherSiblings :: (TreePos Full a -> Maybe (TreePos Full a)) -> Maybe (TreePos Full a) -> [Tree a] gatherSiblings _ Nothing = [] gatherSiblings f (Just n) = tree n : gatherSiblings f (f n) openGeneric :: Code -> Either EC FC -> TreePos Full Code openGeneric c (Left t) = case parent t of Nothing -> insT c t -- We shouldn't be hitting no-parent case. Just p -> insT c $ nextSpace p openGeneric c (Right t) = case parent . delete $ deleteRightNodes t of Nothing -> insT c $ nextSpace t -- shouldn't happen Just p -> case label p of CodeSymbol -> insert (Node CodeSymbol siblings) (nextSpace . insT c $ nextSpace p) _ -> t -- Only split CodeSymbols now where -- Rememeber our neighbours siblings :: [Tree Code] siblings = tree t : rightNodes t insParens :: Tree Code -> Tree Code insParens code = undefined openRound :: Either EC FC -> TreePos Full Code openRound = openGeneric RoundNode openSquare :: Either EC FC -> TreePos Full Code openSquare = openGeneric SquareNode closeRound :: TreePos Full Code -> TreePos Empty Code closeRound = nextSpace insT :: Code -> TreePos Empty Code -> TreePos Full Code insT t = insert (Node t []) dr :: Tree Code -> IO () dr = putStrLn . drawVerticalTree . fmap show dt :: TreePos Full Code -> IO () dt = putStrLn . drawVerticalTree . fmap show . toTree
Fuuzetsu/hs-paredit
src/HSParedit.hs
gpl-3.0
3,945
0
15
1,256
1,085
550
535
71
4
chain :: (Integral a) => a -> [a] chain 1 = [1] chain n | even n = n:chain (n `div` 2) | odd n = n:chain (n*3 + 1) main :: IO() main = print $ length $ chain 8400511
dkensinger/haskell
Collatz.hs
gpl-3.0
178
6
9
53
142
65
77
7
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module System.Arte.MockData.FakeRat where import Control.Monad import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM import qualified Data.Aeson as A import Data.Bool (bool) import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy as BSL import Data.List import Data.Maybe import qualified Data.Serialize as S import Data.Time import GHC.Word import Network import Network.Socket import qualified Network.Socket.ByteString as BS import Pipes import Pipes.RealTime import System.Random import Data.Ephys.Position import Data.Ephys.TrackPosition import Types data State = State { sPos :: Location , sGoal :: Location } deriving (Eq, Show) locSum :: Location -> Location -> Location locSum (Location a b c) (Location x y z) = Location (a+x) (b+y) (c+z) locProd :: Double -> Location -> Location locProd c (Location x y z) = Location (x*c) (y*c) (z*c) locUnit :: Location -> Location locUnit (Location x y z) = let c = sqrt $ x^2 + y^2 + z^2 in Location (x/c) (y/c) (z/c) locDiff' :: Location -> Location -> Location locDiff' l l' = let (x,y,z) = locDiff l l' in Location x y z locMag :: Location -> Double locMag (Location x y z) = sqrt $ x^2 + y^2 + z^2 goal0 = (_location p0) goal n = goals !! (n `mod` 8) goals :: [Location] goals = map (\t -> Location (1.5 * cos t) (1.5 * sin t) 0.5) [pi/4, pi/2 .. 2*pi] stepPos' :: State -> IO State stepPos' (State p g) = do speed <- randomRIO (0.01,0.05) rndX <- randomRIO (0.01,0.05) rndY <- randomRIO (0.01,0.05) n <- randomRIO (0,7) let goalVec = locSum (locDiff' p g) (Location rndX rndY 0) runVec = locProd speed (locUnit goalVec) nextPos = locSum (p) runVec nextGoal = bool g toglGoal (locMag goalVec < 0.01) toglGoal = bool goal0 (goal n) (g == goal0) s' = State nextPos nextGoal print s' return s' p0 :: Position p0 = Position 0 (Location 0 0 0) (Angle 0 0 0) 0 0 ConfSure (replicate 5 0) (replicate 5 0) (0 - 0.03) (Location 0 0 0) streamFakePos :: DataSourceOpts -> IO () streamFakePos DataSourceOpts{..} = withSocketsDo $ do sock <- socket AF_INET Datagram defaultProtocol t0 <- getCurrentTime let saddr = SockAddrInet (fromIntegral myPort) iNADDR_ANY enc = case outputFormat of ArteBinary -> S.encode ArteJSON -> BSL.toStrict . A.encode destAddr <- SockAddrInet (fromIntegral (destPort :: Word32)) <$> inet_addr ipAddy let go p s = do s' <- stepPos' s now <- getCurrentTime let t' = realToFrac (diffUTCTime now t0) + realToFrac expStartTime p' = stepPos p t' (sPos s') (Angle 0 0 0) ConfSure print $ "Message: " ++ BS.unpack (enc p') BS.sendAllTo sock (enc (p')) destAddr threadDelay 30000 go p' s' destAddr <- SockAddrInet (fromIntegral (destPort :: Word32)) <$> inet_addr ipAddy bindSocket sock saddr go p0 (State (_location p0) (goal 1))
imalsogreg/arte-ephys
arte-mock-data/src/System/Arte/MockData/FakeRat.hs
gpl-3.0
3,408
0
19
1,046
1,259
654
605
88
2
-- | Benchmarks for Chapter 03. --module Chapter03.Chapter03Bench where import Chapter03.Concat import Criterion.Main xssLong :: [[Int]] xssLong = mkLists 100 main :: IO () main = defaultMain [ bgroup "concat" [ bench "concatN nf" (nf concatN xssLong) , bench "concatL nf" (nf concatL xssLong) , bench "concat3 nf" (nf concat3 xssLong) ] ]
capitanbatata/sandbox
fp-in-scala-in-haskell/bench/Chapter03Bench.hs
gpl-3.0
394
0
11
107
117
58
59
10
1
{-| Description : Tests for formatting based on source code files -} module Language.Haskell.Formatter.Tests (tests) where import qualified Control.Applicative as Applicative import qualified Control.Exception as Exception import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Language.Haskell.Formatter as Formatter import qualified Language.Haskell.Formatter.Toolkit.FileTesting as FileTesting import qualified Language.Haskell.Formatter.Toolkit.TestTool as TestTool import qualified System.FilePath as FilePath import qualified Test.Tasty as Tasty import qualified Test.Tasty.HUnit as HUnit tests :: IO Tasty.TestTree tests = Tasty.testGroup name Applicative.<$> FileTesting.fileTestForest create root where name = "Formatting files" root = "testsuite" FilePath.</> "resources" FilePath.</> "source" create :: Either Exception.IOException (Map.Map FilePath String) -> [Tasty.TestTree] create (Left exception) = [TestTool.testingError name $ show exception] where name = "I/O exception" create (Right testMap) = if actualKeys == expectedKeys then fileTests input expectedOutput else [TestTool.testingError name message] where actualKeys = Map.keysSet testMap expectedKeys = Set.fromList [inputKey, outputKey] input = testMap Map.! inputKey expectedOutput = testMap Map.! outputKey name = "Set of filenames" message = concat ["The filenames are ", setString actualKeys, " instead of ", setString expectedKeys, "."] setString = show . Set.elems inputKey :: FilePath inputKey = "Input.hs" outputKey :: FilePath outputKey = "Output.hs" fileTests :: String -> String -> [Tasty.TestTree] fileTests input expectedOutput = [HUnit.testCase "Formatting once" base, HUnit.testCase "Idempotence" idempotence] where base = testFormatting inputKey input expectedOutput idempotence = testFormatting outputKey expectedOutput expectedOutput testFormatting :: FilePath -> String -> String -> HUnit.Assertion testFormatting inputFile input expectedOutput = case Formatter.format configuration input of Left unexpectedError -> HUnit.assertFailure $ show unexpectedError Right actualOutput -> actualOutput HUnit.@?= expectedOutput where configuration = Formatter.defaultConfiguration{Formatter.configurationStreamName = inputStream} inputStream = Formatter.createStreamName inputFile
evolutics/haskell-formatter
testsuite/src/Language/Haskell/Formatter/Tests.hs
gpl-3.0
2,534
0
9
493
561
317
244
53
2
{-# LANGUAGE TemplateHaskell, ConstraintKinds #-} module Lamdu.Style ( Style(..) , base, autoNameOrigin, nameAtBinder, bytes, text, num , HasStyle ) where import qualified Control.Lens as Lens import qualified GUI.Momentu.Widgets.TextEdit as TextEdit import qualified GUI.Momentu.Widgets.TextView as TextView import Lamdu.Prelude data Style = Style { _base :: TextEdit.Style , _autoNameOrigin :: TextEdit.Style , _nameAtBinder :: TextEdit.Style , _bytes :: TextEdit.Style , _text :: TextEdit.Style , _num :: TextEdit.Style } Lens.makeLenses ''Style type HasStyle env = (Has TextEdit.Style env, Has TextView.Style env, Has Style env)
Peaker/lamdu
src/Lamdu/Style.hs
gpl-3.0
691
0
9
139
172
108
64
18
0
{-# 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.Vault.Operations.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes a long-running operation. This method indicates that the client -- is no longer interested in the operation result. It does not cancel the -- operation. If the server doesn\'t support this method, it returns -- \`google.rpc.Code.UNIMPLEMENTED\`. -- -- /See:/ <https://developers.google.com/vault G Suite Vault API Reference> for @vault.operations.delete@. module Network.Google.Resource.Vault.Operations.Delete ( -- * REST Resource OperationsDeleteResource -- * Creating a Request , operationsDelete , OperationsDelete -- * Request Lenses , odXgafv , odUploadProtocol , odAccessToken , odUploadType , odName , odCallback ) where import Network.Google.Prelude import Network.Google.Vault.Types -- | A resource alias for @vault.operations.delete@ method which the -- 'OperationsDelete' request conforms to. type OperationsDeleteResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Empty -- | Deletes a long-running operation. This method indicates that the client -- is no longer interested in the operation result. It does not cancel the -- operation. If the server doesn\'t support this method, it returns -- \`google.rpc.Code.UNIMPLEMENTED\`. -- -- /See:/ 'operationsDelete' smart constructor. data OperationsDelete = OperationsDelete' { _odXgafv :: !(Maybe Xgafv) , _odUploadProtocol :: !(Maybe Text) , _odAccessToken :: !(Maybe Text) , _odUploadType :: !(Maybe Text) , _odName :: !Text , _odCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationsDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'odXgafv' -- -- * 'odUploadProtocol' -- -- * 'odAccessToken' -- -- * 'odUploadType' -- -- * 'odName' -- -- * 'odCallback' operationsDelete :: Text -- ^ 'odName' -> OperationsDelete operationsDelete pOdName_ = OperationsDelete' { _odXgafv = Nothing , _odUploadProtocol = Nothing , _odAccessToken = Nothing , _odUploadType = Nothing , _odName = pOdName_ , _odCallback = Nothing } -- | V1 error format. odXgafv :: Lens' OperationsDelete (Maybe Xgafv) odXgafv = lens _odXgafv (\ s a -> s{_odXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). odUploadProtocol :: Lens' OperationsDelete (Maybe Text) odUploadProtocol = lens _odUploadProtocol (\ s a -> s{_odUploadProtocol = a}) -- | OAuth access token. odAccessToken :: Lens' OperationsDelete (Maybe Text) odAccessToken = lens _odAccessToken (\ s a -> s{_odAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). odUploadType :: Lens' OperationsDelete (Maybe Text) odUploadType = lens _odUploadType (\ s a -> s{_odUploadType = a}) -- | The name of the operation resource to be deleted. odName :: Lens' OperationsDelete Text odName = lens _odName (\ s a -> s{_odName = a}) -- | JSONP odCallback :: Lens' OperationsDelete (Maybe Text) odCallback = lens _odCallback (\ s a -> s{_odCallback = a}) instance GoogleRequest OperationsDelete where type Rs OperationsDelete = Empty type Scopes OperationsDelete = '[] requestClient OperationsDelete'{..} = go _odName _odXgafv _odUploadProtocol _odAccessToken _odUploadType _odCallback (Just AltJSON) vaultService where go = buildClient (Proxy :: Proxy OperationsDeleteResource) mempty
brendanhay/gogol
gogol-vault/gen/Network/Google/Resource/Vault/Operations/Delete.hs
mpl-2.0
4,677
0
15
1,071
699
410
289
98
1
-- This file is part of purebred -- Copyright (C) 2019 Róman Joost -- -- purebred is free software: you can redistribute it and/or modify -- it under the terms of the GNU Affero General Public License as published by -- the Free Software Foundation, either version 3 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 Affero General Public License for more details. -- -- You should have received a copy of the GNU Affero General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE FlexibleContexts #-} module Purebred.System ( tryIO , exceptionToError ) where import Control.Exception (IOException, try) import Control.Monad.Except (MonadError, throwError) import Control.Monad.IO.Class (MonadIO, liftIO) import Purebred.Types.Error -- | "Try" a computation but return a Purebred error in the exception case tryIO :: (MonadError Error m, MonadIO m) => IO a -> m a tryIO m = liftIO (try m) >>= either (throwError . exceptionToError) pure exceptionToError :: IOException -> Error exceptionToError = ProcessError . show
purebred-mua/purebred
src/Purebred/System.hs
agpl-3.0
1,295
0
8
216
162
99
63
12
1
-- applicative (<*> is pronounced "app" or "applicative") -- instance Applicative f for a Functor f -- has methods [pure, (<*>)] gs = [(*2), (+4), (\x -> 6*x - 10)] xs = [2..4] app_out = gs <*> xs -- bind (>>=) takes f :: a -> (b, c) and g :: b -> (d, c) -- and combines them like (g >>= f) x = (g.(fst f) x, c) -- where (g >>= f) :: a -> (d, c) -- f :: Int -> (Float, [Char]) -- f x = (3.0, "did f") -- -- g :: Float -> ([Char], [Char]) -- g y = (show y, "did g") h :: Int -> Maybe [Int] h x = if x < 6 then Just $ replicate 3 x else Nothing k :: [Int] -> Maybe Int k xs = let s = sum xs in if s >= 10 then Just s else Nothing -- (h 4) >>= k -- h 4 -> Just [4,4,4], then >>= takes Just [4,4,4] to [4,4,4] -- -- and feeds that to k as in "k [4,4,4] -> Just 16" -- -- (h 3) >>= k -- h 3 gives Just [3,3,3] but sum of that is 9 so k bound to that -- -- result gives Nothing -- -- (h 6) >>= k -- h 6 gives Nothing so k bound to it should also give nothing -- import System.Random -- randomIO >>= (\x -> putStrLn (show x)) -- https://wiki.haskell.org/Pronunciation -- Just 4 >> Just 3 -- gives Just 3 list_id_functor = (:[]) -- maps e.g. 1 -> [1] -- concatMap list_id_functor [1..5] -- gives [1..5] -- concatMap (list_id_functor . head) [[1..4], [2..4], [3..4]] -> [1..3] xxs = [[1..3], [2..3], [3]] -- xs >>= (list_id_functor . head) -> [1..3] -- the monad under consideration here is the List monad over Num and List of Num -- function (list_id_functor . head) takes a List of List of Num and gives a -- singular List of Num. Bind maps that over the List of List of Num and -- concats. -- Just 4 >>= (\x -> Just (x + 3)) -> Just 7 -- Nothing >>= (\x -> Just (x + 3)) -> Nothing -- i1 >> i1 = i1 >>= \_ -> i2 -- from: -- http://hackage.haskell.org/package/base-4.11.1.0/docs/src/GHC.Base.html#>> -- under "class Applicative m => Monad m where" -- guards for case statements f x | x < 0 = "less" | x > 0 = "more" | otherwise = "zero" f2 x | x == 0 = "zero" | x < 0 = "less" | x > 0 = "more" (+2) <$> [1..5] -- (<$>) :: Functor f => (a->b) -> f a -> f b [(+1), (+10)] <*> [1..5] -- (<*>) :: Applicative f => f (a->b) -> f a -> f b -- getName, when executed, will say hello, get a name, and repeat that name getName = putStrLn "hello" >> getLine >>= (\x -> putStrLn $ "hello " ++ x) -- execute repeatMe, then type "asdf" repeatMe = (readLn :: IO String) >>= print
ekalosak/haskell-practice
LearnMonad.hs
lgpl-3.0
2,415
0
9
569
409
239
170
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE TemplateHaskell #-} module Gossim.Internal.Logging ( MonadLogger(monadLoggerLog) , LoggingT , Loc , LogSource , LogLevel(LevelDebug, LevelInfo, LevelWarn, LevelError) , LogStr , ToLogStr(toLogStr) , Format , Only(Only) , Params , format , logDebug , logInfo , logWarn , logError , logGeneric , runStdoutLoggingT ) where import Language.Haskell.TH.Syntax (Lift (lift), Q, Exp, qLocation) import Control.Monad.Logger (MonadLogger(monadLoggerLog), LoggingT, Loc, LogSource, LogLevel(LevelDebug, LevelInfo, LevelWarn, LevelError), liftLoc, runStdoutLoggingT) import System.Log.FastLogger (LogStr, ToLogStr(toLogStr)) import Data.Text (Text) import Data.Text.Lazy (toStrict) import Data.Text.Format (Format, Only(Only)) import qualified Data.Text.Format as Fmt import Data.Text.Format.Params (Params) ------------------------------------------------------------------------------ format :: Params ps => Format -> ps -> Text format fmt = toStrict . Fmt.format fmt ------------------------------------------------------------------------------ logDebug :: Q Exp logDebug = logTH LevelDebug logInfo :: Q Exp logInfo = logTH LevelInfo logWarn :: Q Exp logWarn = logTH LevelWarn logError :: Q Exp logError = logTH LevelError logGeneric :: LogLevel -> Q Exp logGeneric = logTH logTH :: LogLevel -> Q Exp logTH level = [|\fmt -> monadLoggerLog $(qLocation >>= liftLoc) "" $(lift level) . format fmt|]
aartamonau/gossim
src/Gossim/Internal/Logging.hs
lgpl-3.0
1,820
0
7
486
375
236
139
60
1
{-# LANGUAGE OverloadedStrings #-} module RuleInfo.ExecutionRoot ( ExecutionRoot , executionRootPath , getExecutionRoot , fixFilePathFlags , toAbsolute , toAbsoluteT , fakeExecutionRoot -- For testing ) where import Control.Monad (guard) import Data.List.Extra (firstJust) import qualified Data.Text as T import Data.Text (Text) import Bazel (BazelOpts, bazelInfo) import System.FilePath ((</>)) newtype ExecutionRoot = ExecutionRoot FilePath getExecutionRoot :: BazelOpts -> IO ExecutionRoot getExecutionRoot opts = ExecutionRoot <$> bazelInfo opts "execution_root" -- | Construct an execution root from a filepath. Should be used for testing. fakeExecutionRoot :: FilePath -> ExecutionRoot fakeExecutionRoot = ExecutionRoot executionRootPath :: ExecutionRoot -> FilePath executionRootPath (ExecutionRoot f) = f -- | Some flags include google3-relative file paths, and they don't work with -- ghcide when invoked from a subdirectory of google3. Prepends them with the -- execution root directory. fixFilePathFlags :: ExecutionRoot -> [Text] -> [Text] fixFilePathFlags _ [] = [] -- Handles cases like "-foo" "bar". fixFilePathFlags root (f : arg : rest) | Just (prefix, path) <- filePathToFix f arg = f : prefix <> toAbsoluteT root path : fixFilePathFlags root rest -- Handles cases like "-foo=bar". fixFilePathFlags root (x : xs) | not (T.null arg), Just (prefix, path) <- filePathToFix f (T.drop 1 arg) = mconcat [f, "=", prefix, toAbsoluteT root path] : fixFilePathFlags root xs | otherwise = x : fixFilePathFlags root xs where (f, arg) = T.break (== '=') x -- | Converts the file path argument to an absolute path form. toAbsolute :: ExecutionRoot -> FilePath -> FilePath toAbsolute (ExecutionRoot root) f = root </> f -- | Converts the file path argument to an absolute path form. toAbsoluteT :: ExecutionRoot -> Text -> Text toAbsoluteT root = T.pack .toAbsolute root . T.unpack filePathToFix :: Text -> Text -> Maybe (Text, Text) filePathToFix curr next = firstJust matchFlag filePathFlags where matchFlag :: FilePathFlag -> Maybe (Text, Text) matchFlag (FPF s) = guard (curr == s) >> return ("", next) matchFlag (FPFPrefixed s prefix) = do guard (curr == s) next' <- T.stripPrefix prefix next return (prefix, next') data FilePathFlag = -- | Next flag is a file path. -- E.g., -pgmP some/path/clang ==> FPF "-pgmP" FPF Text | -- | Next flag is a file path prefixed with the second argument. -- E.g., -optP-isystem -optPsome/header/file.h -- ==> FPFPrefixed "-optP-isystem" "-optP" FPFPrefixed Text Text deriving (Show) -- | Flags that accept a file path as their argument. filePathFlags :: [FilePathFlag] filePathFlags = [ FPF "-opta--sysroot", FPF "-optc--sysroot", FPF "-optl--sysroot", FPF "-package-db", FPF "-pgmP", FPF "-pgma", FPF "-pgmc", FPF "-pgml", FPFPrefixed "-optP-isystem" "-optP", FPFPrefixed "-optP-iquote" "-optP" ]
google/hrepl
rule_info/RuleInfo/ExecutionRoot.hs
apache-2.0
3,013
1
12
591
737
396
341
61
2
data Triplet a = Trio a a a deriving (Show)
fbartnitzek/notes
7_languages/Haskell/triplet.hs
apache-2.0
43
0
6
9
22
12
10
1
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.RouteSpec where import GHC.Generics import Data.Text import Openshift.V1.ObjectReference import Openshift.V1.RoutePort import Openshift.V1.TLSConfig import qualified Data.Aeson -- | data RouteSpec = RouteSpec { host :: Text -- ^ optional: alias/dns that points to the service, must follow DNS 952 subdomain conventions , path :: Maybe Text -- ^ optional: path that the router watches to route traffic to the service , to :: ObjectReference -- ^ an object the route points to. only the service kind is allowed, and it will be defaulted to a service. , port :: Maybe RoutePort -- ^ port that should be used by the router; this is a hint to control which pod endpoint port is used; if empty routers may use all endpoints and ports , tls :: Maybe TLSConfig -- ^ provides the ability to configure certificates and termination for the route } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON RouteSpec instance Data.Aeson.ToJSON RouteSpec
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/RouteSpec.hs
apache-2.0
1,165
0
9
206
135
84
51
21
0
{- | Module : Cantor.Utils.List Copyright : Copyright (C) 2014 Krzysztof Langner License : BSD3 Helper module with functions operating on lists -} module Cantor.Utils.List ( commonPrefix , simplifyNames , splitByLast , takePrefix , unique ) where import Data.Set (fromList, toList) import Data.List (intercalate) import Data.List.Split (splitOn) -- Remove duplicates from list unique :: Ord a => [a] -> [a] unique = toList . fromList -- | Split by last given element splitByLast :: Eq a => [a] -> [a] -> ([a], [a]) splitByLast sep xs = (intercalate sep (init tokens), last tokens) where tokens = splitOn sep xs -- | find common prefix in list elements commonPrefix :: Eq a => [[a]] -> [a] commonPrefix [] = [] commonPrefix [x] = x commonPrefix (x:xs) = takePrefix x (commonPrefix xs) -- | Take common prefix from 2 lists takePrefix :: Eq a => [a] -> [a] -> [a] takePrefix (x:xs) (y:ys) | x == y = x : takePrefix xs ys takePrefix _ _ = [] -- | Simplify names by removing common prefix simplifyNames :: [String] -> [String] simplifyNames xs = map (drop n) xs where prefix = commonPrefix xs n = length prefix
klangner/cantor
src/Cantor/Utils/List.hs
bsd-2-clause
1,266
0
9
355
385
212
173
25
1
{-# LANGUAGE NoMonomorphismRestriction #-} module System.Find (find ,nonRecursiveFind ,grep ,anything ,hasExt ,withFind ,fOr,fAnd) where import System.Directory import System.Posix.Directory import System.Posix.Files import System.FilePath import System.Posix.Files import System.IO.Unsafe import Control.Monad import qualified Data.ByteString.Char8 as BS f' f x y z = do a <- x z b <- y z return (a `f` b) fAnd,fOr :: (a -> IO Bool) -> (a -> IO Bool) -> a -> IO Bool fOr = f' (||) fAnd = f' (&&) gluePaths a b = a </> b repath path = map (gluePaths path) isNotSymbolicLink path = getFileStatus path >>= return . not . isSymbolicLink anything :: (FilePath -> IO Bool) anything _ = return True hasExt e fp = return (ext == e) where ext = reverse . takeWhile (/= '.') . reverse $ fp grep test path = let test' = BS.pack test in do doesFileExist path >>= \x-> if x then BS.readFile path >>= return . BS.isInfixOf test' else return False noDots = filter (\x->x /= "." && x /= "..") ------------------------------------------------------------------------ expandDir p = getDirectoryContents p >>= return . repath p . noDots find' :: FilePath -> (FilePath -> IO Bool) -> (FilePath -> IO a) -> IO [a] find' path ff iodo = do cur <- catch (expandDir path) (\_->return []) files <- filterM doesFileExist cur >>= filterM ff >>= mapM iodo dirs <- filterM doesDirectoryExist cur dirs' <- filterM ff dirs >>= mapM iodo expanded <- fmap concat . mapM (\x->find' x ff iodo) $ dirs return (dirs' ++ files ++ expanded) find'' :: [FilePath] -> [a] -> (FilePath -> IO Bool) -> (FilePath -> IO a) -> IO [a] find'' [] out _ _ = return out find'' (x:xs) out ff iodo = do nout <- ff x >>= \ch -> if ch then iodo x >>= return . (flip (:) out) else return out isDir <- doesDirectoryExist x if isDir then (catch (expandDir x) (\_->return [])) >>= \y -> find'' (y ++ xs) nout ff iodo else find'' (xs) nout ff iodo withFind path ff iodo = find'' [path] [] ff iodo find path ff = find'' [path] [] ff return nonRecursiveFind path ff = expandDir path >>= filterM ff
jamessanders/hfind
System/Find.hs
bsd-2-clause
2,281
0
15
609
938
478
460
59
3
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-| Module : Grenade.Core.Network Description : Merging layer for parallel network composition Copyright : (c) Huw Campbell, 2016-2017 License : BSD2 Stability : experimental -} module Grenade.Layers.Merge ( Merge (..) ) where import Data.Serialize import Data.Singletons #if MIN_VERSION_base(4,9,0) import Data.Kind (Type) #endif import Grenade.Core -- | A Merging layer. -- -- Similar to Concat layer, except sums the activations instead of creating a larger -- shape. data Merge :: Type -> Type -> Type where Merge :: x -> y -> Merge x y instance (Show x, Show y) => Show (Merge x y) where show (Merge x y) = "Merge\n" ++ show x ++ "\n" ++ show y -- | Run two layers in parallel, combining their outputs. -- This just kind of "smooshes" the weights together. instance (UpdateLayer x, UpdateLayer y) => UpdateLayer (Merge x y) where type Gradient (Merge x y) = (Gradient x, Gradient y) runUpdate lr (Merge x y) (x', y') = Merge (runUpdate lr x x') (runUpdate lr y y') createRandom = Merge <$> createRandom <*> createRandom -- | Combine the outputs and the inputs, summing the output shape instance (SingI i, SingI o, Layer x i o, Layer y i o) => Layer (Merge x y) i o where type Tape (Merge x y) i o = (Tape x i o, Tape y i o) runForwards (Merge x y) input = let (xT, xOut) = runForwards x input (yT, yOut) = runForwards y input in ((xT, yT), xOut + yOut) runBackwards (Merge x y) (xTape, yTape) o = let (x', xB) = runBackwards x xTape o (y', yB) = runBackwards y yTape o in ((x', y'), xB + yB) instance (Serialize a, Serialize b) => Serialize (Merge a b) where put (Merge a b) = put a *> put b get = Merge <$> get <*> get
HuwCampbell/grenade
src/Grenade/Layers/Merge.hs
bsd-2-clause
2,180
0
10
562
610
330
280
37
0
module VFold where import CLaSH.Prelude csSort = vfold csRow where cs a b = if a > b then (a,b) else (b,a) csRow y xs = let (y',xs') = mapAccumL cs y xs in xs' :< y' topEntity :: Vec 4 Int -> Vec 4 Int topEntity = csSort testInput :: Signal (Vec 4 Int) testInput = pure (7 :> 3 :> 9 :> 1 :> Nil) expectedOutput :: Signal (Vec 4 Int) -> Signal Bool expectedOutput = outputVerifier ((1:>3:>7:>9:>Nil):>Nil)
ggreif/clash-compiler
tests/shouldwork/Vector/VFold.hs
bsd-2-clause
424
0
12
99
216
113
103
-1
-1
{-# LANGUAGE TupleSections #-} module Homoiconic.Common.TH where import Prelude import Control.Monad import Data.List import Data.Foldable import Data.Typeable import Data.Kind import GHC.Exts hiding (IsList(..)) import Language.Haskell.TH hiding (Type) import qualified Language.Haskell.TH as TH import Debug.Trace -------------------------------------------------------------------------------- renameClassMethod :: Name -> String renameClassMethod n = concatMap go $ nameBase n where go '+' = "plus" go '-' = "minus" go '.' = "dot" go '*' = "mul" go '/' = "div" go '=' = "eq" go '>' = "gt" go '<' = "lt" go x = [x] isOperator :: String -> Bool isOperator str = not $ length str == length (renameClassMethod $ mkName $ str) isVarT :: TH.Type -> Bool isVarT (VarT _) = True isVarT _ = False -- FIXME: -- This really needs to be in the Q monad to properly handle the AppT case. -- Right now, it returns incorrect results for any concrete type constructor being applied to anything. isConcrete :: TH.Type -> Bool isConcrete t = go t where go (VarT _) = False go (ConT _) = True go (ListT) = True go (AppT ListT _) = True go (AppT a1 a2) = go a1 && go a2 go _ = error ("go: t="++show t) isList :: TH.Type -> Bool isList ListT = True isList (AppT t _) = isList t isList _ = False -- | Given a type that stores a function: -- return a list of the arguments to that function, -- and discard the return value. getArgs :: TH.Type -> [TH.Type] getArgs (ForallT _ _ t) = getArgs t getArgs (AppT (AppT ArrowT t1) t2) = t1:getArgs t2 getArgs t = [] genericArgs :: TH.Type -> [Name] genericArgs (ForallT _ _ t) = genericArgs t genericArgs t = map (\i -> mkName $ "a"++show (i-1)) [1 .. length $ getArgs t] -- | Given a type that stores a function: -- return the return type of the function getReturnType :: TH.Type -> TH.Type getReturnType (ForallT _ _ t) = getReturnType t getReturnType (AppT (AppT ArrowT _) t2) = getReturnType t2 getReturnType t = t -- | Given a type with a single bound variable, -- substitute all occurances of that variable with a different variable. subForall :: Name -> TH.Type -> TH.Type subForall n (ForallT [v] _ t) = go t where go (AppT t1 t2) = AppT (go t1) (go t2) go (VarT _) = VarT n go t = t -- | Given a class name, find all the superclasses listSuperClasses :: Name -> Q [Name] listSuperClasses algName = do qinfo <- reify algName cxt <- case qinfo of ClassI (ClassD cxt _ _ _ _) _ -> return cxt _ -> error $ "listSuperClasses called on "++show algName++", which is not a class" ret <- forM cxt $ \pred -> case pred of (AppT (ConT c) (VarT v)) -> do ret <- listSuperClasses c return $ c:ret _ -> error $ "listSuperClasses, super class is too complicated: "++show pred return $ nub $ concat ret -- | Fiven a class name, find all the superclasses that are not also parents; -- for each superclass, record the parent class that gives rise to the superclass; -- if there are multiple ways to reach the superclass, -- then an arbitrary parent will be selected listSuperClassesWithParents :: Name -> Q [(Name,Name)] listSuperClassesWithParents algName = do parentClasses <- listParentClasses algName superClassesWithParents <- fmap concat $ forM parentClasses $ \parentClass -> do superClasses <- listSuperClasses parentClass return $ map (parentClass,) superClasses return $ nubBy (\(_,a1) (_,a2) -> a1==a2) superClassesWithParents -- | Given a class name, find all the parent classes listParentClasses :: Name -> Q [Name] listParentClasses algName = do qinfo <- reify algName cxt <- case qinfo of ClassI (ClassD cxt _ _ _ _) _ -> return cxt _ -> error $ "listParentClasses called on "++show algName++", which is not a class" ret <- forM cxt $ \pred -> case pred of (AppT (ConT c) (VarT v)) -> do return $ [c] _ -> error $ "listParentClasses, super class is too complicated: "++show pred return $ nub $ concat ret
mikeizbicki/homoiconic
src/Homoiconic/Common/TH.hs
bsd-3-clause
4,183
0
16
1,029
1,288
655
633
86
9
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-} {-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans -XCPP #-} {- | Module : $Header$ Description : SELinux kind-checking implementation Copyright : (c) Galois, Inc. Implementation of SELinux kind-checking algorithms. -} module SCD.M4.KindCheck ( KC , KindCheckOptions(..) , defaultKindCheckOptions , ignoreErrorsKindCheckOptions , Kind(..) , ParameterKind(..) , ParameterIndex(..) , HasKind(..) , Fragment(..) , KindMap , M4Info(..) , KindMaps(..) , InterfaceEnv(..) , kcPolicy , kcBaseEnv , KindInfo(..) , ClassPermissionMap , simpleKindSet , simpleParameterKind , simpleParameterInfo , normalizeId , IdXrefMap , T, P, Env ) where -- import Debug.Trace ( trace ) import SCD.M4.Kind import SCD.M4.KindInfo import SCD.M4.Errors(Error(..), nubError) import SCD.M4.Syntax(IfdefId, LevelId, MlsRange(..), M4Id, LayerModule, Policy(..), PolicyModule(..), Interface(..), InterfaceElement(..), InterfaceType(..), InterfaceDoc(..), Parameter, Stmt(..), Require(..), GenContext(..), FileContext(..), FileContexts(..), Implementation(..), SupportDef(..), ClassPermissionDef(..), GlobalBoolean(..), RefPolicyWarnLine(..), ModuleConfSetting(..), ModuleConf(..), required, IfdefDecl(..)) import SCD.M4.Util ( implementationId, elementId ) import qualified SCD.M4.Syntax as Syntax import SCD.SELinux.Syntax(Identifier, IsIdentifier(..), mkId, ClassId, CommonId, RoleId, PermissionId, TypeId, AllowDeny(..), AttributeId, TypeOrAttributeId, UserId, BoolId, Sid, NetInterfaceId, FileSystemId, CondExpr(..), SignedId(..), signedId2Id, Sign(..), NeverAllow(..), StarTilde(..), Self(..), Permissions(..), SourceTarget(..), SidContext(..), FileSystemUse(..), GenFileSystemContext(..), PortContext(..), NetInterfaceContext(..), NodeContext(..), FilePath(..), AvPerm(..), CommonPerm(..)) import SCD.M4.Options(Options(..)) import SCD.M4.Dependencies(sortCalls, callGraphPolicy, callGraphPolicyModules) import SCD.M4.PShow(PShow) import Prelude hiding (FilePath, mapM_, lookup) import Data.NonEmptyList(NonEmptyList) import Data.Maybe(isNothing, isJust, fromJust, fromMaybe) import Data.Map(Map, union, difference, elems, lookup, member, assocs, mapWithKey, insert, insertWith, fromListWith, findWithDefault, fromList, keys, keysSet, filterWithKey, findMax) import qualified Data.MapSet as MapSet import qualified Data.Map as Map import qualified Data.Set as Set import Data.Set(Set) import Data.Graph(SCC(..), graphFromEdges, dfs) import Data.Foldable(Foldable, mapM_, toList, foldlM) import Data.List ( genericLength, partition ) import Data.Monoid(Monoid) import Control.Arrow(first) import Control.Monad(when, zipWithM_) import Control.Monad.Identity(Identity, runIdentity) import Control.Monad.State(StateT, runStateT, MonadState, gets, modify) import Control.Monad.Writer(WriterT, runWriterT, MonadWriter, tell, censor) import Control.Monad.Reader(ReaderT, runReaderT, MonadReader, asks, local) --------------------------- data KindCheckOptions = KindCheckOptions { emitErrors :: Bool } deriving Show defaultKindCheckOptions :: KindCheckOptions defaultKindCheckOptions = KindCheckOptions{emitErrors = True} ignoreErrorsKindCheckOptions :: KindCheckOptions ignoreErrorsKindCheckOptions = defaultKindCheckOptions{emitErrors=False} newtype P r w s a = P (ReaderT r (StateT s (WriterT w Identity)) a) deriving (Monad, #ifndef __HADDOCK__ MonadState s, MonadWriter w, MonadReader r, #endif Functor) runP :: Monoid w => P r w s a -> s -> r -> ((a,s),w) runP (P p) s r = (runIdentity . runWriterT . flip runStateT s . flip runReaderT r) p type T a = P Env [Error] KindInfo a runT :: Options -> KindCheckOptions -> T a -> ((a,KindInfo),[Error]) runT os kcOpts t = getRes $ compRes $ runP t emptyKindInfo iEnv where getRes (a,errs) | not (emitErrors kcOpts) = (length errs) `seq` (a,[]) | otherwise = (a,errs) compRes (a, errs) = (a, nubError errs) iEnv = Env{ base = Map.empty , moduleConfigMap = Map.empty , source = False , options = os , kcOptions = kcOpts } type BaseEnv = KindMap data Env = Env{ base :: BaseEnv , moduleConfigMap :: ModuleConfigMap , source :: Bool , options :: Options , kcOptions :: KindCheckOptions } deriving Show type ModuleConfigMap = Map.Map Identifier ModuleConfSetting class KC a where kc :: a -> T () instance KC a => KC [a] where kc = mapM_ kc instance KC a => KC (NonEmptyList a) where kc = mapM_ kc instance KC a => KC (Maybe a) where kc (Just a) = kc a kc Nothing = return () {- Kind checking a list of modules 0. get initial environment support: file_patterns.spt, ipc_patterns.spt, misc_patterns.spt obj_perm_sets: how to type, when to expand? special: get env from policy_module def in loadable_module.spt mls_mcs_macros.spt ? 1. sort calls 2. kind-check definitions (templates and interfaces) 3. kind-check implementations and filecontexts -} {- == Checking a list of modules given a policy == Arguments: list of implementation files. * For each implementation file, parse corresponding interface file and file-context file. * Topologically sort the argument modules. * Form definition map from argument modules + policy * Kind check cs, keep only errors for argument modules (?) * Kind check implementation of argument modules Potential problems: + This will not capture duplicate module identifiers between argument modules and unreachable policy modules, or between argument interfaces and unreachable policy interfaces. + some illegal cross references will be reported as undefined identifers instead. -} -- | Performs kind-checking on a list of policy modules given a -- SELinux policy. If the list of policy modules is empty, kind check -- all the modules in the policy instead. kcPolicy :: Options -> KindCheckOptions -> Policy -> [PolicyModule] -> (KindInfo, [Error]) kcPolicy os kcOpts p pms = (s,e) where ((_,s),e) = runT os kcOpts checkPolicy checkPolicy = case pms of [] -> kcPolicy' p{policyModules=[]} (policyModules p) _ -> kcPolicy' p pms kcPolicy' :: Policy -> [PolicyModule] -> T () kcPolicy' p pms = do (_,be) <- baseEnv p -- build up a (ModuleName -> ModuleConfSetting) map. mcm <- (buildModuleConfigMap p :: T ModuleConfigMap) reportUnknownModules mcm p bi <- gets (outputMap . kindMaps . interfaceEnv) -- ..and a mapping from ifdef'ed values to enable flags. ifdefsMap <- buildIdMap (\ (IfdefDecl i v) -> (toId i, v)) (ifdefDecls p) modify $ \s -> s{ m4Env = m4Env s `union` fmap M4Ifdef ifdefsMap } local (\e -> e{ base = be, moduleConfigMap = mcm }) $ do groups <- sortModules p pms let apms = pms ++ policyModules p let dms = definitionMap p{ policyModules = apms} let mds = map fst (filter ((>1).length.snd) (assocs dms)) when (not (null mds)) $ kcError $ DuplicateDefinitions mds let dm = fmap head dms mapM_ (either kc kc . flip (findWithDefault (error "kcPolicyModules")) dm) groups mapM_ kcImplementation pms modify $ \ki -> ki{ xrefs = xrefOutputMaps ki apms } mapM_ (checkXrefDependencies bi) pms kcBaseEnv :: Options -> KindCheckOptions -> Policy -> ((ClassPermissionMap,BaseEnv), [Error]) kcBaseEnv os kcOpts p = (a,e) where ((a,_),e) = runT os kcOpts (baseEnv p) -- | Check for duplicate definitions in classes, sids, permissions, -- commons, and booleans. Return base environment, which is globally -- visible. baseEnv :: Policy -> T (ClassPermissionMap, BaseEnv) baseEnv p = do mapM_ kcAddOrigin (kernelClasses p) mapM_ kcAddOrigin (userClasses p) mapM_ kcAddOrigin (initialSids p) com <- foldlM commonPermissionMapEnv Map.empty (commonPerms p) clm <- foldlM (addAv com) Map.empty (Syntax.avPerms p) mapM_ (checkMissingAv clm) (kernelClasses p++userClasses p) genClassPerms clm mapM_ classPermissionDefEnv (classPermissionDefs p) mapM_ kcAddOrigin [b | GlobalBoolean _ _ b _ <- globalBooleans p] return (clm, computeBaseEnv p clm) sortModules :: Policy -> [PolicyModule] -> T [M4Id] sortModules p pms = do when (not (null cyclic_groups)) $ kcError $ MutuallyRecursive cyclic_groups return acyclic_groups where (cyclic_groups, acyclic_groups) = (\ (x,y) -> (map strip x, concatMap strip y)) $ partition isCyclicSCC css where strip (AcyclicSCC x) = [x] strip (CyclicSCC x) = x css = sortCalls subcg subcg -- check everything, including support definitions | null (policyModules p) = cg | otherwise = only_these_mods only_these_mods = fromList [ ces | (ces,_,_) <- concatMap (map fromV . toList) sorted] cg = callGraphPolicy p `MapSet.union` pmscg pmscg = callGraphPolicyModules pms sorted = dfs g (map (fromJust . toV) (keys pmscg)) (g,fromV,toV) = graphFromEdges [ ((c,es),c,map Left (toList es)) | (c,es) <- assocs cg ] isCyclicSCC :: SCC a -> Bool isCyclicSCC CyclicSCC{} = True isCyclicSCC _ = False -- | @buildModuleConfigMap@ constructs a mapping from modules mentioned in -- the toplevel module config file to their kinds (base/module/..) buildModuleConfigMap :: Policy -> T ModuleConfigMap buildModuleConfigMap p = buildIdMap (\ (ModuleConf i s) -> (toId i,s)) (modulesConf p) -- | @buildIdMap f ls@ is a local utility functions for building up -- new kinds of maps. Lifted into a monad so that we can track duplicates -- warnings\/errors as we go along. buildIdMap :: (a -> (Identifier,b)) -> [a] -> T (Map.Map Identifier b) buildIdMap f ls = foldlM (\m v -> case f v of { (i,x) -> addId m i x}) Map.empty ls reportUnknownModules :: ModuleConfigMap -> Policy -> T () reportUnknownModules mcm p | not (Set.null um) = kcError $ UnknownModuleConfigNames (Set.map fromId um) | otherwise = return () where -- report any of the modules in the map that don't -- have a corresponding composite policy module -- (i.e., the triple of interface/templates, .te, .fc) -- defined. um = (Set.\\) (keysSet mcm) (Set.fromList $ map (mkId . baseName) (policyModules p)) type CommonPermissionMap = Map CommonId (Set PermissionId) type ClassPermissionMap = Map ClassId (Set PermissionId) commonPermissionMapEnv :: CommonPermissionMap -> CommonPerm -> T CommonPermissionMap commonPermissionMapEnv com (CommonPerm c ps) | c `member` com = kcError (DuplicateCommonDef c (findOrig c com)) >> return com | otherwise = do ps' <- foldlM (addPerm (flip DuplicateCommonPermission c)) Set.empty (toList ps) return (insert c ps' com) addAv :: CommonPermissionMap -> ClassPermissionMap -> AvPerm -> T ClassPermissionMap addAv com clm (AvPermClass c eps) | (c `member` clm) = do kcError (DuplicateAccessVectorDefinition c (findOrig c clm)) return clm | otherwise = do (cps,nps) <- findPermissionSet eps -- add permission IDs to permission set, signalling -- any duplicates encountered. ps <- foldlM (addPerm (flip DuplicateClassPermission c)) cps nps return (insert c ps clm) where -- an AV permission class bundles a set of permissionIDs with a name. findPermissionSet (Left pids) = return (Set.empty, toList pids) findPermissionSet (Right (commonId, pids)) = case lookup commonId com of Nothing -> do kcError (UndefinedCommonId commonId) return (Set.empty, pids) Just cPermSet -> return (cPermSet, pids) addPerm :: (PermissionId -> Error) -> Set PermissionId -> PermissionId -> T (Set PermissionId) addPerm dupError cps p = do when (Set.member p cps) (kcError (dupError p)) ks <- lookupKind (toId p) let isPermKind = Set.member PermissionKind ks when (not isPermKind) (kcAddOrigin p) return (Set.insert p cps) -- TODO: use addId in more places. addId :: IsIdentifier i => Map i v -> i -> v -> T (Map i v) addId m i v = do when (i `member` m) $ kcError $ DuplicateIdentifier (toId i) (toId (findOrig i m)) return (insert i v m) checkMissingAv :: ClassPermissionMap -> ClassId -> T () checkMissingAv clm c = when (not (c `member` clm)) $ kcError $ MissingAccessVectorDefinition c genClassPerms :: ClassPermissionMap -> T () genClassPerms clm = mapM_ gen (assocs clm) where gen (c,ps) = addM4Env i (M4IdSet (Set.singleton PermissionKind) (Set.map toId ps) Nothing) where i = mkId ("all_"++idString c++"_perms") classPermissionDefEnv :: ClassPermissionDef -> T () classPermissionDefEnv (ClassPermissionDef i s ow) = do let lo (ps,ks) p = do ks' <- lookupKind p when (Set.null ks') $ kcError $ UndefinedIdentifier p when (Set.member p ps) $ kcError $ DuplicateOccurrences i p _ <- checkNotMacro p return (Set.insert p ps, Set.union ks ks') (ps,ks) <- foldlM lo (Set.empty, Set.empty) =<< expandSets Nothing s let i' = toId i addM4Env i' (M4IdSet ks ps ow) expandSets :: (PShow i, IsIdentifier i, Foldable l) => Maybe Kind -> l i -> T (Set i) expandSets k is = Set.unions `fmap` mapM (expandSet k) (toList is) expandSet :: (PShow i, IsIdentifier i) => Maybe Kind -> i -> T (Set i) expandSet mk i = do let i' = toId i mi <- lookupM4Env i' case mi of Just (M4IdSet ks is ow) -> do checkRefPolicyWarnMacro i' ow case mk of Nothing -> return () Just k -> when (not (k `Set.member` ks)) $ kcError $ KindMismatch k ks (toId i) return (Set.map fromId is) _ -> do return (Set.singleton i) checkRefPolicyWarnMacro :: Identifier -> (Maybe RefPolicyWarnLine) -> T () checkRefPolicyWarnMacro i (Just (RefPolicyWarnLine w)) = kcError $ RefPolicyWarnCall i [w] checkRefPolicyWarnMacro _ Nothing = return () checkNotMacro :: (PShow i, IsIdentifier i) => i -> T Bool checkNotMacro i = do let i' = toId i mi <- lookupM4Env i' case mi of Nothing -> return False Just _ -> do Just oi <- lookupOrigId i' kcError $ IllegalMacroUse (toId i) oi return True computeBaseEnv :: Policy -> ClassPermissionMap -> BaseEnv computeBaseEnv p clm = fromList (concat [mkEnv c ClassKind: [mkEnv p' PermissionKind | p' <- toList (MapSet.lookup c clm)] | c <- kernelClasses p]) `MapSet.union` systemBaseEnv where mkEnv i k = (i', Set.singleton (posKind i' k)) where i' = toId i systemBaseEnv :: BaseEnv systemBaseEnv = fromList $ map (uncurry mkEnv . first (mkId::String->Identifier)) [ -- mls_mcs_macros: ("mcs_systemhigh", LevelKind) , ("s0", LevelKind) , ("mls_systemhigh", LevelKind) -- roles: TODO: parse support/users instead. , ("system_r", RoleKind) , ("system_u", UserKind) , ("object_r", RoleKind) ] setInterfaceEnv :: InterfaceEnv -> T () setInterfaceEnv k = modify $ \s -> s{ interfaceEnv = k } addM4Env :: Identifier -> M4Info -> T () addM4Env i k = do km <- gets m4Env case k of M4Ifdef{} -> return () _ -> when (i `member` km) $ kcError $ DuplicateMacroDef i (findOrig i km) modify $ \s ->s{ m4Env = insert i k km } lookupM4Env :: Identifier -> T (Maybe M4Info) lookupM4Env i = do me <- gets m4Env return (lookup i me) lookupOrigId :: Identifier -> T (Maybe Identifier) lookupOrigId i = do me <- gets m4Env return (lookupKey i me) findOrig :: Ord k => k -> Map k a -> k findOrig k m = fromMaybe undefined (lookupKey k m) lookupKey :: Ord k => k -> Map k a -> Maybe k lookupKey k m = lookup k (mapWithKey const m) kcError :: Error -> T () kcError err = do o <- asks kcOptions if not (emitErrors o) then return () else tell [err] kcExtendError :: Error -> T a -> T a kcExtendError e m = do o <- asks kcOptions if not (emitErrors o) then m else do censor (\ds -> if null ds then [] else [ErrorsIn e ds]) m definitionMap :: Policy -> Map M4Id [Either InterfaceElement SupportDef] definitionMap p = fromListWith (++) ([(elementId e,[Left e]) | e <- concat [es | InterfaceModule _ es <- map interface (policyModules p)]] ++ [(i, [Right s]) | s@(SupportDef i _) <- supportDefs p]) instance KC InterfaceElement where kc (InterfaceElement it d i ss) = kcDefinition (it == InterfaceType) (Just d) i ss -- | @kcDefinition@ kind check an interface/template -- definition, ending up with a final 'InterfaceEnv' which -- we then associate with the interface id. kcDefinition :: KC a => Bool -> Maybe InterfaceDoc -> M4Id -> a -> T () kcDefinition isInterface mdoc i ss = kcExtendError (InDefinition i) $ do setInterfaceEnv emptyInterfaceEnv modify $ \s -> s{ parameterMap = Map.empty } -- process body of defintion... kc ss -- ..check in on what it produced ke <- gets interfaceEnv let km = simpleKindMaps (kindMaps ke) pil <- checkForErrors ke km let ke1 = ke{parameterInfo=pil} -- with any errors accounted for, record resulting interface environment. let ke_final | not isInterface = ke1{kindMaps=km} -- clear them for interfaces only (not templates.) | otherwise = ke1{ kindMaps = km{ iOutputMap = Map.empty , outputMap = Map.empty } } addM4Env (toId i) $ M4Macro ke_final where checkForErrors ke km = do pm <- gets parameterMap pil <- case mdoc of Nothing -> return (documentParameters [] pm) Just d -> do let ps = parameters d pil = documentParameters ps pm when (null (refpolicywarn ke) && any (isNothing . name) pil) $ kcError $ UndocumentedParameters i pil return pil reportUndefinedIds km reportUnusedArgs ke pil -- For output check: ignore identifiers that only define roles. let oks = MapSet.union (iOutputMap km) (outputMap km) let okeys = keysSet (Map.filter (Set.singleton (posKind' RoleKind) /=) oks) when (isInterface && not (Set.null okeys)) $ kcError $ IllegalSymbolDeclarations okeys return pil reportUnusedArgs ke pil | null (refpolicywarn ke) && any ((==unusedParameterKind) . parameterKinds) pil = kcError $ UnusedArguments i pil | otherwise = return () reportUndefinedIds km = do ir <- asks (implicitRequire.options) when (not ir && not (Map.null si)) $ do kcError $ UndefinedIds (kindMapElems si) where si = filterWithKey (const . isStatic) (inputMap km) unusedParameterKind :: Set ParameterKind unusedParameterKind = Set.singleton (ParameterKind Whole AnyKind) documentParameters ::[Parameter] -> ParameterMap -> [ParameterInfo] documentParameters ps pm = map doc (zip [1..max (genericLength ps) mx] (map Just ps++repeat Nothing)) where mx = if Map.null pm then 0 else fst (findMax pm) doc :: (ParameterIndex, Maybe Parameter) -> ParameterInfo doc (i,p) = ParameterInfo{ name = fmap Syntax.name p , optional = maybe False Syntax.optional p , parameterKinds = fromMaybe unusedParameterKind (lookup i pm) } instance KC SupportDef where kc (SupportDef i ss) = kcDefinition False Nothing i ss instance KC Stmt where kc (Tunable c s1 s2) = do kcCondExpr True c kcExtendError (WhenTunableTrue c) $ kc s1 kcExtendError (WhenTunableFalse c) $ kc s2 kc (Optional s1 s2) = kc s1 >> kc s2 kc (Ifdef c s1 s2) = kcIfdef c (kc s1) (kc s2) kc (Ifndef c s) = kcIfdef c (return ()) (kc s) kc (RefPolicyWarn wl) = modify $ \s -> s{ interfaceEnv = (interfaceEnv s){ refpolicywarn = refpolicywarn (interfaceEnv s)++[w] }} where RefPolicyWarnLine w = wl kc (Call i al) = kcCall i al kc (Role r tas) = kcAddOrigin r >> kcSource tas kc (RoleTransition rs tas r) = kc rs >> kcSource tas >> kc r kc (RoleAllow rs1 rs2) = kc rs1 >> kc rs2 kc (Attribute a) = kcAddOrigin a kc (Type t ts as) = kcAddOrigin t >> mapM_ kcAddOrigin ts >> kc as kc (TypeAlias t as) = kc t >> mapM_ kcAddOrigin as kc (TypeAttribute t as) = kc t >> kc as kc (RangeTransition tas1 tas2 cs mr) = kc tas1 >> kc tas2 >> kc cs >> kc mr kc (TeNeverAllow st ps) = kc st >> kc ps kc (Transition _ st t) = kc st >> kc t kc (TeAvTab av st ps) = kcAvTab av st ps -- kc st >> kc ps kc (CondStmt c s1 s2) = kcCondExpr False c >> kc s1 >> kc s2 kc (XMLDocStmt _) = return () kc (SidStmt c) = kc c kc (FileSystemUseStmt c) = kc c kc (GenFileSystemStmt c) = kc c kc (PortStmt c) = kc c kc (NetInterfaceStmt c) = kc c kc (NodeStmt c) = kc c kc (Define i) = addM4Env (toId i) (M4Ifdef (Just True)) kc (Require r) = kc r kc (GenBoolean _ i _) = kcAddOrigin i kcCall :: M4Id -> [NonEmptyList (SignedId Identifier)] -> T () kcCall i al = do mm <- lookupM4Env (toId i) case mm of Just (M4Macro m) -> checkMacro m _ -> kcError $ UndefinedCall i where checkMacro m = do when argMismatch $ do Just oi <- lookupOrigId (toId i) kcError $ WrongNumberOfArguments i pil oi when hasWarnings $ kcError $ RefPolicyWarnCall (toId i) warnings zipWithM_ kcParams (map parameterKinds pil) args_expanded updateAllowMap m args_expanded updateKindMaps m args_expanded [ (kcAddIInput', inputMap) , (kcAddIInput', iInputMap) , (kcAddIOut', outputMap) , (kcAddIOut', iOutputMap) ] where argMismatch = (length args_expanded < length mpil) || (length args_expanded > length pil ) hasWarnings = not (null warnings) warnings = refpolicywarn m pil = parameterInfo m mpil = takeWhile (not . optional) pil args_expanded = expandDollarStar (length pil) (map toList al) updateKindMaps :: InterfaceEnv -> [[SignedId Identifier]] -> [(Kind -> Identifier -> T a, KindMaps -> KindMap)] -> T () updateKindMaps m al ls = do mapM_ (\ (f,getMap) -> do kms <- substKindMap al (getMap (kindMaps m)) mapM_ (uncurry f) kms) ls -- Uses of a macro means importing updateAllowMap :: InterfaceEnv -> [[SignedId Identifier]] -> T () updateAllowMap m al = do let am = allowMap (kindMaps m) kms <- substAllowMap al am ke <- gets interfaceEnv setInterfaceEnv ke{ kindMaps=(kindMaps ke){ allowMap = foldl (\ amap (ai,i) -> MapSet.insert i ai amap) (allowMap (kindMaps ke)) kms}} {- TODO: * Scope rules for required types/attributes. * Only allow inputMap to refer to stuff declared in templates/implementation of the same module, and only through parameters. Whole parameters are OK. * Prune inputMap from illegal stuff to avoid follow-on errors. * Support definitions: empty inputMap except for parameters (special case of above). * Only allow requiring types/attributes generated in the same module. inputMap localMap prune from inputMap at calls whole parameters: yes yes fragmented/same yes yes fragmented/other no no static/same no yes yes static/other no no yes implementation/same yes yes implementation/other no no * tunable scope rules? * role .. types ... ? * Allow types/attributes before they are declared (but warn). * Distinguish between domain types and domain attributes. * Consider doing two passes over policy: 1. collect (i)OutputMap, compute xrefs 2. analyze rest (input, require) That way, we can check xref map as we directly refer to symbols according to the map above. * Associate interfaces with templates. * Refine IdXrefMap into Id -> Kind -> ... * Treatment of identifiers declared with different kinds. * warn, or * track origin better and fix checkSameId. * Treatment of declarations in branches. * Nicer layout of parameter types for group definitions. * Check file contexts etc. Define suitable scope rules. * Information flow inference. * Parse file "users", "rolemap". * Role declaration/use is a mess. -} {- sets of signed identifiers: examples: substitute { a b $1_c } for $1 of kind k = Whole TypeKind a -> k, b -> k, $1_c -> k { a $1_t } for $1_s of kind k = Fragment TypeKind a_s -> k, $1_t_s -> k subst apa(p) -> apa(p) subst apa_$1_bepa(p) -> apa_a_bepa(p) subst $1 -> a(q) if $1 is a(q) -} isStatic :: IsIdentifier i => i -> Bool isStatic = isJust . staticFragments . fragments . idString -- | To get the effect of a macro call, we take the effects of the macro and -- substitute for the actual parameters. substKindMap :: [[SignedId Identifier]] -> KindMap -> T [(Kind, Identifier)] substKindMap al rm = substMap al (\ k -> return $ getKind k) rm substAllowMap :: [[SignedId Identifier]] -> AllowMap -> T [(AllowInfo, Identifier)] substAllowMap al rm = substMap al upd rm where upd ai = do t' <- substId al (avTarget ai) -- note: don't substitute for other fields of AllowInfo. -- (class and perms.) return $ case t' of [] -> ai (x:_) -> ai{avTarget=x} substMap :: [[SignedId Identifier]] -> (a -> T b) -> Map Identifier (Set a) -> T [(b, Identifier)] substMap al getI rm = do sss <- mapM (substId al) (keys rm) let kss = elems rm mapM (\ (k,s) -> do v <- getI k return (v,s)) [ (k, s) | (ss,ks) <- zip sss kss, s <- ss, k <- toList ks ] substId :: [[SignedId Identifier]] -> Identifier -> T [Identifier] substId al i = do mapM_ (checkNoM4 i) $ fst fs:map snd (snd fs) return $ case wholeFragments fs of Just n -> fromMaybe [] (lookup n am) _ -> [mkId' (pos i) s | s <- substfs (fst fs) (snd fs)] where fs = fragments (idString i) substfs :: String -> [(ParameterIndex,String)] -> [String] substfs a [] = [a] substfs a ((n,b):r) = [a++ns++l | ns <- maybe [] (map idString) (lookup n am) , l <- substfs b r] am :: Map ParameterIndex [Identifier] am = fromList [(ParameterIndex ix,map signedId2Id (toList vs)) |(ix,vs) <- zip [1..] al] checkNoM4 :: Identifier -> String -> T () checkNoM4 vi s = when (not (null s)) $ do mi <- lookupM4Env (mkId s) when (isJust mi) $ kcError $ IllegalFragment s vi expandDollarStar :: Int -> [[SignedId Identifier]] -> [[SignedId Identifier]] expandDollarStar n [i] | simpleId i == Just dollarStar = [[SignedId Positive (mkId' (pos i') ("$"++show j))] | j <- [1..n]] where Just i' = simpleId i expandDollarStar _ al = al dollarStar :: Identifier dollarStar = mkId "$*" {- | kcParams: check that a parameter set kan take on all the parameterkinds in kis, and extend the parameterKinds environment. * only single positive parameters can take on fragment parameterkinds. * complex parameters can only take on whole parameterkinds. -} kcParams :: Set ParameterKind -> [SignedId Identifier] -> T () kcParams kis a = do mapM_ (kcParam kis) a let fragmentKinds = Set.filter ((==Fragment) . fragment) kis when (isNothing (simpleId a) && not (Set.null fragmentKinds)) $ kcError $ FragmentKindError a fragmentKinds simpleId :: [SignedId Identifier] -> Maybe Identifier simpleId [SignedId Positive i] = Just i simpleId _ = Nothing -- | kcParam :: Set ParameterKind -> SignedId Identifier -> T () kcParam kis = mapM_ (kcIdentifierParams kis) . m4Params . signedId2Id kcIdentifierParams :: Set ParameterKind -> (ParameterIndex, Fragment) -> T () kcIdentifierParams kis (i,f) = extendParameterKinds i kis' where frag pk | f == Fragment = pk{ fragment = Fragment } | otherwise = pk kis' = Set.map frag kis extendParameterKinds :: ParameterIndex -> Set ParameterKind -> T () extendParameterKinds i pk = modify $ \s->s{ parameterMap = insertWith Set.union i pk (parameterMap s) } kcIdentifierParam :: IsIdentifier i => Kind -> i -> T () kcIdentifierParam k i = mapM_ kcI (m4Params i) where kcI (j,f) = extendParameterKinds j (Set.singleton (ParameterKind f k)) -- | Get all the M4 parameter indices from a string, together with fragment information. m4Params :: IsIdentifier i => i -> [(ParameterIndex, Fragment)] m4Params i = [ (p, if isJust (wholeFragments fs) then Whole else Fragment) | (p,_) <- snd fs ] where fs = fragments (idString i) lookupKind' :: Identifier -> T (Set PosKind) lookupKind' i = do ke <- gets (kindMaps . interfaceEnv) me <- gets m4Env be <- asks base let f = MapSet.lookup i ks <- case lookup (fromId i) me of Just (M4IdSet ks _ ow) -> do checkRefPolicyWarnMacro i ow return (Set.map (posKind i) ks) _ -> return Set.empty return $ f be `Set.union` f (iOutputMap ke) `Set.union` f (outputMap ke) `Set.union` f (localMap ke) `Set.union` ks lookupKind :: Identifier -> T (Set Kind) lookupKind i = Set.map getKind `fmap` lookupKind' i kcAddIOut' :: (PShow i, IsIdentifier i) => Kind -> i -> T () kcAddIOut' = kcAddO' (\km f -> km{ iOutputMap = f (iOutputMap km) }) kcAddOrigin :: (PShow i, IsIdentifier i, HasKind i) => i -> T () kcAddOrigin i = kcAddOrigin' (iKind i) i kcAddOrigin' :: (PShow i, IsIdentifier i) => Kind -> i -> T () kcAddOrigin' = kcAddO' (\km f -> km{ outputMap = f (outputMap km) }) kcAddO' :: (PShow i, IsIdentifier i) => (KindMaps -> (KindMap -> KindMap) -> KindMaps) -> Kind -> i -> T () kcAddO' omap k i = do let i' = toId i pk = posKind' k ks <- lookupKind' i' let defined = pk `Set.member` ks when (defined && k /= RoleKind) $ do let PosKind p _ = head (filter (==pk) (Set.elems ks)) kcError $ DuplicateSymbolDeclaration (toId i) k (mkId' p (idString i)) when (not defined) $ do ke <- gets interfaceEnv setInterfaceEnv ke{ kindMaps = omap (kindMaps ke) (MapSet.insert i' (posKind i' k)) } _ <- checkNotMacro i kcIdentifierParam k i kcAddLocal :: (PShow i, IsIdentifier i, HasKind i) => i -> T () kcAddLocal i = kcAddLocal' (iKind i) i kcAddLocal' :: (PShow i, IsIdentifier i) => Kind -> i -> T () kcAddLocal' k i = do ke <- gets interfaceEnv let i' = toId i setInterfaceEnv ke{ kindMaps = (kindMaps ke){ localMap = MapSet.insert i' (posKind i' k) (localMap (kindMaps ke)) } } _ <- checkNotMacro i kcIdentifierParam k i kcAddIInput' :: (PShow i, IsIdentifier i) => Kind -> i -> T () kcAddIInput' = kcAddI' (\km f -> km{ iInputMap = f (iInputMap km) }) kcAddInput :: (PShow i, IsIdentifier i, HasKind i) => i -> T () kcAddInput i = kcAddInput' (iKind i) i kcAddInput' :: (PShow i, IsIdentifier i) => Kind -> i -> T () kcAddInput' = kcAddI' (\km f -> km{ inputMap = f (inputMap km) }) kcAddI' :: (PShow i, IsIdentifier i) => (KindMaps -> (KindMap -> KindMap) -> KindMaps) -> Kind -> i -> T () kcAddI' imap k i = do let i' = toId i subs = if k == TypeOrAttributeKind then Set.fromList [k, TypeKind, AttributeKind] else Set.fromList [k] ks <- lookupKind i' when (Set.null (subs `Set.intersection` ks)) $ do ke <- gets interfaceEnv setInterfaceEnv ke{ kindMaps = imap (kindMaps ke) (MapSet.insert i' (posKind i' k)) } kcIdentifierParam k i instance (KC s, KC t) => KC (SourceTarget s t) where kc (SourceTarget st tt cs) = do kcSource st kc tt kc cs kcAvTab :: AllowDeny -> SourceTarget (NonEmptyList (SignedId TypeOrAttributeId)) (NonEmptyList (SignedId Self)) -> Permissions -> T () kcAvTab Allow (SourceTarget st tt cs) ps = do kcSource st ke <- gets interfaceEnv -- somewhat inscrutable, but the next couple -- of bindings is simply ferreting out the Identifiers -- that hide insde the source, target, classes and perm let srcs = toSList st let tgts = toTList tt let cls = toIdList cs let psl = toPList ps -- list of AllowInfos to augment map with; one for -- each target, i.e., a target is associated with -- a set of classes and permissions allowed over them... let allows = map (\ t -> allowInfo t cls psl) tgts -- ...which we pair with the sources in the AV decl: let ais = map (\ s -> (s, allows)) srcs -- Having generated the associations from source -- to (target,perms) pairs, add them in to the -- AllowMap: let am = allowMap (kindMaps ke) let new_amap = foldr add am ais where -- add each (tgt,perms) pair to Set associated -- with the source domain 'i'. add (i,ails) s = foldr (MapSet.insert i) s ails setInterfaceEnv ke{kindMaps = (kindMaps ke){allowMap = new_amap}} -- check the targets and perms, as before. kc tt kc ps where toSList s = map (toId . signedId2Id) (toList s) toTList s = map toSelfId (toList s) toIdList = map toId . toList toPList (Permissions ls) = map toId $ toList ls toPList _ = [] toSelfId (SignedId _ Self) = mkId "self" toSelfId (SignedId _ (NotSelf i)) = toId i kcAvTab _ st ps = kc st >> kc ps kcSource :: KC a => a -> T () kcSource = local (\e -> e{ source = True }) . kc kcCondExpr :: Bool -> CondExpr -> T () kcCondExpr t (Not c) = kcCondExpr t c kcCondExpr t (Op c1 _ c2) = kcCondExpr t c1 >> kcCondExpr t c2 kcCondExpr t (Var b) = if t then kcAddLocal b else kcAddInput b instance KC Require where kc (RequireClass c ps) = do kcAddLocal c let k = iKind (head (toList ps)) expandSets (Just k) ps >>= mapM_ kcAddLocal kc (RequireRole rs) = mapM_ kcAddLocal rs kc (RequireType ts) = mapM_ kcAddLocal ts kc (RequireAttribute as) = mapM_ kcAddLocal as kc (RequireBool bs) = mapM_ kcAddLocal bs kc (RequireIfdef i t e) = kcIfdef i (kc t) (kc e) kc (RequireIfndef i e) = kcIfdef i (return ()) (kc e) instance KC ClassId where kc = kcAddInput instance KC PermissionId where kc = kcAddInput instance KC TypeId where kc = kcAddInput instance KC AttributeId where kc = kcAddInput instance KC Sid where kc = kcAddInput instance KC BoolId where kc = kcAddInput instance KC UserId where kc = kcAddInput instance KC RoleId where kc = kcAddInput instance KC NetInterfaceId where kc = kcAddInput instance KC FileSystemId where kc = kcAddInput instance KC LevelId where kc = kcAddInput instance KC TypeOrAttributeId where kc i = do s <- asks source kcAddInput' (if s then DomainKind else TypeOrAttributeKind) i kcIfdef :: IfdefId -> T () -> T () -> T () kcIfdef i t e = do let i' = toId i mm <- lookupM4Env i' case mm of Just (M4Ifdef (Just b)) -> if b then t else e Nothing -> do kcError $ UnknownIfdefId i mergeBranches t e _ -> mergeBranches t e -- TODO: figure out more efficient handling of branches mergeBranches :: T () -> T () -> T () mergeBranches t e = do let getBranched = do k <- gets (kindMaps . interfaceEnv) m <- gets m4Env return (k,m) (k,m) <- getBranched t bt <- getBranched modify $ \s -> s{ interfaceEnv = (interfaceEnv s){ kindMaps = k } , m4Env = m } e be <- getBranched mergeKindMaps bt be type BranchedState = (KindMaps, Map Identifier M4Info) mergeKindMaps :: BranchedState -> BranchedState -> T () mergeKindMaps (k1,m1) (k2,m2) = do checkBranchedOutputMaps (outputMap k1) (outputMap k2) checkBranchedOutputMaps (iOutputMap k1) (iOutputMap k2) let md = [ k | (k, i) <- assocs (difference m1 m2 `union` difference m2 m1) , case i of M4Ifdef _ -> False; _ -> True ] when (not (null md)) $ do kcError $ InconsistentMacroDefinitions md let mf s = MapSet.union (s k1) (s k2) km = KindMaps{ inputMap = mf inputMap , iInputMap = mf iInputMap , outputMap = mf outputMap , iOutputMap = mf iOutputMap , localMap = mf localMap , allowMap = mf allowMap } modify $ \s -> s{ interfaceEnv = (interfaceEnv s){ kindMaps = km } , m4Env = union m1 m2 } checkBranchedOutputMaps :: KindMap -> KindMap -> T () checkBranchedOutputMaps m1 m2 = do let _ds = kindMapElems (MapSet.difference m1 m2 `MapSet.union` MapSet.difference m2 m1) --when (not (null ds)) $ do -- kcError $ InconsistentSymbolDefinitions ds return () instance KC t => KC (SignedId t) where kc (SignedId _ t) = kc t instance KC a => KC (NeverAllow a) where kc (NeverAllow ts) = kc ts kc (NAStarTilde s) = kc s instance KC Permissions where kc (Permissions ps) = kc ps kc (PStarTilde st) = kc st instance KC i => KC (StarTilde i) where kc Star = return () kc (Tilde is) = kc is instance KC Self where kc (NotSelf t) = kc t kc Self = return () instance KC MlsRange where kc (MlsRange l1 l2) = kc l1 >> kc l2 instance KC a => KC (SidContext a) where kc (SidContext s c) = kc s >> kc c instance KC a => KC (PortContext a) where kc (PortContext _ _ _ s) = kc s instance KC a => KC (NetInterfaceContext a) where kc (NetInterfaceContext i s1 s2) = kcAddOrigin i >> kc s1 >> kc s2 instance KC a => KC (NodeContext a) where kc (NodeContext _ s) = kc s instance KC a => KC (FileSystemUse a) where kc (FSUseXattr f s) = kcAddOrigin f >> kc s kc (FSUseTask f s) = kcAddOrigin f >> kc s kc (FSUseTrans f s) = kcAddOrigin f >> kc s instance KC a => KC (GenFileSystemContext a) where kc (GenFSCon _ p _ s) = kc p >> kc s instance KC GenContext where kc (GenContext u r t m) = kc u >> kc r >> kc t >> kc m instance KC FileContext where kc (FileContext _ _ c) = kc c kc (FileContextIfdef i f1 f2) = kcIfdef i (kc f1) (kc f2) kc (FileContextIfndef i f) = kcIfdef i (return ()) (kc f) instance KC FilePath where kc (FilePath _) = return () instance KC FileContexts where kc (FileContexts fc) = kc fc kcImplementation :: PolicyModule -> T () kcImplementation m = kcExtendError (InImplementation lm) $ do case implementation m of Implementation mi _ ss -> do when (idString mi /= baseName m) $ kcError $ ModuleIdMismatch mi (baseName m) {- mmc <- lookup (mkId (baseName m)) `fmap` asks moduleConfigMap mc <- case mmc of Just c -> return c Nothing -> do kcError $ MissingModuleConfig mi return Module -} let mc = if required (moduleDoc (interface m)) then Base else Module setInterfaceEnv emptyInterfaceEnv modify $ \s -> s{ parameterMap = Map.empty } kc ss ke <- gets interfaceEnv let km = simpleKindMaps (kindMaps ke) ir <- asks (implicitRequire.options) when (not ir && mc /= Base) $ do let im = inputMap km when (not (Map.null im)) $ kcError $ UndefinedIds (kindMapElems im) let fcs = fileContexts m kc fcs pm <- gets parameterMap when (not (Map.null pm)) $ kcError $ IllegalParameterUse pm ie <- gets implEnv if (mi `member` ie) then kcError $ DuplicateIdentifier (toId mi) (toId (findOrig mi ie)) else modify $ \s->s{ implEnv = insert mi (simpleKindMaps km) ie } where lm = layerModule m checkXrefDependencies :: KindMap -> PolicyModule -> T () checkXrefDependencies bi pm = do mapM_ (checkXrefInterface bi lm) (interfaceElements (interface pm)) checkXrefImplementation bi lm (implementation pm) where lm = layerModule pm checkXrefInterface :: KindMap -> LayerModule -> InterfaceElement -> T () checkXrefInterface bi lm (InterfaceElement _ _ i _) = kcExtendError (InDefinition i) $ do me <- lookupM4Env (toId i) case me of Just (M4Macro ie) -> checkSameModule bi lm (kindMaps ie) _ -> return () checkXrefImplementation :: KindMap -> LayerModule -> Implementation -> T () checkXrefImplementation bi lm i = kcExtendError (InImplementation lm) $ do ie <- gets implEnv maybe (return ()) (checkSameModule bi lm) (lookup (implementationId i) ie) checkSameModule :: KindMap -> LayerModule -> KindMaps -> T () checkSameModule bi lm km = do checkSameMap (inputMap km) checkSameMap (localMap km) where checkSameMap :: KindMap -> T () checkSameMap = mapM_ checkSameId . keysSet checkSameId :: Identifier -> T () checkSameId i | isJust (wholeFragments (fragments (idString i))) = return () | otherwise = do be <- asks base when (Set.null (MapSet.lookup i bi) && Set.null (MapSet.lookup i be)) $ do xr <- gets xrefs let lms = [ (i',lm') | (i',lm',_,_,_) <- toList (MapSet.lookup (normalizeId (toId i)) xr) ] when (null (filter ((==lm) . snd) lms)) $ do let l = map snd (toList (Set.fromList [(pos j,j) | j <- map fst lms])) kcError $ if null l then UndefinedIdentifier i else IllegalSymbolReference i l
GaloisInc/sk-dev-platform
libs/SCD/src/SCD/M4/KindCheck.hs
bsd-3-clause
42,320
49
27
11,261
14,548
7,360
7,188
867
4
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.ARB.TextureEnvAdd -- Copyright : (c) Sven Panne 2013 -- License : BSD3 -- -- Maintainer : Sven Panne <svenpanne@gmail.com> -- Stability : stable -- Portability : portable -- -- All tokens from the ARB_texture_env_add extension, see -- <http://www.opengl.org/registry/specs/ARB/texture_env_add.txt>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.ARB.TextureEnvAdd ( -- * Tokens gl_ADD ) where import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility
mfpi/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/ARB/TextureEnvAdd.hs
bsd-3-clause
678
0
4
85
39
33
6
3
0
module Language.Ast ( Program(..) , Statement(..) , Block(..) , Element(..) , Application(..) , ApplicationArg(..) , Lambda(..) , LambdaBodyElement(..) , Func(..) , FuncArg(..) , Loop(..) , Assignment(..) , Expression(..) , Variable(..) , Value(..) , If(..) , Identifier ) where import Language.Interpreter.Scope ( ScopeStack ) newtype Program = Program [Statement] deriving (Eq, Show) data Statement = StLoop Loop | StAssign Assignment | StExpression Expression | StIf If | StFunc Func deriving (Eq, Show) newtype Block = Block [Element] deriving (Eq, Show) data Element = ElLoop Loop | ElAssign Assignment | ElExpression Expression | ElIf If deriving (Eq, Show) data Application = Application Variable [ApplicationArg] (Maybe Lambda) deriving (Eq, Show) data ApplicationArg = ApplicationSingleArg Expression | ApplicationSpreadArg Expression deriving (Eq, Show) data Loop = Loop Expression (Maybe Identifier) Block deriving (Eq, Show) data Assignment = AbsoluteAssignment Identifier Expression | ConditionalAssignment Identifier Expression deriving (Eq, Show) newtype If = If [(Expression, Block)] deriving (Eq, Show) data Lambda = Lambda [FuncArg] (Maybe (ScopeStack Identifier Value)) Block deriving (Eq, Show) data LambdaBodyElement = LambdaArgs [FuncArg] | LambdaElement Element deriving (Eq, Show) data Func = Func Identifier [FuncArg] Block deriving (Eq, Show) data FuncArg = VarArg Identifier Value | BlockArg Identifier deriving (Eq, Show) data Expression = EApp Application | BinaryOp String Expression Expression | UnaryOp String Expression | EVar Variable | EVal Value | EList [Expression] | EAccess Expression Expression deriving (Eq, Show) data Variable = LocalVariable Identifier | GlobalVariable Identifier deriving (Eq, Show) data Value = Number Float | Null | Symbol String | LambdaRef Lambda | VList [Value] | BuiltInFunctionRef Identifier deriving (Eq, Show) type Identifier = String
rumblesan/proviz
src/Language/Ast.hs
bsd-3-clause
2,230
0
10
589
659
392
267
97
0
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE OverloadedStrings #-} {-# Language DeriveDataTypeable #-} module Data.IHO.S52.Types.LookupTable ( LookupTable (..) , Record (..) , FTYP (..) , RPRI (..) , TNAM (..) ) where import Prelude hiding (take, takeWhile) import Data.Text (Text) import qualified Data.Text as T import Data.Int import Data.Attoparsec.Text import Data.IHO.S52.Types.Module import Data.IHO.S52.Types.Helper import Data.IHO.S52.Types.Symbology import Data.Data (Data) import Data.Typeable (Typeable) import Control.Lens import Data.Map (Map) import qualified Data.Map as Map data LookupTable data FTYP = Area | Point | Line deriving (Data, Typeable, Show, Eq) makeClassy ''FTYP parseFTYP :: Parser FTYP parseFTYP = do ftyp <- satisfy $ inClass "ALP" return $ case ftyp of 'A' -> Area 'L' -> Line 'P' -> Point _ -> error "unknown FTYP" data TNAM = PLAIN_BOUNDARIES | SYMBOLIZED_BOUNDARIES | LINES | SIMPLIFIED | PAPER_CHART deriving (Data, Typeable, Show, Eq) makeClassy ''TNAM data RPRI = OnTopOfRadar | SupressedByRadar deriving (Data, Typeable, Show, Eq) makeClassy ''RPRI tnamP t = try $ do _ <- string $ T.pack . show $ t ; return t parseTNAM :: FTYP -> Parser TNAM parseTNAM Area = choice [ tnamP PLAIN_BOUNDARIES , tnamP SYMBOLIZED_BOUNDARIES ] parseTNAM Line = choice [ tnamP LINES] parseTNAM Point = choice [ tnamP SIMPLIFIED , tnamP PAPER_CHART ] parseRPRI :: Parser RPRI parseRPRI = do rpri <- satisfy $ inClass "OS" return $ case rpri of 'O' -> OnTopOfRadar 'S' -> SupressedByRadar _ -> error "unknown RPRI" instance Module LookupTable where data Record LookupTable = LookupTableEntry { lupt_modn :: ! Text -- ^ Module Identifier (Module Name) , lupt_rcid :: ! Int16 -- ^ Record Identifier , lupt_stat :: ! Text -- ^ status of module contents , lupt_obcl :: ! Text -- ^ Name of the addressed object class , lupt_ftyp :: ! FTYP -- ^ Addressed Object Type , lupt_dpri :: ! Int16 -- ^ Display Priority , lupt_rpri :: ! RPRI -- ^ Radar Priority , lupt_tnam :: ! TNAM -- ^ Name of the addressed Look Up Table Set , lupt_attc :: ! (Map Text Text) -- ^ Attributes , lupt_inst :: ! [SymbologyCommand] -- ^ Symbology Information , lupt_disc :: ! Text -- ^ Display Category , lupt_lucm :: ! Text -- ^ Look-Up Comment } deriving (Show, Eq) module_modn = lupt_modn module_rcid = lupt_rcid module_stat = lupt_stat module_parser = do rcid' <- parseLine "0001" (take 5) (modn, rcid, stat, obcl, ftyp, dpri, rpri, tnam) <- parseLine "LUPT" $ do modn <- string "LU" rcid <- parseInt16 stat <- take 3 obcl <- take 6 ftyp <- parseFTYP dpri <- parseInt16 rpri <- parseRPRI tnam <- parseTNAM ftyp return (modn, rcid, stat, obcl, ftyp, dpri, rpri, tnam) attc <- parseLine "ATTC" $ many' $ do attl <- take 6 attv <- varString return (attl, attv) inst <- parseLine "INST" $ parseSymbology disc <- parseLine "DISC" $ varString lucm <- parseLine "LUCM" $ varString _ <- parseLine "****" endOfInput return $ LookupTableEntry { lupt_modn = modn , lupt_rcid = rcid , lupt_stat = stat , lupt_obcl = obcl , lupt_ftyp = ftyp , lupt_dpri = dpri , lupt_rpri = rpri , lupt_tnam = tnam , lupt_attc = Map.fromList attc , lupt_inst = inst , lupt_disc = disc , lupt_lucm = lucm }
alios/iho-presentation
Data/IHO/S52/Types/LookupTable.hs
bsd-3-clause
4,361
24
13
1,698
1,035
570
465
-1
-1
module Main where import Data.Map (Map) import qualified Data.Map as Map import Data.List (minimumBy, sort, transpose) import Data.Ord (comparing) -- A `Point` is a just a `List` of `Double` entries (a Euclidean vector): type Point = [Double] -- Computes the Euclidean distance between two points `a` and `b`. dist :: Point -> Point -> Double dist a b = undefined -- Returns a `Map`, which assigns each point from `points` to the closest -- centroid (taken from `centroids`). assign :: [Point] -> [Point] -> Map Point [Point] assign centroids points = undefined -- Replaces the centroid (key) in `centroidsMap` with the centroids -- computed from the points (value) in `centroidsMap`, thus returning. relocate :: Map Point [Point] -> Map Point [Point] relocate centroidsMap = undefined -- Performs the k-means algorithm kmeans :: [Point] -> [Point] -> [Point] kmeans centroids points = undefined main :: IO () main = do let points = [ [0, 0], [1, 0], [0,1], [1,1] , [7, 5], [9, 6], [8, 7] ] let centroids = kmeans (take 2 points) points print centroids
daniel-pape/haskell-meetup-k-means
src/Main.hs
bsd-3-clause
1,081
0
12
205
304
177
127
20
1
module Sexy.Instances.Show.Int () where import Sexy.Classes (Show(..)) import Sexy.Data (Int) import qualified Prelude as P instance Show Int where show = P.show
DanBurton/sexy
src/Sexy/Instances/Show/Int.hs
bsd-3-clause
166
0
6
26
56
36
20
6
0
{-| Description: SDL video subsystem. -} module Graphics.UI.SDL.Video ( module Keyboard , module KeyboardTypes , module OpenGL , module ScreenSaver , module Mouse , module Surface , module WMInfo , module Window ) where import Graphics.UI.SDL.Video.Keyboard as Keyboard import Graphics.UI.SDL.Video.Keyboard.Types as KeyboardTypes import Graphics.UI.SDL.Video.OpenGL as OpenGL import Graphics.UI.SDL.Video.ScreenSaver as ScreenSaver import Graphics.UI.SDL.Video.Mouse as Mouse import Graphics.UI.SDL.Video.Surface as Surface import Graphics.UI.SDL.Video.WMInfo as WMInfo import Graphics.UI.SDL.Video.Window as Window
abbradar/MySDL
src/Graphics/UI/SDL/Video.hs
bsd-3-clause
682
0
4
131
124
97
27
17
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE TemplateHaskell #-} module Check.Either where import qualified Data.List as P import qualified Data.Bifunctor as Bi import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range import qualified Prelude as P import Control.Applicative import Data.Either as P import Hedgehog import Hedgehog.Extra import Koan.Either as K import Prelude hiding (elem, filter) toK :: P.Either a b -> K.Either a b toK (P.Left a) = K.Left a toK (P.Right b) = K.Right b frK :: K.Either a b -> P.Either a b frK (K.Left a) = P.Left a frK (K.Right b) = P.Right b genEither :: Monad m => Gen m a -> Gen m b -> Gen m (P.Either a b) genEither genA genB = Gen.sized $ \n -> Gen.frequency [ (1 + fromIntegral n, P.Right <$> genB), (1 + fromIntegral n, P.Left <$> genA) ] genListEither = Gen.list (Range.linear 1 100) (genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded)) prop_isLeft :: Property prop_isLeft = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) K.isLeft (toK eab) === P.isLeft eab prop_isRight :: Property prop_isRight = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) K.isRight (toK eab) === P.isRight eab prop_lefts :: Property prop_lefts = property $ do leab <- forAll genListEither K.lefts (toK <$> leab) === P.lefts leab prop_rights :: Property prop_rights = property $ do leab <- forAll genListEither K.rights (toK <$> leab) === P.rights leab prop_either :: Property prop_either = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) K.either (*2) (+1) (toK eab) === P.either (*2) (+1) eab prop_partition :: Property prop_partition = property $ do leab <- forAll genListEither K.partition (toK <$> leab) === P.partitionEithers leab prop_mapEither :: Property prop_mapEither = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) frK (mapEither (*2) (toK eab)) === ((*2) P.<$> eab) prop_bimapEither :: Property prop_bimapEither = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) frK (bimapEither (+3) (*2) (toK eab)) === Bi.bimap (+3) (*2) eab prop_applyEitherRight :: Property prop_applyEitherRight = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) frK (applyEither (K.Right (*2)) (toK eab)) === (pure (*2) <*> eab) prop_applyEitherLeft :: Property prop_applyEitherLeft = property $ do eab <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) i <- forAll $ Gen.int Range.constantBounded let l = frK (applyEither (K.Left i) (toK eab)) :: P.Either Int Int let r = P.Left i <*> eab l === r prop_bindEither :: Property prop_bindEither = property $ do eabIn <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) eabOut <- forAll $ genEither (Gen.int Range.constantBounded) (Gen.int Range.constantBounded) frK (bindEither (const (toK eabOut)) (toK eabIn)) === (eabIn >>= (const eabOut)) tests :: IO Bool tests = checkSequential $ reversed $$(discover)
Kheldar/hw-koans
test/Check/Either.hs
bsd-3-clause
3,503
0
16
725
1,356
691
665
80
1
module Main where import Lib import Grammar import Tokens main = do content <- readFile "app/example" let tokens = scanTokens content let structure = parseTokenss tokens eval structure emptyDataStore
JCepedaVillamayor/functional-compiler
app/Main.hs
bsd-3-clause
209
0
10
38
60
29
31
9
1
{-# LANGUAGE CPP #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} -- |Random and Binary IO with generic Iteratees, using File Descriptors for IO. -- when available, these are the preferred functions for performing IO as they -- run in constant space and function properly with sockets, pipes, etc. module Data.Iteratee.IO.Fd( #if defined(USE_POSIX) -- * File enumerators -- ** FileDescriptor based enumerators for monadic iteratees enumFd ,enumFdCatch ,enumFdRandom ,enumFile ,enumFileRandom -- * Iteratee drivers ,fileDriverFd ,fileDriverRandomFd #endif ) where #if defined(USE_POSIX) import Data.Iteratee.Base.ReadableChunk import Data.Iteratee.Iteratee import Data.Iteratee.Binary() import Data.Iteratee.IO.Base import Control.Concurrent (yield) import Control.Monad import Control.Monad.Trans.Control import Control.Monad.Base import Control.Exception.Lifted import Foreign.Ptr import Foreign.Storable import System.IO (SeekMode(..)) import "unix-bytestring" System.Posix.IO.ByteString (tryFdSeek) -- ------------------------------------------------------------------------ -- Binary Random IO enumerators makefdCallback :: (MonadBase IO m, ReadableChunk s el) => ByteCount -> Fd -> Callback st m s makefdCallback bufsize fd st = do let fillFn p = fmap fromIntegral . fdReadBuf fd (castPtr p) . fromIntegral (s,numCopied) <- liftBase $ fillFromCallback (fromIntegral bufsize) fillFn case numCopied of 0 -> liftBase yield >> return (Finished st s) _n' -> return (HasMore st s) {-# INLINABLE makefdCallback #-} -- |The enumerator of a POSIX File Descriptor. This version enumerates -- over the entire contents of a file, in order, unless stopped by -- the iteratee. In particular, seeking is not supported. enumFd :: forall s el m a.(ReadableChunk s el, MonadBase IO m) => Int -> Fd -> Enumerator s m a enumFd bs fd = let bufsize = bs * (sizeOf (undefined :: el)) in enumFromCallback (makefdCallback (fromIntegral bufsize) fd) () {-# INLINABLE enumFd #-} -- |A variant of enumFd that catches exceptions raised by the @Iteratee@. enumFdCatch :: forall e s el m a.(IException e, ReadableChunk s el, MonadBase IO m) => Int -> Fd -> (e -> m (Maybe EnumException)) -> Enumerator s m a enumFdCatch bs fd handler iter = let bufsize = bs * (sizeOf (undefined :: el)) handlers = [IHandler handler, IHandler eofHandler] in enumFromCallbackCatches (makefdCallback (fromIntegral bufsize) fd) handlers () iter {-# INLINABLE enumFdCatch #-} -- |The enumerator of a POSIX File Descriptor: a variation of @enumFd@ that -- supports RandomIO (seek requests). enumFdRandom :: forall s el m a.(ReadableChunk s el, MonadBase IO m) => Int -> Fd -> Enumerator s m a enumFdRandom bs fd iter = enumFdCatch bs fd handler iter where handler (SeekException off) = liftM (either (const . Just $ enStrExc "Error seeking within file descriptor") (const Nothing)) . liftBase . tryFdSeek fd AbsoluteSeek $ fromIntegral off {-# INLINABLE enumFdRandom #-} fileDriver :: (MonadBaseControl IO m, ReadableChunk s el) => (Int -> Fd -> Enumerator s m a) -> Int -> Iteratee s m a -> FilePath -> m a fileDriver enumf bufsize iter filepath = bracket (liftBase $ openFd filepath ReadOnly Nothing defaultFileFlags) (liftBase . closeFd) (run <=< flip (enumf bufsize) iter) {-# INLINABLE fileDriver #-} -- |Process a file using the given @Iteratee@. fileDriverFd :: (MonadBaseControl IO m, ReadableChunk s el) => Int -- ^Buffer size (number of elements) -> Iteratee s m a -> FilePath -> m a fileDriverFd = fileDriver enumFd {-# INLINABLE fileDriverFd #-} -- |A version of fileDriverFd that supports seeking. fileDriverRandomFd :: (MonadBaseControl IO m, ReadableChunk s el) => Int -> Iteratee s m a -> FilePath -> m a fileDriverRandomFd = fileDriver enumFdRandom {-# INLINABLE fileDriverRandomFd #-} enumFile' :: (MonadBaseControl IO m, ReadableChunk s el) => (Int -> Fd -> Enumerator s m a) -> Int -- ^Buffer size -> FilePath -> Enumerator s m a enumFile' enumf bufsize filepath iter = bracket (liftBase $ openFd filepath ReadOnly Nothing defaultFileFlags) (liftBase . closeFd) (flip (enumf bufsize) iter) {-# INLINABLE enumFile' #-} enumFile :: (MonadBaseControl IO m, ReadableChunk s el) => Int -- ^Buffer size -> FilePath -> Enumerator s m a enumFile = enumFile' enumFd {-# INLINABLE enumFile #-} enumFileRandom :: (MonadBaseControl IO m, ReadableChunk s el) => Int -- ^Buffer size -> FilePath -> Enumerator s m a enumFileRandom = enumFile' enumFdRandom {-# INLINABLE enumFileRandom #-} #endif
JohnLato/iteratee
src/Data/Iteratee/IO/Fd.hs
bsd-3-clause
4,829
0
15
987
1,178
634
544
5
0
module Database.HDBC.ODBC.ConnectionImpl where import qualified Database.HDBC.Statement as Types import qualified Database.HDBC.Types as Types import Database.HDBC.ColTypes as ColTypes import Control.Exception (finally) data Connection = Connection { getQueryInfo :: String -> IO ([SqlColDesc], [(String, SqlColDesc)]), disconnect :: IO (), commit :: IO (), rollback :: IO (), run :: String -> [Types.SqlValue] -> IO Integer, prepare :: String -> IO Types.Statement, clone :: IO Connection, hdbcDriverName :: String, hdbcClientVer :: String, proxiedClientName :: String, proxiedClientVer :: String, dbServerVer :: String, dbTransactionSupport :: Bool, getTables :: IO [String], describeTable :: String -> IO [(String, ColTypes.SqlColDesc)], -- | Changes AutoCommit mode of the given connection. Returns previous value. setAutoCommit :: Bool -> IO Bool } instance Types.IConnection Connection where disconnect = disconnect commit = commit rollback = rollback run = run runRaw conn sql = do sth <- prepare conn sql Types.executeRaw sth `finally` Types.finish sth prepare = prepare clone = clone hdbcDriverName = hdbcDriverName hdbcClientVer = hdbcClientVer proxiedClientName = proxiedClientName proxiedClientVer = proxiedClientVer dbServerVer = dbServerVer dbTransactionSupport = dbTransactionSupport getTables = getTables describeTable = describeTable
hdbc/hdbc-odbc
Database/HDBC/ODBC/ConnectionImpl.hs
bsd-3-clause
1,683
0
13
504
370
218
152
41
0
{-# LANGUAGE ImplicitParams #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} module Tct.Trs.Strategy.Runtime ( runtime , runtime' , runtimeDeclaration ) where import Tct.Core import qualified Tct.Core.Data as T import Tct.Trs.Data import qualified Tct.Trs.Data.DependencyGraph as DG import qualified Tct.Trs.Data.Problem as Prob import qualified Tct.Trs.Data.Rules as RS import Tct.Trs.Processors import Tct.Trs.Processor.Matrix.MI as MI (mxeda, mxida) -- | Declaration for "derivational" strategy. runtimeDeclaration :: T.Declaration ('[T.Argument 'Optional CombineWith] T.:-> TrsStrategy) runtimeDeclaration = strategy "runtime" (T.OneTuple $ combineWithArg `T.optional` Fastest) runtimeStrategy -- | Default strategy for "runtime" complexity. runtime :: TrsStrategy runtime = T.deflFun runtimeDeclaration -- | A strategy for "runtime" complexity. runtime' :: CombineWith -> TrsStrategy runtime' = T.declFun runtimeDeclaration --- * direct --------------------------------------------------------------------------------------------------------- mx dim deg = matrix' dim deg Algebraic ?ua ?ur ?sel mxCP dim deg = matrixCP' dim deg Algebraic ?ua ?ur mxseda dim = MI.mxeda dim ?ua ?ur ?sel mxsida dim deg = MI.mxida dim deg ?ua ?ur ?sel px 1 = poly' Linear Restrict ?ua ?ur ?sel px n = poly' (Mixed n) Restrict ?ua ?ur ?sel pxCP 1 = polyCP' Linear Restrict ?ua ?ur pxCP n = polyCP' (Mixed n) Restrict ?ua ?ur -- mx _ = ax 1 -- px = ax 1 wgOnUsable dim deg = weightgap' dim deg Algebraic ?ua WgOnTrs wg dim deg = weightgap' dim deg Algebraic ?ua WgOnAny ax, axLeaf :: Int -> Int -> TrsStrategy ax lo up = ara' (Just 1) lo up 8 axLeaf lo up = ara' Nothing lo up 5 axHeur lo up = ara' Nothing lo up 3 --- * rc ------------------------------------------------------------------------------------------------------------- runtimeStrategy :: CombineWith -> TrsStrategy runtimeStrategy combineWith = withState $ \st -> let mto = T.remainingTime st in mto `seq` runtimeStrategy' combineWith mto runtimeStrategy' :: CombineWith -> Maybe Int -> TrsStrategy runtimeStrategy' combineWith mto = let ?timeoutRel = timeoutRelative mto ?combine = case combineWith of { Best -> best cmpTimeUB; Fastest -> fastest } ?ua = UArgs ?ur = URules ?sel = Just selAny in withProblem $ \ prob -> if Prob.isInnermostProblem prob then best cmpTimeUB [ timeoutIn 7 direct , ?combine [ timeoutIn 25 interp , raml , rci ] ] else ite toInnermost rci rc direct = try trivial .>>> tew (fastest [axHeur 1 2, axLeaf 1 2]) -- up to quadratic bound .>>> empty withDP = try (withProblem toDP') .>>> try removeInapplicable .>>> try cleanSuffix .>>> te removeHeads .>>> te (withProblem partIndep) .>>> try cleanSuffix .>>> try trivial .>>> try usableRules where toDP' prob | Prob.isInnermostProblem prob = timeoutIn 5 (dependencyPairs .>>> try usableRules .>>> wgOnTrs) .<|> dependencyTuples .>>> try usableRules | otherwise = dependencyPairs .>>> try usableRules .>>> try wgOnTrs partIndep prob | Prob.isInnermostProblem prob = decomposeIndependentSG | otherwise = linearPathAnalysis wgOnTrs = withProblem $ \ prob -> if RS.null (Prob.strictTrs prob) then identity else wgOnUsable 1 1 .<||> wgOnUsable 2 1 trivialDP = dependencyTuples .>>> try usableRules .>>> try trivial .>>> try dpsimps .>>> tew (wg 1 0 .<||> mx 1 0) withCWDG s = withProblem $ \ prob -> s (Prob.congruenceGraph prob) --- ** interpretations ---------------------------------------------------------------------------------------------------------- interp = try trivial .>>> tew (try $ fastest [ax 1 1, mx 1 1, px 1]) .>>> tew (try $ fastest [ax 2 2, px 2]) .>>> tew (try $ fastest [mx 3 3, px 3]) .>>> tew (try $ fastest [mxs1 .>>> tew mxs2 .>>> tew mxs3 .>>> tew mxs4]) .>>> empty where mxs1 = mxsida 2 1 .<||> mxsida 3 1 mxs2 = mxsida 2 2 .<||> mxsida 3 2 .<||> wg 2 2 mxs3 = mxsida 3 3 .<||> mxsida 4 3 mxs4 = mxsida 4 4 -- | Is now included in interp function -- interpretations = -- tew (?timeoutRel 15 $ mx 1 1 .<||> px 1) -- .>>> -- fastest -- [ tew (px 3) .>>> empty -- , tew (?timeoutRel 15 mxs1) .>>> tew (?timeoutRel 15 mxs2) .>>> tew mxs3 .>>> tew mxs4 .>>> empty -- ] -- where -- mxs1 = mxsida 2 1 .<||> mxsida 3 1 -- mxs2 = mxsida 2 2 .<||> mxsida 3 2 .<||> wg 2 2 -- mxs3 = mxsida 3 3 .<||> mxsida 4 3 -- mxs4 = mxsida 4 4 --- ** raml ---------------------------------------------------------------------------------------------------------- toDP = dependencyTuples .<||> (dependencyPairs .>>> try usableRules .>>> try (wgOnUsable 2 1)) .>>> try removeInapplicable .>>> try dpsimps simpDP = try cleanSuffix .>>> te decomposeIndependentSG .>>> te removeHeads .>>> try trivial .>>> try usableRules data Methods = PopStar | Matrices | Polys -- semantic methods i = whenNonTrivial $ -- -- (when (PopStar `elem` methods) (peAny (spopstarPS `withDegree` Just i))) -- -- <||> -- (when (Matrices `elem` methods) -- (peAny (mx i i) -- .<||> peAny (mx (i + 1) i) -- .<||> when (i == 1) (mx 3 1)) -- .<||> when (Polys `elem` methods && (i == 2 || i == 3)) -- (peAny (poly `withDegree` Just i))) -- where peAny p = p `withPEOn` -- (selLeafWDG `selInter` selStricts) >>> try cleanUpTail raml = dependencyTuples .>>> try dpsimps .>>> tew decomposeDG' .>||> try dpsimps .>>> tew basics' .>>> empty basics' = tew (try $ ?timeoutRel 15 $ fastest [mx 1 1, wg 1 1, ax 1 2]) .>>> tew (try $ ?timeoutRel 15 $ fastest [ax 2 2, eda2]) .>>> tew (try $ ?timeoutRel 15 $ fastest [eda3]) .>>> tew (try $ fastest [ida4]) .>>> tew (try $ fastest [ida5]) where -- eda1 = mxseda 1 eda2 = mxseda 2 eda3 = mxseda 3 eda4 = mxseda 4 ida4 = mxsida 4 1 .<||> mxsida 4 2 .<||> mxsida 4 3 ida5 = mxsida 5 1 .<||> mxsida 5 2 .<||> mxsida 5 3 .<||> mxsida 5 4 --- ** rci ---------------------------------------------------------------------------------------------------------- rci = try innermostRuleRemoval .>>! ?combine [ timeoutIn 7 $ trivialDP .>>> empty , timeoutIn 7 $ matchbounds .>>> empty , withDP .>>!! dpi .>>> empty ] where dpi = tew (withCWDG trans) .>>> basics where trans cwdg | cwdgDepth cwdg == (0::Int) = shiftLeafs | otherwise = ?timeoutRel 25 shiftLeafs .<|> removeFirstCongruence cwdgDepth cwdg = maximum $ 0 : [ dp r | r <- DG.roots cwdg] where dp n = maximum $ 0 : [ 1 + dp m | m <- DG.successors cwdg n] shiftLeafs = force $ removeLeafs 0 .<||> (removeLeafs 1 .<|> removeLeafs 2) removeLeafs 0 = force $ tew $ removeLeaf (mxCP 1 0) removeLeafs i = removeLeaf (mxCP i i) .<||> removeLeaf (mxCP (i+1) i) .<||> when' (i == 1) (removeLeaf (mxCP 3 1)) .<||> when' (i == 2) (removeLeaf (pxCP 2)) removeFirstCongruence = decomposeDG decomposeDGselect (Just proc) Nothing .>>! try simps where proc = try simps .>>> tew shiftLeafs .>>> basics .>>> empty basics = tew shift -- uncomment following line for script.sh where shift = fastest [ ax 1 1 .<||> mx 1 1 .<||> px 1 .<||> ax 2 2 .<||> mx 2 2 .<||> px 2 .<||> mx 3 3 .<||> px 3 .<||> -- ax 3 3 .<||> mx 4 4 ] simps = try empty .>>> cleanSuffix .>>! try trivial .>>> try usableRules when' b st = if b then st else abort --- ** rc ------------------------------------------------------------------------------------------------------------ rc = ?combine [ timeoutIn 7 $ trivialDP .>>> empty , timeoutIn 7 $ matchbounds .>>> empty , ?combine [ interp .>>> empty , withDP .>>!! dp .>>> empty ] ] where dp = withProblem $ loopFrom 1 where loopFrom i prob | RS.null (Prob.strictTrs prob) = dpi | otherwise = tew (is i) .>>! withProblem (loopFrom $ succ i) is i = let ?sel = Just selAnyRule in mx i i .<||> wg i i .<||> when' (i == 2 || i == 3) (px i) .<||> when' (i < 4) (mx (succ i) i .<||> wg (succ i) i)
ComputationWithBoundedResources/tct-trs
src/Tct/Trs/Strategy/Runtime.hs
bsd-3-clause
8,758
0
19
2,415
2,458
1,236
1,222
-1
-1
import Data.Char import Data.List myFavoriteFruit = "apple" encrypt m = m ^ 13 `mod` 138689 decrypt c = c ^ 95497 `mod` 138689 twice f x = f (f x) maybeTriple (Just x) = x * 3 maybeTriple _ = 0 allOrNothing x | x < 10 = 0 | otherwise = 100 num1, num2, num3 :: Integer num1 = 2 num2 = 8 num3 = 15 calc1 :: Integer -> Integer -> Integer -> Integer calc1 x y z = x * y + z val1 :: Integer val1 = x ^ y where x = 3 y = 4 checkAnswer :: Char -> Maybe Bool checkAnswer c = case toLower c of 'y' -> Just True 'n' -> Just False _ -> Nothing aho :: Integer -> String aho x = if x `mod` 3 == 0 then "aho" else "normal" type Point = (Double, Double) geometric :: Integer -> Integer geometric n | n < 1 = 1 | otherwise = 2 * geometric (n - 1) mySum :: [Integer] -> Integer mySum (x : xs) = x + mySum xs mySum [] = 0 enumerate :: Integer -> [Integer] enumerate n = n : enumerate (n + 1) cookie :: Integer -> [Integer] cookie = unfoldr $ \s -> if s < 3 then Nothing else let b = s `div` 3 in Just (b, s - b) fibs, tfibs :: [Integer] fibs@(_ : tfibs) = 0 : 1 : zipWith (+) fibs tfibs data Point2 = Cartesian Double Double | Polar Double Double deriving Show data Cap = Red | Blue | Yellow deriving Show data Order = Cap :-> Cap deriving Show data List a = Empty | Cons a (List a) deriving Show data Circle = Circle { centerX :: Double, centerY :: Double, radius :: Double } deriving Show class BoolLike a where toBool :: a -> Bool instance BoolLike Integer where toBool 0 = False toBool _ = True data Size = Short | Tall | Grande | Venti deriving (Eq, Ord, Show, Read, Bounded, Enum)
YoshikuniJujo/funpaala
samples/45_summary/summary.hs
bsd-3-clause
1,608
6
12
384
744
404
340
56
3
{-# LANGUAGE ScopedTypeVariables #-} module Control.Pipe.Network ( Application, socketReader, socketWriter, ServerSettings(..), runTCPServer, ClientSettings(..), runTCPClient, ) where import qualified Network.Socket as NS import Network.Socket (Socket) import Network.Socket.ByteString (sendAll, recv) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Control.Concurrent (forkIO) import qualified Control.Exception as E import Control.Monad (forever, unless) import Control.Monad.IO.Class import Control.Monad.Trans.Class import Control.Pipe -- adapted from conduit -- | Stream data from the socket. socketReader :: MonadIO m => Socket -> Pipe () ByteString m () socketReader socket = go where go = do bs <- lift . liftIO $ recv socket 4096 unless (B.null bs) $ yield bs >> go -- | Stream data to the socket. socketWriter :: MonadIO m => Socket -> Pipe ByteString Void m r socketWriter socket = forever $ await >>= lift . liftIO . sendAll socket -- | A simple TCP application. It takes two arguments: the 'Producer' to read -- input data from, and the 'Consumer' to send output data to. type Application m r = Pipe () ByteString m () -> Pipe ByteString Void m () -> IO r -- | Settings for a TCP server. It takes a port to listen on, and an optional -- hostname to bind to. data ServerSettings = ServerSettings { serverPort :: Int , serverHost :: Maybe String -- ^ 'Nothing' indicates no preference } -- | Run an @Application@ with the given settings. This function will create a -- new listening socket, accept connections on it, and spawn a new thread for -- each connection. runTCPServer :: MonadIO m => ServerSettings -> Application m r -> IO r runTCPServer (ServerSettings port host) app = E.bracket (bindPort host port) NS.sClose (forever . serve) where serve lsocket = do (socket, _addr) <- NS.accept lsocket forkIO $ do E.finally (app (socketReader socket) (socketWriter socket)) (NS.sClose socket) return () -- | Settings for a TCP client, specifying how to connect to the server. data ClientSettings = ClientSettings { clientPort :: Int , clientHost :: String } -- | Run an 'Application' by connecting to the specified server. runTCPClient :: MonadIO m => ClientSettings -> Application m r -> IO r runTCPClient (ClientSettings port host) app = E.bracket (getSocket host port) NS.sClose (\s -> app (socketReader s) (socketWriter s)) -- | Attempt to connect to the given host/port. getSocket :: String -> Int -> IO NS.Socket getSocket host' port' = do let hints = NS.defaultHints { NS.addrFlags = [NS.AI_ADDRCONFIG] , NS.addrSocketType = NS.Stream } (addr:_) <- NS.getAddrInfo (Just hints) (Just host') (Just $ show port') E.bracketOnError (NS.socket (NS.addrFamily addr) (NS.addrSocketType addr) (NS.addrProtocol addr)) NS.sClose (\sock -> NS.connect sock (NS.addrAddress addr) >> return sock) -- | Attempt to bind a listening @Socket@ on the given host/port. If no host is -- given, will use the first address available. bindPort :: Maybe String -> Int -> IO Socket bindPort host p = do let hints = NS.defaultHints { NS.addrFlags = [ NS.AI_PASSIVE , NS.AI_NUMERICSERV , NS.AI_NUMERICHOST ] , NS.addrSocketType = NS.Stream } port = Just . show $ p addrs <- NS.getAddrInfo (Just hints) host port let tryAddrs (addr1:rest@(_:_)) = E.catch (theBody addr1) (\(_ :: E.IOException) -> tryAddrs rest) tryAddrs (addr1:[]) = theBody addr1 tryAddrs _ = error "bindPort: addrs is empty" theBody addr = E.bracketOnError (NS.socket (NS.addrFamily addr) (NS.addrSocketType addr) (NS.addrProtocol addr)) NS.sClose (\sock -> do NS.setSocketOption sock NS.ReuseAddr 1 NS.bindSocket sock (NS.addrAddress addr) NS.listen sock NS.maxListenQueue return sock ) tryAddrs addrs
pcapriotti/pipes-network
Control/Pipe/Network.hs
bsd-3-clause
4,425
0
18
1,295
1,139
597
542
95
3
-- | Utility functions {-# LANGUAGE OverloadedStrings #-} module NumberSix.Util ( sleep , forkIrc , (<>) , (==?) , toLower , breakWord , prettyList , removeNewlines , randomElement , parseJsonEither , readText , maxLineLength ) where -------------------------------------------------------------------------------- import Control.Arrow (second) import Control.Concurrent (forkIO, threadDelay) import Control.Monad.Reader (ask) import Control.Monad.Trans (liftIO) import Data.Aeson (FromJSON, json, parseJSON) import Data.Aeson.Types (parseEither) import Data.Attoparsec (parseOnly) import Data.ByteString (ByteString) import Data.Char (isSpace) import Data.Text (Text) import qualified Data.Text as T import System.Random (randomRIO) -------------------------------------------------------------------------------- import NumberSix.Irc import NumberSix.Message -------------------------------------------------------------------------------- -- | Sleep a while. sleep :: Double -- ^ Number of seconds to sleep -> Irc () -- ^ Result sleep x = liftIO $ threadDelay (round $ x * 1000000) -------------------------------------------------------------------------------- -- | 'forkIO' lifted to the Irc monad forkIrc :: Irc () -- ^ Action to execute in another thread -> Irc () -- ^ Returns immediately forkIrc irc = do _<- liftIO . forkIO . runIrc irc =<< ask return () -------------------------------------------------------------------------------- -- | Take a word from a string, returing the word and the remainder. breakWord :: Text -> (Text, Text) breakWord = second (T.drop 1) . T.break isSpace -------------------------------------------------------------------------------- -- | Show a list of strings in a pretty format prettyList :: [Text] -> Text prettyList [] = "none" prettyList (x : []) = x prettyList (x : y : []) = x <> " and " <> y prettyList (x : y : z : r) = x <> ", " <> prettyList (y : z : r) -------------------------------------------------------------------------------- -- | Replace newlines by spaces removeNewlines :: Text -> Text removeNewlines = T.map (\x -> if x `elem` ['\r', '\n'] then ' ' else x) -------------------------------------------------------------------------------- -- | Random element from a list randomElement :: [a] -> IO a randomElement ls = fmap (ls !!) $ randomRIO (0, length ls - 1) -------------------------------------------------------------------------------- -- | Parse JSON from a bytestring parseJsonEither :: FromJSON a => ByteString -> Either String a parseJsonEither bs = parseOnly json bs >>= parseEither parseJSON -------------------------------------------------------------------------------- -- | Read applied to a bytestring, lifted to maybe readText :: Read a => Text -> Maybe a readText t = case reads (T.unpack t) of [(x, "")] -> Just x _ -> Nothing -------------------------------------------------------------------------------- -- | To prevent flooding maxLineLength :: Int maxLineLength = 450
jaspervdj/number-six
src/NumberSix/Util.hs
bsd-3-clause
3,285
0
10
698
678
384
294
55
2
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------- -- | -- Module: HTrade.Test.TestMarketFetch -- -- Functional tests covering the MarketFetch module in the backend -- but also verfication of the whole backend-proxy construction. -- Executes a web server and loads a simple configuration, thereby -- simulating an entire market. module Main where import Control.Applicative ((<$>)) import qualified Control.Concurrent.Async as C import qualified Control.Concurrent.STM as STM import qualified Control.Error as E import Control.Monad.Trans (liftIO) import qualified Data.ByteString.Char8 as B import Data.Monoid ((<>), mempty) import GHC.Conc (threadDelay) import qualified Pipes.Concurrent as P import qualified Snap.Core as SNAP import qualified Snap.Http.Server as SNAP import qualified System.Directory as D import HTrade.Backend.Configuration import HTrade.Backend.Types import HTrade.Shared.Utils import HTrade.Test.Utils -- | HTTP state carried around in handlers. data HTTPState = HTTPState { _orderBookCount :: Int, -- ^ Number of requests to order book. _tradesCount :: Int, -- ^ Number of requests to trades. _response :: P.Input (B.ByteString, B.ByteString) -- ^ Channel used to read latest orders/trades. } -- | HTTP state bundled in a shared variable. -- Needed in order to communicate with HTTP route handlers. type SharedState = STM.TVar HTTPState -- | HTTP port to listen on. httpPort :: Int httpPort = 9999 -- | Market configuration used by all test cases. testConf :: MarketConfiguration testConf = MarketConfiguration (MarketIdentifier "testMarket" "sek") ("http://127.0.0.1:" <> B.pack (show httpPort)) "" "trades.json" "orders.json" 1000000 -- TODO: Add management of C* (separate keyspace, parameterize all existing functions over KS) -- | Run a monadic action after initializing the snap backend simulating a market. -- The action can communicate with route handlers through a shared variable. withSnap :: (SharedState -> IO a) -> IO a withSnap action = do (_, contentIn) <- P.spawn $ P.Latest (emptyOrderBook, emptyTrades) shared <- STM.newTVarIO (HTTPState 0 0 contentIn) let routes = SNAP.route [(_marketOrders testConf, orderBookHandler shared), (_marketTrades testConf, tradesHandler shared)] -- launch HTTP thread httpThread <- C.async $ SNAP.httpServe config routes threadDelay 500000 -- evaluate action result <- action shared -- cleanup C.cancel httpThread return result where config = SNAP.setAccessLog SNAP.ConfigNoLog $ SNAP.setErrorLog SNAP.ConfigNoLog $ SNAP.setPort httpPort $ SNAP.setBind "127.0.0.1" mempty emptyOrderBook = "{\"asks\": [], \"bids\": []}" emptyTrades = "[]" orderBookHandler = genericHandler (\s -> s { _orderBookCount = _orderBookCount s + 1 }) fst tradesHandler = genericHandler (\s -> s { _tradesCount = _tradesCount s + 1 }) snd -- | Generic HTTP handler used by both routes, parameterized over path and relevant actions. genericHandler :: (HTTPState -> HTTPState) -> ((B.ByteString, B.ByteString) -> B.ByteString) -> SharedState -> SNAP.Snap () genericHandler onRequest getResponse state = do -- pattern matching valid by construction Just s <- liftIO . STM.atomically $ do STM.modifyTVar' state onRequest chan <- _response <$> STM.readTVar state P.recv chan SNAP.writeBS $ getResponse s -- | Verify that there are reasonable many HTTP queries to order book and trades. -- Basically initializes all functionality and inspects counters after a given time slot. verifyProbes :: IO Bool verifyProbes = withSnap $ withLayers poolSize . buildRet . withConfiguration . tester where poolSize = 10^(1 :: Int) :: Int tester state = do -- write configuration to disk and load liftIO $ writeTempConf confDir filePattern testConf loadConfigurations confDir >>= liftIO . print liftIO . threadDelay . fromIntegral $ seconds 1 -- wait for a given time period liftIO $ putStrLn "[*] Waiting for samples" liftIO . threadDelay $ probes * fromIntegral (_marketInterval testConf) liftIO $ putStrLn "[*] Sampling done" stats <- liftIO $ STM.readTVarIO state -- cleanup liftIO $ D.removeDirectoryRecursive confDir -- check the number of requests let orderCount = _orderBookCount stats tradeCount = _tradesCount stats liftIO . putStrLn $ "[*] Order book count: " <> show orderCount <> ", trade count: " <> show tradeCount return $ (_orderBookCount stats >= probes - 1) && (_tradesCount stats >= probes - 1) probes = 10 confDir = "/tmp/test_configurations/" filePattern = "verify-probes-test.conf" buildRet = E.MaybeT . fmap convJust convJust True = Just () convJust False = Nothing -- | Entry point executing all tests related to market fetching funtionality. main :: IO () main = checkTestCases [ ("verifyProbes", verifyProbes) ]
davnils/distr-btc
src/HTrade/Test/TestMarketFetch.hs
bsd-3-clause
5,379
6
14
1,300
1,060
568
492
92
2
module EDSL.Monad.Default where import Data.BitCode.LLVM.Type (Ty, isPtr) import Data.BitCode.LLVM.Value import Data.BitCode.LLVM.CallingConv (CallingConv) import qualified Data.BitCode.LLVM.CallingConv as CallingConv import qualified Data.BitCode.LLVM.Linkage as Linkage import qualified Data.BitCode.LLVM.Visibility as Visibility import qualified Data.BitCode.LLVM.ThreadLocalMode as ThreadLocalMode import qualified Data.BitCode.LLVM.StorageClass as StorageClass -- | Defaults defLinkage = Linkage.External defVisibility = Visibility.Default defTLM = ThreadLocalMode.NotThreadLocal defStorageClass = StorageClass.Default defCC = CallingConv.C defSymbol :: Symbol defSymbol = undefined defGlobal, defFunction, defAlias :: Ty -> Value defGlobal ty = Global ty True 0 Nothing defLinkage 0 0 defVisibility defTLM False False defStorageClass 0 defFunction ty = Function ty defCC defLinkage 0 0 0 defVisibility 0 False defStorageClass 0 0 (FE True Nothing Nothing) defAlias ty = Alias ty 0 defSymbol defLinkage defVisibility defTLM False defStorageClass
angerman/data-bitcode-edsl
src/EDSL/Monad/Default.hs
bsd-3-clause
1,080
0
7
146
255
155
100
20
1
module Shaders where import Graphics.Rendering.OpenGL import Graphics.Rendering.OpenGL.GL.Shaders (VertexShader, FragmentShader, Program) import Graphics.Rendering.OpenGL.Raw.Core31 import Foreign.Ptr (Ptr) import Control.Monad (unless) import Unsafe.Coerce (unsafeCoerce) import System.IO (hPutStrLn, stderr) import Control.Applicative data SSAO_Shader = SSAO_Shader { vertShaders :: VertexShader , fragShaders :: FragmentShader , program :: Program , rnm :: AttribLocation , normalMap :: AttribLocation } -- actually, this is probably going to be scrapped. Too much work for the small benefit initSSAO = do vs <- loadShader "shaders/ssao.vert" fs <- loadShader "shaders/ssao.frag" p <- linkShaderProgram [vs] [fs] SSAO_Shader vs fs p <$> get (attribLocation p "rnm") -- TODO: Actually pipe the depth map in here (At least I think it's the depth map) <*> get (attribLocation p "normalMap") -- TODO: Also pipe in the normal map here. -- |Check OpenGL error flags and print them on 'stderr'. checkErrors :: IO () checkErrors = get errors >>= mapM_ (hPutStrLn stderr . ("GL: "++) . show) -- |Load a shader program from a file. loadShader :: Shader s => FilePath -> IO s loadShader filePath = do src <- readFile filePath [shader] <- genObjectNames 1 shaderSource shader $= [src] compileShader shader checkErrors ok <- get (compileStatus shader) infoLog <- get (shaderInfoLog shader) unless (null infoLog) (mapM_ putStrLn ["Shader info log for '" ++ filePath ++ "':", infoLog, ""]) unless ok $ do deleteObjectNames [shader] ioError (userError "shader compilation failed") return shader -- |Link vertex and fragment shaders into a 'Program'. linkShaderProgram :: [VertexShader] -> [FragmentShader] -> IO Program linkShaderProgram vs fs = do [prog] <- genObjectNames 1 attachedShaders prog $= (vs, fs) linkProgram prog checkErrors ok <- get (linkStatus prog) infoLog <- get (programInfoLog prog) unless (null infoLog) (mapM_ putStrLn ["Program info log:", infoLog, ""]) unless ok $ do deleteObjectNames [prog] ioError (userError "GLSL linking failed") return prog -- |Work with a named uniform shader parameter. Note that this looks -- up the variable name on each access, so uniform parameters that -- will be accessed frequently should instead be resolved to a -- 'UniformLocation'. namedUniform :: (Uniform a) => String -> StateVar a namedUniform name = makeStateVar (loc >>= get) (\x -> loc >>= ($= x)) where loc = do Just p <- get currentProgram l <- get (uniformLocation p name) checkErrors return $ uniform l -- Allocate an OpenGL matrix from a nested list matrix, and pass a -- pointer to that matrix to an 'IO' action. withHMatrix :: [[GLfloat]] -> (Ptr GLfloat -> IO a) -> IO a withHMatrix lstMat m = do mat <- newMatrix RowMajor (concat lstMat) :: IO (GLmatrix GLfloat) withMatrix mat (\_ -> m) -- Not all raw uniform setters are wrapped by the OpenGL interface, -- but the UniformLocation newtype is still helpful for type -- discipline. unUL :: UniformLocation -> GLint unUL = unsafeCoerce -- |Set a 'UniformLocation' from a list representation of a -- low-dimensional vector of 'GLfloat's. Only 2, 3, and 4 dimensional -- vectors are supported. uniformVec :: UniformLocation -> SettableStateVar [GLfloat] uniformVec loc = makeSettableStateVar aux where aux [x,y] = glUniform2f loc' x y aux [x,y,z] = glUniform3f loc' x y z aux [x,y,z,w] = glUniform4f loc' x y z w aux _ = ioError . userError $ "Only 2, 3, and 4 dimensional vectors are supported" loc' = unUL loc -- |Set a named uniform shader parameter from a nested list matrix -- representation. Only 3x3 and 4x4 matrices are supported. namedUniformMat :: String -> SettableStateVar [[GLfloat]] namedUniformMat var = makeSettableStateVar (\m -> loc >>= ($= m) . uniformMat) where loc = do Just p <- get currentProgram location <- get (uniformLocation p var) checkErrors return location -- |Set a uniform shader location from a nested list matrix -- representation. Only 3x3 and 4x4 matrices are supported. uniformMat :: UniformLocation -> SettableStateVar [[GLfloat]] uniformMat loc = makeSettableStateVar aux where aux mat = do withHMatrix mat $ \ptr -> case length mat of 4 -> glUniformMatrix4fv loc' 1 1 ptr 3 -> glUniformMatrix3fv loc' 1 1 ptr _ -> ioError . userError $ "Only 3x3 and 4x4 matrices are supported" loc' = unUL loc -- |Set a uniform shader location with a 4x4 'GLmatrix'. uniformGLMat4 :: UniformLocation -> SettableStateVar (GLmatrix GLfloat) uniformGLMat4 loc = makeSettableStateVar aux where aux m = withMatrix m $ \_ -> glUniformMatrix4fv loc' 1 1 loc' = unUL loc
gbluma/opengl1
src/Shaders.hs
bsd-3-clause
5,037
0
15
1,201
1,241
631
610
93
4
{- DATX02-17-26, automated assessment of imperative programs. - Copyright, 2017, see AUTHORS.md. - - 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -} module Norm.ForIndexTest ( allTests ) where import Norm.NormTestUtil import Norm.ForIndex normalizers :: NormalizerCU normalizers = [ normForIndex ] allTests :: TestTree allTests = testGroup "Norm.ForIndex tests" [ normTestDir "for_index_norm_test" "forindex" 1 normalizers ]
DATX02-17-26/DATX02-17-26
Test/Norm/ForIndexTest.hs
gpl-2.0
1,115
0
7
206
62
36
26
9
1
{-# LANGUAGE ParallelArrays #-} {-# OPTIONS_GHC -fvectorise #-} {-# LANGUAGE UnboxedTuples #-} module Vect where -- import Data.Array.Parallel {-# VECTORISe isFive = blah #-} {-# NoVECTORISE isEq #-} {-# VECTORISE SCALAR type Int #-} {-# VECTORISE type Char #-} {-# VECTORISE type ( ) #-} {-# VECTORISE type (# #) #-} {-# VECTORISE SCALAR type Integer = Int #-} {-# VECTORISE type Bool = String #-} {-# Vectorise class Eq #-} blah = 5 data MyBool = MyTrue | MyFalse class Eq a => Cmp a where cmp :: a -> a -> Bool -- FIXME: -- instance Cmp Int where -- cmp = (==) -- isFive :: (Eq a, Num a) => a -> Bool isFive :: Int -> Bool isFive x = x == 5 isEq :: Eq a => a -> Bool isEq x = x == x fiveEq :: Int -> Bool fiveEq x = isFive x && isEq x cmpArrs :: PArray Int -> PArray Int -> Bool {-# NOINLINE cmpArrs #-} cmpArrs v w = cmpArrs' (fromPArrayP v) (fromPArrayP w) cmpArrs' :: [:Int:] -> [:Int:] -> Bool cmpArrs' xs ys = andP [:x == y | x <- xs | y <- ys:] isFives :: PArray Int -> Bool {-# NOINLINE isFives #-} isFives xs = isFives' (fromPArrayP xs) isFives' :: [:Int:] -> Bool isFives' xs = andP (mapP isFive xs) isEqs :: PArray Int -> Bool {-# NOINLINE isEqs #-} isEqs xs = isEqs' (fromPArrayP xs) isEqs' :: [:Int:] -> Bool isEqs' xs = undefined -- andP (mapP isEq xs) -- fudge for compiler fromPArrayP = undefined andP = undefined mapP = undefined data PArray a = PArray a
mpickering/ghc-exactprint
tests/examples/ghc710/Vect.hs
bsd-3-clause
1,433
16
8
335
401
217
184
33
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/IntMap/Merge/Strict.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-} {-# LANGUAGE Safe #-} {-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE MagicHash #-} ----------------------------------------------------------------------------- -- | -- Module : Data.IntMap.Merge.Strict -- Copyright : (c) wren romano 2016 -- License : BSD-style -- Maintainer : libraries@haskell.org -- Portability : portable -- -- This module defines an API for writing functions that merge two -- maps. The key functions are 'merge' and 'mergeA'. -- Each of these can be used with several different \"merge tactics\". -- -- The 'merge' and 'mergeA' functions are shared by -- the lazy and strict modules. Only the choice of merge tactics -- determines strictness. If you use 'Data.Map.Merge.Strict.mapMissing' -- from this module then the results will be forced before they are -- inserted. If you use 'Data.Map.Merge.Lazy.mapMissing' from -- "Data.Map.Merge.Lazy" then they will not. -- -- == Efficiency note -- -- The 'Category', 'Applicative', and 'Monad' instances for 'WhenMissing' -- tactics are included because they are valid. However, they are -- inefficient in many cases and should usually be avoided. The instances -- for 'WhenMatched' tactics should not pose any major efficiency problems. module Data.IntMap.Merge.Strict ( -- ** Simple merge tactic types SimpleWhenMissing , SimpleWhenMatched -- ** General combining function , merge -- *** @WhenMatched@ tactics , zipWithMaybeMatched , zipWithMatched -- *** @WhenMissing@ tactics , mapMaybeMissing , dropMissing , preserveMissing , mapMissing , filterMissing -- ** Applicative merge tactic types , WhenMissing , WhenMatched -- ** Applicative general combining function , mergeA -- *** @WhenMatched@ tactics -- | The tactics described for 'merge' work for -- 'mergeA' as well. Furthermore, the following -- are available. , zipWithMaybeAMatched , zipWithAMatched -- *** @WhenMissing@ tactics -- | The tactics described for 'merge' work for -- 'mergeA' as well. Furthermore, the following -- are available. , traverseMaybeMissing , traverseMissing , filterAMissing -- ** Covariant maps for tactics , mapWhenMissing , mapWhenMatched -- ** Miscellaneous functions on tactics , runWhenMatched , runWhenMissing ) where import Data.IntMap.Internal
phischu/fragnix
tests/packages/scotty/Data.IntMap.Merge.Strict.hs
bsd-3-clause
3,024
0
4
949
132
105
27
33
0
module Handler.Root where import Import import Text.Blaze.Html (unsafeByteString) import qualified Data.ByteString as S import Text.Hamlet (hamletFile) import Yesod.AtomFeed (atomLink) getRootR :: Handler Html getRootR = do c <- liftIO $ S.readFile "content/homepage.html" let widget = do setTitle "Yesod Web Framework for Haskell" atomLink FeedR "Yesod Web Framework Blog" $(widgetFile "normalize") $(widgetFile "homepage") $(widgetFile "mobile") toWidget $ unsafeByteString c pc <- widgetToPageContent widget (blogLink, post) <- getNewestBlog withUrlRenderer $(hamletFile "templates/homepage-wrapper.hamlet")
wolftune/yesodweb.com
Handler/Root.hs
bsd-2-clause
705
0
14
163
176
86
90
19
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module RunSpec (main, spec, withApp, MySocket, msWrite, msRead, withMySocket) where import Control.Concurrent (forkIO, killThread, threadDelay) import Control.Concurrent.MVar (newEmptyMVar, takeMVar, putMVar) import Control.Concurrent.STM import qualified UnliftIO.Exception as E import UnliftIO.Exception (bracket, try, IOException, onException) import Control.Monad (forM_, replicateM_, unless) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.ByteString (ByteString) import qualified Data.ByteString as S import Data.ByteString.Builder (byteString) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import qualified Data.IORef as I import Data.Streaming.Network (bindPortTCP, getSocketTCP, safeRecv) import Network.HTTP.Types import Network.Socket import Network.Socket.ByteString (sendAll) import Network.Wai hiding (responseHeaders) import Network.Wai.Internal (getRequestBodyChunk) import Network.Wai.Handler.Warp import System.IO.Unsafe (unsafePerformIO) import System.Timeout (timeout) import Test.Hspec import HTTP main :: IO () main = hspec spec type Counter = I.IORef (Either String Int) type CounterApplication = Counter -> Application data MySocket = MySocket { msSocket :: !Socket , msBuffer :: !(I.IORef ByteString) } msWrite :: MySocket -> ByteString -> IO () msWrite ms bs = sendAll (msSocket ms) bs msRead :: MySocket -> Int -> IO ByteString msRead (MySocket s ref) expected = do bs <- I.readIORef ref inner (bs:) (S.length bs) where inner front total = case compare total expected of EQ -> do I.writeIORef ref mempty pure $ S.concat $ front [] GT -> do let bs = S.concat $ front [] (x, y) = S.splitAt expected bs I.writeIORef ref y pure x LT -> do bs <- safeRecv s 4096 if S.null bs then do I.writeIORef ref mempty pure $ S.concat $ front [] else inner (front . (bs:)) (total + S.length bs) msClose :: MySocket -> IO () msClose = Network.Socket.close . msSocket connectTo :: Int -> IO MySocket connectTo port = do s <- fst <$> getSocketTCP "127.0.0.1" port ref <- I.newIORef mempty return MySocket { msSocket = s , msBuffer = ref } withMySocket :: (MySocket -> IO a) -> Int -> IO a withMySocket body port = bracket (connectTo port) msClose body incr :: MonadIO m => Counter -> m () incr icount = liftIO $ I.atomicModifyIORef icount $ \ecount -> ((case ecount of Left s -> Left s Right i -> Right $ i + 1), ()) err :: (MonadIO m, Show a) => Counter -> a -> m () err icount msg = liftIO $ I.writeIORef icount $ Left $ show msg readBody :: CounterApplication readBody icount req f = do body <- consumeBody $ getRequestBodyChunk req case () of () | pathInfo req == ["hello"] && L.fromChunks body /= "Hello" -> err icount ("Invalid hello" :: String, body) | requestMethod req == "GET" && L.fromChunks body /= "" -> err icount ("Invalid GET" :: String, body) | not $ requestMethod req `elem` ["GET", "POST"] -> err icount ("Invalid request method (readBody)" :: String, requestMethod req) | otherwise -> incr icount f $ responseLBS status200 [] "Read the body" ignoreBody :: CounterApplication ignoreBody icount req f = do if (requestMethod req `elem` ["GET", "POST"]) then incr icount else err icount ("Invalid request method" :: String, requestMethod req) f $ responseLBS status200 [] "Ignored the body" doubleConnect :: CounterApplication doubleConnect icount req f = do _ <- consumeBody $ getRequestBodyChunk req _ <- consumeBody $ getRequestBodyChunk req incr icount f $ responseLBS status200 [] "double connect" nextPort :: I.IORef Int nextPort = unsafePerformIO $ I.newIORef 5000 {-# NOINLINE nextPort #-} getPort :: IO Int getPort = do port <- I.atomicModifyIORef nextPort $ \p -> (p + 1, p) esocket <- try $ bindPortTCP port "127.0.0.1" case esocket of Left (_ :: IOException) -> RunSpec.getPort Right sock -> do close sock return port withApp :: Settings -> Application -> (Int -> IO a) -> IO a withApp settings app f = do port <- RunSpec.getPort baton <- newEmptyMVar let settings' = setPort port $ setHost "127.0.0.1" $ setBeforeMainLoop (putMVar baton ()) settings bracket (forkIO $ runSettings settings' app `onException` putMVar baton ()) killThread (const $ do takeMVar baton -- use timeout to make sure we don't take too long mres <- timeout (60 * 1000 * 1000) (f port) case mres of Nothing -> error "Timeout triggered, too slow!" Just a -> pure a) runTest :: Int -- ^ expected number of requests -> CounterApplication -> [ByteString] -- ^ chunks to send -> IO () runTest expected app chunks = do ref <- I.newIORef (Right 0) withApp defaultSettings (app ref) $ withMySocket $ \ms -> do forM_ chunks $ \chunk -> msWrite ms chunk _ <- timeout 100000 $ replicateM_ expected $ msRead ms 4096 res <- I.readIORef ref case res of Left s -> error s Right i -> i `shouldBe` expected dummyApp :: Application dummyApp _ f = f $ responseLBS status200 [] "foo" runTerminateTest :: InvalidRequest -> ByteString -> IO () runTerminateTest expected input = do ref <- I.newIORef Nothing let onExc _ = I.writeIORef ref . Just withApp (setOnException onExc defaultSettings) dummyApp $ withMySocket $ \ms -> do msWrite ms input msClose ms -- explicitly threadDelay 1000 res <- I.readIORef ref show res `shouldBe` show (Just expected) singleGet :: ByteString singleGet = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n" singlePostHello :: ByteString singlePostHello = "POST /hello HTTP/1.1\r\nHost: localhost\r\nContent-length: 5\r\n\r\nHello" singleChunkedPostHello :: [ByteString] singleChunkedPostHello = [ "POST /hello HTTP/1.1\r\nHost: localhost\r\nTransfer-Encoding: chunked\r\n\r\n" , "5\r\nHello\r\n0\r\n" ] spec :: Spec spec = do describe "non-pipelining" $ do it "no body, read" $ runTest 5 readBody $ replicate 5 singleGet it "no body, ignore" $ runTest 5 ignoreBody $ replicate 5 singleGet it "has body, read" $ runTest 2 readBody [ singlePostHello , singleGet ] it "has body, ignore" $ runTest 2 ignoreBody [ singlePostHello , singleGet ] it "chunked body, read" $ runTest 2 readBody $ concat [ singleChunkedPostHello , [singleGet] ] it "chunked body, ignore" $ runTest 2 ignoreBody $ concat [ singleChunkedPostHello , [singleGet] ] describe "pipelining" $ do it "no body, read" $ runTest 5 readBody [S.concat $ replicate 5 singleGet] it "no body, ignore" $ runTest 5 ignoreBody [S.concat $ replicate 5 singleGet] it "has body, read" $ runTest 2 readBody $ return $ S.concat [ singlePostHello , singleGet ] it "has body, ignore" $ runTest 2 ignoreBody $ return $ S.concat [ singlePostHello , singleGet ] it "chunked body, read" $ runTest 2 readBody $ return $ S.concat [ S.concat singleChunkedPostHello , singleGet ] it "chunked body, ignore" $ runTest 2 ignoreBody $ return $ S.concat [ S.concat singleChunkedPostHello , singleGet ] describe "no hanging" $ do it "has body, read" $ runTest 1 readBody $ map S.singleton $ S.unpack singlePostHello it "double connect" $ runTest 1 doubleConnect [singlePostHello] describe "connection termination" $ do -- it "ConnectionClosedByPeer" $ runTerminateTest ConnectionClosedByPeer "GET / HTTP/1.1\r\ncontent-length: 10\r\n\r\nhello" it "IncompleteHeaders" $ runTerminateTest IncompleteHeaders "GET / HTTP/1.1\r\ncontent-length: 10\r\n" describe "special input" $ do it "multiline headers" $ do iheaders <- I.newIORef [] let app req f = do liftIO $ I.writeIORef iheaders $ requestHeaders req f $ responseLBS status200 [] "" withApp defaultSettings app $ withMySocket $ \ms -> do let input = S.concat [ "GET / HTTP/1.1\r\nfoo: bar\r\n baz\r\n\tbin\r\n\r\n" ] msWrite ms input threadDelay 1000 headers <- I.readIORef iheaders headers `shouldBe` [ ("foo", "bar baz\tbin") ] it "no space between colon and value" $ do iheaders <- I.newIORef [] let app req f = do liftIO $ I.writeIORef iheaders $ requestHeaders req f $ responseLBS status200 [] "" withApp defaultSettings app $ withMySocket $ \ms -> do let input = S.concat [ "GET / HTTP/1.1\r\nfoo:bar\r\n\r\n" ] msWrite ms input threadDelay 1000 headers <- I.readIORef iheaders headers `shouldBe` [ ("foo", "bar") ] describe "chunked bodies" $ do it "works" $ do countVar <- newTVarIO (0 :: Int) ifront <- I.newIORef id let app req f = do bss <- consumeBody $ getRequestBodyChunk req liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss:), ()) atomically $ modifyTVar countVar (+ 1) f $ responseLBS status200 [] "" withApp defaultSettings app $ withMySocket $ \ms -> do let input = S.concat [ "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n" , "c\r\nHello World\n\r\n3\r\nBye\r\n0\r\n\r\n" , "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n" , "b\r\nHello World\r\n0\r\n\r\n" ] msWrite ms input atomically $ do count <- readTVar countVar check $ count == 2 front <- I.readIORef ifront front [] `shouldBe` [ "Hello World\nBye" , "Hello World" ] it "lots of chunks" $ do ifront <- I.newIORef id countVar <- newTVarIO (0 :: Int) let app req f = do bss <- consumeBody $ getRequestBodyChunk req I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss:), ()) atomically $ modifyTVar countVar (+ 1) f $ responseLBS status200 [] "" withApp defaultSettings app $ withMySocket $ \ms -> do let input = concat $ replicate 2 $ ["POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"] ++ (replicate 50 "5\r\n12345\r\n") ++ ["0\r\n\r\n"] mapM_ (msWrite ms) input atomically $ do count <- readTVar countVar check $ count == 2 front <- I.readIORef ifront front [] `shouldBe` replicate 2 (S.concat $ replicate 50 "12345") -- For some reason, the following test on Windows causes the socket -- to be killed prematurely. Worth investigating in the future if possible. it "in chunks" $ do ifront <- I.newIORef id countVar <- newTVarIO (0 :: Int) let app req f = do bss <- consumeBody $ getRequestBodyChunk req liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss:), ()) atomically $ modifyTVar countVar (+ 1) f $ responseLBS status200 [] "" withApp defaultSettings app $ withMySocket $ \ms -> do let input = S.concat [ "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n" , "c\r\nHello World\n\r\n3\r\nBye\r\n0\r\n" , "POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n" , "b\r\nHello World\r\n0\r\n\r\n" ] mapM_ (msWrite ms) $ map S.singleton $ S.unpack input atomically $ do count <- readTVar countVar check $ count == 2 front <- I.readIORef ifront front [] `shouldBe` [ "Hello World\nBye" , "Hello World" ] it "timeout in request body" $ do ifront <- I.newIORef id let app req f = do bss <- (consumeBody $ getRequestBodyChunk req) `onException` liftIO (I.atomicModifyIORef ifront (\front -> (front . ("consume interrupted":), ()))) liftIO $ threadDelay 4000000 `E.catch` \e -> do I.atomicModifyIORef ifront (\front -> ( front . ((S8.pack $ "threadDelay interrupted: " ++ show e):) , ())) E.throwIO (e :: E.SomeException) liftIO $ I.atomicModifyIORef ifront $ \front -> (front . (S.concat bss:), ()) f $ responseLBS status200 [] "" withApp (setTimeout 1 defaultSettings) app $ withMySocket $ \ms -> do let bs1 = S.replicate 2048 88 bs2 = "This is short" bs = S.append bs1 bs2 msWrite ms "POST / HTTP/1.1\r\n" msWrite ms "content-length: " msWrite ms $ S8.pack $ show $ S.length bs msWrite ms "\r\n\r\n" threadDelay 100000 msWrite ms bs1 threadDelay 100000 msWrite ms bs2 threadDelay 5000000 front <- I.readIORef ifront S.concat (front []) `shouldBe` bs describe "raw body" $ do it "works" $ do let app _req f = do let backup = responseLBS status200 [] "Not raw" f $ flip responseRaw backup $ \src sink -> do let loop = do bs <- src unless (S.null bs) $ do sink $ doubleBS bs loop loop doubleBS = S.concatMap $ \w -> S.pack [w, w] withApp defaultSettings app $ withMySocket $ \ms -> do msWrite ms "POST / HTTP/1.1\r\n\r\n12345" timeout 100000 (msRead ms 10) >>= (`shouldBe` Just "1122334455") msWrite ms "67890" timeout 100000 (msRead ms 10) >>= (`shouldBe` Just "6677889900") it "only one date and server header" $ do let app _ f = f $ responseLBS status200 [ ("server", "server") , ("date", "date") ] "" getValues key = map snd . filter (\(key', _) -> key == key') . responseHeaders withApp defaultSettings app $ \port -> do res <- sendGET $ "http://127.0.0.1:" ++ show port getValues hServer res `shouldBe` ["server"] getValues hDate res `shouldBe` ["date"] it "streaming echo #249" $ do countVar <- newTVarIO (0 :: Int) let app req f = f $ responseStream status200 [] $ \write _ -> do let loop = do bs <- getRequestBodyChunk req unless (S.null bs) $ do write $ byteString bs atomically $ modifyTVar countVar (+ 1) loop loop withApp defaultSettings app $ withMySocket $ \ms -> do msWrite ms "POST / HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n" threadDelay 10000 msWrite ms "5\r\nhello\r\n0\r\n\r\n" atomically $ do count <- readTVar countVar check $ count >= 1 bs <- safeRecv (msSocket ms) 4096 -- must not use msRead S.takeWhile (/= 13) bs `shouldBe` "HTTP/1.1 200 OK" it "streaming response with length" $ do let app _ f = f $ responseStream status200 [("content-length", "20")] $ \write _ -> do replicateM_ 4 $ write $ byteString "Hello" withApp defaultSettings app $ \port -> do res <- sendGET $ "http://127.0.0.1:" ++ show port responseBody res `shouldBe` "HelloHelloHelloHello" describe "head requests" $ do let fp = "test/head-response" let app req f = f $ case pathInfo req of ["builder"] -> responseBuilder status200 [] $ error "should never be evaluated" ["streaming"] -> responseStream status200 [] $ \write _ -> write $ error "should never be evaluated" ["file"] -> responseFile status200 [] fp Nothing _ -> error "invalid path" it "builder" $ withApp defaultSettings app $ \port -> do res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/builder"] responseBody res `shouldBe` "" it "streaming" $ withApp defaultSettings app $ \port -> do res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/streaming"] responseBody res `shouldBe` "" it "file, no range" $ withApp defaultSettings app $ \port -> do bs <- S.readFile fp res <- sendHEAD $ concat ["http://127.0.0.1:", show port, "/file"] getHeaderValue hContentLength (responseHeaders res) `shouldBe` Just (S8.pack $ show $ S.length bs) it "file, with range" $ withApp defaultSettings app $ \port -> do res <- sendHEADwH (concat ["http://127.0.0.1:", show port, "/file"]) [(hRange, "bytes=0-1")] getHeaderValue hContentLength (responseHeaders res) `shouldBe` Just "2" consumeBody :: IO ByteString -> IO [ByteString] consumeBody body = loop id where loop front = do bs <- body if S.null bs then return $ front [] else loop $ front . (bs:)
sordina/wai
warp/test/RunSpec.hs
bsd-2-clause
19,132
0
31
6,911
5,388
2,611
2,777
409
4
-- | -- Module: Control.Wire.Core -- Copyright: (c) 2013 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <es@ertes.de> module Control.Wire.Core ( -- * Wires Wire(..), stepWire, -- * Constructing wires mkConst, mkEmpty, mkGen, mkGen_, mkGenN, mkId, mkPure, mkPure_, mkPureN, mkSF, mkSF_, mkSFN, -- * Data flow and dependencies delay, evalWith, force, forceNF, -- * Utilities (&&&!), (***!), lstrict, mapWire ) where import qualified Data.Semigroup as Sg import Control.Applicative import Control.Arrow import Control.Category import Control.DeepSeq hiding (force) import Control.Monad import Control.Monad.Fix import Control.Parallel.Strategies import Data.Profunctor import Data.Monoid import Data.String import Prelude hiding ((.), id) -- | A wire is a signal function. It maps a reactive value to another -- reactive value. data Wire s e m a b where WArr :: (Either e a -> Either e b) -> Wire s e m a b WConst :: Either e b -> Wire s e m a b WGen :: (s -> Either e a -> m (Either e b, Wire s e m a b)) -> Wire s e m a b WId :: Wire s e m a a WPure :: (s -> Either e a -> (Either e b, Wire s e m a b)) -> Wire s e m a b instance (Monad m, Monoid e) => Alternative (Wire s e m a) where empty = WConst (Left mempty) w1@(WConst (Right _)) <|> _ = w1 w1@WId <|> _ = w1 WConst (Left ex) <|> w2 = mapLeft (ex <>) w2 w1' <|> w2' = WGen $ \ds mx' -> liftM2 (\(mx1, w1) (mx2, w2) -> lstrict (choose mx1 mx2, w1 <|> w2)) (stepWire w1' ds mx') (stepWire w2' ds mx') where choose mx1@(Right _) _ = mx1 choose _ mx2@(Right _) = mx2 choose (Left ex1) (Left ex2) = Left (ex1 <> ex2) instance (Monad m) => Applicative (Wire s e m a) where pure = WConst . Right wf' <*> wx' = WGen $ \ds mx' -> liftM2 (\(mf, wf) (mx, wx) -> lstrict (mf <*> mx, wf <*> wx)) (stepWire wf' ds mx') (stepWire wx' ds mx') instance (Monad m) => Arrow (Wire s e m) where arr f = WArr (fmap f) first w' = WGen $ \ds mxy' -> liftM (\(mx, w) -> lstrict (liftA2 (,) mx (fmap snd mxy'), first w)) (stepWire w' ds (fmap fst mxy')) instance (Monad m, Monoid e) => ArrowChoice (Wire s e m) where left w' = WGen $ \ds mmx' -> liftM (fmap Left ***! left) . stepWire w' ds $ case mmx' of Right (Left x) -> Right x Right (Right _) -> Left mempty Left ex -> Left ex right w' = WGen $ \ds mmx' -> liftM (fmap Right ***! right) . stepWire w' ds $ case mmx' of Right (Right x) -> Right x Right (Left _) -> Left mempty Left ex -> Left ex wl' +++ wr' = WGen $ \ds mmx' -> case mmx' of Right (Left x) -> do liftM2 (\(mx, wl) (_, wr) -> lstrict (fmap Left mx, wl +++ wr)) (stepWire wl' ds (Right x)) (stepWire wr' ds (Left mempty)) Right (Right x) -> do liftM2 (\(_, wl) (mx, wr) -> lstrict (fmap Right mx, wl +++ wr)) (stepWire wl' ds (Left mempty)) (stepWire wr' ds (Right x)) Left ex -> liftM2 (\(_, wl) (_, wr) -> lstrict (Left ex, wl +++ wr)) (stepWire wl' ds (Left ex)) (stepWire wr' ds (Left ex)) wl' ||| wr' = WGen $ \ds mmx' -> case mmx' of Right (Left x) -> do liftM2 (\(mx, wl) (_, wr) -> lstrict (mx, wl ||| wr)) (stepWire wl' ds (Right x)) (stepWire wr' ds (Left mempty)) Right (Right x) -> do liftM2 (\(_, wl) (mx, wr) -> lstrict (mx, wl ||| wr)) (stepWire wl' ds (Left mempty)) (stepWire wr' ds (Right x)) Left ex -> liftM2 (\(_, wl) (_, wr) -> lstrict (Left ex, wl ||| wr)) (stepWire wl' ds (Left ex)) (stepWire wr' ds (Left ex)) instance (MonadFix m) => ArrowLoop (Wire s e m) where loop w' = WGen $ \ds mx' -> liftM (fmap fst ***! loop) . mfix $ \ ~(mx, _) -> let d | Right (_, d) <- mx = d | otherwise = error "Feedback broken by inhibition" in stepWire w' ds (fmap (, d) mx') instance (Monad m, Monoid e) => ArrowPlus (Wire s e m) where (<+>) = (<|>) instance (Monad m, Monoid e) => ArrowZero (Wire s e m) where zeroArrow = empty instance (Monad m) => Category (Wire s e m) where id = WId w2' . w1' = WGen $ \ds mx0 -> do (mx1, w1) <- stepWire w1' ds mx0 (mx2, w2) <- stepWire w2' ds mx1 mx2 `seq` return (mx2, w2 . w1) instance (Monad m, Monoid e) => Choice (Wire s e m) where left' = left right' = right instance (Monad m, Floating b) => Floating (Wire s e m a b) where (**) = liftA2 (**) acos = fmap acos acosh = fmap acosh asin = fmap asin asinh = fmap asinh atan = fmap atan atanh = fmap atanh cos = fmap cos cosh = fmap cosh exp = fmap exp log = fmap log logBase = liftA2 logBase pi = pure pi sin = fmap sin sinh = fmap sinh sqrt = fmap sqrt tan = fmap tan tanh = fmap tanh instance (Monad m, Fractional b) => Fractional (Wire s e m a b) where (/) = liftA2 (/) recip = fmap recip fromRational = pure . fromRational instance (Monad m) => Functor (Wire s e m a) where fmap f (WArr g) = WArr (fmap f . g) fmap f (WConst mx) = WConst (fmap f mx) fmap f (WGen g) = WGen (\ds -> liftM (fmap f ***! fmap f) . g ds) fmap f WId = WArr (fmap f) fmap f (WPure g) = WPure (\ds -> (fmap f ***! fmap f) . g ds) instance (Monad m, IsString b) => IsString (Wire s e m a b) where fromString = pure . fromString instance (Monad m, Monoid b) => Monoid (Wire s e m a b) where mempty = pure mempty mappend = liftA2 mappend instance (Monad m, Num b) => Num (Wire s e m a b) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) abs = fmap abs negate = fmap negate signum = fmap signum fromInteger = pure . fromInteger instance (Monad m) => Profunctor (Wire s e m) where dimap f g (WArr h) = WArr (fmap g . h . fmap f) dimap _ g (WConst mx) = WConst (fmap g mx) dimap f g (WGen h) = WGen (\ds -> liftM (fmap g ***! dimap f g) . h ds . fmap f) dimap f g WId = WArr (fmap (g . f)) dimap f g (WPure h) = WPure (\ds -> (fmap g ***! dimap f g) . h ds . fmap f) lmap f (WArr g) = WArr (g . fmap f) lmap _ (WConst mx) = WConst mx lmap f (WGen g) = WGen (\ds -> liftM (fmap (lmap f)) . g ds . fmap f) lmap f WId = WArr (fmap f) lmap f (WPure g) = WPure (\ds -> fmap (lmap f) . g ds . fmap f) rmap = fmap instance (Monad m, Sg.Semigroup b) => Sg.Semigroup (Wire s e m a b) where (<>) = liftA2 (Sg.<>) instance (Monad m, Monoid e) => Strong (Wire s e m) where first' = first second' = second -- | Left-strict version of '&&&' for functions. (&&&!) :: (a -> b) -> (a -> c) -> (a -> (b, c)) (&&&!) f g x' = let (x, y) = (f x', g x') in x `seq` (x, y) -- | Left-strict version of '***' for functions. (***!) :: (a -> c) -> (b -> d) -> ((a, b) -> (c, d)) (***!) f g (x', y') = let (x, y) = (f x', g y') in x `seq` (x, y) -- | This wire delays its input signal by the smallest possible -- (semantically infinitesimal) amount of time. You can use it when you -- want to use feedback ('ArrowLoop'): If the user of the feedback -- depends on /now/, delay the value before feeding it back. The -- argument value is the replacement signal at the beginning. -- -- * Depends: before now. delay :: a -> Wire s e m a a delay x' = mkSFN $ \x -> (x', delay x) -- | Evaluate the input signal using the given 'Strategy' here. This -- wire evaluates only produced values. -- -- * Depends: now. evalWith :: Strategy a -> Wire s e m a a evalWith s = WArr $ \mx -> case mx of Right x -> (x `using` s) `seq` mx Left _ -> mx -- | Force the input signal to WHNF here. This wire forces both -- produced values and inhibition values. -- -- * Depends: now. force :: Wire s e m a a force = WArr $ \mx -> case mx of Right x -> x `seq` mx Left ex -> ex `seq` mx -- | Force the input signal to NF here. This wire forces only produced -- values. -- -- * Depends: now. forceNF :: (NFData a) => Wire s e m a a forceNF = WArr $ \mx -> case mx of Right x -> x `deepseq` mx Left _ -> mx -- | Left-strict tuple. lstrict :: (a, b) -> (a, b) lstrict (x, y) = x `seq` (x, y) -- | Apply the given function to the wire's inhibition value. mapLeft :: (Monad m) => (e -> e) -> Wire s e m a b -> Wire s e m a b mapLeft _ w1@WId = w1 mapLeft f' w = mapOutput f w where f (Left ex) = Left (f' ex) f (Right x) = Right x -- | Apply the given function to the wire's output. mapOutput :: (Monad m) => (Either e b' -> Either e b) -> Wire s e m a b' -> Wire s e m a b mapOutput f (WArr g) = WArr (f . g) mapOutput f (WConst mx) = WConst (f mx) mapOutput f (WGen g) = WGen (\ds -> liftM (f *** mapOutput f) . g ds) mapOutput f WId = WArr f mapOutput f (WPure g) = WPure (\ds -> (f *** mapOutput f) . g ds) -- | Apply the given monad morphism to the wire's underlying monad. mapWire :: (Monad m', Monad m) => (forall a. m' a -> m a) -> Wire s e m' a b -> Wire s e m a b mapWire _ (WArr g) = WArr g mapWire _ (WConst mx) = WConst mx mapWire f (WGen g) = WGen (\ds -> liftM (lstrict . second (mapWire f)) . f . g ds) mapWire _ WId = WId mapWire f (WPure g) = WPure (\ds -> lstrict . second (mapWire f) . g ds) -- | Construct a stateless wire from the given signal mapping function. mkConst :: Either e b -> Wire s e m a b mkConst = WConst -- | Construct the empty wire, which inhibits forever. mkEmpty :: (Monoid e) => Wire s e m a b mkEmpty = mkConst (Left mempty) -- | Construct a stateful wire from the given transition function. mkGen :: (Monad m, Monoid s) => (s -> a -> m (Either e b, Wire s e m a b)) -> Wire s e m a b mkGen f = loop mempty where loop s' = WGen $ \ds mx -> let s = s' <> ds in s `seq` case mx of Left ex -> return (Left ex, loop s) Right x' -> liftM lstrict (f s x') -- | Construct a stateless wire from the given transition function. mkGen_ :: (Monad m) => (a -> m (Either e b)) -> Wire s e m a b mkGen_ f = loop where loop = WGen $ \_ mx -> case mx of Left ex -> return (Left ex, loop) Right x -> liftM (lstrict . (, loop)) (f x) -- | Construct a stateful wire from the given transition function. mkGenN :: (Monad m) => (a -> m (Either e b, Wire s e m a b)) -> Wire s e m a b mkGenN f = loop where loop = WGen $ \_ mx -> case mx of Left ex -> return (Left ex, loop) Right x' -> liftM lstrict (f x') -- | Construct the identity wire. mkId :: Wire s e m a a mkId = WId -- | Construct a pure stateful wire from the given transition function. mkPure :: (Monoid s) => (s -> a -> (Either e b, Wire s e m a b)) -> Wire s e m a b mkPure f = loop mempty where loop s' = WPure $ \ds mx -> let s = s' <> ds in s `seq` case mx of Left ex -> (Left ex, loop s) Right x' -> lstrict (f s x') -- | Construct a pure stateless wire from the given transition function. mkPure_ :: (a -> Either e b) -> Wire s e m a b mkPure_ f = WArr $ (>>= f) -- | Construct a pure stateful wire from the given transition function. mkPureN :: (a -> (Either e b, Wire s e m a b)) -> Wire s e m a b mkPureN f = loop where loop = WPure $ \_ mx -> case mx of Left ex -> (Left ex, loop) Right x' -> lstrict (f x') -- | Construct a pure stateful wire from the given signal function. mkSF :: (Monoid s) => (s -> a -> (b, Wire s e m a b)) -> Wire s e m a b mkSF f = mkPure (\ds -> lstrict . first (Right) . f ds) -- | Construct a pure stateless wire from the given function. mkSF_ :: (a -> b) -> Wire s e m a b mkSF_ f = WArr (fmap f) -- | Construct a pure stateful wire from the given signal function. mkSFN :: (a -> (b, Wire s e m a b)) -> Wire s e m a b mkSFN f = mkPureN (lstrict . first (Right) . f) -- | Perform one step of the given wire. stepWire :: (Monad m) => Wire s e m a b -> s -> Either e a -> m (Either e b, Wire s e m a b) stepWire w@(WArr f) _ mx' = return (f mx', w) stepWire w@(WConst mx) _ mx' = return (mx' *> mx, w) stepWire (WGen f) ds mx' = f ds mx' stepWire w@WId _ mx' = return (mx', w) stepWire (WPure f) ds mx' = return (f ds mx')
jship/metronome
local_deps/netwire/Control/Wire/Core.hs
bsd-3-clause
13,473
0
19
4,725
5,668
2,948
2,720
-1
-1
module Opaleye.Internal.PrimQuery where import Prelude hiding (product) import qualified Data.List.NonEmpty as NEL import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import Opaleye.Internal.HaskellDB.PrimQuery (Symbol) data LimitOp = LimitOp Int | OffsetOp Int | LimitOffsetOp Int Int deriving Show data BinOp = Except | Union | UnionAll deriving Show data JoinType = LeftJoin deriving Show -- In the future it may make sense to introduce this datatype -- type Bindings a = [(Symbol, a)] -- We use a 'NEL.NonEmpty' for Product because otherwise we'd have to check -- for emptiness explicity in the SQL generation phase. data PrimQuery = Unit | BaseTable String [(Symbol, HPQ.PrimExpr)] | Product (NEL.NonEmpty PrimQuery) [HPQ.PrimExpr] | Aggregate [(Symbol, (Maybe HPQ.AggrOp, HPQ.PrimExpr))] PrimQuery | Order [HPQ.OrderExpr] PrimQuery | Limit LimitOp PrimQuery | Join JoinType HPQ.PrimExpr PrimQuery PrimQuery | Values [Symbol] [[HPQ.PrimExpr]] | Binary BinOp [(Symbol, (HPQ.PrimExpr, HPQ.PrimExpr))] (PrimQuery, PrimQuery) deriving Show type PrimQueryFold p = ( p , String -> [(Symbol, HPQ.PrimExpr)] -> p , NEL.NonEmpty p -> [HPQ.PrimExpr] -> p , [(Symbol, (Maybe HPQ.AggrOp, HPQ.PrimExpr))] -> p -> p , [HPQ.OrderExpr] -> p -> p , LimitOp -> p -> p , JoinType -> HPQ.PrimExpr -> p -> p -> p , [Symbol] -> [[HPQ.PrimExpr]] -> p , BinOp -> [(Symbol, (HPQ.PrimExpr, HPQ.PrimExpr))] -> (p, p) -> p ) foldPrimQuery :: PrimQueryFold p -> PrimQuery -> p foldPrimQuery (unit, baseTable, product, aggregate, order, limit, join, values, binary) = fix fold where fold self primQ = case primQ of Unit -> unit BaseTable n s -> baseTable n s Product pqs pes -> product (fmap self pqs) pes Aggregate aggrs pq -> aggregate aggrs (self pq) Order pes pq -> order pes (self pq) Limit op pq -> limit op (self pq) Join j cond q1 q2 -> join j cond (self q1) (self q2) Values ss pes -> values ss pes Binary binop pes (pq, pq') -> binary binop pes (self pq, self pq') fix f = let x = f x in x times :: PrimQuery -> PrimQuery -> PrimQuery times q q' = Product (q NEL.:| [q']) [] restrict :: HPQ.PrimExpr -> PrimQuery -> PrimQuery restrict cond primQ = Product (return primQ) [cond] isUnit :: PrimQuery -> Bool isUnit Unit = True isUnit _ = False
alanz/haskell-opaleye
src/Opaleye/Internal/PrimQuery.hs
bsd-3-clause
2,847
0
12
979
858
474
384
49
9
{-| Module : IRTS.DumpBC Description : Serialise Idris to its IBC format. Copyright : License : BSD3 Maintainer : The Idris Community. -} module IRTS.DumpBC where import IRTS.Lang import IRTS.Simplified import Idris.Core.TT import IRTS.Bytecode import Data.List interMap :: [a] -> [b] -> (a -> [b]) -> [b] interMap xs y f = concat (intersperse y (map f xs)) indent :: Int -> String indent n = replicate (n*4) ' ' serializeReg :: Reg -> String serializeReg (L n) = "L" ++ show n serializeReg (T n) = "T" ++ show n serializeReg r = show r serializeCase :: Show a => Int -> (a, [BC]) -> String serializeCase n (x, bcs) = indent n ++ show x ++ ":\n" ++ interMap bcs "\n" (serializeBC (n + 1)) serializeDefault :: Int -> [BC] -> String serializeDefault n bcs = indent n ++ "default:\n" ++ interMap bcs "\n" (serializeBC (n + 1)) serializeBC :: Int -> BC -> String serializeBC n bc = indent n ++ case bc of ASSIGN a b -> "ASSIGN " ++ serializeReg a ++ " " ++ serializeReg b ASSIGNCONST a b -> "ASSIGNCONST " ++ serializeReg a ++ " " ++ show b UPDATE a b -> "UPDATE " ++ serializeReg a ++ " " ++ serializeReg b MKCON a Nothing b xs -> "MKCON " ++ serializeReg a ++ " " ++ show b ++ " [" ++ (interMap xs ", " serializeReg) ++ "]" MKCON a (Just r) b xs -> "MKCON@" ++ serializeReg r ++ " " ++ serializeReg a ++ " " ++ show b ++ " [" ++ (interMap xs ", " serializeReg) ++ "]" CASE safe r cases def -> "CASE " ++ serializeReg r ++ ":\n" ++ interMap cases "\n" (serializeCase (n + 1)) ++ maybe "" (\def' -> "\n" ++ serializeDefault (n + 1) def') def PROJECT a b c -> "PROJECT " ++ serializeReg a ++ " " ++ show b ++ " " ++ show c PROJECTINTO a b c -> "PROJECTINTO " ++ serializeReg a ++ " " ++ serializeReg b ++ " " ++ show c CONSTCASE r cases def -> "CONSTCASE " ++ serializeReg r ++ ":\n" ++ interMap cases "\n" (serializeCase (n + 1)) ++ maybe "" (\def' -> "\n" ++ serializeDefault (n + 1) def') def CALL x -> "CALL " ++ show x TAILCALL x -> "TAILCALL " ++ show x FOREIGNCALL r ret name args -> "FOREIGNCALL " ++ serializeReg r ++ " \"" ++ show name ++ "\" " ++ show ret ++ " [" ++ interMap args ", " (\(ty, r) -> serializeReg r ++ " : " ++ show ty) ++ "]" SLIDE n -> "SLIDE " ++ show n REBASE -> "REBASE" RESERVE n -> "RESERVE " ++ show n ADDTOP n -> "ADDTOP " ++ show n TOPBASE n -> "TOPBASE " ++ show n BASETOP n -> "BASETOP " ++ show n STOREOLD -> "STOREOLD" OP a b c -> "OP " ++ serializeReg a ++ " " ++ show b ++ " [" ++ interMap c ", " serializeReg ++ "]" NULL r -> "NULL " ++ serializeReg r ERROR s -> "ERROR \"" ++ s ++ "\"" -- FIXME: s may contain quotes -- Issue #1596 serialize :: [(Name, [BC])] -> String serialize decls = interMap decls "\n\n" serializeDecl where serializeDecl :: (Name, [BC]) -> String serializeDecl (name, bcs) = show name ++ ":\n" ++ interMap bcs "\n" (serializeBC 1) dumpBC :: [(Name, SDecl)] -> String -> IO () dumpBC c output = writeFile output $ serialize $ map toBC c
enolan/Idris-dev
src/IRTS/DumpBC.hs
bsd-3-clause
3,232
0
17
934
1,278
628
650
67
22
{-# LANGUAGE StandaloneKindSignatures #-} {-# LANGUAGE RankNTypes, DataKinds, PolyKinds, GADTs, TypeFamilies #-} module SAKS_026 where import Data.Kind data HigherRank (f :: forall x. x -> Type) data P :: forall k. k -> Type type PSyn :: forall k. k -> Type type PSyn = (P :: forall k. k -> Type) type Test = HigherRank PSyn
sdiehl/ghc
testsuite/tests/saks/should_compile/saks026.hs
bsd-3-clause
331
1
7
63
90
56
34
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} #if __GLASGOW_HASKELL__ >= 711 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif ----------------------------------------------------------------------------- -- | -- Module : Control.Lens.Internal.Fold -- Copyright : (C) 2012-2015 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- ---------------------------------------------------------------------------- module Control.Lens.Internal.Fold ( -- * Monoids for folding Folding(..) , Traversed(..) , Sequenced(..) , Max(..), getMax , Min(..), getMin , Leftmost(..), getLeftmost , Rightmost(..), getRightmost , ReifiedMonoid(..), M(..) , reifyFold ) where import Control.Applicative import Control.Lens.Internal.Getter import Data.Functor.Bind import Data.Functor.Contravariant import Data.Maybe import Data.Semigroup hiding (Min, getMin, Max, getMax) import Data.Reflection import Prelude #ifdef HLINT {-# ANN module "HLint: ignore Avoid lambda" #-} #endif ------------------------------------------------------------------------------ -- Folding ------------------------------------------------------------------------------ -- | A 'Monoid' for a 'Contravariant' 'Applicative'. newtype Folding f a = Folding { getFolding :: f a } instance (Contravariant f, Apply f) => Semigroup (Folding f a) where Folding fr <> Folding fs = Folding (fr .> fs) {-# INLINE (<>) #-} instance (Contravariant f, Applicative f) => Monoid (Folding f a) where mempty = Folding noEffect {-# INLINE mempty #-} Folding fr `mappend` Folding fs = Folding (fr *> fs) {-# INLINE mappend #-} ------------------------------------------------------------------------------ -- Traversed ------------------------------------------------------------------------------ -- | Used internally by 'Control.Lens.Traversal.traverseOf_' and the like. -- -- The argument 'a' of the result should not be used! newtype Traversed a f = Traversed { getTraversed :: f a } instance Apply f => Semigroup (Traversed a f) where Traversed ma <> Traversed mb = Traversed (ma .> mb) {-# INLINE (<>) #-} instance Applicative f => Monoid (Traversed a f) where mempty = Traversed (pure (error "Traversed: value used")) {-# INLINE mempty #-} Traversed ma `mappend` Traversed mb = Traversed (ma *> mb) {-# INLINE mappend #-} ------------------------------------------------------------------------------ -- Sequenced ------------------------------------------------------------------------------ -- | Used internally by 'Control.Lens.Traversal.mapM_' and the like. -- -- The argument 'a' of the result should not be used! newtype Sequenced a m = Sequenced { getSequenced :: m a } instance Apply m => Semigroup (Sequenced a m) where Sequenced ma <> Sequenced mb = Sequenced (ma .> mb) {-# INLINE (<>) #-} instance Monad m => Monoid (Sequenced a m) where mempty = Sequenced (return (error "Sequenced: value used")) {-# INLINE mempty #-} Sequenced ma `mappend` Sequenced mb = Sequenced (ma >> mb) {-# INLINE mappend #-} ------------------------------------------------------------------------------ -- Min ------------------------------------------------------------------------------ -- | Used for 'Control.Lens.Fold.minimumOf'. data Min a = NoMin | Min a instance Ord a => Semigroup (Min a) where NoMin <> m = m m <> NoMin = m Min a <> Min b = Min (min a b) {-# INLINE (<>) #-} instance Ord a => Monoid (Min a) where mempty = NoMin {-# INLINE mempty #-} mappend NoMin m = m mappend m NoMin = m mappend (Min a) (Min b) = Min (min a b) {-# INLINE mappend #-} -- | Obtain the minimum. getMin :: Min a -> Maybe a getMin NoMin = Nothing getMin (Min a) = Just a {-# INLINE getMin #-} ------------------------------------------------------------------------------ -- Max ------------------------------------------------------------------------------ -- | Used for 'Control.Lens.Fold.maximumOf'. data Max a = NoMax | Max a instance Ord a => Semigroup (Max a) where NoMax <> m = m m <> NoMax = m Max a <> Max b = Max (max a b) {-# INLINE (<>) #-} instance Ord a => Monoid (Max a) where mempty = NoMax {-# INLINE mempty #-} mappend NoMax m = m mappend m NoMax = m mappend (Max a) (Max b) = Max (max a b) {-# INLINE mappend #-} -- | Obtain the maximum. getMax :: Max a -> Maybe a getMax NoMax = Nothing getMax (Max a) = Just a {-# INLINE getMax #-} ------------------------------------------------------------------------------ -- Leftmost and Rightmost ------------------------------------------------------------------------------ -- | Used for 'Control.Lens.Fold.preview'. data Leftmost a = LPure | LLeaf a | LStep (Leftmost a) instance Semigroup (Leftmost a) where (<>) = mappend {-# INLINE (<>) #-} instance Monoid (Leftmost a) where mempty = LPure {-# INLINE mempty #-} mappend x y = LStep $ case x of LPure -> y LLeaf _ -> x LStep x' -> case y of -- The last two cases make firstOf produce a Just as soon as any element -- is encountered, and possibly serve as a micro-optimisation; this -- behaviour can be disabled by replacing them with _ -> mappend x y'. -- Note that this means that firstOf (backwards folded) [1..] is Just _|_. LPure -> x' LLeaf a -> LLeaf $ fromMaybe a (getLeftmost x') LStep y' -> mappend x' y' -- | Extract the 'Leftmost' element. This will fairly eagerly determine that it can return 'Just' -- the moment it sees any element at all. getLeftmost :: Leftmost a -> Maybe a getLeftmost LPure = Nothing getLeftmost (LLeaf a) = Just a getLeftmost (LStep x) = getLeftmost x -- | Used for 'Control.Lens.Fold.lastOf'. data Rightmost a = RPure | RLeaf a | RStep (Rightmost a) instance Semigroup (Rightmost a) where (<>) = mappend {-# INLINE (<>) #-} instance Monoid (Rightmost a) where mempty = RPure {-# INLINE mempty #-} mappend x y = RStep $ case y of RPure -> x RLeaf _ -> y RStep y' -> case x of -- The last two cases make lastOf produce a Just as soon as any element -- is encountered, and possibly serve as a micro-optimisation; this -- behaviour can be disabled by replacing them with _ -> mappend x y'. -- Note that this means that lastOf folded [1..] is Just _|_. RPure -> y' RLeaf a -> RLeaf $ fromMaybe a (getRightmost y') RStep x' -> mappend x' y' -- | Extract the 'Rightmost' element. This will fairly eagerly determine that it can return 'Just' -- the moment it sees any element at all. getRightmost :: Rightmost a -> Maybe a getRightmost RPure = Nothing getRightmost (RLeaf a) = Just a getRightmost (RStep x) = getRightmost x ------------------------------------------------------------------------------ -- Folding with Reified Monoid ------------------------------------------------------------------------------ data ReifiedMonoid a = ReifiedMonoid { reifiedMappend :: a -> a -> a, reifiedMempty :: a } instance Reifies s (ReifiedMonoid a) => Monoid (M a s) where mappend (M x) (M y) = reflectResult (\m -> M (reifiedMappend m x y)) mempty = reflectResult (\m -> M (reifiedMempty m )) reflectResult :: Reifies s a => (a -> f s) -> f s reflectResult f = let r = f (reflect r) in r newtype M a s = M a unM :: M a s -> proxy s -> a unM (M a) _ = a reifyFold :: (a -> a -> a) -> a -> (forall s. Reifies s (ReifiedMonoid a) => t -> M a s) -> t -> a reifyFold f z m xs = reify (ReifiedMonoid f z) (unM (m xs))
danidiaz/lens
src/Control/Lens/Internal/Fold.hs
bsd-3-clause
7,712
0
16
1,478
1,826
981
845
131
1
{- This module handles generation of position independent code and dynamic-linking related issues for the native code generator. This depends both the architecture and OS, so we define it here instead of in one of the architecture specific modules. Things outside this module which are related to this: + module CLabel - PIC base label (pretty printed as local label 1) - DynamicLinkerLabels - several kinds: CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset - labelDynamic predicate + module Cmm - The GlobalReg datatype has a PicBaseReg constructor - The CmmLit datatype has a CmmLabelDiffOff constructor + codeGen & RTS - When tablesNextToCode, no absolute addresses are stored in info tables any more. Instead, offsets from the info label are used. - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers because Win32 doesn't support external references in data sections. TODO: make sure this still works, it might be bitrotted + NCG - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all labels. - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output all the necessary stuff for imported symbols. - The NCG monad keeps track of a list of imported symbols. - MachCodeGen invokes initializePicBase to generate code to initialize the PIC base register when needed. - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel that wasn't in the original Cmm code (e.g. floating point literals). -} module PIC ( cmmMakeDynamicReference, CmmMakeDynamicReferenceM(..), ReferenceKind(..), needImportedSymbols, pprImportedSymbol, pprGotDeclaration, initializePicBase_ppc, initializePicBase_x86 ) where import qualified PPC.Instr as PPC import qualified PPC.Regs as PPC import qualified X86.Instr as X86 import Platform import Instruction import Reg import NCGMonad import Hoopl import Cmm import CLabel ( CLabel, ForeignLabelSource(..), pprCLabel, mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..), dynamicLinkerLabelInfo, mkPicBaseLabel, labelDynamic, externallyVisibleCLabel ) import CLabel ( mkForeignLabel ) import BasicTypes import Module import Outputable import DynFlags import FastString -------------------------------------------------------------------------------- -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm -- code. It does The Right Thing(tm) to convert the CmmLabel into a -- position-independent, dynamic-linking-aware reference to the thing -- in question. -- Note that this also has to be called from MachCodeGen in order to -- access static data like floating point literals (labels that were -- created after the cmmToCmm pass). -- The function must run in a monad that can keep track of imported symbols -- A function for recording an imported symbol must be passed in: -- - addImportCmmOpt for the CmmOptM monad -- - addImportNat for the NatM monad. data ReferenceKind = DataReference | CallReference | JumpReference deriving(Eq) class Monad m => CmmMakeDynamicReferenceM m where addImport :: CLabel -> m () getThisModule :: m Module instance CmmMakeDynamicReferenceM NatM where addImport = addImportNat getThisModule = getThisModuleNat cmmMakeDynamicReference :: CmmMakeDynamicReferenceM m => DynFlags -> ReferenceKind -- whether this is the target of a jump -> CLabel -- the label -> m CmmExpr cmmMakeDynamicReference dflags referenceKind lbl | Just _ <- dynamicLinkerLabelInfo lbl = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through | otherwise = do this_mod <- getThisModule case howToAccessLabel dflags (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) this_mod referenceKind lbl of AccessViaStub -> do let stub = mkDynamicLinkerLabel CodeStub lbl addImport stub return $ CmmLit $ CmmLabel stub AccessViaSymbolPtr -> do let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl addImport symbolPtr return $ CmmLoad (cmmMakePicReference dflags symbolPtr) (bWord dflags) AccessDirectly -> case referenceKind of -- for data, we might have to make some calculations: DataReference -> return $ cmmMakePicReference dflags lbl -- all currently supported processors support -- PC-relative branch and call instructions, -- so just jump there if it's a call or a jump _ -> return $ CmmLit $ CmmLabel lbl -- ----------------------------------------------------------------------------- -- Create a position independent reference to a label. -- (but do not bother with dynamic linking). -- We calculate the label's address by adding some (platform-dependent) -- offset to our base register; this offset is calculated by -- the function picRelative in the platform-dependent part below. cmmMakePicReference :: DynFlags -> CLabel -> CmmExpr cmmMakePicReference dflags lbl -- Windows doesn't need PIC, -- everything gets relocated at runtime | OSMinGW32 <- platformOS $ targetPlatform dflags = CmmLit $ CmmLabel lbl | (gopt Opt_PIC dflags || not (gopt Opt_Static dflags)) && absoluteLabel lbl = CmmMachOp (MO_Add (wordWidth dflags)) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | otherwise = CmmLit $ CmmLabel lbl absoluteLabel :: CLabel -> Bool absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of Just (GotSymbolPtr, _) -> False Just (GotSymbolOffset, _) -> False _ -> True -------------------------------------------------------------------------------- -- Knowledge about how special dynamic linker labels like symbol -- pointers, code stubs and GOT offsets look like is located in the -- module CLabel. -- We have to decide which labels need to be accessed -- indirectly or via a piece of stub code. data LabelAccessStyle = AccessViaStub | AccessViaSymbolPtr | AccessDirectly howToAccessLabel :: DynFlags -> Arch -> OS -> Module -> ReferenceKind -> CLabel -> LabelAccessStyle -- Windows -- In Windows speak, a "module" is a set of objects linked into the -- same Portable Exectuable (PE) file. (both .exe and .dll files are PEs). -- -- If we're compiling a multi-module program then symbols from other modules -- are accessed by a symbol pointer named __imp_SYMBOL. At runtime we have the -- following. -- -- (in the local module) -- __imp_SYMBOL: addr of SYMBOL -- -- (in the other module) -- SYMBOL: the real function / data. -- -- To access the function at SYMBOL from our local module, we just need to -- dereference the local __imp_SYMBOL. -- -- If Opt_Static is set then we assume that all our code will be linked -- into the same .exe file. In this case we always access symbols directly, -- and never use __imp_SYMBOL. -- howToAccessLabel dflags _ OSMinGW32 this_mod _ lbl -- Assume all symbols will be in the same PE, so just access them directly. | gopt Opt_Static dflags = AccessDirectly -- If the target symbol is in another PE we need to access it via the -- appropriate __imp_SYMBOL pointer. | labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr -- Target symbol is in the same PE as the caller, so just access it directly. | otherwise = AccessDirectly -- Mach-O (Darwin, Mac OS X) -- -- Indirect access is required in the following cases: -- * things imported from a dynamic library -- * (not on x86_64) data from a different module, if we're generating PIC code -- It is always possible to access something indirectly, -- even when it's not necessary. -- howToAccessLabel dflags arch OSDarwin this_mod DataReference lbl -- data access to a dynamic library goes via a symbol pointer | labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr -- when generating PIC code, all cross-module data references must -- must go via a symbol pointer, too, because the assembler -- cannot generate code for a label difference where one -- label is undefined. Doesn't apply t x86_64. -- Unfortunately, we don't know whether it's cross-module, -- so we do it for all externally visible labels. -- This is a slight waste of time and space, but otherwise -- we'd need to pass the current Module all the way in to -- this function. | arch /= ArchX86_64 , gopt Opt_PIC dflags && externallyVisibleCLabel lbl = AccessViaSymbolPtr | otherwise = AccessDirectly howToAccessLabel dflags arch OSDarwin this_mod JumpReference lbl -- dyld code stubs don't work for tailcalls because the -- stack alignment is only right for regular calls. -- Therefore, we have to go via a symbol pointer: | arch == ArchX86 || arch == ArchX86_64 , labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr howToAccessLabel dflags arch OSDarwin this_mod _ lbl -- Code stubs are the usual method of choice for imported code; -- not needed on x86_64 because Apple's new linker, ld64, generates -- them automatically. | arch /= ArchX86_64 , labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaStub | otherwise = AccessDirectly -- ELF (Linux) -- -- ELF tries to pretend to the main application code that dynamic linking does -- not exist. While this may sound convenient, it tends to mess things up in -- very bad ways, so we have to be careful when we generate code for the main -- program (-dynamic but no -fPIC). -- -- Indirect access is required for references to imported symbols -- from position independent code. It is also required from the main program -- when dynamic libraries containing Haskell code are used. howToAccessLabel _ ArchPPC_64 os _ kind _ | osElfTarget os = if kind == DataReference -- ELF PPC64 (powerpc64-linux), AIX, MacOS 9, BeOS/PPC then AccessViaSymbolPtr -- actually, .label instead of label else AccessDirectly howToAccessLabel dflags _ os _ _ _ -- no PIC -> the dynamic linker does everything for us; -- if we don't dynamically link to Haskell code, -- it actually manages to do so without messing things up. | osElfTarget os , not (gopt Opt_PIC dflags) && gopt Opt_Static dflags = AccessDirectly howToAccessLabel dflags arch os this_mod DataReference lbl | osElfTarget os = case () of -- A dynamic label needs to be accessed via a symbol pointer. _ | labelDynamic dflags (thisPackage dflags) this_mod lbl -> AccessViaSymbolPtr -- For PowerPC32 -fPIC, we have to access even static data -- via a symbol pointer (see below for an explanation why -- PowerPC32 Linux is especially broken). | arch == ArchPPC , gopt Opt_PIC dflags -> AccessViaSymbolPtr | otherwise -> AccessDirectly -- In most cases, we have to avoid symbol stubs on ELF, for the following reasons: -- on i386, the position-independent symbol stubs in the Procedure Linkage Table -- require the address of the GOT to be loaded into register %ebx on entry. -- The linker will take any reference to the symbol stub as a hint that -- the label in question is a code label. When linking executables, this -- will cause the linker to replace even data references to the label with -- references to the symbol stub. -- This leaves calling a (foreign) function from non-PIC code -- (AccessDirectly, because we get an implicit symbol stub) -- and calling functions from PIC code on non-i386 platforms (via a symbol stub) howToAccessLabel dflags arch os this_mod CallReference lbl | osElfTarget os , labelDynamic dflags (thisPackage dflags) this_mod lbl && not (gopt Opt_PIC dflags) = AccessDirectly | osElfTarget os , arch /= ArchX86 , labelDynamic dflags (thisPackage dflags) this_mod lbl && gopt Opt_PIC dflags = AccessViaStub howToAccessLabel dflags _ os this_mod _ lbl | osElfTarget os = if labelDynamic dflags (thisPackage dflags) this_mod lbl then AccessViaSymbolPtr else AccessDirectly -- all other platforms howToAccessLabel dflags _ _ _ _ _ | not (gopt Opt_PIC dflags) = AccessDirectly | otherwise = panic "howToAccessLabel: PIC not defined for this platform" -- ------------------------------------------------------------------- -- | Says what we we have to add to our 'PIC base register' in order to -- get the address of a label. picRelative :: Arch -> OS -> CLabel -> CmmLit -- Darwin, but not x86_64: -- The PIC base register points to the PIC base label at the beginning -- of the current CmmDecl. We just have to use a label difference to -- get the offset. -- We have already made sure that all labels that are not from the current -- module are accessed indirectly ('as' can't calculate differences between -- undefined labels). picRelative arch OSDarwin lbl | arch /= ArchX86_64 = CmmLabelDiffOff lbl mkPicBaseLabel 0 -- PowerPC Linux: -- The PIC base register points to our fake GOT. Use a label difference -- to get the offset. -- We have made sure that *everything* is accessed indirectly, so this -- is only used for offsets from the GOT to symbol pointers inside the -- GOT. picRelative ArchPPC os lbl | osElfTarget os = CmmLabelDiffOff lbl gotLabel 0 -- Most Linux versions: -- The PIC base register points to the GOT. Use foo@got for symbol -- pointers, and foo@gotoff for everything else. -- Linux and Darwin on x86_64: -- The PIC base register is %rip, we use foo@gotpcrel for symbol pointers, -- and a GotSymbolOffset label for other things. -- For reasons of tradition, the symbol offset label is written as a plain label. picRelative arch os lbl | osElfTarget os || (os == OSDarwin && arch == ArchX86_64) = let result | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl' | otherwise = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl in result picRelative _ _ _ = panic "PositionIndependentCode.picRelative undefined for this platform" -------------------------------------------------------------------------------- needImportedSymbols :: DynFlags -> Arch -> OS -> Bool needImportedSymbols dflags arch os | os == OSDarwin , arch /= ArchX86_64 = True -- PowerPC Linux: -fPIC or -dynamic | osElfTarget os , arch == ArchPPC = gopt Opt_PIC dflags || not (gopt Opt_Static dflags) -- i386 (and others?): -dynamic but not -fPIC | osElfTarget os , arch /= ArchPPC_64 = not (gopt Opt_Static dflags) && not (gopt Opt_PIC dflags) | otherwise = False -- gotLabel -- The label used to refer to our "fake GOT" from -- position-independent code. gotLabel :: CLabel gotLabel -- HACK: this label isn't really foreign = mkForeignLabel (fsLit ".LCTOC1") Nothing ForeignLabelInThisPackage IsData -------------------------------------------------------------------------------- -- We don't need to declare any offset tables. -- However, for PIC on x86, we need a small helper function. pprGotDeclaration :: DynFlags -> Arch -> OS -> SDoc pprGotDeclaration dflags ArchX86 OSDarwin | gopt Opt_PIC dflags = vcat [ ptext (sLit ".section __TEXT,__textcoal_nt,coalesced,no_toc"), ptext (sLit ".weak_definition ___i686.get_pc_thunk.ax"), ptext (sLit ".private_extern ___i686.get_pc_thunk.ax"), ptext (sLit "___i686.get_pc_thunk.ax:"), ptext (sLit "\tmovl (%esp), %eax"), ptext (sLit "\tret") ] pprGotDeclaration _ _ OSDarwin = empty -- Emit GOT declaration -- Output whatever needs to be output once per .s file. pprGotDeclaration dflags arch os | osElfTarget os , arch /= ArchPPC_64 , not (gopt Opt_PIC dflags) = empty | osElfTarget os , arch /= ArchPPC_64 = vcat [ -- See Note [.LCTOC1 in PPC PIC code] ptext (sLit ".section \".got2\",\"aw\""), ptext (sLit ".LCTOC1 = .+32768") ] pprGotDeclaration _ _ _ = panic "pprGotDeclaration: no match" -------------------------------------------------------------------------------- -- On Darwin, we have to generate our own stub code for lazy binding.. -- For each processor architecture, there are two versions, one for PIC -- and one for non-PIC. -- -- Whenever you change something in this assembler output, make sure -- the splitter in driver/split/ghc-split.lprl recognizes the new output pprImportedSymbol :: DynFlags -> Platform -> CLabel -> SDoc pprImportedSymbol dflags platform@(Platform { platformArch = ArchPPC, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ ptext (sLit ".symbol_stub"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tlis r11,ha16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)"), ptext (sLit "\tlwz r12,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)(r11)"), ptext (sLit "\tmtctr r12"), ptext (sLit "\taddi r11,r11,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)"), ptext (sLit "\tbctr") ] True -> vcat [ ptext (sLit ".section __TEXT,__picsymbolstub1,") <> ptext (sLit "symbol_stubs,pure_instructions,32"), ptext (sLit "\t.align 2"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tmflr r0"), ptext (sLit "\tbcl 20,31,L0$") <> pprCLabel platform lbl, ptext (sLit "L0$") <> pprCLabel platform lbl <> char ':', ptext (sLit "\tmflr r11"), ptext (sLit "\taddis r11,r11,ha16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel platform lbl <> char ')', ptext (sLit "\tmtlr r0"), ptext (sLit "\tlwzu r12,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel platform lbl <> ptext (sLit ")(r11)"), ptext (sLit "\tmtctr r12"), ptext (sLit "\tbctr") ] $+$ vcat [ ptext (sLit ".lazy_symbol_pointer"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long dyld_stub_binding_helper")] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ ptext (sLit ".non_lazy_symbol_pointer"), char 'L' <> pprCLabel platform lbl <> ptext (sLit "$non_lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long\t0")] | otherwise = empty pprImportedSymbol dflags platform@(Platform { platformArch = ArchX86, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ ptext (sLit ".symbol_stub"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tjmp *L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder:"), ptext (sLit "\tpushl $L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr"), ptext (sLit "\tjmp dyld_stub_binding_helper") ] True -> vcat [ ptext (sLit ".section __TEXT,__picsymbolstub2,") <> ptext (sLit "symbol_stubs,pure_instructions,25"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tcall ___i686.get_pc_thunk.ax"), ptext (sLit "1:"), ptext (sLit "\tmovl L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-1b(%eax),%edx"), ptext (sLit "\tjmp *%edx"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder:"), ptext (sLit "\tlea L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-1b(%eax),%eax"), ptext (sLit "\tpushl %eax"), ptext (sLit "\tjmp dyld_stub_binding_helper") ] $+$ vcat [ ptext (sLit ".section __DATA, __la_sym_ptr") <> (if gopt Opt_PIC dflags then int 2 else int 3) <> ptext (sLit ",lazy_symbol_pointers"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder")] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ ptext (sLit ".non_lazy_symbol_pointer"), char 'L' <> pprCLabel platform lbl <> ptext (sLit "$non_lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long\t0")] | otherwise = empty pprImportedSymbol _ (Platform { platformOS = OSDarwin }) _ = empty -- ELF / Linux -- -- In theory, we don't need to generate any stubs or symbol pointers -- by hand for Linux. -- -- Reality differs from this in two areas. -- -- 1) If we just use a dynamically imported symbol directly in a read-only -- section of the main executable (as GCC does), ld generates R_*_COPY -- relocations, which are fundamentally incompatible with reversed info -- tables. Therefore, we need a table of imported addresses in a writable -- section. -- The "official" GOT mechanism (label@got) isn't intended to be used -- in position dependent code, so we have to create our own "fake GOT" -- when not Opt_PIC && not (gopt Opt_Static dflags). -- -- 2) PowerPC Linux is just plain broken. -- While it's theoretically possible to use GOT offsets larger -- than 16 bit, the standard crt*.o files don't, which leads to -- linker errors as soon as the GOT size exceeds 16 bit. -- Also, the assembler doesn't support @gotoff labels. -- In order to be able to use a larger GOT, we have to circumvent the -- entire GOT mechanism and do it ourselves (this is also what GCC does). -- When needImportedSymbols is defined, -- the NCG will keep track of all DynamicLinkerLabels it uses -- and output each of them using pprImportedSymbol. pprImportedSymbol _ platform@(Platform { platformArch = ArchPPC_64 }) _ | osElfTarget (platformOS platform) = empty pprImportedSymbol dflags platform importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> let symbolSize = case wordWidth dflags of W32 -> sLit "\t.long" W64 -> sLit "\t.quad" _ -> panic "Unknown wordRep in pprImportedSymbol" in vcat [ ptext (sLit ".section \".got2\", \"aw\""), ptext (sLit ".LC_") <> pprCLabel platform lbl <> char ':', ptext symbolSize <+> pprCLabel platform lbl ] -- PLT code stubs are generated automatically by the dynamic linker. _ -> empty pprImportedSymbol _ _ _ = panic "PIC.pprImportedSymbol: no match" -------------------------------------------------------------------------------- -- Generate code to calculate the address that should be put in the -- PIC base register. -- This is called by MachCodeGen for every CmmProc that accessed the -- PIC base register. It adds the appropriate instructions to the -- top of the CmmProc. -- It is assumed that the first NatCmmDecl in the input list is a Proc -- and the rest are CmmDatas. -- Darwin is simple: just fetch the address of a local label. -- The FETCHPC pseudo-instruction is expanded to multiple instructions -- during pretty-printing so that we don't have to deal with the -- local label: -- PowerPC version: -- bcl 20,31,1f. -- 1: mflr picReg -- i386 version: -- call 1f -- 1: popl %picReg -- Get a pointer to our own fake GOT, which is defined on a per-module basis. -- This is exactly how GCC does it in linux. initializePicBase_ppc :: Arch -> OS -> Reg -> [NatCmmDecl CmmStatics PPC.Instr] -> NatM [NatCmmDecl CmmStatics PPC.Instr] initializePicBase_ppc ArchPPC os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = do let gotOffset = PPC.ImmConstantDiff (PPC.ImmCLbl gotLabel) (PPC.ImmCLbl mkPicBaseLabel) blocks' = case blocks of [] -> [] (b:bs) -> fetchPC b : map maybeFetchPC bs maybeFetchPC b@(BasicBlock bID _) | bID `mapMember` info = fetchPC b | otherwise = b -- GCC does PIC prologs thusly: -- bcl 20,31,.L1 -- .L1: -- mflr 30 -- addis 30,30,.LCTOC1-.L1@ha -- addi 30,30,.LCTOC1-.L1@l -- TODO: below we use it over temporary register, -- it can and should be optimised by picking -- correct PIC reg. fetchPC (BasicBlock bID insns) = BasicBlock bID (PPC.FETCHPC picReg : PPC.ADDIS picReg picReg (PPC.HA gotOffset) : PPC.ADDI picReg picReg (PPC.LO gotOffset) : PPC.MR PPC.r30 picReg : insns) return (CmmProc info lab live (ListGraph blocks') : statics) initializePicBase_ppc ArchPPC OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) -- just one entry because of splitting = return (CmmProc info lab live (ListGraph (b':blocks)) : statics) where BasicBlock bID insns = entry b' = BasicBlock bID (PPC.FETCHPC picReg : insns) initializePicBase_ppc _ _ _ _ = panic "initializePicBase_ppc: not needed" -- We cheat a bit here by defining a pseudo-instruction named FETCHGOT -- which pretty-prints as: -- call 1f -- 1: popl %picReg -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg -- (See PprMach.hs) initializePicBase_x86 :: Arch -> OS -> Reg -> [NatCmmDecl (Alignment, CmmStatics) X86.Instr] -> NatM [NatCmmDecl (Alignment, CmmStatics) X86.Instr] initializePicBase_x86 ArchX86 os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = return (CmmProc info lab live (ListGraph blocks') : statics) where blocks' = case blocks of [] -> [] (b:bs) -> fetchGOT b : map maybeFetchGOT bs -- we want to add a FETCHGOT instruction to the beginning of -- every block that is an entry point, which corresponds to -- the blocks that have entries in the info-table mapping. maybeFetchGOT b@(BasicBlock bID _) | bID `mapMember` info = fetchGOT b | otherwise = b fetchGOT (BasicBlock bID insns) = BasicBlock bID (X86.FETCHGOT picReg : insns) initializePicBase_x86 ArchX86 OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = return (CmmProc info lab live (ListGraph (block':blocks)) : statics) where BasicBlock bID insns = entry block' = BasicBlock bID (X86.FETCHPC picReg : insns) initializePicBase_x86 _ _ _ _ = panic "initializePicBase_x86: not needed"
christiaanb/ghc
compiler/nativeGen/PIC.hs
bsd-3-clause
30,409
0
20
9,073
4,812
2,443
2,369
384
7
module Stackage.GhcPkg where import Stackage.Types import System.Process import Distribution.Text (simpleParse) import Distribution.Version (Version (Version)) import Data.Char (isSpace) import qualified Data.Set as Set getPackages :: [String] -> GhcMajorVersion -> IO (Set PackageIdentifier) getPackages extraArgs version = do output <- readProcess "ghc-pkg" (extraArgs ++ [arg, "list"]) "" fmap Set.unions $ mapM parse $ drop 1 $ lines output where -- Account for a change in command line option name arg | version >= GhcMajorVersion 7 6 = "--no-user-package-db" | otherwise = "--no-user-package-conf" parse s = case clean s of "" -> return Set.empty s' -> case simpleParse s' of Just x -> return $ Set.singleton x Nothing -> error $ "Could not parse ghc-pkg output: " ++ show s clean = stripParens . dropWhile isSpace . reverse . dropWhile isSpace . reverse stripParens x@('(':_:_) | last x == ')' = tail $ init $ x stripParens x = x getGlobalPackages :: GhcMajorVersion -> IO (Set PackageIdentifier) getGlobalPackages version = getPackages [] version getDBPackages :: [FilePath] -> GhcMajorVersion -> IO (Set PackageIdentifier) getDBPackages [] _ = return Set.empty getDBPackages packageDirs version = getPackages (map packageDbArg packageDirs) version where packageDbArg db | version >= GhcMajorVersion 7 6 = "--package-db=" ++ db | otherwise = "--package-conf" ++ db getGhcVersion :: IO GhcMajorVersion getGhcVersion = do versionOutput <- readProcess "ghc-pkg" ["--version"] "" maybe (error $ "Invalid version output: " ++ show versionOutput) return $ do verS:_ <- Just $ reverse $ words versionOutput Version (x:y:_) _ <- simpleParse verS return $ GhcMajorVersion x y
Tarrasch/stackage
Stackage/GhcPkg.hs
mit
1,904
0
15
477
589
289
300
41
4
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="si-LK"> <title>SVN Digger Files</title> <maps> <homeID>svndigger</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/svndigger/src/main/javahelp/help_si_LK/helpset_si_LK.hs
apache-2.0
967
77
66
157
409
207
202
-1
-1
module InfixIn6 where data Inf = Nil | Int :* [Int] f :: (Inf, Either Int Int) -> Int f (a, b) = case a of a@Nil -> hd a a@(b_1 :* b_2) -> hd a f (a, b) = hd a hd :: Inf -> Int hd Nil = 0 hd ((x :* xs)) = x
kmate/HaRe
old/testing/introCase/InfixIn6AST.hs
bsd-3-clause
246
0
10
96
142
78
64
11
2
#!/usr/bin/runhaskell import Distribution.Simple import Distribution.Simple.Setup (ConfigFlags (..)) import Distribution.PackageDescription (emptyHookedBuildInfo,HookedBuildInfo(..)) import Language.Haskell.HsColour (hscolour,Output(CSS)) import Language.Haskell.HsColour.Colourise (defaultColourPrefs) import Control.Monad import Data.Maybe import Data.List main :: IO () main = defaultMainWithHooks hooks hooks :: UserHooks hooks = simpleUserHooks { preConf = myPreConf } -- read template file with markers, call replaceOrEcho for each marker myPreConf :: Args -> ConfigFlags -> IO HookedBuildInfo myPreConf _ _ = do putStr "Generating custom html documentation... " -- file <- readFile "data/astview-tmpl.html" replaced <- mapM replaceOrEcho . lines =<< readFile "data/astview-tmpl.html" putStrLn " done." writeFile "data/astview.html" (unlines . concat $ replaced) return emptyHookedBuildInfo -- echoes the current line, or, if mymatch succeeds: -- replaces the line with colourized haskell code. replaceOrEcho :: String -> IO [String] replaceOrEcho s = if not $ match s then return [s] else do putStr $ (extract s)++" " file <- readFile ("data/"++(extract s)++".hs.txt") let replacement = lines $ hscolour CSS defaultColourPrefs False True (extract s) False file return (["<!-- Example "++(extract s)++" follows: -->"] ++ replacement ++ ["<!-- Example "++(extract s)++" done. -->"]) -- interface that delegates to various implementations: -- recognizes Template marker of the form "%%asdf%%" match :: String -> Bool match = match0 "%%" --extracts the filename from the marker extract :: String -> String extract = extract1 "%%" -------- Implementations -------------- match0 :: String -> String -> Bool match0 p s = take 2 s == p && take 2 (reverse s) == p match1 :: String -> String -> Bool match1 p = liftM2 (&&) (help p) (help p . reverse) where help q = (q ==) . (take (length q)) match2 :: String -> String -> Bool match2 p s = p `isSuffixOf` s && (reverse p) `isPrefixOf` s extract1 :: String -> String -> String extract1 p s = let remainder = (drop (length p) s) in reverse (drop (length p) (reverse remainder) ) extract2 :: String -> String -> String extract2 p s = reverse (drop (length p) (reverse (drop (length p) s))) extract3 :: String -> String -> String extract3 p s = reverse . drop (length p) $ reverse $ drop (length p) s extract4 :: String -> String extract4 = help . reverse . help where help :: String -> String help = fromJust . (stripPrefix "%%%")
kmate/HaRe
hareview/Setup.hs
bsd-3-clause
2,746
0
16
648
825
431
394
60
2
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns , CPP , ExistentialQuantification , NoImplicitPrelude , RecordWildCards , TypeSynonymInstances , FlexibleInstances #-} module GHC.Event.Manager ( -- * Types EventManager -- * Creation , new , newWith , newDefaultBackend -- * Running , finished , loop , step , shutdown , cleanup , wakeManager -- * Registering interest in I/O events , Event , evtRead , evtWrite , IOCallback , FdKey(keyFd) , registerFd_ , registerFd , unregisterFd_ , unregisterFd , closeFd -- * Registering interest in timeout events , TimeoutCallback , TimeoutKey , registerTimeout , updateTimeout , unregisterTimeout ) where #include "EventConfig.h" ------------------------------------------------------------------------ -- Imports import Control.Concurrent.MVar (MVar, modifyMVar, newMVar, readMVar) import Control.Exception (finally) import Control.Monad ((=<<), forM_, liftM, sequence_, when) import Data.IORef (IORef, atomicModifyIORef, mkWeakIORef, newIORef, readIORef, writeIORef) import Data.Maybe (Maybe(..)) import Data.Monoid (mappend, mconcat, mempty) import GHC.Base import GHC.Conc.Signal (runHandlers) import GHC.List (filter) import GHC.Num (Num(..)) import GHC.Real ((/), fromIntegral ) import GHC.Show (Show(..)) import GHC.Event.Clock (getMonotonicTime) import GHC.Event.Control import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite, Timeout(..)) import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique) import System.Posix.Types (Fd) import qualified GHC.Event.IntMap as IM import qualified GHC.Event.Internal as I import qualified GHC.Event.PSQ as Q #if defined(HAVE_KQUEUE) import qualified GHC.Event.KQueue as KQueue #elif defined(HAVE_EPOLL) import qualified GHC.Event.EPoll as EPoll #elif defined(HAVE_POLL) import qualified GHC.Event.Poll as Poll #else # error not implemented for this operating system #endif ------------------------------------------------------------------------ -- Types data FdData = FdData { fdKey :: {-# UNPACK #-} !FdKey , fdEvents :: {-# UNPACK #-} !Event , _fdCallback :: !IOCallback } -- | A file descriptor registration cookie. data FdKey = FdKey { keyFd :: {-# UNPACK #-} !Fd , keyUnique :: {-# UNPACK #-} !Unique } deriving (Eq, Show) -- | Callback invoked on I/O events. type IOCallback = FdKey -> Event -> IO () -- | A timeout registration cookie. newtype TimeoutKey = TK Unique deriving (Eq) -- | Callback invoked on timeout events. type TimeoutCallback = IO () data State = Created | Running | Dying | Finished deriving (Eq, Show) -- | A priority search queue, with timeouts as priorities. type TimeoutQueue = Q.PSQ TimeoutCallback {- Instead of directly modifying the 'TimeoutQueue' in e.g. 'registerTimeout' we keep a list of edits to perform, in the form of a chain of function closures, and have the I/O manager thread perform the edits later. This exist to address the following GC problem: Since e.g. 'registerTimeout' doesn't force the evaluation of the thunks inside the 'emTimeouts' IORef a number of thunks build up inside the IORef. If the I/O manager thread doesn't evaluate these thunks soon enough they'll get promoted to the old generation and become roots for all subsequent minor GCs. When the thunks eventually get evaluated they will each create a new intermediate 'TimeoutQueue' that immediately becomes garbage. Since the thunks serve as roots until the next major GC these intermediate 'TimeoutQueue's will get copied unnecesarily in the next minor GC, increasing GC time. This problem is known as "floating garbage". Keeping a list of edits doesn't stop this from happening but makes the amount of data that gets copied smaller. TODO: Evaluate the content of the IORef to WHNF on each insert once this bug is resolved: http://hackage.haskell.org/trac/ghc/ticket/3838 -} -- | An edit to apply to a 'TimeoutQueue'. type TimeoutEdit = TimeoutQueue -> TimeoutQueue -- | The event manager state. data EventManager = EventManager { emBackend :: !Backend , emFds :: {-# UNPACK #-} !(MVar (IM.IntMap [FdData])) , emTimeouts :: {-# UNPACK #-} !(IORef TimeoutEdit) , emState :: {-# UNPACK #-} !(IORef State) , emUniqueSource :: {-# UNPACK #-} !UniqueSource , emControl :: {-# UNPACK #-} !Control } ------------------------------------------------------------------------ -- Creation handleControlEvent :: EventManager -> FdKey -> Event -> IO () handleControlEvent mgr reg _evt = do msg <- readControlMessage (emControl mgr) (keyFd reg) case msg of CMsgWakeup -> return () CMsgDie -> writeIORef (emState mgr) Finished CMsgSignal fp s -> runHandlers fp s newDefaultBackend :: IO Backend #if defined(HAVE_KQUEUE) newDefaultBackend = KQueue.new #elif defined(HAVE_EPOLL) newDefaultBackend = EPoll.new #elif defined(HAVE_POLL) newDefaultBackend = Poll.new #else newDefaultBackend = error "no back end for this platform" #endif -- | Create a new event manager. new :: IO EventManager new = newWith =<< newDefaultBackend newWith :: Backend -> IO EventManager newWith be = do iofds <- newMVar IM.empty timeouts <- newIORef id ctrl <- newControl state <- newIORef Created us <- newSource _ <- mkWeakIORef state $ do st <- atomicModifyIORef state $ \s -> (Finished, s) when (st /= Finished) $ do I.delete be closeControl ctrl let mgr = EventManager { emBackend = be , emFds = iofds , emTimeouts = timeouts , emState = state , emUniqueSource = us , emControl = ctrl } _ <- registerFd_ mgr (handleControlEvent mgr) (controlReadFd ctrl) evtRead _ <- registerFd_ mgr (handleControlEvent mgr) (wakeupReadFd ctrl) evtRead return mgr -- | Asynchronously shuts down the event manager, if running. shutdown :: EventManager -> IO () shutdown mgr = do state <- atomicModifyIORef (emState mgr) $ \s -> (Dying, s) when (state == Running) $ sendDie (emControl mgr) finished :: EventManager -> IO Bool finished mgr = (== Finished) `liftM` readIORef (emState mgr) cleanup :: EventManager -> IO () cleanup EventManager{..} = do writeIORef emState Finished I.delete emBackend closeControl emControl ------------------------------------------------------------------------ -- Event loop -- | Start handling events. This function loops until told to stop, -- using 'shutdown'. -- -- /Note/: This loop can only be run once per 'EventManager', as it -- closes all of its control resources when it finishes. loop :: EventManager -> IO () loop mgr@EventManager{..} = do state <- atomicModifyIORef emState $ \s -> case s of Created -> (Running, s) _ -> (s, s) case state of Created -> go Q.empty `finally` cleanup mgr Dying -> cleanup mgr _ -> do cleanup mgr error $ "GHC.Event.Manager.loop: state is already " ++ show state where go q = do (running, q') <- step mgr q when running $ go q' step :: EventManager -> TimeoutQueue -> IO (Bool, TimeoutQueue) step mgr@EventManager{..} tq = do (timeout, q') <- mkTimeout tq I.poll emBackend timeout (onFdEvent mgr) state <- readIORef emState state `seq` return (state == Running, q') where -- | Call all expired timer callbacks and return the time to the -- next timeout. mkTimeout :: TimeoutQueue -> IO (Timeout, TimeoutQueue) mkTimeout q = do now <- getMonotonicTime applyEdits <- atomicModifyIORef emTimeouts $ \f -> (id, f) let (expired, q'') = let q' = applyEdits q in q' `seq` Q.atMost now q' sequence_ $ map Q.value expired let timeout = case Q.minView q'' of Nothing -> Forever Just (Q.E _ t _, _) -> -- This value will always be positive since the call -- to 'atMost' above removed any timeouts <= 'now' let t' = t - now in t' `seq` Timeout t' return (timeout, q'') ------------------------------------------------------------------------ -- Registering interest in I/O events -- | Register interest in the given events, without waking the event -- manager thread. The 'Bool' return value indicates whether the -- event manager ought to be woken. registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> IO (FdKey, Bool) registerFd_ EventManager{..} cb fd evs = do u <- newUnique emUniqueSource modifyMVar emFds $ \oldMap -> do let fd' = fromIntegral fd reg = FdKey fd u !fdd = FdData reg evs cb (!newMap, (oldEvs, newEvs)) = case IM.insertWith (++) fd' [fdd] oldMap of (Nothing, n) -> (n, (mempty, evs)) (Just prev, n) -> (n, pairEvents prev newMap fd') modify = oldEvs /= newEvs when modify $ I.modifyFd emBackend fd oldEvs newEvs return (newMap, (reg, modify)) {-# INLINE registerFd_ #-} -- | @registerFd mgr cb fd evs@ registers interest in the events @evs@ -- on the file descriptor @fd@. @cb@ is called for each event that -- occurs. Returns a cookie that can be handed to 'unregisterFd'. registerFd :: EventManager -> IOCallback -> Fd -> Event -> IO FdKey registerFd mgr cb fd evs = do (r, wake) <- registerFd_ mgr cb fd evs when wake $ wakeManager mgr return r {-# INLINE registerFd #-} -- | Wake up the event manager. wakeManager :: EventManager -> IO () wakeManager mgr = sendWakeup (emControl mgr) eventsOf :: [FdData] -> Event eventsOf = mconcat . map fdEvents pairEvents :: [FdData] -> IM.IntMap [FdData] -> Int -> (Event, Event) pairEvents prev m fd = let l = eventsOf prev r = case IM.lookup fd m of Nothing -> mempty Just fds -> eventsOf fds in (l, r) -- | Drop a previous file descriptor registration, without waking the -- event manager thread. The return value indicates whether the event -- manager ought to be woken. unregisterFd_ :: EventManager -> FdKey -> IO Bool unregisterFd_ EventManager{..} (FdKey fd u) = modifyMVar emFds $ \oldMap -> do let dropReg cbs = case filter ((/= u) . keyUnique . fdKey) cbs of [] -> Nothing cbs' -> Just cbs' fd' = fromIntegral fd (!newMap, (oldEvs, newEvs)) = case IM.updateWith dropReg fd' oldMap of (Nothing, _) -> (oldMap, (mempty, mempty)) (Just prev, newm) -> (newm, pairEvents prev newm fd') modify = oldEvs /= newEvs when modify $ I.modifyFd emBackend fd oldEvs newEvs return (newMap, modify) -- | Drop a previous file descriptor registration. unregisterFd :: EventManager -> FdKey -> IO () unregisterFd mgr reg = do wake <- unregisterFd_ mgr reg when wake $ wakeManager mgr -- | Close a file descriptor in a race-safe way. closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO () closeFd mgr close fd = do fds <- modifyMVar (emFds mgr) $ \oldMap -> do close fd case IM.delete (fromIntegral fd) oldMap of (Nothing, _) -> return (oldMap, []) (Just fds, !newMap) -> do when (eventsOf fds /= mempty) $ wakeManager mgr return (newMap, fds) forM_ fds $ \(FdData reg ev cb) -> cb reg (ev `mappend` evtClose) ------------------------------------------------------------------------ -- Registering interest in timeout events -- | Register a timeout in the given number of microseconds. The -- returned 'TimeoutKey' can be used to later unregister or update the -- timeout. The timeout is automatically unregistered after the given -- time has passed. registerTimeout :: EventManager -> Int -> TimeoutCallback -> IO TimeoutKey registerTimeout mgr us cb = do !key <- newUnique (emUniqueSource mgr) if us <= 0 then cb else do now <- getMonotonicTime let expTime = fromIntegral us / 1000000.0 + now -- We intentionally do not evaluate the modified map to WHNF here. -- Instead, we leave a thunk inside the IORef and defer its -- evaluation until mkTimeout in the event loop. This is a -- workaround for a nasty IORef contention problem that causes the -- thread-delay benchmark to take 20 seconds instead of 0.2. atomicModifyIORef (emTimeouts mgr) $ \f -> let f' = (Q.insert key expTime cb) . f in (f', ()) wakeManager mgr return $ TK key -- | Unregister an active timeout. unregisterTimeout :: EventManager -> TimeoutKey -> IO () unregisterTimeout mgr (TK key) = do atomicModifyIORef (emTimeouts mgr) $ \f -> let f' = (Q.delete key) . f in (f', ()) wakeManager mgr -- | Update an active timeout to fire in the given number of -- microseconds. updateTimeout :: EventManager -> TimeoutKey -> Int -> IO () updateTimeout mgr (TK key) us = do now <- getMonotonicTime let expTime = fromIntegral us / 1000000.0 + now atomicModifyIORef (emTimeouts mgr) $ \f -> let f' = (Q.adjust (const expTime) key) . f in (f', ()) wakeManager mgr ------------------------------------------------------------------------ -- Utilities -- | Call the callbacks corresponding to the given file descriptor. onFdEvent :: EventManager -> Fd -> Event -> IO () onFdEvent mgr fd evs = do fds <- readMVar (emFds mgr) case IM.lookup (fromIntegral fd) fds of Just cbs -> forM_ cbs $ \(FdData reg ev cb) -> when (evs `I.eventIs` ev) $ cb reg evs Nothing -> return ()
beni55/haste-compiler
libraries/ghc-7.8/base/GHC/Event/Manager.hs
bsd-3-clause
13,957
0
21
3,479
3,252
1,723
1,529
-1
-1
-- !!! Testing duplicate type constructors data T = K1 data T = K2
wxwxwwxxx/ghc
testsuite/tests/module/mod21.hs
bsd-3-clause
67
0
5
14
16
9
7
2
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Compiler (compileProg) where import Insn import Preprocessor import Program import Data.Either.Unwrap (fromRight) import Control.Monad.State data CompilerState = CompilerState {preprocessorState :: PreprocessorState ,compiledObj :: Object} initialCompilerState :: PreprocessorState -> CompilerState initialCompilerState prep = CompilerState {preprocessorState = prep ,compiledObj = []} newtype Compiler a = Compiler {runCompiler :: State CompilerState a} deriving (Functor,Applicative,Monad,MonadState CompilerState) appendInsn :: Insn -> Compiler () appendInsn insn = modify $ \s -> s {compiledObj = (compiledObj s) ++ [insn]} compileStmt :: Stmt -> Compiler () compileStmt (StInsn insn) = do prep <- gets preprocessorState appendInsn $ modifyInsnExpr (fromRight . (resolveExpr prep)) insn compileStmt _ = return () execCompiler :: PreprocessorState -> Compiler a -> CompilerState execCompiler prep m = execState (runCompiler m) (initialCompilerState prep) compileProg :: PreprocessorState -> Program -> Either String Object compileProg prep prog = Right $ compiledObj $ execCompiler prep $ mapM_ compileStmt prog
nyaxt/dmix
nkmd/as/Compiler.hs
mit
1,278
0
12
257
349
187
162
36
1
module PEPrimes where intSqrt :: Int -> Int intSqrt = floor . sqrt . fromIntegral prime :: Int -> Bool prime 2 = True prime x = if even x then False else computePrime 3 where computePrime p | p <= intSqrt x = if rem x p == 0 then False else computePrime (p+2) computePrime _ = True factorize :: Int -> [Int] factorize x = doFactorize x 2 where doFactorize 1 _ = [] doFactorize y s | prime s && rem y s == 0 = s : doFactorize (div y s) s doFactorize y s = doFactorize y (s+1)
rrohrer/ProjectEuler
haskell/peprimes.hs
mit
525
0
12
153
233
116
117
13
4
module KeyGenerarionPermutations () where
tombusby/haskell-des
keyschedule/KeyGenerarionPermutations.hs
mit
42
0
3
4
7
5
2
1
0
{-# Language KindSignatures, GADTs, TemplateHaskell, NoMonomorphismRestriction, TypeFamilies #-} module Control.Template where import Control.Arrow import Control.Category import Control.Monad import Control.CCA.Apply import Language.Haskell.TH import Language.Haskell.TH.Syntax import Control.CCA.List import Prelude (undefined, Show(..), (++)) data Template :: * -> * -> * where ArrTH :: ExpQ -> (a -> b) -> Template a b (:.) :: Template b c -> Template a b -> Template a c First :: Template a b -> Template (a, c) (b, c) instance Category Template where id = ArrTH lambdaLift id (.) = (:.) instance Arrow Template where arr = ArrTH lambdaLift first = First lambdaLift = do n <- newName "f" lamE [varP n] (varE n) foo = [| \x -> x |] runArrow :: (List l, List l') => Template a b -> l -> (ExpQ, l') runArrow (ArrTH th f) fns = (th, undefined) test :: Template a a test = arr id
farre/ccat
src/Control/Template.hs
mit
907
0
9
175
340
191
149
28
1
module SnakeLadd where end 100 = [] oneL = [1..38] fourL = [4..14] nineL = [9..31]
HaskellForCats/HaskellForCats
SnakeLadd.hs
mit
87
0
5
20
44
26
18
5
1