code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
module Control.Lens.Action.Extras (perform_) where import Control.Lens import Control.Lens.Internal.Action import Data.Profunctor.Unsafe perform_ :: Monad m => Acting m () s a -> s -> m () perform_ l = getEffect #. l (Effect #. const (return ()))
sonyandy/wart-lens
src/Control/Lens/Action/Extras.hs
bsd-3-clause
249
0
12
38
100
54
46
6
1
module SecondTransfer.Utils.Alarm ( newAlarm, cancelAlarm, Alarm, AlarmCancelResult ) where import Control.Concurrent -- import Control.Concurrent.MVar data AlarmCancelResult a = Success_ACR |AlreadyFired_ACR (MVar a) data AlarmState = Waiting |Cancelled |HandlerStarted data Alarm a = Alarm_AtFire (MVar a) (MVar AlarmState) newAlarm :: Int -> IO a ->IO (Alarm a) newAlarm wait_time comp = do wait_for_a <- newEmptyMVar alarm_state <- newMVar Waiting forkIO $ do threadDelay wait_time modifyMVar_ alarm_state $ \ state -> case state of Cancelled -> return Cancelled Waiting -> do forkIO $ do a <- comp putMVar wait_for_a a return $ HandlerStarted HandlerStarted -> error "Logical error" return $ Alarm_AtFire wait_for_a alarm_state cancelAlarm :: Alarm a -> IO (AlarmCancelResult a) cancelAlarm (Alarm_AtFire wait_for_a alarm_state) = do modifyMVar alarm_state $ \ state -> case state of Waiting -> do return (Cancelled, Success_ACR) Cancelled -> do return (Cancelled, Success_ACR) HandlerStarted -> do return $ (HandlerStarted, AlreadyFired_ACR wait_for_a)
shimmercat/second-transfer
hs-src/SecondTransfer/Utils/Alarm.hs
bsd-3-clause
1,378
0
20
463
346
172
174
40
3
{- | Module : $Header$ Copyright : (c) Florian Mossakowski, Uni Bremen 2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : till@informatik.uni-bremen.de Stability : provisional Portability : portable parse terms and formulae -} module ConstraintCASL.Formula where import Common.AnnoState import Common.Id import Common.Lexer import Common.Token import ConstraintCASL.AS_ConstraintCASL import Text.ParserCombinators.Parsec import CASL.AS_Basic_CASL {- ------------------------------------------------------------------------ formula ------------------------------------------------------------------------ -} cformula :: [String] -> AParser st ConstraintFORMULA cformula k = try ( do c1 <- conjunction k impliesT c2 <- conjunction k return (Implication_ConstraintFormula c1 c2)) <|> try ( do c1 <- conjunction k equivalentT c2 <- conjunction k return (Equivalence_ConstraintFormula c1 c2)) <|> do impliesT c <- conjunction k return (Axiom_ConstraintFormula c) conjunction :: [String] -> AParser st ATOMCONJUNCTION conjunction k = do (atoms, _) <- atom k `separatedBy` anComma return (Atom_Conjunction atoms) atom :: [String] -> AParser st ATOM atom k = try (do r <- relation k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT `notFollowedWith` relation k return (Prefix_Atom r terms)) <|> do t1 <- constraintterm k r <- relation k t2 <- constraintterm k return (Infix_Atom t1 r t2) simplerelation :: [String] -> AParser st RELATION simplerelation k = do emptyRelationT return Empty_Relation <|> do equalityRelationT return Equal_Relation <|> do oParenT r <- relation k cParenT return r <|> do ide <- parseId k return (Id_Relation ide) <|> do inverseT r <- relation k return (Inverse_Relation r) relation :: [String] -> AParser st RELATION relation k = try ( do (rels, _) <- simplerelation k `separatedBy` anComma return (Relation_Disjunction rels)) <|> simplerelation k constraintterm :: [String] -> AParser st ConstraintTERM constraintterm k = try (do ide <- parseId k return (Atomar_Term ide)) <|> do ide <- parseId k oParenT (terms, _) <- constraintterm k `separatedBy` anComma cParenT return (Composite_Term ide terms) formula :: [String] -> AParser st ConstraintCASLFORMULA formula k = do x <- cformula k return (ExtFORMULA x) emptyRelation :: String emptyRelation = "{}" emptyRelationT :: GenParser Char st Token emptyRelationT = pToken $ toKey emptyRelation equalityRelation :: String equalityRelation = "=" equalityRelationT :: GenParser Char st Token equalityRelationT = pToken $ toKey equalityRelation inverse :: String inverse = "~" inverseT :: GenParser Char st Token inverseT = pToken $ toKey inverse implies :: String implies = "|-" impliesT :: GenParser Char st Token impliesT = pToken $ toKey implies equivalent :: String equivalent = "-||-" equivalentT :: GenParser Char st Token equivalentT = pToken $ toKey equivalent constraintKeywords :: [String] constraintKeywords = [equivalent, implies] instance TermParser ConstraintFORMULA where termParser = aToTermParser $ cformula []
keithodulaigh/Hets
ConstraintCASL/Formula.hs
gpl-2.0
3,416
0
13
810
956
463
493
102
1
module Reddit.Routes.Flair where import Reddit.Types.Options import Reddit.Types.Subreddit import Reddit.Types.User import Data.Text (Text) import Network.API.Builder.Routes import qualified Data.Text as Text flairList :: Options UserID -> SubredditName -> Route flairList opts (R r) = Route [ "r", r, "api", "flairlist" ] [ "after" =. after opts , "before" =. before opts , "limit" =. limit opts ] "GET" addLinkFlairTemplate :: SubredditName -> Text -> Text -> Bool -> Route addLinkFlairTemplate (R sub) css label editable = Route [ "r", sub, "api", "flairtemplate" ] [ "css_class" =. css , "flair_type" =. ("LINK_FLAIR" :: Text) , "text" =. label , "text_editable" =. editable ] "POST" flairCSVRoute :: SubredditName -> [(Username, Text, Text)] -> Route flairCSVRoute (R sub) sets = Route [ "r", sub, "api", "flaircsv" ] [ "flair_csv" =. Text.unlines (map f sets) ] "POST" where f (Username u, t, c) = Text.intercalate "," $ map (Text.pack . show) [u,t,c]
FranklinChen/reddit
src/Reddit/Routes/Flair.hs
bsd-2-clause
1,070
0
11
258
359
201
158
29
1
{-| Module : Language.Qux.Llvm.Builder Description : Build utilities for the LLVM compiler. Copyright : (c) Henry J. Wylde, 2015 License : BSD3 Maintainer : hjwylde@gmail.com Build utilities for the LLVM compiler, see "Compiler". -} {-# OPTIONS_HADDOCK hide, prune #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} module Language.Qux.Llvm.Builder where import Control.Lens import Control.Monad.State import Control.Monad.Writer import Data.Maybe import LLVM.AST data FunctionBuilder = FunctionBuilder { _currentBlock :: (Name, BlockBuilder) , _blocks :: [BasicBlock] , _counter :: Word } deriving (Eq, Show) data BlockBuilder = BlockBuilder { _stack :: [Named Instruction] , _term :: First (Named Terminator) } deriving (Eq, Show) makeLenses ''FunctionBuilder makeLenses ''BlockBuilder instance Monoid BlockBuilder where mempty = BlockBuilder mempty mempty mappend a b = a & stack <>~ b ^. stack & term <>~ b ^. term newFunctionBuilder :: FunctionBuilder newFunctionBuilder = FunctionBuilder { _currentBlock = (name, mempty) , _blocks = [] , _counter = 1 } where name = UnName 0 buildBlock :: Name -> BlockBuilder -> BasicBlock buildBlock name (BlockBuilder stack term) = BasicBlock name stack (fromJust $ getFirst term) withCurrentBlock :: MonadState FunctionBuilder m => WriterT BlockBuilder m a -> m a withCurrentBlock instrs = do (result, instrs') <- runWriterT instrs currentBlock . _2 <>= instrs' return result commitCurrentBlock :: MonadState FunctionBuilder m => m () commitCurrentBlock = do basicBlock <- uses currentBlock $ uncurry buildBlock blocks <>= [basicBlock] name <- freeUnName currentBlock .= (name, mempty) createNewBlock :: MonadState FunctionBuilder m => Name -> m () createNewBlock name = currentBlock .= (name, mempty) withNewBlock :: MonadState FunctionBuilder m => Name -> WriterT BlockBuilder m a -> m a withNewBlock name instrs = createNewBlock name >> withCurrentBlock instrs append :: (MonadState FunctionBuilder m, MonadWriter BlockBuilder m) => Named Instruction -> m () append instr = scribe stack [instr] terminate :: (MonadState FunctionBuilder m, MonadWriter BlockBuilder m) => Named Terminator -> m () terminate instr = scribe term (First $ Just instr) freeUnName :: MonadState FunctionBuilder m => m Name freeUnName = UnName <$> use counter <* (counter += 1)
hjwylde/qux-haskell
src/Language/Qux/Llvm/Builder.hs
bsd-3-clause
2,503
0
11
518
681
353
328
-1
-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.Core.CaseTree (SC, SC'(STerm), findCalls, findUsedArgs) import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Evaluate import Idris.Core.ProofTerm (getProofTerm) import Idris.Core.TT import Idris.Core.Typecheck (check, converts, isType, recheck) import Idris.Core.Unify import Idris.Core.WHNF (whnf, whnfArgs) import Idris.Coverage (genClauses, recoverableCoverage, validCoverageCase) import Idris.Delaborate import Idris.DSL import Idris.Elab.Quasiquote (extractUnquotes) import Idris.Elab.Rewrite import Idris.Elab.Utils import Idris.Error import Idris.ErrReverse (errReverse) import Idris.Options import Idris.Output (pshow) import Idris.ProofSearch import Idris.Reflection import Idris.Termination (buildSCG, checkDeclTotality, checkPositive) 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 (catMaybes, fromMaybe, mapMaybe, maybeToList) import qualified Data.Set as S import qualified Data.Text as T import Debug.Trace data ElabMode = ETyDecl | ETransLHS | ELHS | EImpossible | 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_implementations ptm <- get_term -- Resolve remaining interfaces. Two passes - first to get the -- default Num implementations, 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_implementations 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 || emode == EImpossible 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 an interface 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 || emode == EImpossible -- | 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 lookupBinder 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 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 ptm <- get_term when pattern $ -- Look for Rig1 (linear) pattern bindings do let pnms = findLinear ist [] ptm update_term (setLinear pnms) where pattern = emode == ELHS || emode == EImpossible eimpossible = emode == EImpossible intransform = emode == ETransLHS bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS || emode == EImpossible 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 ina 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 fstEnv 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 fc' u) = do unless (UniquenessTypes `elem` idris_language_extensions ist || e_qq ina) $ lift $ tfail $ At fc' (Msg "You must turn on the UniquenessTypes extension to use UniqueType or AnyType") apply (RUType u) [] solve highlightSource fc' (AnnType (show u) "The type of unique types") -- 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 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 interfaces = do g <- goal; resolveTC False False 5 g fn elabRec ist elab' ina fc (PResolveTC fc') = do c <- getNameFrom (sMN 0 "__interface") implementationArg 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 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 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 (PHidden h) = showHd h showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here doPrune as = do compute -- to get 'Delayed' if it's there ty <- goal ctxt <- get_context env <- get_env let ty' = unDelay ty let (tc, _) = unApply ty' return $ pruneByType eimpossible env tc 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 fc' tm@(PRef fc hls 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 env <- get_env -- If the name is defined, globally or locally, elaborate it -- as a reference, otherwise it might end up as a pattern var. let defined = case lookupTy n ctxt of [] -> case lookupTyEnv n env of Just _ -> True _ -> False _ -> True -- this is to stop us resolving interfaces recursively if (tcname n && ina && not intransform) then erun fc $ do patvar n update_term liftPats highlightSource fc (AnnBoundName n False) else if defined -- finally, ordinary PRef elaboration then elabRef ec fc' fc hls n tm 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 = elabRef ina fc' fc hls n 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; case pcount p of RigW -> return () _ -> unless (LinearTypes `elem` idris_language_extensions ist || e_qq ina) $ lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a count") arg n (pcount p) (is_scoped p) (sMN 0 "phTy") 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 "piTy") claim tyn RType n' <- case n of MN _ _ -> unique_hole n _ -> return n case pcount p of RigW -> return () _ -> unless (LinearTypes `elem` idris_language_extensions ist || e_qq ina) $ lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a linear argument") forall n' (pcount p) (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_implementations 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_implementations 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 lookupBinder 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 RigW Nothing xt RType) (fnTy xs ret) localVar env (PRef _ _ x) = case lookupBinder 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 let dataCon = isDConName f ctxt annot <- findHighlight f knowns_m <- mapM getKnownImplicit args_in let knowns = mapMaybe id knowns_m args <- insertScopedImps fc f knowns (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 fstEnv 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, e_guarded = dataCon }) (Just fc) (getTm (head args))) (show tm) solve mapM (uncurry highlightSource) $ (ffc, annot) : map (\f -> (f, annot)) hls return [] else do ivs <- get_implementations ps <- get_probs -- HACK: we shouldn't resolve interfaces if we're defining an implementation -- function or default definition. let isinf = f == inferCon || tcname f -- if f is an interface, we need to know its arguments so that -- we can unify with them case lookupCtxt f (idris_interfaces 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 interface 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, e_guarded = dataCon }) [] 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 fstEnv 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_implementations -- Attempt to resolve any interfaces which have 'complete' types, -- i.e. no holes in them when (not pattern || (e_inarg ina && not tcgen)) $ 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) getKnownImplicit imp | UnknownImp `elem` argopts imp = return Nothing -- lift $ tfail $ UnknownImplicit (pname imp) f | otherwise = return (Just (pname imp)) getReqImps (Bind x (Pi _ (Just i) ty _) sc) = i : getReqImps sc getReqImps _ = [] checkIfInjective n = do env <- get_env case lookupBinder n env of Nothing -> return () Just b -> case unApply (normalise (tt_ctxt ist) env (binderTy b)) of (P _ c _, args) -> case lookupCtxtExact c (idris_interfaces ist) of Nothing -> return () Just ci -> -- interface, set as injective do mapM_ setinjArg (getDets 0 (interface_determiners ci) args) -- maybe we can solve more things now... ulog <- getUnifyLog probs <- get_probs inj <- get_inj traceWhen ulog ("Injective now " ++ show args ++ "\nAll: " ++ show inj ++ "\nProblems: " ++ 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 -- A common error case if trying to typecheck an autogenerated case block elab' ina _ c@(PCase fc Placeholder opts) = lift $ tfail (Msg "No expression for the case to inspect.\nYou need to replace the _ with an expression.") 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 fstEnv args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts) let argsDropped = filter (\t -> isUnique envU t || isNotLift args t) (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 lookupBinder 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_interfaces ist) of [_] -> True _ -> False tcName _ = False isNotLift env n = case lookupBinder n env of Just ty -> case unApply (binderTy ty) of (P _ n _, _) -> n `elem` noCaseLift info _ -> False _ -> 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) $ lookupBinder 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, RigW, Lam RigW 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 lookupBinder 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 (h' : hs) <- get_holes -- If we're at the end anyway, do it now if h == h' then elabHidden h else delayElab 10 $ elabHidden h where elabHidden h = do hs <- get_holes when (h `elem` hs) $ do focus h dotterm elab' ina fc t elab' ina fc (PRunElab fc' tm ns) = do unless (ElabReflection `elem` idris_language_extensions ist) $ lift $ tfail $ At fc' (Msg "You must turn on the ElabReflection extension to use %runElab") attack let elabName = sNS (sUN "Elab") ["Elab", "Reflection", "Language"] n <- getNameFrom (sMN 0 "tacticScript") let scriptTy = RApp (Var elabName) (Var unitTy) claim n scriptTy focus n elabUnit <- goal attack -- to get an extra hole elab' ina (Just fc') tm script <- get_guess fullyElaborated script solve -- eliminate the hole. Because there are no references, the script is only in the binding ctxt <- get_context env <- get_env (scriptTm, scriptTy) <- lift $ check ctxt [] (forget script) lift $ converts ctxt env elabUnit scriptTy 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) (lookupBinder 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, RigCount, 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 :: ElabCtxt -> PTerm -> ElabD PTerm insertLazy ina t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t insertLazy ina t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t insertLazy ina (PCoerced t) = return t -- Don't add a delay to top level pattern variables, since they -- can be forced on the rhs if needed insertLazy ina t@(PPatvar _ _) | pattern && not (e_guarded ina) = return t insertLazy ina 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 fstEnv 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 <- lookupBinder 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 -- See if the name is listed as an implicit. If it is, return it, and -- drop it from the rest of the list findImplicit :: Name -> [PArg] -> (Maybe PArg, [PArg]) findImplicit n [] = (Nothing, []) findImplicit n (i@(PImp _ _ _ n' _) : args) | n == n' = (Just i, args) findImplicit n (i@(PTacImplicit _ _ n' _ _) : args) | n == n' = (Just i, args) findImplicit n (x : xs) = let (arg, rest) = findImplicit n xs in (arg, x : rest) insertScopedImps :: FC -> Name -> [Name] -> Type -> [PArg] -> ElabD [PArg] insertScopedImps fc f knowns ty xs = do mapM_ (checkKnownImplicit (map fst (getArgTys ty) ++ knowns)) xs doInsert ty xs where doInsert ty@(Bind n (Pi _ im@(Just i) _ _) sc) xs | (Just arg, xs') <- findImplicit n xs, not (toplevel_imp i) = liftM (arg :) (doInsert sc xs') | tcimplementation i && not (toplevel_imp i) = liftM (pimp n (PResolveTC fc) True :) (doInsert sc xs) | not (toplevel_imp i) = liftM (pimp n Placeholder True :) (doInsert sc xs) doInsert (Bind n (Pi _ _ _ _) sc) (x : xs) = liftM (x :) (doInsert sc xs) doInsert ty xs = return xs -- Any implicit in the application needs to have the name of a -- scoped implicit or a top level implicit, otherwise report an error checkKnownImplicit ns imp@(PImp{}) | pname imp `elem` ns = return () | otherwise = lift $ tfail $ At fc $ UnknownImplicit (pname imp) f checkKnownImplicit ns _ = return () 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 goal@(Bind n (Pi _ (Just _) _ _) sc) t = do impn <- unique_hole n -- (sMN 0 "scoped_imp") 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 fstEnv env) (PApp fc (PRef fc [] n) [pexp (PCoerced t)]) elabRef :: ElabCtxt -> Maybe FC -> FC -> [FC] -> Name -> PTerm -> ElabD () elabRef ina fc' fc hls n tm = do fty <- get_type (Var n) -- check for implicits ctxt <- get_context env <- get_env a' <- insertScopedImps fc n [] (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 []) -- | 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 -- | 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 lookupBinder 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 an interface 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) = lookupBinder 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'' let argtys = map (\x -> (x, isCanonical x ctxt)) (map snd (getArgTys (normalise ctxt [] ty))) ctxt'<- lift $ addCasedef n (const []) info False (STerm Erased) True False -- TODO what are these? argtys [] -- TODO inaccessible types 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 RigW 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 elabScriptStuck :: Term -> ElabD a elabScriptStuck x = lift . tfail $ ElabScriptStuck x -- Should be dependent tacTmArgs :: Int -> Term -> [Term] -> ElabD [Term] tacTmArgs l t args | length args == l = return args | otherwise = elabScriptStuck t -- Probably should be an argument size mismatch internal error -- | 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 tac@(unApply -> (P _ n _, args)) | n == tacN "Prim__Solve" = do ~[] <- tacTmArgs 0 tac args -- patterns are irrefutable because `tacTmArgs` returns lists of exactly the size given to it as first argument solve returnUnit | n == tacN "Prim__Goal" = do ~[] <- tacTmArgs 0 tac args 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" = do ~[] <- tacTmArgs 0 tac args hs <- get_holes fmap fst . checkClosed $ mkList (Var $ reflm "TTName") (map reflectName hs) | n == tacN "Prim__Guess" = do ~[] <- tacTmArgs 0 tac args g <- get_guess fmap fst . checkClosed $ reflect g | n == tacN "Prim__LookupTy" = do ~[name] <- tacTmArgs 1 tac args n' <- reifyTTName name 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" = do ~[name] <- tacTmArgs 1 tac args 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" = do ~[name] <- tacTmArgs 1 tac args n' <- reifyTTName name fmap fst . checkClosed $ rawList (RApp (Var $ tacN "FunDefn") (Var $ reflm "TT")) (map reflectFunDefn (buildFunDefns ist n')) | n == tacN "Prim__LookupArgs" = do ~[name] <- tacTmArgs 1 tac args 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" = do ~[] <- tacTmArgs 0 tac args fmap fst . checkClosed $ reflectFC fc | n == tacN "Prim__Namespace" = do ~[] <- tacTmArgs 0 tac args fmap fst . checkClosed $ rawList (RConstant StrType) (map (RConstant . Str) ns) | n == tacN "Prim__Env" = do ~[] <- tacTmArgs 0 tac args env <- get_env fmap fst . checkClosed $ reflectEnv env | n == tacN "Prim__Fail" = do ~[_a, errs] <- tacTmArgs 2 tac args errs' <- eval errs parts <- reifyReportParts errs' lift . tfail $ ReflectionError [parts] (Msg "") | n == tacN "Prim__PureElab" = do ~[_a, tm] <- tacTmArgs 2 tac args return tm | n == tacN "Prim__BindElab" = do ~[_a, _b, first, andThen] <- tacTmArgs 4 tac args first' <- eval first res <- eval =<< runTacTm first' next <- eval (App Complete andThen res) runTacTm next | n == tacN "Prim__Try" = do ~[_a, first, alt] <- tacTmArgs 3 tac args first' <- eval first alt' <- eval alt try' (runTacTm first') (runTacTm alt') True | n == tacN "Prim__Fill" = do ~[raw] <- tacTmArgs 1 tac args raw' <- reifyRaw =<< eval raw apply raw' [] returnUnit | n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply" = do ~[raw, argSpec] <- tacTmArgs 2 tac args 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" = do ~[hint] <- tacTmArgs 1 tac args 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" = do ~[n, ty] <- tacTmArgs 2 tac args n' <- reifyTTName n ty' <- reifyRaw ty claim n' ty' returnUnit | n == tacN "Prim__Check" = do ~[env', raw] <- tacTmArgs 2 tac args 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" = do ~[] <- tacTmArgs 0 tac args attack returnUnit | n == tacN "Prim__Rewrite" = do ~[rule] <- tacTmArgs 1 tac args r <- reifyRaw rule rewrite r returnUnit | n == tacN "Prim__Focus" = do ~[what] <- tacTmArgs 1 tac args 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" = do ~[what] <- tacTmArgs 1 tac args n' <- reifyTTName what movelast n' returnUnit | n == tacN "Prim__Intro" = do ~[mn] <- tacTmArgs 1 tac args n <- case fromTTMaybe mn of Nothing -> return Nothing Just name -> fmap Just $ reifyTTName name intro n returnUnit | n == tacN "Prim__Forall" = do ~[n, ty] <- tacTmArgs 2 tac args n' <- reifyTTName n ty' <- reifyRaw ty forall n' RigW Nothing ty' returnUnit | n == tacN "Prim__PatVar" = do ~[n] <- tacTmArgs 1 tac args n' <- reifyTTName n patvar' n' returnUnit | n == tacN "Prim__PatBind" = do ~[n] <- tacTmArgs 1 tac args n' <- reifyTTName n patbind n' RigW returnUnit | n == tacN "Prim__LetBind" = do ~[n, ty, tm] <- tacTmArgs 3 tac args n' <- reifyTTName n ty' <- reifyRaw ty tm' <- reifyRaw tm letbind n' ty' tm' returnUnit | n == tacN "Prim__Compute" = do ~[] <- tacTmArgs 0 tac args; compute ; returnUnit | n == tacN "Prim__Normalise" = do ~[env, tm] <- tacTmArgs 2 tac args 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" = do ~[tm] <- tacTmArgs 1 tac args tm' <- reifyTT tm ctxt <- get_context fmap fst . checkClosed . reflect $ whnf ctxt [] tm' | n == tacN "Prim__Converts" = do ~[env, tm1, tm2] <- tacTmArgs 3 tac args env' <- reifyEnv env tm1' <- reifyTT tm1 tm2' <- reifyTT tm2 ctxt <- get_context lift $ converts ctxt env' tm1' tm2' returnUnit | n == tacN "Prim__DeclareType" = do ~[decl] <- tacTmArgs 1 tac args (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" = do ~[decl] <- tacTmArgs 1 tac args defn <- reifyFunDefn decl defineFunction defn returnUnit | n == tacN "Prim__DeclareDatatype" = do ~[decl] <- tacTmArgs 1 tac args 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" = do ~[defn] <- tacTmArgs 1 tac args 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__AddImplementation" = do ~[cls, impl] <- tacTmArgs 2 tac args interfaceName <- reifyTTName cls implName <- reifyTTName impl updateAux $ \e -> e { new_tyDecls = RAddImplementation interfaceName implName : new_tyDecls e } returnUnit | n == tacN "Prim__IsTCName" = do ~[n] <- tacTmArgs 1 tac args n' <- reifyTTName n case lookupCtxtExact n' (idris_interfaces 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" = do ~[fn] <- tacTmArgs 1 tac args g <- goal fn <- reifyTTName fn resolveTC' False True 100 g fn ist returnUnit | n == tacN "Prim__Search" = do ~[depth, hints] <- tacTmArgs 2 tac args 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" = do ~[goal, script] <- tacTmArgs 2 tac args 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" = do ~[n] <- tacTmArgs 1 tac args 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" = do ~[op'] <- tacTmArgs 1 tac args 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" = do ~[ty, msg] <- tacTmArgs 2 tac args msg' <- eval msg parts <- reifyReportParts msg debugElaborator parts runTacTm x = 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 fstEnv 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 lookupBinder 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 lookupBinder 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 TCImplementation = 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 RigW Nothing (RApp listTy envTupleType) RType) (RBind (sMN 1 "__pi_arg") (Pi RigW 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 env <- get_env let denv = map (\(n, _, b) -> (n, binderTy b)) env elab ist toplevel ERHS [] (sMN 0 "tac") (PApp emptyFC tm [pexp (delabTy' ist [] denv tgoal True 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' = normalise 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, most -- likely something which is needed by it has not -- been imported, so keep the original error. handlers <- case mapM (check (tt_ctxt ist) []) reports of Error _ -> return [] -- 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 [] False -- 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 RAddImplementation interfaceName implName -> do -- The interface resolution machinery relies on a special logElab 2 $ "Adding elab script implementation " ++ show implName ++ " for " ++ show interfaceName addImplementation False True interfaceName implName addIBC (IBCImplementation False True interfaceName implName) RClausesInstrs n cs -> do logElab 3 $ "Pattern-matching definition from tactics: " ++ show n solveDeferred emptyFC n let lhss = map (\(ns, lhs, _) -> (map fst ns, lhs)) cs let fc = fileFC "elab_reflected" pmissing <- do ist <- getIState possible <- genClauses fc n lhss (map (\ (ns, lhs) -> delab' ist lhs True True) lhss) missing <- filterM (checkPossible n) possible let undef = filter (noMatch ist (map snd lhss)) missing return undef 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. -- These are always cases generated by genClauses 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" case elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "refPatLHS") infP initEState (erun fc (buildTC ist info EImpossible [] 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 -> return (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
Heather/Idris-dev
src/Idris/Elab/Term.hs
bsd-3-clause
130,762
1,309
29
56,449
25,734
14,954
10,780
2,316
249
{-# LANGUAGE BangPatterns, CPP, NondecreasingIndentation, ScopedTypeVariables #-} {-# OPTIONS_GHC -fno-warn-warnings-deprecations #-} -- NB: we specifically ignore deprecations. GHC 7.6 marks the .QSem module as -- deprecated, although it became un-deprecated later. As a result, using 7.6 -- as your bootstrap compiler throws annoying warnings. -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2011 -- -- This module implements multi-module compilation, and is used -- by --make and GHCi. -- -- ----------------------------------------------------------------------------- module GhcMake( depanal, load, LoadHowMuch(..), topSortModuleGraph, noModError, cyclicModuleErr ) where #include "HsVersions.h" #ifdef GHCI import qualified Linker ( unload ) #endif import DriverPhases import DriverPipeline import DynFlags import ErrUtils import Finder import GhcMonad import HeaderInfo import HsSyn import HscTypes import Module import RdrName ( RdrName ) import TcIface ( typecheckIface ) import TcRnMonad ( initIfaceCheck ) import Bag ( listToBag ) import BasicTypes import Digraph import Exception ( tryIO, gbracket, gfinally ) import FastString import Maybes ( expectJust ) import MonadUtils ( allM, MonadIO ) import Outputable import Panic import SrcLoc import StringBuffer import SysTools import UniqFM import Util import Data.Either ( rights, partitionEithers ) import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import qualified FiniteMap as Map ( insertListWith ) import Control.Concurrent ( forkIOWithUnmask, killThread ) import qualified GHC.Conc as CC import Control.Concurrent.MVar import Control.Concurrent.QSem import Control.Exception import Control.Monad import Data.IORef import Data.List import qualified Data.List as List import Data.Maybe import Data.Ord ( comparing ) import Data.Time import System.Directory import System.FilePath import System.IO ( fixIO ) import System.IO.Error ( isDoesNotExistError ) import GHC.Conc ( getNumProcessors, getNumCapabilities, setNumCapabilities ) label_self :: String -> IO () label_self thread_name = do self_tid <- CC.myThreadId CC.labelThread self_tid thread_name -- ----------------------------------------------------------------------------- -- Loading the program -- | Perform a dependency analysis starting from the current targets -- and update the session with the new module graph. -- -- Dependency analysis entails parsing the @import@ directives and may -- therefore require running certain preprocessors. -- -- Note that each 'ModSummary' in the module graph caches its 'DynFlags'. -- These 'DynFlags' are determined by the /current/ session 'DynFlags' and the -- @OPTIONS@ and @LANGUAGE@ pragmas of the parsed module. Thus if you want to -- changes to the 'DynFlags' to take effect you need to call this function -- again. -- depanal :: GhcMonad m => [ModuleName] -- ^ excluded modules -> Bool -- ^ allow duplicate roots -> m ModuleGraph depanal excluded_mods allow_dup_roots = do hsc_env <- getSession let dflags = hsc_dflags hsc_env targets = hsc_targets hsc_env old_graph = hsc_mod_graph hsc_env liftIO $ showPass dflags "Chasing dependencies" liftIO $ debugTraceMsg dflags 2 (hcat [ text "Chasing modules from: ", hcat (punctuate comma (map pprTarget targets))]) mod_graphE <- liftIO $ downsweep hsc_env old_graph excluded_mods allow_dup_roots mod_graph <- reportImportErrors mod_graphE modifySession $ \_ -> hsc_env { hsc_mod_graph = mod_graph } return mod_graph -- | Describes which modules of the module graph need to be loaded. data LoadHowMuch = LoadAllTargets -- ^ Load all targets and its dependencies. | LoadUpTo ModuleName -- ^ Load only the given module and its dependencies. | LoadDependenciesOf ModuleName -- ^ Load only the dependencies of the given module, but not the module -- itself. -- | Try to load the program. See 'LoadHowMuch' for the different modes. -- -- This function implements the core of GHC's @--make@ mode. It preprocesses, -- compiles and loads the specified modules, avoiding re-compilation wherever -- possible. Depending on the target (see 'DynFlags.hscTarget') compilating -- and loading may result in files being created on disk. -- -- Calls the 'reportModuleCompilationResult' callback after each compiling -- each module, whether successful or not. -- -- Throw a 'SourceError' if errors are encountered before the actual -- compilation starts (e.g., during dependency analysis). All other errors -- are reported using the callback. -- load :: GhcMonad m => LoadHowMuch -> m SuccessFlag load how_much = do mod_graph <- depanal [] False guessOutputFile hsc_env <- getSession let hpt1 = hsc_HPT hsc_env let dflags = hsc_dflags hsc_env -- The "bad" boot modules are the ones for which we have -- B.hs-boot in the module graph, but no B.hs -- The downsweep should have ensured this does not happen -- (see msDeps) let all_home_mods = [ms_mod_name s | s <- mod_graph, not (isBootSummary s)] bad_boot_mods = [s | s <- mod_graph, isBootSummary s, not (ms_mod_name s `elem` all_home_mods)] ASSERT( null bad_boot_mods ) return () -- check that the module given in HowMuch actually exists, otherwise -- topSortModuleGraph will bomb later. let checkHowMuch (LoadUpTo m) = checkMod m checkHowMuch (LoadDependenciesOf m) = checkMod m checkHowMuch _ = id checkMod m and_then | m `elem` all_home_mods = and_then | otherwise = do liftIO $ errorMsg dflags (text "no such module:" <+> quotes (ppr m)) return Failed checkHowMuch how_much $ do -- mg2_with_srcimps drops the hi-boot nodes, returning a -- graph with cycles. Among other things, it is used for -- backing out partially complete cycles following a failed -- upsweep, and for removing from hpt all the modules -- not in strict downwards closure, during calls to compile. let mg2_with_srcimps :: [SCC ModSummary] mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing -- If we can determine that any of the {-# SOURCE #-} imports -- are definitely unnecessary, then emit a warning. warnUnnecessarySourceImports mg2_with_srcimps let -- check the stability property for each module. stable_mods@(stable_obj,stable_bco) = checkStability hpt1 mg2_with_srcimps all_home_mods -- prune bits of the HPT which are definitely redundant now, -- to save space. pruned_hpt = pruneHomePackageTable hpt1 (flattenSCCs mg2_with_srcimps) stable_mods _ <- liftIO $ evaluate pruned_hpt -- before we unload anything, make sure we don't leave an old -- interactive context around pointing to dead bindings. Also, -- write the pruned HPT to allow the old HPT to be GC'd. modifySession $ \_ -> discardIC $ hsc_env { hsc_HPT = pruned_hpt } liftIO $ debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$ text "Stable BCO:" <+> ppr stable_bco) -- Unload any modules which are going to be re-linked this time around. let stable_linkables = [ linkable | m <- stable_obj++stable_bco, Just hmi <- [lookupUFM pruned_hpt m], Just linkable <- [hm_linkable hmi] ] liftIO $ unload hsc_env stable_linkables -- We could at this point detect cycles which aren't broken by -- a source-import, and complain immediately, but it seems better -- to let upsweep_mods do this, so at least some useful work gets -- done before the upsweep is abandoned. --hPutStrLn stderr "after tsort:\n" --hPutStrLn stderr (showSDoc (vcat (map ppr mg2))) -- Now do the upsweep, calling compile for each module in -- turn. Final result is version 3 of everything. -- Topologically sort the module graph, this time including hi-boot -- nodes, and possibly just including the portion of the graph -- reachable from the module specified in the 2nd argument to load. -- This graph should be cycle-free. -- If we're restricting the upsweep to a portion of the graph, we -- also want to retain everything that is still stable. let full_mg :: [SCC ModSummary] full_mg = topSortModuleGraph False mod_graph Nothing maybe_top_mod = case how_much of LoadUpTo m -> Just m LoadDependenciesOf m -> Just m _ -> Nothing partial_mg0 :: [SCC ModSummary] partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod -- LoadDependenciesOf m: we want the upsweep to stop just -- short of the specified module (unless the specified module -- is stable). partial_mg | LoadDependenciesOf _mod <- how_much = ASSERT( case last partial_mg0 of AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False ) List.init partial_mg0 | otherwise = partial_mg0 stable_mg = [ AcyclicSCC ms | AcyclicSCC ms <- full_mg, ms_mod_name ms `elem` stable_obj++stable_bco ] -- the modules from partial_mg that are not also stable -- NB. also keep cycles, we need to emit an error message later unstable_mg = filter not_stable partial_mg where not_stable (CyclicSCC _) = True not_stable (AcyclicSCC ms) = ms_mod_name ms `notElem` stable_obj++stable_bco -- Load all the stable modules first, before attempting to load -- an unstable module (#7231). mg = stable_mg ++ unstable_mg -- clean up between compilations let cleanup hsc_env = intermediateCleanTempFiles (hsc_dflags hsc_env) (flattenSCCs mg2_with_srcimps) hsc_env liftIO $ debugTraceMsg dflags 2 (hang (text "Ready for upsweep") 2 (ppr mg)) n_jobs <- case parMakeCount dflags of Nothing -> liftIO getNumProcessors Just n -> return n let upsweep_fn | n_jobs > 1 = parUpsweep n_jobs | otherwise = upsweep setSession hsc_env{ hsc_HPT = emptyHomePackageTable } (upsweep_ok, modsUpswept) <- upsweep_fn pruned_hpt stable_mods cleanup mg -- Make modsDone be the summaries for each home module now -- available; this should equal the domain of hpt3. -- Get in in a roughly top .. bottom order (hence reverse). let modsDone = reverse modsUpswept -- Try and do linking in some form, depending on whether the -- upsweep was completely or only partially successful. if succeeded upsweep_ok then -- Easy; just relink it all. do liftIO $ debugTraceMsg dflags 2 (text "Upsweep completely successful.") -- Clean up after ourselves hsc_env1 <- getSession liftIO $ intermediateCleanTempFiles dflags modsDone hsc_env1 -- Issue a warning for the confusing case where the user -- said '-o foo' but we're not going to do any linking. -- We attempt linking if either (a) one of the modules is -- called Main, or (b) the user said -no-hs-main, indicating -- that main() is going to come from somewhere else. -- let ofile = outputFile dflags let no_hs_main = gopt Opt_NoHsMain dflags let main_mod = mainModIs dflags a_root_is_Main = any ((==main_mod).ms_mod) mod_graph do_linking = a_root_is_Main || no_hs_main || ghcLink dflags == LinkDynLib || ghcLink dflags == LinkStaticLib when (ghcLink dflags == LinkBinary && isJust ofile && not do_linking) $ liftIO $ debugTraceMsg dflags 1 $ text ("Warning: output was redirected with -o, " ++ "but no output will be generated\n" ++ "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module.") -- link everything together linkresult <- liftIO $ link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1) loadFinish Succeeded linkresult else -- Tricky. We need to back out the effects of compiling any -- half-done cycles, both so as to clean up the top level envs -- and to avoid telling the interactive linker to link them. do liftIO $ debugTraceMsg dflags 2 (text "Upsweep partially successful.") let modsDone_names = map ms_mod modsDone let mods_to_zap_names = findPartiallyCompletedCycles modsDone_names mg2_with_srcimps let mods_to_keep = filter ((`notElem` mods_to_zap_names).ms_mod) modsDone hsc_env1 <- getSession let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep) (hsc_HPT hsc_env1) -- Clean up after ourselves liftIO $ intermediateCleanTempFiles dflags mods_to_keep hsc_env1 -- there should be no Nothings where linkables should be, now ASSERT(all (isJust.hm_linkable) (eltsUFM (hsc_HPT hsc_env))) do -- Link everything together linkresult <- liftIO $ link (ghcLink dflags) dflags False hpt4 modifySession $ \hsc_env -> hsc_env{ hsc_HPT = hpt4 } loadFinish Failed linkresult -- | Finish up after a load. loadFinish :: GhcMonad m => SuccessFlag -> SuccessFlag -> m SuccessFlag -- If the link failed, unload everything and return. loadFinish _all_ok Failed = do hsc_env <- getSession liftIO $ unload hsc_env [] modifySession discardProg return Failed -- Empty the interactive context and set the module context to the topmost -- newly loaded module, or the Prelude if none were loaded. loadFinish all_ok Succeeded = do modifySession discardIC return all_ok -- | Forget the current program, but retain the persistent info in HscEnv discardProg :: HscEnv -> HscEnv discardProg hsc_env = discardIC $ hsc_env { hsc_mod_graph = emptyMG , hsc_HPT = emptyHomePackageTable } -- | Discard the contents of the InteractiveContext, but keep the DynFlags discardIC :: HscEnv -> HscEnv discardIC hsc_env = hsc_env { hsc_IC = emptyInteractiveContext (ic_dflags (hsc_IC hsc_env)) } intermediateCleanTempFiles :: DynFlags -> [ModSummary] -> HscEnv -> IO () intermediateCleanTempFiles dflags summaries hsc_env = do notIntermediate <- readIORef (filesToNotIntermediateClean dflags) cleanTempFilesExcept dflags (notIntermediate ++ except) where except = -- Save preprocessed files. The preprocessed file *might* be -- the same as the source file, but that doesn't do any -- harm. map ms_hspp_file summaries ++ -- Save object files for loaded modules. The point of this -- is that we might have generated and compiled a stub C -- file, and in the case of GHCi the object file will be a -- temporary file which we must not remove because we need -- to load/link it later. hptObjs (hsc_HPT hsc_env) -- | If there is no -o option, guess the name of target executable -- by using top-level source file name as a base. guessOutputFile :: GhcMonad m => m () guessOutputFile = modifySession $ \env -> let dflags = hsc_dflags env mod_graph = hsc_mod_graph env mainModuleSrcPath :: Maybe String mainModuleSrcPath = do let isMain = (== mainModIs dflags) . ms_mod [ms] <- return (filter isMain mod_graph) ml_hs_file (ms_location ms) name = fmap dropExtension mainModuleSrcPath #if defined(mingw32_HOST_OS) -- we must add the .exe extention unconditionally here, otherwise -- when name has an extension of its own, the .exe extension will -- not be added by DriverPipeline.exeFileName. See #2248 name_exe = fmap (<.> "exe") name #else name_exe = name #endif in case outputFile dflags of Just _ -> env Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } } -- ----------------------------------------------------------------------------- -- -- | Prune the HomePackageTable -- -- Before doing an upsweep, we can throw away: -- -- - For non-stable modules: -- - all ModDetails, all linked code -- - all unlinked code that is out of date with respect to -- the source file -- -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the -- space at the end of the upsweep, because the topmost ModDetails of the -- old HPT holds on to the entire type environment from the previous -- compilation. pruneHomePackageTable :: HomePackageTable -> [ModSummary] -> ([ModuleName],[ModuleName]) -> HomePackageTable pruneHomePackageTable hpt summ (stable_obj, stable_bco) = mapUFM prune hpt where prune hmi | is_stable modl = hmi' | otherwise = hmi'{ hm_details = emptyModDetails } where modl = moduleName (mi_module (hm_iface hmi)) hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms = hmi{ hm_linkable = Nothing } | otherwise = hmi where ms = expectJust "prune" (lookupUFM ms_map modl) ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ] is_stable m = m `elem` stable_obj || m `elem` stable_bco -- ----------------------------------------------------------------------------- -- -- | Return (names of) all those in modsDone who are part of a cycle as defined -- by theGraph. findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module] findPartiallyCompletedCycles modsDone theGraph = chew theGraph where chew [] = [] chew ((AcyclicSCC _):rest) = chew rest -- acyclic? not interesting. chew ((CyclicSCC vs):rest) = let names_in_this_cycle = nub (map ms_mod vs) mods_in_this_cycle = nub ([done | done <- modsDone, done `elem` names_in_this_cycle]) chewed_rest = chew rest in if notNull mods_in_this_cycle && length mods_in_this_cycle < length names_in_this_cycle then mods_in_this_cycle ++ chewed_rest else chewed_rest -- --------------------------------------------------------------------------- -- -- | Unloading unload :: HscEnv -> [Linkable] -> IO () unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables' = case ghcLink (hsc_dflags hsc_env) of #ifdef GHCI LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables #else LinkInMemory -> panic "unload: no interpreter" -- urgh. avoid warnings: hsc_env stable_linkables #endif _other -> return () -- ----------------------------------------------------------------------------- {- | Stability tells us which modules definitely do not need to be recompiled. There are two main reasons for having stability: - avoid doing a complete upsweep of the module graph in GHCi when modules near the bottom of the tree have not changed. - to tell GHCi when it can load object code: we can only load object code for a module when we also load object code fo all of the imports of the module. So we need to know that we will definitely not be recompiling any of these modules, and we can use the object code. The stability check is as follows. Both stableObject and stableBCO are used during the upsweep phase later. @ stable m = stableObject m || stableBCO m stableObject m = all stableObject (imports m) && old linkable does not exist, or is == on-disk .o && date(on-disk .o) > date(.hs) stableBCO m = all stable (imports m) && date(BCO) > date(.hs) @ These properties embody the following ideas: - if a module is stable, then: - if it has been compiled in a previous pass (present in HPT) then it does not need to be compiled or re-linked. - if it has not been compiled in a previous pass, then we only need to read its .hi file from disk and link it to produce a 'ModDetails'. - if a modules is not stable, we will definitely be at least re-linking, and possibly re-compiling it during the 'upsweep'. All non-stable modules can (and should) therefore be unlinked before the 'upsweep'. - Note that objects are only considered stable if they only depend on other objects. We can't link object code against byte code. -} checkStability :: HomePackageTable -- HPT from last compilation -> [SCC ModSummary] -- current module graph (cyclic) -> [ModuleName] -- all home modules -> ([ModuleName], -- stableObject [ModuleName]) -- stableBCO checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs where checkSCC (stable_obj, stable_bco) scc0 | stableObjects = (scc_mods ++ stable_obj, stable_bco) | stableBCOs = (stable_obj, scc_mods ++ stable_bco) | otherwise = (stable_obj, stable_bco) where scc = flattenSCC scc0 scc_mods = map ms_mod_name scc home_module m = m `elem` all_home_mods && m `notElem` scc_mods scc_allimps = nub (filter home_module (concatMap ms_home_allimps scc)) -- all imports outside the current SCC, but in the home pkg stable_obj_imps = map (`elem` stable_obj) scc_allimps stable_bco_imps = map (`elem` stable_bco) scc_allimps stableObjects = and stable_obj_imps && all object_ok scc stableBCOs = and (zipWith (||) stable_obj_imps stable_bco_imps) && all bco_ok scc object_ok ms | gopt Opt_ForceRecomp (ms_hspp_opts ms) = False | Just t <- ms_obj_date ms = t >= ms_hs_date ms && same_as_prev t | otherwise = False where same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of Just hmi | Just l <- hm_linkable hmi -> isObjectLinkable l && t == linkableTime l _other -> True -- why '>=' rather than '>' above? If the filesystem stores -- times to the nearset second, we may occasionally find that -- the object & source have the same modification time, -- especially if the source was automatically generated -- and compiled. Using >= is slightly unsafe, but it matches -- make's behaviour. -- -- But see #5527, where someone ran into this and it caused -- a problem. bco_ok ms | gopt Opt_ForceRecomp (ms_hspp_opts ms) = False | otherwise = case lookupUFM hpt (ms_mod_name ms) of Just hmi | Just l <- hm_linkable hmi -> not (isObjectLinkable l) && linkableTime l >= ms_hs_date ms _other -> False {- Parallel Upsweep - - The parallel upsweep attempts to concurrently compile the modules in the - compilation graph using multiple Haskell threads. - - The Algorithm - - A Haskell thread is spawned for each module in the module graph, waiting for - its direct dependencies to finish building before it itself begins to build. - - Each module is associated with an initially empty MVar that stores the - result of that particular module's compile. If the compile succeeded, then - the HscEnv (synchronized by an MVar) is updated with the fresh HMI of that - module, and the module's HMI is deleted from the old HPT (synchronized by an - IORef) to save space. - - Instead of immediately outputting messages to the standard handles, all - compilation output is deferred to a per-module TQueue. A QSem is used to - limit the number of workers that are compiling simultaneously. - - Meanwhile, the main thread sequentially loops over all the modules in the - module graph, outputting the messages stored in each module's TQueue. -} -- | Each module is given a unique 'LogQueue' to redirect compilation messages -- to. A 'Nothing' value contains the result of compilation, and denotes the -- end of the message queue. data LogQueue = LogQueue !(IORef [Maybe (Severity, SrcSpan, PprStyle, MsgDoc)]) !(MVar ()) -- | The graph of modules to compile and their corresponding result 'MVar' and -- 'LogQueue'. type CompilationGraph = [(ModSummary, MVar SuccessFlag, LogQueue)] -- | Build a 'CompilationGraph' out of a list of strongly-connected modules, -- also returning the first, if any, encountered module cycle. buildCompGraph :: [SCC ModSummary] -> IO (CompilationGraph, Maybe [ModSummary]) buildCompGraph [] = return ([], Nothing) buildCompGraph (scc:sccs) = case scc of AcyclicSCC ms -> do mvar <- newEmptyMVar log_queue <- do ref <- newIORef [] sem <- newEmptyMVar return (LogQueue ref sem) (rest,cycle) <- buildCompGraph sccs return ((ms,mvar,log_queue):rest, cycle) CyclicSCC mss -> return ([], Just mss) -- A Module and whether it is a boot module. type BuildModule = (Module, Bool) mkBuildModule :: ModSummary -> BuildModule mkBuildModule ms = (ms_mod ms, isBootSummary ms) -- | The entry point to the parallel upsweep. -- -- See also the simpler, sequential 'upsweep'. parUpsweep :: GhcMonad m => Int -- ^ The number of workers we wish to run in parallel -> HomePackageTable -> ([ModuleName],[ModuleName]) -> (HscEnv -> IO ()) -> [SCC ModSummary] -> m (SuccessFlag, [ModSummary]) parUpsweep n_jobs old_hpt stable_mods cleanup sccs = do hsc_env <- getSession let dflags = hsc_dflags hsc_env -- The bits of shared state we'll be using: -- The global HscEnv is updated with the module's HMI when a module -- successfully compiles. hsc_env_var <- liftIO $ newMVar hsc_env -- The old HPT is used for recompilation checking in upsweep_mod. When a -- module sucessfully gets compiled, its HMI is pruned from the old HPT. old_hpt_var <- liftIO $ newIORef old_hpt -- What we use to limit parallelism with. par_sem <- liftIO $ newQSem n_jobs let updNumCapabilities = liftIO $ do n_capabilities <- getNumCapabilities unless (n_capabilities /= 1) $ setNumCapabilities n_jobs return n_capabilities -- Reset the number of capabilities once the upsweep ends. let resetNumCapabilities orig_n = liftIO $ setNumCapabilities orig_n gbracket updNumCapabilities resetNumCapabilities $ \_ -> do -- Sync the global session with the latest HscEnv once the upsweep ends. let finallySyncSession io = io `gfinally` do hsc_env <- liftIO $ readMVar hsc_env_var setSession hsc_env finallySyncSession $ do -- Build the compilation graph out of the list of SCCs. Module cycles are -- handled at the very end, after some useful work gets done. Note that -- this list is topologically sorted (by virtue of 'sccs' being sorted so). (comp_graph,cycle) <- liftIO $ buildCompGraph sccs let comp_graph_w_idx = zip comp_graph [1..] -- The list of all loops in the compilation graph. -- NB: For convenience, the last module of each loop (aka the module that -- finishes the loop) is prepended to the beginning of the loop. let comp_graph_loops = go (map fstOf3 (reverse comp_graph)) where go [] = [] go (ms:mss) | Just loop <- getModLoop ms (ms:mss) = map mkBuildModule (ms:loop) : go mss | otherwise = go mss -- Build a Map out of the compilation graph with which we can efficiently -- look up the result MVar associated with a particular home module. let home_mod_map :: Map BuildModule (MVar SuccessFlag, Int) home_mod_map = Map.fromList [ (mkBuildModule ms, (mvar, idx)) | ((ms,mvar,_),idx) <- comp_graph_w_idx ] liftIO $ label_self "main --make thread" -- For each module in the module graph, spawn a worker thread that will -- compile this module. let { spawnWorkers = forM comp_graph_w_idx $ \((mod,!mvar,!log_queue),!mod_idx) -> forkIOWithUnmask $ \unmask -> do liftIO $ label_self $ unwords [ "worker --make thread" , "for module" , show (moduleNameString (ms_mod_name mod)) , "number" , show mod_idx ] -- Replace the default log_action with one that writes each -- message to the module's log_queue. The main thread will -- deal with synchronously printing these messages. -- -- Use a local filesToClean var so that we can clean up -- intermediate files in a timely fashion (as soon as -- compilation for that module is finished) without having to -- worry about accidentally deleting a simultaneous compile's -- important files. lcl_files_to_clean <- newIORef [] let lcl_dflags = dflags { log_action = parLogAction log_queue , filesToClean = lcl_files_to_clean } -- Unmask asynchronous exceptions and perform the thread-local -- work to compile the module (see parUpsweep_one). m_res <- try $ unmask $ prettyPrintGhcErrors lcl_dflags $ parUpsweep_one mod home_mod_map comp_graph_loops lcl_dflags cleanup par_sem hsc_env_var old_hpt_var stable_mods mod_idx (length sccs) res <- case m_res of Right flag -> return flag Left exc -> do -- Don't print ThreadKilled exceptions: they are used -- to kill the worker thread in the event of a user -- interrupt, and the user doesn't have to be informed -- about that. when (fromException exc /= Just ThreadKilled) (errorMsg lcl_dflags (text (show exc))) return Failed -- Populate the result MVar. putMVar mvar res -- Write the end marker to the message queue, telling the main -- thread that it can stop waiting for messages from this -- particular compile. writeLogQueue log_queue Nothing -- Add the remaining files that weren't cleaned up to the -- global filesToClean ref, for cleanup later. files_kept <- readIORef (filesToClean lcl_dflags) addFilesToClean dflags files_kept -- Kill all the workers, masking interrupts (since killThread is -- interruptible). XXX: This is not ideal. ; killWorkers = uninterruptibleMask_ . mapM_ killThread } -- Spawn the workers, making sure to kill them later. Collect the results -- of each compile. results <- liftIO $ bracket spawnWorkers killWorkers $ \_ -> -- Loop over each module in the compilation graph in order, printing -- each message from its log_queue. forM comp_graph $ \(mod,mvar,log_queue) -> do printLogs dflags log_queue result <- readMVar mvar if succeeded result then return (Just mod) else return Nothing -- Collect and return the ModSummaries of all the successful compiles. -- NB: Reverse this list to maintain output parity with the sequential upsweep. let ok_results = reverse (catMaybes results) -- Handle any cycle in the original compilation graph and return the result -- of the upsweep. case cycle of Just mss -> do liftIO $ fatalErrorMsg dflags (cyclicModuleErr mss) return (Failed,ok_results) Nothing -> do let success_flag = successIf (all isJust results) return (success_flag,ok_results) where writeLogQueue :: LogQueue -> Maybe (Severity,SrcSpan,PprStyle,MsgDoc) -> IO () writeLogQueue (LogQueue ref sem) msg = do atomicModifyIORef ref $ \msgs -> (msg:msgs,()) _ <- tryPutMVar sem () return () -- The log_action callback that is used to synchronize messages from a -- worker thread. parLogAction :: LogQueue -> LogAction parLogAction log_queue _dflags !severity !srcSpan !style !msg = do writeLogQueue log_queue (Just (severity,srcSpan,style,msg)) -- Print each message from the log_queue using the log_action from the -- session's DynFlags. printLogs :: DynFlags -> LogQueue -> IO () printLogs !dflags (LogQueue ref sem) = read_msgs where read_msgs = do takeMVar sem msgs <- atomicModifyIORef ref $ \xs -> ([], reverse xs) print_loop msgs print_loop [] = read_msgs print_loop (x:xs) = case x of Just (severity,srcSpan,style,msg) -> do log_action dflags dflags severity srcSpan style msg print_loop xs -- Exit the loop once we encounter the end marker. Nothing -> return () -- The interruptible subset of the worker threads' work. parUpsweep_one :: ModSummary -- ^ The module we wish to compile -> Map BuildModule (MVar SuccessFlag, Int) -- ^ The map of home modules and their result MVar -> [[BuildModule]] -- ^ The list of all module loops within the compilation graph. -> DynFlags -- ^ The thread-local DynFlags -> (HscEnv -> IO ()) -- ^ The callback for cleaning up intermediate files -> QSem -- ^ The semaphore for limiting the number of simultaneous compiles -> MVar HscEnv -- ^ The MVar that synchronizes updates to the global HscEnv -> IORef HomePackageTable -- ^ The old HPT -> ([ModuleName],[ModuleName]) -- ^ Lists of stable objects and BCOs -> Int -- ^ The index of this module -> Int -- ^ The total number of modules -> IO SuccessFlag -- ^ The result of this compile parUpsweep_one mod home_mod_map comp_graph_loops lcl_dflags cleanup par_sem hsc_env_var old_hpt_var stable_mods mod_index num_mods = do let this_build_mod = mkBuildModule mod let home_imps = map unLoc $ ms_home_imps mod let home_src_imps = map unLoc $ ms_home_srcimps mod -- All the textual imports of this module. let textual_deps = Set.fromList $ mapFst (mkModule (thisPackage lcl_dflags)) $ zip home_imps (repeat False) ++ zip home_src_imps (repeat True) -- Dealing with module loops -- ~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- Not only do we have to deal with explicit textual dependencies, we also -- have to deal with implicit dependencies introduced by import cycles that -- are broken by an hs-boot file. We have to ensure that: -- -- 1. A module that breaks a loop must depend on all the modules in the -- loop (transitively or otherwise). This is normally always fulfilled -- by the module's textual dependencies except in degenerate loops, -- e.g.: -- -- A.hs imports B.hs-boot -- B.hs doesn't import A.hs -- C.hs imports A.hs, B.hs -- -- In this scenario, getModLoop will detect the module loop [A,B] but -- the loop finisher B doesn't depend on A. So we have to explicitly add -- A in as a dependency of B when we are compiling B. -- -- 2. A module that depends on a module in an external loop can't proceed -- until the entire loop is re-typechecked. -- -- These two invariants have to be maintained to correctly build a -- compilation graph with one or more loops. -- The loop that this module will finish. After this module successfully -- compiles, this loop is going to get re-typechecked. let finish_loop = listToMaybe [ tail loop | loop <- comp_graph_loops , head loop == this_build_mod ] -- If this module finishes a loop then it must depend on all the other -- modules in that loop because the entire module loop is going to be -- re-typechecked once this module gets compiled. These extra dependencies -- are this module's "internal" loop dependencies, because this module is -- inside the loop in question. let int_loop_deps = Set.fromList $ case finish_loop of Nothing -> [] Just loop -> filter (/= this_build_mod) loop -- If this module depends on a module within a loop then it must wait for -- that loop to get re-typechecked, i.e. it must wait on the module that -- finishes that loop. These extra dependencies are this module's -- "external" loop dependencies, because this module is outside of the -- loop(s) in question. let ext_loop_deps = Set.fromList [ head loop | loop <- comp_graph_loops , any (`Set.member` textual_deps) loop , this_build_mod `notElem` loop ] let all_deps = foldl1 Set.union [textual_deps, int_loop_deps, ext_loop_deps] -- All of the module's home-module dependencies. let home_deps_with_idx = [ home_dep | dep <- Set.toList all_deps , Just home_dep <- [Map.lookup dep home_mod_map] ] -- Sort the list of dependencies in reverse-topological order. This way, by -- the time we get woken up by the result of an earlier dependency, -- subsequent dependencies are more likely to have finished. This step -- effectively reduces the number of MVars that each thread blocks on. let home_deps = map fst $ sortBy (flip (comparing snd)) home_deps_with_idx -- Wait for the all the module's dependencies to finish building. deps_ok <- allM (fmap succeeded . readMVar) home_deps -- We can't build this module if any of its dependencies failed to build. if not deps_ok then return Failed else do -- Any hsc_env at this point is OK to use since we only really require -- that the HPT contains the HMIs of our dependencies. hsc_env <- readMVar hsc_env_var old_hpt <- readIORef old_hpt_var let logger err = printBagOfErrors lcl_dflags (srcErrorMessages err) -- Limit the number of parallel compiles. let withSem sem = bracket_ (waitQSem sem) (signalQSem sem) mb_mod_info <- withSem par_sem $ handleSourceError (\err -> do logger err; return Nothing) $ do -- Have the ModSummary and HscEnv point to our local log_action -- and filesToClean var. let lcl_mod = localize_mod mod let lcl_hsc_env = localize_hsc_env hsc_env -- Compile the module. mod_info <- upsweep_mod lcl_hsc_env old_hpt stable_mods lcl_mod mod_index num_mods return (Just mod_info) case mb_mod_info of Nothing -> return Failed Just mod_info -> do let this_mod = ms_mod_name mod -- Prune the old HPT unless this is an hs-boot module. unless (isBootSummary mod) $ atomicModifyIORef old_hpt_var $ \old_hpt -> (delFromUFM old_hpt this_mod, ()) -- Update and fetch the global HscEnv. lcl_hsc_env' <- modifyMVar hsc_env_var $ \hsc_env -> do let hsc_env' = hsc_env { hsc_HPT = addToUFM (hsc_HPT hsc_env) this_mod mod_info } -- If this module is a loop finisher, now is the time to -- re-typecheck the loop. hsc_env'' <- case finish_loop of Nothing -> return hsc_env' Just loop -> typecheckLoop lcl_dflags hsc_env' $ map (moduleName . fst) loop return (hsc_env'', localize_hsc_env hsc_env'') -- Clean up any intermediate files. cleanup lcl_hsc_env' return Succeeded where localize_mod mod = mod { ms_hspp_opts = (ms_hspp_opts mod) { log_action = log_action lcl_dflags , filesToClean = filesToClean lcl_dflags } } localize_hsc_env hsc_env = hsc_env { hsc_dflags = (hsc_dflags hsc_env) { log_action = log_action lcl_dflags , filesToClean = filesToClean lcl_dflags } } -- ----------------------------------------------------------------------------- -- -- | The upsweep -- -- This is where we compile each module in the module graph, in a pass -- from the bottom to the top of the graph. -- -- There better had not be any cyclic groups here -- we check for them. upsweep :: GhcMonad m => HomePackageTable -- ^ HPT from last time round (pruned) -> ([ModuleName],[ModuleName]) -- ^ stable modules (see checkStability) -> (HscEnv -> IO ()) -- ^ How to clean up unwanted tmp files -> [SCC ModSummary] -- ^ Mods to do (the worklist) -> m (SuccessFlag, [ModSummary]) -- ^ Returns: -- -- 1. A flag whether the complete upsweep was successful. -- 2. The 'HscEnv' in the monad has an updated HPT -- 3. A list of modules which succeeded loading. upsweep old_hpt stable_mods cleanup sccs = do (res, done) <- upsweep' old_hpt [] sccs 1 (length sccs) return (res, reverse done) where upsweep' _old_hpt done [] _ _ = return (Succeeded, done) upsweep' _old_hpt done (CyclicSCC ms:_) _ _ = do dflags <- getSessionDynFlags liftIO $ fatalErrorMsg dflags (cyclicModuleErr ms) return (Failed, done) upsweep' old_hpt done (AcyclicSCC mod:mods) mod_index nmods = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ -- show (map (moduleUserString.moduleName.mi_module.hm_iface) -- (moduleEnvElts (hsc_HPT hsc_env))) let logger _mod = defaultWarnErrLogger hsc_env <- getSession -- Remove unwanted tmp files between compilations liftIO (cleanup hsc_env) mb_mod_info <- handleSourceError (\err -> do logger mod (Just err); return Nothing) $ do mod_info <- liftIO $ upsweep_mod hsc_env old_hpt stable_mods mod mod_index nmods logger mod Nothing -- log warnings return (Just mod_info) case mb_mod_info of Nothing -> return (Failed, done) Just mod_info -> do let this_mod = ms_mod_name mod -- Add new info to hsc_env hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info hsc_env1 = hsc_env { hsc_HPT = hpt1 } -- Space-saving: delete the old HPT entry -- for mod BUT if mod is a hs-boot -- node, don't delete it. For the -- interface, the HPT entry is probaby for the -- main Haskell source file. Deleting it -- would force the real module to be recompiled -- every time. old_hpt1 | isBootSummary mod = old_hpt | otherwise = delFromUFM old_hpt this_mod done' = mod:done -- fixup our HomePackageTable after we've finished compiling -- a mutually-recursive loop. See reTypecheckLoop, below. hsc_env2 <- liftIO $ reTypecheckLoop hsc_env1 mod done' setSession hsc_env2 upsweep' old_hpt1 done' mods (mod_index+1) nmods -- | Compile a single module. Always produce a Linkable for it if -- successful. If no compilation happened, return the old Linkable. upsweep_mod :: HscEnv -> HomePackageTable -> ([ModuleName],[ModuleName]) -> ModSummary -> Int -- index of module -> Int -- total number of modules -> IO HomeModInfo upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods = let this_mod_name = ms_mod_name summary this_mod = ms_mod summary mb_obj_date = ms_obj_date summary obj_fn = ml_obj_file (ms_location summary) hs_date = ms_hs_date summary is_stable_obj = this_mod_name `elem` stable_obj is_stable_bco = this_mod_name `elem` stable_bco old_hmi = lookupUFM old_hpt this_mod_name -- We're using the dflags for this module now, obtained by -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas. dflags = ms_hspp_opts summary prevailing_target = hscTarget (hsc_dflags hsc_env) local_target = hscTarget dflags -- If OPTIONS_GHC contains -fasm or -fllvm, be careful that -- we don't do anything dodgy: these should only work to change -- from -fllvm to -fasm and vice-versa, otherwise we could -- end up trying to link object code to byte code. target = if prevailing_target /= local_target && (not (isObjectTarget prevailing_target) || not (isObjectTarget local_target)) then prevailing_target else local_target -- store the corrected hscTarget into the summary summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } } -- The old interface is ok if -- a) we're compiling a source file, and the old HPT -- entry is for a source file -- b) we're compiling a hs-boot file -- Case (b) allows an hs-boot file to get the interface of its -- real source file on the second iteration of the compilation -- manager, but that does no harm. Otherwise the hs-boot file -- will always be recompiled mb_old_iface = case old_hmi of Nothing -> Nothing Just hm_info | isBootSummary summary -> Just iface | not (mi_boot iface) -> Just iface | otherwise -> Nothing where iface = hm_iface hm_info compile_it :: Maybe Linkable -> SourceModified -> IO HomeModInfo compile_it mb_linkable src_modified = compileOne hsc_env summary' mod_index nmods mb_old_iface mb_linkable src_modified compile_it_discard_iface :: Maybe Linkable -> SourceModified -> IO HomeModInfo compile_it_discard_iface mb_linkable src_modified = compileOne hsc_env summary' mod_index nmods Nothing mb_linkable src_modified -- With the HscNothing target we create empty linkables to avoid -- recompilation. We have to detect these to recompile anyway if -- the target changed since the last compile. is_fake_linkable | Just hmi <- old_hmi, Just l <- hm_linkable hmi = null (linkableUnlinked l) | otherwise = -- we have no linkable, so it cannot be fake False implies False _ = True implies True x = x in case () of _ -- Regardless of whether we're generating object code or -- byte code, we can always use an existing object file -- if it is *stable* (see checkStability). | is_stable_obj, Just hmi <- old_hmi -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "skipping stable obj mod:" <+> ppr this_mod_name) return hmi -- object is stable, and we have an entry in the -- old HPT: nothing to do | is_stable_obj, isNothing old_hmi -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling stable on-disk mod:" <+> ppr this_mod_name) linkable <- liftIO $ findObjectLinkable this_mod obj_fn (expectJust "upsweep1" mb_obj_date) compile_it (Just linkable) SourceUnmodifiedAndStable -- object is stable, but we need to load the interface -- off disk to make a HMI. | not (isObjectTarget target), is_stable_bco, (target /= HscNothing) `implies` not is_fake_linkable -> ASSERT(isJust old_hmi) -- must be in the old_hpt let Just hmi = old_hmi in do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "skipping stable BCO mod:" <+> ppr this_mod_name) return hmi -- BCO is stable: nothing to do | not (isObjectTarget target), Just hmi <- old_hmi, Just l <- hm_linkable hmi, not (isObjectLinkable l), (target /= HscNothing) `implies` not is_fake_linkable, linkableTime l >= ms_hs_date summary -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling non-stable BCO mod:" <+> ppr this_mod_name) compile_it (Just l) SourceUnmodified -- we have an old BCO that is up to date with respect -- to the source: do a recompilation check as normal. -- When generating object code, if there's an up-to-date -- object file on the disk, then we can use it. -- However, if the object file is new (compared to any -- linkable we had from a previous compilation), then we -- must discard any in-memory interface, because this -- means the user has compiled the source file -- separately and generated a new interface, that we must -- read from the disk. -- | isObjectTarget target, Just obj_date <- mb_obj_date, obj_date >= hs_date -> do case old_hmi of Just hmi | Just l <- hm_linkable hmi, isObjectLinkable l && linkableTime l == obj_date -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling mod with new on-disk obj:" <+> ppr this_mod_name) compile_it (Just l) SourceUnmodified _otherwise -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling mod with new on-disk obj2:" <+> ppr this_mod_name) linkable <- liftIO $ findObjectLinkable this_mod obj_fn obj_date compile_it_discard_iface (Just linkable) SourceUnmodified _otherwise -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling mod:" <+> ppr this_mod_name) compile_it Nothing SourceModified -- Filter modules in the HPT retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable retainInTopLevelEnvs keep_these hpt = listToUFM [ (mod, expectJust "retain" mb_mod_info) | mod <- keep_these , let mb_mod_info = lookupUFM hpt mod , isJust mb_mod_info ] -- --------------------------------------------------------------------------- -- Typecheck module loops {- See bug #930. This code fixes a long-standing bug in --make. The problem is that when compiling the modules *inside* a loop, a data type that is only defined at the top of the loop looks opaque; but after the loop is done, the structure of the data type becomes apparent. The difficulty is then that two different bits of code have different notions of what the data type looks like. The idea is that after we compile a module which also has an .hs-boot file, we re-generate the ModDetails for each of the modules that depends on the .hs-boot file, so that everyone points to the proper TyCons, Ids etc. defined by the real module, not the boot module. Fortunately re-generating a ModDetails from a ModIface is easy: the function TcIface.typecheckIface does exactly that. Picking the modules to re-typecheck is slightly tricky. Starting from the module graph consisting of the modules that have already been compiled, we reverse the edges (so they point from the imported module to the importing module), and depth-first-search from the .hs-boot node. This gives us all the modules that depend transitively on the .hs-boot module, and those are exactly the modules that we need to re-typecheck. Following this fix, GHC can compile itself with --make -O2. -} reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv reTypecheckLoop hsc_env ms graph | Just loop <- getModLoop ms graph , let non_boot = filter (not.isBootSummary) loop = typecheckLoop (hsc_dflags hsc_env) hsc_env (map ms_mod_name non_boot) | otherwise = return hsc_env getModLoop :: ModSummary -> ModuleGraph -> Maybe [ModSummary] getModLoop ms graph | not (isBootSummary ms) , any (\m -> ms_mod m == this_mod && isBootSummary m) graph , let mss = reachableBackwards (ms_mod_name ms) graph = Just mss | otherwise = Nothing where this_mod = ms_mod ms typecheckLoop :: DynFlags -> HscEnv -> [ModuleName] -> IO HscEnv typecheckLoop dflags hsc_env mods = do debugTraceMsg dflags 2 $ text "Re-typechecking loop: " <> ppr mods new_hpt <- fixIO $ \new_hpt -> do let new_hsc_env = hsc_env{ hsc_HPT = new_hpt } mds <- initIfaceCheck new_hsc_env $ mapM (typecheckIface . hm_iface) hmis let new_hpt = addListToUFM old_hpt (zip mods [ hmi{ hm_details = details } | (hmi,details) <- zip hmis mds ]) return new_hpt return hsc_env{ hsc_HPT = new_hpt } where old_hpt = hsc_HPT hsc_env hmis = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary] reachableBackwards mod summaries = [ ms | (ms,_,_) <- reachableG (transposeG graph) root ] where -- the rest just sets up the graph: (graph, lookup_node) = moduleGraphNodes False summaries root = expectJust "reachableBackwards" (lookup_node HsBootFile mod) -- --------------------------------------------------------------------------- -- -- | Topological sort of the module graph topSortModuleGraph :: Bool -- ^ Drop hi-boot nodes? (see below) -> [ModSummary] -> Maybe ModuleName -- ^ Root module name. If @Nothing@, use the full graph. -> [SCC ModSummary] -- ^ Calculate SCCs of the module graph, possibly dropping the hi-boot nodes -- The resulting list of strongly-connected-components is in topologically -- sorted order, starting with the module(s) at the bottom of the -- dependency graph (ie compile them first) and ending with the ones at -- the top. -- -- Drop hi-boot nodes (first boolean arg)? -- -- - @False@: treat the hi-boot summaries as nodes of the graph, -- so the graph must be acyclic -- -- - @True@: eliminate the hi-boot nodes, and instead pretend -- the a source-import of Foo is an import of Foo -- The resulting graph has no hi-boot nodes, but can be cyclic topSortModuleGraph drop_hs_boot_nodes summaries mb_root_mod = map (fmap summaryNodeSummary) $ stronglyConnCompG initial_graph where (graph, lookup_node) = moduleGraphNodes drop_hs_boot_nodes summaries initial_graph = case mb_root_mod of Nothing -> graph Just root_mod -> -- restrict the graph to just those modules reachable from -- the specified module. We do this by building a graph with -- the full set of nodes, and determining the reachable set from -- the specified node. let root | Just node <- lookup_node HsSrcFile root_mod, graph `hasVertexG` node = node | otherwise = throwGhcException (ProgramError "module does not exist") in graphFromEdgedVertices (seq root (reachableG graph root)) type SummaryNode = (ModSummary, Int, [Int]) summaryNodeKey :: SummaryNode -> Int summaryNodeKey (_, k, _) = k summaryNodeSummary :: SummaryNode -> ModSummary summaryNodeSummary (s, _, _) = s moduleGraphNodes :: Bool -> [ModSummary] -> (Graph SummaryNode, HscSource -> ModuleName -> Maybe SummaryNode) moduleGraphNodes drop_hs_boot_nodes summaries = (graphFromEdgedVertices nodes, lookup_node) where numbered_summaries = zip summaries [1..] lookup_node :: HscSource -> ModuleName -> Maybe SummaryNode lookup_node hs_src mod = Map.lookup (mod, hs_src) node_map lookup_key :: HscSource -> ModuleName -> Maybe Int lookup_key hs_src mod = fmap summaryNodeKey (lookup_node hs_src mod) node_map :: NodeMap SummaryNode node_map = Map.fromList [ ((moduleName (ms_mod s), ms_hsc_src s), node) | node@(s, _, _) <- nodes ] -- We use integers as the keys for the SCC algorithm nodes :: [SummaryNode] nodes = [ (s, key, out_keys) | (s, key) <- numbered_summaries -- Drop the hi-boot ones if told to do so , not (isBootSummary s && drop_hs_boot_nodes) , let out_keys = out_edge_keys hs_boot_key (map unLoc (ms_home_srcimps s)) ++ out_edge_keys HsSrcFile (map unLoc (ms_home_imps s)) ++ (-- see [boot-edges] below if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile then [] else case lookup_key HsBootFile (ms_mod_name s) of Nothing -> [] Just k -> [k]) ] -- [boot-edges] if this is a .hs and there is an equivalent -- .hs-boot, add a link from the former to the latter. This -- has the effect of detecting bogus cases where the .hs-boot -- depends on the .hs, by introducing a cycle. Additionally, -- it ensures that we will always process the .hs-boot before -- the .hs, and so the HomePackageTable will always have the -- most up to date information. -- Drop hs-boot nodes by using HsSrcFile as the key hs_boot_key | drop_hs_boot_nodes = HsSrcFile | otherwise = HsBootFile out_edge_keys :: HscSource -> [ModuleName] -> [Int] out_edge_keys hi_boot ms = mapMaybe (lookup_key hi_boot) ms -- If we want keep_hi_boot_nodes, then we do lookup_key with -- the IsBootInterface parameter True; else False type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are type NodeMap a = Map.Map NodeKey a -- keyed by (mod, src_file_type) pairs msKey :: ModSummary -> NodeKey msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot) mkNodeMap :: [ModSummary] -> NodeMap ModSummary mkNodeMap summaries = Map.fromList [ (msKey s, s) | s <- summaries] nodeMapElts :: NodeMap a -> [a] nodeMapElts = Map.elems -- | If there are {-# SOURCE #-} imports between strongly connected -- components in the topological sort, then those imports can -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE -- were necessary, then the edge would be part of a cycle. warnUnnecessarySourceImports :: GhcMonad m => [SCC ModSummary] -> m () warnUnnecessarySourceImports sccs = do dflags <- getDynFlags logWarnings (listToBag (concatMap (check dflags . flattenSCC) sccs)) where check dflags ms = let mods_in_this_cycle = map ms_mod_name ms in [ warn dflags i | m <- ms, i <- ms_home_srcimps m, unLoc i `notElem` mods_in_this_cycle ] warn :: DynFlags -> Located ModuleName -> WarnMsg warn dflags (L loc mod) = mkPlainErrMsg dflags loc (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ") <+> quotes (ppr mod)) reportImportErrors :: MonadIO m => [Either ErrMsg b] -> m [b] reportImportErrors xs | null errs = return oks | otherwise = throwManyErrors errs where (errs, oks) = partitionEithers xs throwManyErrors :: MonadIO m => [ErrMsg] -> m ab throwManyErrors errs = liftIO $ throwIO $ mkSrcErr $ listToBag errs ----------------------------------------------------------------------------- -- -- | Downsweep (dependency analysis) -- -- Chase downwards from the specified root set, returning summaries -- for all home modules encountered. Only follow source-import -- links. -- -- We pass in the previous collection of summaries, which is used as a -- cache to avoid recalculating a module summary if the source is -- unchanged. -- -- The returned list of [ModSummary] nodes has one node for each home-package -- module, plus one for any hs-boot files. The imports of these nodes -- are all there, including the imports of non-home-package modules. downsweep :: HscEnv -> [ModSummary] -- Old summaries -> [ModuleName] -- Ignore dependencies on these; treat -- them as if they were package modules -> Bool -- True <=> allow multiple targets to have -- the same module name; this is -- very useful for ghc -M -> IO [Either ErrMsg ModSummary] -- The elts of [ModSummary] all have distinct -- (Modules, IsBoot) identifiers, unless the Bool is true -- in which case there can be repeats downsweep hsc_env old_summaries excl_mods allow_dup_roots = do rootSummaries <- mapM getRootSummary roots rootSummariesOk <- reportImportErrors rootSummaries let root_map = mkRootMap rootSummariesOk checkDuplicates root_map summs <- loop (concatMap msDeps rootSummariesOk) root_map return summs where dflags = hsc_dflags hsc_env roots = hsc_targets hsc_env old_summary_map :: NodeMap ModSummary old_summary_map = mkNodeMap old_summaries getRootSummary :: Target -> IO (Either ErrMsg ModSummary) getRootSummary (Target (TargetFile file mb_phase) obj_allowed maybe_buf) = do exists <- liftIO $ doesFileExist file if exists then Right `fmap` summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf else return $ Left $ mkPlainErrMsg dflags noSrcSpan $ text "can't find file:" <+> text file getRootSummary (Target (TargetModule modl) obj_allowed maybe_buf) = do maybe_summary <- summariseModule hsc_env old_summary_map False (L rootLoc modl) obj_allowed maybe_buf excl_mods case maybe_summary of Nothing -> return $ Left $ packageModErr dflags modl Just s -> return s rootLoc = mkGeneralSrcSpan (fsLit "<command line>") -- In a root module, the filename is allowed to diverge from the module -- name, so we have to check that there aren't multiple root files -- defining the same module (otherwise the duplicates will be silently -- ignored, leading to confusing behaviour). checkDuplicates :: NodeMap [Either ErrMsg ModSummary] -> IO () checkDuplicates root_map | allow_dup_roots = return () | null dup_roots = return () | otherwise = liftIO $ multiRootsErr dflags (head dup_roots) where dup_roots :: [[ModSummary]] -- Each at least of length 2 dup_roots = filterOut isSingleton $ map rights $ nodeMapElts root_map loop :: [(Located ModuleName,IsBootInterface)] -- Work list: process these modules -> NodeMap [Either ErrMsg ModSummary] -- Visited set; the range is a list because -- the roots can have the same module names -- if allow_dup_roots is True -> IO [Either ErrMsg ModSummary] -- The result includes the worklist, except -- for those mentioned in the visited set loop [] done = return (concat (nodeMapElts done)) loop ((wanted_mod, is_boot) : ss) done | Just summs <- Map.lookup key done = if isSingleton summs then loop ss done else do { multiRootsErr dflags (rights summs); return [] } | otherwise = do mb_s <- summariseModule hsc_env old_summary_map is_boot wanted_mod True Nothing excl_mods case mb_s of Nothing -> loop ss done Just (Left e) -> loop ss (Map.insert key [Left e] done) Just (Right s)-> loop (msDeps s ++ ss) (Map.insert key [Right s] done) where key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile) mkRootMap :: [ModSummary] -> NodeMap [Either ErrMsg ModSummary] mkRootMap summaries = Map.insertListWith (flip (++)) [ (msKey s, [Right s]) | s <- summaries ] Map.empty -- | Returns the dependencies of the ModSummary s. -- A wrinkle is that for a {-# SOURCE #-} import we return -- *both* the hs-boot file -- *and* the source file -- as "dependencies". That ensures that the list of all relevant -- modules always contains B.hs if it contains B.hs-boot. -- Remember, this pass isn't doing the topological sort. It's -- just gathering the list of all relevant ModSummaries msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)] msDeps s = concat [ [(m,True), (m,False)] | m <- ms_home_srcimps s ] ++ [ (m,False) | m <- ms_home_imps s ] home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName] home_imps imps = [ ideclName i | L _ i <- imps, isLocal (ideclPkgQual i) ] where isLocal Nothing = True isLocal (Just pkg) | pkg == fsLit "this" = True -- "this" is special isLocal _ = False ms_home_allimps :: ModSummary -> [ModuleName] ms_home_allimps ms = map unLoc (ms_home_srcimps ms ++ ms_home_imps ms) ms_home_srcimps :: ModSummary -> [Located ModuleName] ms_home_srcimps = home_imps . ms_srcimps ms_home_imps :: ModSummary -> [Located ModuleName] ms_home_imps = home_imps . ms_imps ----------------------------------------------------------------------------- -- Summarising modules -- We have two types of summarisation: -- -- * Summarise a file. This is used for the root module(s) passed to -- cmLoadModules. The file is read, and used to determine the root -- module name. The module name may differ from the filename. -- -- * Summarise a module. We are given a module name, and must provide -- a summary. The finder is used to locate the file in which the module -- resides. summariseFile :: HscEnv -> [ModSummary] -- old summaries -> FilePath -- source file name -> Maybe Phase -- start phase -> Bool -- object code allowed? -> Maybe (StringBuffer,UTCTime) -> IO ModSummary summariseFile hsc_env old_summaries file mb_phase obj_allowed maybe_buf -- we can use a cached summary if one is available and the -- source file hasn't changed, But we have to look up the summary -- by source file, rather than module name as we do in summarise. | Just old_summary <- findSummaryBySourceFile old_summaries file = do let location = ms_location old_summary src_timestamp <- get_src_timestamp -- The file exists; we checked in getRootSummary above. -- If it gets removed subsequently, then this -- getModificationUTCTime may fail, but that's the right -- behaviour. -- return the cached summary if the source didn't change if ms_hs_date old_summary == src_timestamp && not (gopt Opt_ForceRecomp (hsc_dflags hsc_env)) then do -- update the object-file timestamp obj_timestamp <- if isObjectTarget (hscTarget (hsc_dflags hsc_env)) || obj_allowed -- bug #1205 then liftIO $ getObjTimestamp location False else return Nothing return old_summary{ ms_obj_date = obj_timestamp } else new_summary src_timestamp | otherwise = do src_timestamp <- get_src_timestamp new_summary src_timestamp where get_src_timestamp = case maybe_buf of Just (_,t) -> return t Nothing -> liftIO $ getModificationUTCTime file -- getMofificationUTCTime may fail new_summary src_timestamp = do let dflags = hsc_dflags hsc_env (dflags', hspp_fn, buf) <- preprocessFile hsc_env file mb_phase maybe_buf (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file -- Make a ModLocation for this file location <- liftIO $ mkHomeModLocation dflags mod_name file -- Tell the Finder cache where it is, so that subsequent calls -- to findModule will find it, even if it's not on any search path mod <- liftIO $ addHomeModuleToFinder hsc_env mod_name location -- when the user asks to load a source file by name, we only -- use an object file if -fobject-code is on. See #1205. obj_timestamp <- if isObjectTarget (hscTarget (hsc_dflags hsc_env)) || obj_allowed -- bug #1205 then liftIO $ modificationTimeIfExists (ml_obj_file location) else return Nothing return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile, ms_location = location, ms_hspp_file = hspp_fn, ms_hspp_opts = dflags', ms_hspp_buf = Just buf, ms_srcimps = srcimps, ms_textual_imps = the_imps, ms_hs_date = src_timestamp, ms_obj_date = obj_timestamp }) findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary findSummaryBySourceFile summaries file = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms], expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of [] -> Nothing (x:_) -> Just x -- Summarise a module, and pick up source and timestamp. summariseModule :: HscEnv -> NodeMap ModSummary -- Map of old summaries -> IsBootInterface -- True <=> a {-# SOURCE #-} import -> Located ModuleName -- Imported module to be summarised -> Bool -- object code allowed? -> Maybe (StringBuffer, UTCTime) -> [ModuleName] -- Modules to exclude -> IO (Maybe (Either ErrMsg ModSummary)) -- Its new summary summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) obj_allowed maybe_buf excl_mods | wanted_mod `elem` excl_mods = return Nothing | Just old_summary <- Map.lookup (wanted_mod, hsc_src) old_summary_map = do -- Find its new timestamp; all the -- ModSummaries in the old map have valid ml_hs_files let location = ms_location old_summary src_fn = expectJust "summariseModule" (ml_hs_file location) -- check the modification time on the source file, and -- return the cached summary if it hasn't changed. If the -- file has disappeared, we need to call the Finder again. case maybe_buf of Just (_,t) -> check_timestamp old_summary location src_fn t Nothing -> do m <- tryIO (getModificationUTCTime src_fn) case m of Right t -> check_timestamp old_summary location src_fn t Left e | isDoesNotExistError e -> find_it | otherwise -> ioError e | otherwise = find_it where dflags = hsc_dflags hsc_env hsc_src = if is_boot then HsBootFile else HsSrcFile check_timestamp old_summary location src_fn src_timestamp | ms_hs_date old_summary == src_timestamp && not (gopt Opt_ForceRecomp dflags) = do -- update the object-file timestamp obj_timestamp <- if isObjectTarget (hscTarget (hsc_dflags hsc_env)) || obj_allowed -- bug #1205 then getObjTimestamp location is_boot else return Nothing return (Just (Right old_summary{ ms_obj_date = obj_timestamp })) | otherwise = -- source changed: re-summarise. new_summary location (ms_mod old_summary) src_fn src_timestamp find_it = do -- Don't use the Finder's cache this time. If the module was -- previously a package module, it may have now appeared on the -- search path, so we want to consider it to be a home module. If -- the module was previously a home module, it may have moved. uncacheModule hsc_env wanted_mod found <- findImportedModule hsc_env wanted_mod Nothing case found of Found location mod | isJust (ml_hs_file location) -> -- Home package just_found location mod | otherwise -> -- Drop external-pkg ASSERT(modulePackageKey mod /= thisPackage dflags) return Nothing err -> return $ Just $ Left $ noModError dflags loc wanted_mod err -- Not found just_found location mod = do -- Adjust location to point to the hs-boot source file, -- hi file, object file, when is_boot says so let location' | is_boot = addBootSuffixLocn location | otherwise = location src_fn = expectJust "summarise2" (ml_hs_file location') -- Check that it exists -- It might have been deleted since the Finder last found it maybe_t <- modificationTimeIfExists src_fn case maybe_t of Nothing -> return $ Just $ Left $ noHsFileErr dflags loc src_fn Just t -> new_summary location' mod src_fn t new_summary location mod src_fn src_timestamp = do -- Preprocess the source file and get its imports -- The dflags' contains the OPTIONS pragmas (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn when (mod_name /= wanted_mod) $ throwOneError $ mkPlainErrMsg dflags' mod_loc $ text "File name does not match module name:" $$ text "Saw:" <+> quotes (ppr mod_name) $$ text "Expected:" <+> quotes (ppr wanted_mod) -- Find the object timestamp, and return the summary obj_timestamp <- if isObjectTarget (hscTarget (hsc_dflags hsc_env)) || obj_allowed -- bug #1205 then getObjTimestamp location is_boot else return Nothing return (Just (Right (ModSummary { ms_mod = mod, ms_hsc_src = hsc_src, ms_location = location, ms_hspp_file = hspp_fn, ms_hspp_opts = dflags', ms_hspp_buf = Just buf, ms_srcimps = srcimps, ms_textual_imps = the_imps, ms_hs_date = src_timestamp, ms_obj_date = obj_timestamp }))) getObjTimestamp :: ModLocation -> Bool -> IO (Maybe UTCTime) getObjTimestamp location is_boot = if is_boot then return Nothing else modificationTimeIfExists (ml_obj_file location) preprocessFile :: HscEnv -> FilePath -> Maybe Phase -- ^ Starting phase -> Maybe (StringBuffer,UTCTime) -> IO (DynFlags, FilePath, StringBuffer) preprocessFile hsc_env src_fn mb_phase Nothing = do (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase) buf <- hGetStringBuffer hspp_fn return (dflags', hspp_fn, buf) preprocessFile hsc_env src_fn mb_phase (Just (buf, _time)) = do let dflags = hsc_dflags hsc_env let local_opts = getOptions dflags buf src_fn (dflags', leftovers, warns) <- parseDynamicFilePragma dflags local_opts checkProcessArgsResult dflags leftovers handleFlagWarnings dflags' warns let needs_preprocessing | Just (Unlit _) <- mb_phase = True | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True -- note: local_opts is only required if there's no Unlit phase | xopt Opt_Cpp dflags' = True | gopt Opt_Pp dflags' = True | otherwise = False when needs_preprocessing $ throwGhcExceptionIO (ProgramError "buffer needs preprocesing; interactive check disabled") return (dflags', src_fn, buf) ----------------------------------------------------------------------------- -- Error messages ----------------------------------------------------------------------------- noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> ErrMsg -- ToDo: we don't have a proper line number for this error noModError dflags loc wanted_mod err = mkPlainErrMsg dflags loc $ cannotFindModule dflags wanted_mod err noHsFileErr :: DynFlags -> SrcSpan -> String -> ErrMsg noHsFileErr dflags loc path = mkPlainErrMsg dflags loc $ text "Can't find" <+> text path packageModErr :: DynFlags -> ModuleName -> ErrMsg packageModErr dflags mod = mkPlainErrMsg dflags noSrcSpan $ text "module" <+> quotes (ppr mod) <+> text "is a package module" multiRootsErr :: DynFlags -> [ModSummary] -> IO () multiRootsErr _ [] = panic "multiRootsErr" multiRootsErr dflags summs@(summ1:_) = throwOneError $ mkPlainErrMsg dflags noSrcSpan $ text "module" <+> quotes (ppr mod) <+> text "is defined in multiple files:" <+> sep (map text files) where mod = ms_mod summ1 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs cyclicModuleErr :: [ModSummary] -> SDoc -- From a strongly connected component we find -- a single cycle to report cyclicModuleErr mss = ASSERT( not (null mss) ) case findCycle graph of Nothing -> ptext (sLit "Unexpected non-cycle") <+> ppr mss Just path -> vcat [ ptext (sLit "Module imports form a cycle:") , nest 2 (show_path path) ] where graph :: [Node NodeKey ModSummary] graph = [(ms, msKey ms, get_deps ms) | ms <- mss] get_deps :: ModSummary -> [NodeKey] get_deps ms = ([ (unLoc m, HsBootFile) | m <- ms_home_srcimps ms ] ++ [ (unLoc m, HsSrcFile) | m <- ms_home_imps ms ]) show_path [] = panic "show_path" show_path [m] = ptext (sLit "module") <+> ppr_ms m <+> ptext (sLit "imports itself") show_path (m1:m2:ms) = vcat ( nest 7 (ptext (sLit "module") <+> ppr_ms m1) : nest 6 (ptext (sLit "imports") <+> ppr_ms m2) : go ms ) where go [] = [ptext (sLit "which imports") <+> ppr_ms m1] go (m:ms) = (ptext (sLit "which imports") <+> ppr_ms m) : go ms ppr_ms :: ModSummary -> SDoc ppr_ms ms = quotes (ppr (moduleName (ms_mod ms))) <+> (parens (text (msHsFilePath ms)))
lukexi/ghc
compiler/main/GhcMake.hs
bsd-3-clause
83,069
992
25
26,383
12,111
7,017
5,094
-1
-1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable import Cryptol.Parser.Lexer import Cryptol.Parser.PP main :: IO () main = interact (unlines . map (show . pp) . fst . primLexer)
iblumenfeld/cryptol
tests/parser/RunLexer.hs
bsd-3-clause
325
1
12
72
66
37
29
4
1
module LeftSectionIn1 where {- map2 xs = map (+ 1) xs -} map2 xs = (case ((+ 1), xs) of (f, []) -> [] (f, (x : xs)) -> (f x) : (map2 xs))
kmate/HaRe
old/testing/generativeFold/LeftSectionIn1_TokOut.hs
bsd-3-clause
171
0
11
67
81
47
34
4
2
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Unittests for 'Ganeti.THH.Types'. -} {- Copyright (C) 2014 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.THH.Types ( testTHH_Types ) where import Test.QuickCheck as QuickCheck hiding (Result) import qualified Text.JSON as J import Test.Ganeti.TestCommon import Test.Ganeti.TestHelper import Ganeti.THH.Types {-# ANN module "HLint: ignore Use camelCase" #-} -- * Instances instance Arbitrary a => Arbitrary (OneTuple a) where arbitrary = fmap OneTuple arbitrary -- * Properties -- | Tests OneTuple serialisation. prop_OneTuple_serialisation :: OneTuple String -> Property prop_OneTuple_serialisation = testSerialisation -- | Tests OneTuple doesn't deserialize wrong input. prop_OneTuple_deserialisationFail :: Property prop_OneTuple_deserialisationFail = conjoin . map (testDeserialisationFail (OneTuple "")) $ [ J.JSArray [] , J.JSArray [J.showJSON "a", J.showJSON "b"] , J.JSArray [J.showJSON (1 :: Int)] ] -- * Test suite testSuite "THH_Types" [ 'prop_OneTuple_serialisation , 'prop_OneTuple_deserialisationFail ]
leshchevds/ganeti
test/hs/Test/Ganeti/THH/Types.hs
bsd-2-clause
2,385
0
11
371
215
125
90
23
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} module ValidSubsInteractions where import Data.Kind data SBool :: Bool -> Type where SFalse :: SBool 'False STrue :: SBool 'True f :: SBool 'True f = _
sdiehl/ghc
testsuite/tests/typecheck/should_compile/valid_hole_fits_interactions.hs
bsd-3-clause
242
0
7
49
58
34
24
10
1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE Safe #-} module T10598_fail3 where import GHC.Generics data T = MkT Int deriving anyclass Generic
olsner/ghc
testsuite/tests/deriving/should_fail/T10598_fail3.hs
bsd-3-clause
181
0
6
27
26
17
9
6
0
-- !!! Multiple modules per file module M where foo = 'a' module N where bar = 'b'
siddhanathan/ghc
testsuite/tests/module/mod76.hs
bsd-3-clause
85
0
5
20
22
13
9
-1
-1
module Control.Concurrent.Transactional.Var ( module Control.Concurrent.Transactional.Var.Class, module Control.Concurrent.Transactional.Var.Buffer, module Control.Concurrent.Transactional.Var.Mutable, module Control.Concurrent.Transactional.Var.Immutable ) where import Control.Concurrent.Transactional.Var.Class import Control.Concurrent.Transactional.Var.Buffer import Control.Concurrent.Transactional.Var.Mutable import Control.Concurrent.Transactional.Var.Immutable
YellPika/Hannel
src/Control/Concurrent/Transactional/Var.hs
mit
488
0
5
38
78
59
19
9
0
module Main where import Hello main = sayHello "GoatScreams McGee"
mikegehard/haskellBookExercises
call-em-up/src/Main.hs
mit
74
0
5
17
15
9
6
4
1
module Melvin ( doAMelvin ) where import Control.Concurrent.Lifted import Control.Concurrent.Async.Lifted import Control.Monad import Control.Monad.Fix import Data.Set import Melvin.Client as Client import Melvin.Damn as Damn import Melvin.Client.Auth import Melvin.Exception import Melvin.Prelude hiding (index, set, utf8) import Melvin.Options import Melvin.Types (Chatroom, ClientSettings(..), ClientState(..), ClientT) import qualified Melvin.Types as M import Network import System.IO doAMelvin :: Mopts -> [String] -> IO () doAMelvin Mopts { moptPort = p , moptLogLevel = l , moptMaxClients = _ } _args = runStdoutLoggingT l . (`evalStateT` error "no state") $ do $logInfo $ [st|Listening on %?.|] p server <- liftIO $ listenOn p forM_ [1..] $ \i -> do triple <- liftIO $ accept server async $ runClientPair i triple runClientPair :: ClientT m => Integer -> (Handle, String, t) -> m () runClientPair index (h, host, _) = do $logInfo $ [st|Client #%? has connected from %s.|] index host liftIO $ hSetEncoding h utf8 tokpair <- authenticate h case tokpair of Left e -> do $logWarn $ [st|Client #%? couldn't authenticate: %?.|] index e liftIO $ hClose h Right (uname, token_, rs) -> do put =<< buildClientSettings index h uname token_ rs result <- concurrently (runClient h) runServer case result of (Right{}, Right{}) -> $logInfo $ [st|Client #%d exited cleanly|] index (Left m, _) -> $logWarn $ [st|Client #%d encountered an error: %?|] index m (_, Left m) -> $logWarn $ [st|Client #%d's server encountered an error: %?|] index m -- This isn't retried because nobody cares what happened on dAmn if the -- client quits. runClient :: ClientT m => Handle -> m (Either SomeException ()) runClient h = do mt <- myThreadId ct <- use M.clientThreadId putMVar ct mt try $ Client.loop h runServer :: ClientT m => m (Either SomeException ()) runServer = do mt <- myThreadId st_ <- use M.serverThreadId putMVar st_ mt fix $ \f -> do result <- try Damn.loop case result of r@Right{} -> return r Left e -> if isRetryable e then f else return $ Left e buildClientSettings :: ClientT m => Integer -> Handle -> Text -> Text -> Set Chatroom -> m ClientSettings buildClientSettings clientNum clientHandle username token joinList = do -- mutexes serverWriteLock <- newMVar () clientWriteLock <- newMVar () -- holds the Handle connected to dAmn serverMVar <- newEmptyMVar serverThreadId <- newEmptyMVar clientThreadId <- newEmptyMVar clientState <- newMVar ClientState { _loggedIn = False , _joinList = joinList , _joining = mempty , _privclasses = mempty , _users = mempty } return ClientSettings { clientNumber = clientNum , _clientHandle = clientHandle , _serverWriteLock = serverWriteLock , _clientWriteLock = clientWriteLock , _username = username , _token = token , _serverMVar = serverMVar , _serverThreadId = serverThreadId , _clientThreadId = clientThreadId , _clientState = clientState }
pikajude/melvin
src/Melvin.hs
mit
3,472
0
16
1,040
979
517
462
-1
-1
module Graphics.Urho3D.UI.Internal.Text3D( Text3D , text3DCntx , sharedText3DPtrCntx , SharedText3D ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Types as C import Graphics.Urho3D.Container.Ptr import qualified Data.Map as Map data Text3D text3DCntx :: C.Context text3DCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Text3D", [t| Text3D |]) ] } sharedPtrImpl "Text3D"
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/UI/Internal/Text3D.hs
mit
492
0
11
87
120
80
40
-1
-1
-- Copyright 2015 Mitchell Kember. Subject to the MIT License. import Data.Char (toLower, chr, ord) import Data.List (genericLength, minimumBy) import Data.Ord (comparing) import qualified Data.Map as M -- Relative letter frequencies of English (http://norvig.com/mayzner.html). englishFreqs :: (Fractional a) => [a] englishFreqs = map (/ 100) $ [ 8.04, 1.48, 3.34, 3.82, 12.49, 2.40, 1.87, 5.05, 7.57, 0.16, 0.54, 4.07 , 2.51, 7.23, 7.64, 2.14, 0.12, 6.28, 6.51, 9.28, 2.73, 1.05, 1.68, 0.23 , 1.66 , 0.09] -- Calculates the relative letter frequencies of a string, considering only -- alphabetical characters. Returns a list of 26 frequencies. relativeFreqs :: (Fractional a) => String -> [a] relativeFreqs s = freqs where letters = filter (`elem` ['a'..'z']) . map toLower $ s zeros = M.fromDistinctAscList $ map (flip (,) 0) ['a'..'z'] inc m x = M.adjust (+ 1) x m counts = M.elems $ foldl inc zeros letters divide n = fromIntegral n / genericLength letters freqs = map divide counts -- Computers Pearson's chi-squared test-statistic for the given expected -- frequencies and observed frequencies. chiSqr :: (Fractional a) => [a] -> [a] -> a chiSqr es os = sum $ zipWith term es os where term e o = (o - e)^2 / e -- Shifts a character around the alphabet, wrapping if necessary. shift :: Int -> Char -> Char shift n c | c `elem` ['a'..'z'] = chr $ ord 'a' + (ord c - ord 'a' + n) `mod` 26 | c `elem` ['A'..'Z'] = chr $ ord 'A' + (ord c - ord 'A' + n) `mod` 26 | otherwise = c -- Caesar-encrypts a string using the given key. encrypt :: Int -> String -> String encrypt = map . shift -- Caesar-decrypts a string using the given key. decrypt :: Int -> String -> String decrypt = map . shift . negate -- Rotates a list by the given number of positions. Elements move forward -- through the list and ones that fall off the end return to the beginning. rotate :: [a] -> Int -> [a] rotate xs n = back ++ front where (front, back) = splitAt n xs -- Returns the index of the minimum element in the list. minIndex :: (Ord a) => [a] -> Int minIndex = fst . minimumBy (comparing snd) . zip [0..] -- Cracks a Caesar cipher given the ciphertext. Returns the key. crack :: String -> Int crack s = minIndex chis where freqs = relativeFreqs s chis = map (chiSqr englishFreqs . rotate freqs) [0..25]
mk12/algorithms
caesar.hs
mit
2,382
0
14
515
755
418
337
37
1
-------------------------------------------------------------------------- -- -- Haskell: The Craft of Functional Programming, 3e -- Simon Thompson -- (c) Addison-Wesley, 1996-2011. -- -- Chapter 4 -- -------------------------------------------------------------------------- -- NOTE -- -- Added HUnit and QuickCheck tests -- -- HUnit 1.0 documentation is out of date -- re package name. module Chapter4 where import PicturesSVG hiding (test2) import Test.HUnit import Test.QuickCheck -- Designing a program in Haskell -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ maxThree :: Int -> Int -> Int -> Int maxThree x y z = (x `max` y) `max` z testMax1 = TestCase (assertEqual "for: maxThree 6 4 1" 6 (maxThree 6 4 1)) testMax2 = TestCase (assertEqual "for: maxThree 6 6 6" 6 (maxThree 6 6 6)) testMax3 = TestCase (assertEqual "for: maxThree 2 6 6" 6 (maxThree 2 6 6)) testMax4 = TestCase (assertEqual "for: maxThree 2 2 6" 6 (maxThree 2 2 6)) -- run as -- runTestTT testsMax testsMax = TestList [testMax1, testMax2, testMax3, testMax4] -- NOTE -- -- Added this type synonym so that can switch easily -- between Integer and Int. type MyNum = Integer middleNumber :: MyNum -> MyNum -> MyNum -> MyNum middleNumber x y z | between y x z = x | between x y z = y | otherwise = z -- What follows here is a dummy definition of between; you need to replace this -- with a proper definition for the function middleNumber to work. between :: MyNum -> MyNum -> MyNum -> Bool -- dummy definition -- for you to complete! between = between -- NOTE -- -- HUnit tests added -- -- To run evaluate: runTestTT tests test1 = TestCase (assertEqual "for: between 2 3 4" True (between 2 3 4)) test2 = TestCase (assertEqual "for: between 2 3 2" False (between 2 3 2)) test3 = TestCase (assertEqual "for: between 2 3 3" True (between 2 3 3)) test4 = TestCase (assertEqual "for: between 3 3 3" True (between 3 3 3)) test5 = TestCase (assertEqual "for: between 3 2 3" False (between 3 2 3)) test6 = TestCase (assertEqual "for: between 3 2 1" True (between 3 2 1)) testsBetween = TestList [test1, test2, test3, test4, test5, test6] -- NOTE -- -- Interesting to vary the implementation and see which tests fail. -- Simple form of mutation testing. -- QuickCheck test -- -- Does the tricky implementation of between work in the -- same way as the case analysis? prop_between :: MyNum -> MyNum -> MyNum -> Bool prop_between x y z = between x y z == ((x<=y)&&(y<=z))||((x>=y)&&(y>=z)) -- Unit tests as Quick Check properties prop_between1 :: Bool prop_between1 = between 2 3 4 == True -- Local definitions -- ^^^^^^^^^^^^^^^^^ -- Four ways of defining a Picture using -- different combinations of loca definitions. fourPics1 :: Picture -> Picture fourPics1 pic = left `beside` right where left = pic `above` invertColour pic right = invertColour (flipV pic) `above` flipV pic fourPics2 :: Picture -> Picture fourPics2 pic = left `beside` right where left = pic `above` invertColour pic right = invertColour flipped `above` flipped flipped = flipV pic fourPics3 :: Picture -> Picture fourPics3 pic = left `beside` right where left = pic `above` invertColour pic right = invertColour (flipV left) fourPics4 :: Picture -> Picture fourPics4 pic = left `beside` right where stack p = p `above` invertColour p left = stack pic right = stack (invertColour (flipV pic)) -- Area of a triangle triArea' :: Float -> Float -> Float -> Float triArea' a b c | possible = sqrt(s*(s-a)*(s-b)*(s-c)) | otherwise = 0 where s = (a+b+c)/2 possible = possible -- dummy definition -- Sum of squares sumSquares :: Integer -> Integer -> Integer sumSquares n m = sqN + sqM where sqN = n*n sqM = m*m -- Let expressions -- ^^^^^^^^^^^^^^^ -- Two examples which use `let'. letEx1 :: Integer letEx1 = let x = 3+2 in x^2 + 2*x - 4 letEx2 :: Integer letEx2 = let x = 3+2 ; y = 5-1 in x^2 + 2*x - y -- Scopes isOdd, isEven :: Int -> Bool isOdd n | n<=0 = False | otherwise = isEven (n-1) isEven n | n<0 = False | n==0 = True | otherwise = isOdd (n-1) -- Defining types for ourselves -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- Rock - Paper - Scissors data Move = Rock | Paper | Scissors deriving Eq -- Showing Moves in an abbreviated form. instance Show Move where show Rock = "r" show Paper = "p" show Scissors = "s" -- For QuickCheck to work over the Move type. instance Arbitrary Move where arbitrary = elements [Rock, Paper, Scissors] -- Calculating the Move to beat or lose against the -- argument Move. beat, lose :: Move -> Move beat Rock = Paper beat Paper = Scissors beat Scissors = Rock lose Rock = Scissors lose Paper = Rock lose Scissors = Paper -- Primitive recursion over Int -- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -- The factorial of n is 1*2*...*(n-1)*n, so that factorial of four is 24. -- It is often written n! fac :: Integer -> Integer fac n | n==0 = 1 | n>0 = fac (n-1) * n | otherwise = error "fac only defined on natural numbers" -- n -- Raising two to a power: power2 n is 2 in mathematical notation. power2 :: Integer -> Integer power2 n | n==0 = 1 | n>0 = 2 * power2 (n-1) -- The sum of the factorials up to a particular value, 0! + 1! + ... n!. sumFacs :: Integer -> Integer sumFacs n | n==0 = 1 | n>0 = sumFacs (n-1) + fac n -- The sum of the values of a function up to a particular value: -- f 0 + f 1 + ... f n -- from which you can reconstruct sumFacs: sumFacs n = sumFun fac n sumFun :: (Integer -> Integer) -> Integer -> Integer sumFun f n | n==0 = f 0 | n>0 = sumFun f (n-1) + f n -- The maximum number of regions into which n lines can cut a plane. regions :: Integer -> Integer regions n | n==0 = 1 | n>0 = regions (n-1) + n -- The Fibonacci numbers 0, 1, 1, 2, 3, 5, ..., u, v, u+v, ... fib :: Integer -> Integer fib n | n==0 = 0 | n==1 = 1 | n>1 = fib (n-2) + fib (n-1) -- Division of integers remainder :: Integer -> Integer -> Integer remainder m n | m<n = m | otherwise = remainder (m-n) n divide :: Integer -> Integer -> Integer divide m n | m<n = 0 | otherwise = 1 + divide (m-n) n -- Testing -- ^^^^^^^ -- Does this function calculate the maximum of three numbers? mysteryMax :: Integer -> Integer -> Integer -> Integer mysteryMax x y z | x > y && x > z = x | y > x && y > z = y | otherwise = z testMMax1 = TestCase (assertEqual "for: mysteryMax 6 4 1" 6 (mysteryMax 6 4 1)) testMMax2 = TestCase (assertEqual "for: mysteryMax 6 6 6" 6 (mysteryMax 6 6 6)) testMMax3 = TestCase (assertEqual "for: mysteryMax 2 6 6" 6 (mysteryMax 2 6 6)) testMMax4 = TestCase (assertEqual "for: mysteryMax 2 2 6" 6 (mysteryMax 2 2 6)) testMMax5 = TestCase (assertEqual "for: mysteryMax 6 6 2" 6 (mysteryMax 6 6 2)) testsMMax = TestList [testMMax1, testMMax2, testMMax3, testMMax4, testMMax5] -- Numbers of roots numberNDroots :: Float -> Float -> Float -> Integer numberNDroots a b c | bsq > fac = 2 | bsq == fac = 1 | bsq < fac = 0 where bsq = b*b fac = 4.0*a*c -- Area of a triangle triArea :: Float -> Float -> Float -> Float triArea a b c | possible a b c = sqrt(s*(s-a)*(s-b)*(s-c)) | otherwise = 0 where s = (a+b+c)/2 possible :: Float -> Float -> Float -> Bool possible a b c = True -- dummy definition fact :: Int -> Int fact n | n>1 = n * fact (n-1) | otherwise = 1 prop_fact n = fact n > 0 -- Extended exercise -- ^^^^^^^^^^^^^^^^^ blackSquares :: Integer -> Picture blackSquares n | n<=1 = black | otherwise = black `beside` blackSquares (n-1) blackWhite :: Integer -> Picture blackWhite n | n<=1 = black | otherwise = black `beside` whiteBlack (n-1) whiteBlack = error "exercise for you" blackChess :: Integer -> Integer -> Picture blackChess n m | n<=1 = blackWhite m | otherwise = blackWhite m `above` whiteChess (n-1) m whiteChess n m = error "exercise for you"
tonyfloatersu/solution-haskell-craft-of-FP
Chapter4.hs
mit
8,408
0
12
2,243
2,621
1,373
1,248
173
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.IDBVersionChangeEvent ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.IDBVersionChangeEvent #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.IDBVersionChangeEvent #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/IDBVersionChangeEvent.hs
mit
376
0
5
33
33
26
7
4
0
{-| This module provides every single type defined within the spice framework. This allows people to write functions on data structures without being concerned about recursive imports (and thereby being unable to compile) due to the fact that this file does not and WILL NEVER import any other local libraries. -} module FRP.Spice.Internal.Types where -------------------- -- Global Imports -- import qualified Data.Map.Strict as Map import Graphics.Rendering.OpenGL import Graphics.UI.GLFW as GLFW import Control.Applicative import FRP.Elerea.Param import Data.Default import Data.Monoid ---------- -- Code -- {-| A data type that can be composed (so long as the data stored is a Monoid) in do-notation. -} data DoListT a b = DoListT a b {-| A type synonym for the @'DoListT'@ that should be used. -} type DoList a = DoListT a () {-| A Functor instance to satisfy the Applicative's requirements. -} instance Functor (DoListT a) where fmap fn (DoListT a b) = DoListT a $ fn b {-| An Applicative instance to satisfy the Monad's requirements in the future. -} instance Monoid a => Applicative (DoListT a) where pure b = DoListT mempty b (DoListT a' bfn) <*> (DoListT a b) = DoListT (a `mappend` a') $ bfn b {-| The Monad instance to allow the DoList to compose through do-notation. -} instance Monoid a => Monad (DoListT a) where return = pure (DoListT a b) >>= fn = let (DoListT a' b') = fn b in DoListT (mappend a a') b' {-| The config that is used to define the GLFW window's properties. -} data WindowConfig = WindowConfig { getWindowWidth :: Int , getWindowHeight :: Int , getWindowFullscreen :: Bool , getWindowTitle :: String } {-| The default state for a @'WindowConfig'@. -} instance Default WindowConfig where def = WindowConfig { getWindowWidth = 640 , getWindowHeight = 480 , getWindowFullscreen = False , getWindowTitle = "Spice Application" } {-| A data type representing a color as 4 floats (r, g, b, a) representing red, green, blue, and the alpha channel respectively. The floats should range from 0 to 1, representing 0 to 255 in more classical representations. -} data Color = Color { colorRed :: Float , colorGreen :: Float , colorBlue :: Float , colorAlpha :: Float } {-| A data type that stores two values. It can be used to perform basic vector logic. It should be noted that the @'Vector'@ logic provided in this library is not linear-algebra style vector logic. -} data Vector a = Vector a a {-| The default state for a @'Vector'@. -} instance Default a => Default (Vector a) where def = Vector def def {-| A functor instance to apply a function onto both values stored in a @'Vector'@. -} instance Functor Vector where fmap fn (Vector x y) = Vector (fn x) (fn y) {-| An applicative instance to allow one to write functions on @'Vector'@s that have separate functions for both values. -} instance Applicative Vector where pure a = Vector a a (Vector fnx fny) <*> (Vector x y) = Vector (fnx x) (fny y) {-| A wrapper around the sinks for the mouse position, mouse buttons, and keyboard keys. -} data Sinks = Sinks { mousePosSink :: Vector Float -> IO () , mouseButtonSink :: Map.Map MouseButton (Bool -> IO ()) , keySink :: Map.Map Key (Bool -> IO ()) } {-| A data structure that represents the current state of the input. Used in the @'InputContainer'@ along with the @'Sink'@ to handle all input -- updating and referencing. -} data Input = Input { mousePos :: Vector Float , mouseButton :: Map.Map MouseButton Bool , key :: Map.Map Key Bool } {-| The container for both @'Sink'@ and @'Input'@. The @'Input'@ is stored within a @'Signal'@ so it may be used within the FRP/Elerea part of the framework. -} data InputContainer = InputContainer { getSinks :: Sinks , getInput :: Signal Input } {-| Containing all of the necessary information for rendering an image on screen (aside from the position where the sprite should be rendered.) -} data Sprite = Sprite { spriteTex :: TextureObject , spriteSize :: Vector Float } {-| Containing all necessary information for playing a sound. -} data Sound = Sound {-| Representing the loading of an asset into the game framework. -} data LoadAsset = LoadSprite FilePath | LoadSound FilePath {-| A @'DoList'@ synonym for @'LoadAsset'@. -} type LoadAssets = DoList [LoadAsset] {-| Storing the loaded assets in a single data structure. -} data Assets = Assets { sprites :: Map.Map FilePath Sprite , sounds :: Map.Map FilePath Sound } {-| The default state for an @'Assets'@. -} instance Default Assets where def = Assets { sprites = Map.fromList [] , sounds = Map.fromList [] } {-| A type synonym to imply that functions performed in this function should solely render. -} type Scene = IO () {-| A type synonym to make the delta time (in the @'Game'@ definition) more self documenting. -} type DeltaTime = Float {-| The requirements for a given data structure to be used as a game within the framework. -} class Game a where update :: DeltaTime -> Input -> a -> a render :: Assets -> a -> Scene loadAssets :: a -> LoadAssets
crockeo/spice
src/FRP/Spice/Internal/Types.hs
mit
5,823
0
13
1,708
910
505
405
68
0
module Unfold where -- take 10 $ myIterate (+1) 0 myIterate :: (a -> a) -> a -> [a] myIterate f x = x : myIterate f (f x) myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr f x = myUnfoldr' x' where x' = f x myUnfoldr' Nothing = [] myUnfoldr' (Just (y, z)) = y : myUnfoldr f z -- take 10 $ myIterate (+1) 0 betterIterate :: (a -> a) -> a -> [a] betterIterate f = myUnfoldr (\x -> let x' = f x in Just (x', x'))
JoshuaGross/haskell-learning-log
Code/Haskellbook/Unfold.hs
mit
437
0
12
118
213
113
100
10
2
module Main where import Control.Monad import System.Environment import BankHolidayService.Server (runServer) import qualified Control.Exception as Exception -- | Main application init main :: IO () main = do let port = 8081 :: Int putStrLn ("Starting on port " ++ show port ++ "...") Exception.catch (runServer port) (\ Exception.UserInterrupt -> putStrLn "\nStopping...")
tippenein/BankHolidayService
src/Main.hs
mit
391
0
11
68
109
59
50
12
1
{-# OPTIONS_GHC -w #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} {-# LANGUAGE TupleSections #-} module Logistic where import Numeric.AD import qualified Data.Vector as V import Control.Monad import Control.Monad.State import Data.List import Text.Printf import System.Random import Data.Random () import Data.Random.Distribution.Beta import Data.RVar logit :: Floating a => a -> a logit x = 1 / (1 + exp (negate x)) logLikelihood :: Floating a => V.Vector a -> a -> V.Vector a -> a logLikelihood theta y x = y * log (logit z) + (1 - y) * log (1 - logit z) where z = V.sum $ V.zipWith (*) theta x totalLogLikelihood :: Floating a => V.Vector a -> V.Vector a -> V.Vector (V.Vector a) -> a totalLogLikelihood theta y x = (a - delta * b)/l where l = fromIntegral $ V.length y a = V.sum $ V.zipWith (logLikelihood theta) y x b = (/2) $ V.sum $ V.map (^2) theta delta :: Floating a => a delta = 1.0 gamma :: Double gamma = 0.1 nIters :: Int nIters = 4000 delTotalLoglikelihood :: Floating a => V.Vector a -> V.Vector (V.Vector a) -> V.Vector a -> V.Vector a delTotalLoglikelihood y x = grad f where f theta = totalLogLikelihood theta (V.map auto y) (V.map (V.map auto) x) stepOnce :: Double -> V.Vector Double -> V.Vector (V.Vector Double) -> V.Vector Double -> V.Vector Double stepOnce gamma y x theta = V.zipWith (+) theta (V.map (* gamma) $ del theta) where del = delTotalLoglikelihood y x estimates :: (Floating a, Ord a) => V.Vector a -> V.Vector (V.Vector a) -> V.Vector a -> [V.Vector a] estimates y x = gradientAscent $ \theta -> totalLogLikelihood theta (V.map auto y) (V.map (V.map auto) x) betas :: Int -> Double -> Double -> [Double] betas n a b = evalState (replicateM n (sampleRVar (beta a b))) (mkStdGen seed) where seed = 0 a, b :: Double a = 15 b = 6 nSamples :: Int nSamples = 100000 sample0, sample1 :: [Double] sample0 = betas nSamples a b sample1 = betas nSamples b a mixSamples :: [Double] -> [Double] -> [(Double, Double)] mixSamples xs ys = unfoldr g (map (0,) xs, map (1,) ys) where g ([], []) = Nothing g ([], _) = Nothing g (_, []) = Nothing g (x:xs, y) = Just (x, (y, xs)) createSample :: V.Vector (Double, Double) createSample = V.fromList $ take 100 $ mixSamples sample1 sample0 actualTheta :: V.Vector Double actualTheta = V.fromList [0.0, 1.0] initTheta :: V.Vector Double initTheta = V.replicate (V.length actualTheta) 0.1 vals :: V.Vector (Double, V.Vector Double) vals = V.map (\(y, x) -> (y, V.fromList [1.0, x])) createSample main :: IO () main = do let u = V.map fst vals v = V.map snd vals hs = iterate (stepOnce gamma u v) initTheta xs = V.map snd vals theta = head $ drop nIters hs theta' = estimates u v initTheta !! 100 printf "Hand crafted descent: theta_0 = %5.3f, theta_1 = %5.3f\n" (theta V.! 0) (theta V.! 1) printf "Library descent: theta_0 = %5.3f, theta_1 = %5.3f\n" (theta' V.! 0) (theta' V.! 1) let predProbs = V.map (logit . V.sum . V.zipWith (*) theta) xs mismatches = V.filter (> 0.5) $ V.map abs $ V.zipWith (-) actuals preds where actuals = V.map fst vals preds = V.map (\x -> fromIntegral $ fromEnum (x > 0.5)) predProbs let lActuals, lMisMatches :: Double lActuals = fromIntegral $ V.length vals lMisMatches = fromIntegral $ V.length mismatches printf "%5.2f%% correct\n" $ 100.0 * (lActuals - lMisMatches) / lActuals
syllogismos/machine-learning-haskell
Logistic.hs
mit
4,161
8
18
1,388
1,540
804
736
115
4
-- Sum of numbers from 0 to N -- http://www.codewars.com/kata/56e9e4f516bcaa8d4f001763 module Sequence.JorgeVS.Kata where import Data.List (intercalate) sequenceSum :: Int -> String sequenceSum n | n < 0 = show n ++ " < 0" | n == 0 = "0 = 0" | otherwise = (intercalate "+" . map show $ [0..n]) ++ " = " ++ show (n*(n+1) `div` 2)
gafiatulin/codewars
src/7 kyu/Sum0ToN.hs
mit
360
0
12
92
128
67
61
6
1
-- Write a sort that takes a list and a function that compares its two arguments -- and then returns a sorted list. module Main where import Data.List sortByComparator :: Eq a => [a] -> (a -> a -> Integer) -> [a] sortByComparator [] comparator = [] sortByComparator xs comparator = minx:(sortByComparator (delete minx xs) comparator) where minx = foldl minByComparator (head xs) xs minByComparator x minx = if (comparator x minx) < 0 then x else minx
ryanplusplus/seven-languages-in-seven-weeks
haskell/day2/sort_with_comparator.hs
mit
505
0
10
132
142
76
66
10
2
module SDLTools ( wipe , pollEvents ) where import Graphics.UI.SDL as SDL -- wipe clears a surface (paints it black) wipe :: Surface -> IO Bool wipe surface = fillRect surface Nothing (Pixel $ 0) -- Poll Events gets all the pending events in one go for processing pollEvents :: IO [SDL.Event] pollEvents = do event <- pollEvent if event == SDL.NoEvent then return [] else (fmap (event:) pollEvents)
rlupton20/yampaTutorial
src/SDLTools.hs
cc0-1.0
408
0
10
78
115
64
51
10
2
{-# LANGUAGE OverloadedStrings #-} module DarkPlaces.Text.Lexer ( dptextToken, maybeDPTextToken ) where import Data.Attoparsec.ByteString hiding (takeWhile1) import Data.Attoparsec.ByteString.Char8 (isDigit_w8, char, takeWhile1) import Control.Applicative import DarkPlaces.Text.Types import Data.Word import Data.Bits (shiftL, (.|.)) isHexDigit :: Word8 -> Bool isHexDigit w = (w >= 48 && w <= 57) || (w >= 97 && w <= 102) || (w >= 65 && w <= 70) digitInt :: Parser Int digitInt = (\i -> fromIntegral (i - 48)) <$> satisfy isDigit_w8 hexdigitInt :: Parser Int hexdigitInt = convert <$> satisfy isHexDigit where convert w | w >= 48 && w <= 57 = fromIntegral $ w - 48 | w >= 97 = fromIntegral $ w - 87 | otherwise = fromIntegral $ w - 55 threeHex :: Parser Int threeHex = convert <$> hexdigitInt <*> hexdigitInt <*> hexdigitInt where convert a b c = (a `shiftL` 8) .|. (b `shiftL` 4) .|. c color :: Parser BinDPTextToken color = char '^' *> (hex <|> simple) <?> "color" where simple = SimpleColor <$> digitInt hex = char 'x' *> (HexColor <$> threeHex) dptextToken :: Parser BinDPTextToken dptextToken = newline <|> color <|> (other <?> "other") where newline = char '\n' *> return DPNewline other = DPString <$> (takeWhile1 (\c -> c /= '\n' && c /= '^') <|> caret) caret = char '^' *> return "^" maybeDPTextToken :: Parser (Maybe BinDPTextToken) maybeDPTextToken = option Nothing (Just <$> dptextToken)
bacher09/darkplaces-text
src/DarkPlaces/Text/Lexer.hs
gpl-2.0
1,515
0
15
346
535
288
247
36
1
{-# LANGUAGE OverloadedStrings #-} module Fresh.BuiltIn where import Fresh.Types import Fresh.Module (Module(..)) import Fresh.Expr (Expr(..), EVarName(..), ETypeAsc(..)) import Fresh.Kind (Kind(..)) import qualified Data.Map as Map tcon :: String -> Type tcon x = Fix $ TyCon $ TCon (Id x) Star _String :: Type _String = tcon "String" _Number :: Type _Number = tcon "Number" _Bool :: Type _Bool = tcon "Bool" _Int :: Type _Int = tcon "Int" _Func :: Type _Func = Fix tyFunc (~=>) :: [Pred t] -> t -> QualType t (~=>) = QualType (^$) :: Type -> Type -> Type f ^$ x = Fix $ TyAp f x infixr 5 ^-> (^->) :: Type -> Type -> Type targ ^-> tres = Fix $ TyAp (Fix $ TyAp _Func targ) tres ---------------------------------------------------------------------- gv0 :: GenVar () gv0 = GenVar { genVarId = 0 , genVarKind = Star , genVarAnnot = () } genericBinOp :: QualType Type genericBinOp = QualType [] (a ^-> a ^-> a) where a = Fix $ TyGenVar gv0 -- Classes numClass :: Class Type (Expr ()) numClass = Class { clsId = ClassId "Num" , clsSupers = [] , clsParam = gv0 , clsMembers = Map.fromList [ (MemberName "+", genericBinOp) , (MemberName "-", genericBinOp) , (MemberName "*", genericBinOp) , (MemberName "/", genericBinOp) ] , clsInstances = [intNumInstance] } ---------------------------------------------------------------------- binaryOp :: Type -> QualType Type binaryOp t = QualType [] $ t ^-> t ^-> t ebinOp :: Type -> String -> (EVarName, Expr ()) ebinOp t name = (vname, EBuiltIn () vname (ETypeAsc $ binaryOp t)) where vname = (EVarName $ "#int" ++ name) intBinOp :: String -> (EVarName, Expr ()) intBinOp = ebinOp _Int intPlus, intMinus, intMul, intDiv :: (EVarName, Expr()) intPlus = intBinOp "+" intMinus = intBinOp "-" intMul = intBinOp "*" intDiv = intBinOp "/" intNumInstance :: Instance Type (Expr ()) intNumInstance = Instance (ClassId "Num") (QualType [] _Int) m where m = Map.fromList [ (MemberName "+", snd intPlus) , (MemberName "-", snd intMinus) , (MemberName "*", snd intMinus) , (MemberName "/", snd intMinus) ] intBuiltIn :: Module Type (Expr ()) intBuiltIn = Module { moduleTypes = Map.fromList [ (Id "Int", _Int) ] , moduleExprs = Map.fromList [ intPlus , intMinus , intMul , intDiv ] , moduleClasses = Map.empty , moduleInstances = [] } ---------------------------------------------------------------------- boolBinOp :: String -> (EVarName, Expr ()) boolBinOp = ebinOp _Bool boolBuiltIn :: Module Type (Expr ()) boolBuiltIn = Module { moduleTypes = Map.fromList [ (Id "Bool", _Bool) ] , moduleExprs = Map.fromList [ boolBinOp "&&" , boolBinOp "||" ] , moduleClasses = Map.empty , moduleInstances = [] } ---------------------------------------------------------------------- builtIns :: Module Type (Expr ()) builtIns = mconcat [boolBuiltIn, intBuiltIn]
sinelaw/fresh
src/Fresh/BuiltIn.hs
gpl-2.0
3,150
0
10
813
1,046
580
466
90
1
module Access.Data.Time.Clock ( module Data.Time.Clock , ClockAccess(..) ) where import Data.Time.Clock import Access.Core class Access io => ClockAccess io where getCurrentTime' :: io UTCTime instance ClockAccess IO where getCurrentTime' = getCurrentTime
bheklilr/time-io-access
Access/Data/Time/Clock.hs
gpl-2.0
283
0
7
58
72
42
30
9
0
{-# LANGUAGE BangPatterns #-} {-| Implementation of configuration reader with watching support. -} {- Copyright (C) 2011, 2012, 2013 Google Inc. 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 Ganeti.ConfigReader ( ConfigReader , initConfigReader ) where import Control.Concurrent import Control.Exception import Control.Monad (liftM, unless) import Data.IORef import System.Posix.Files import System.Posix.Types import System.INotify import Ganeti.BasicTypes import Ganeti.Objects import Ganeti.Confd.Utils import Ganeti.Config import Ganeti.Logging import qualified Ganeti.Constants as C import qualified Ganeti.Path as Path import Ganeti.Utils -- | A type for functions that can return the configuration when -- executed. type ConfigReader = IO (Result ConfigData) -- | File stat identifier. type FStat = (EpochTime, FileID, FileOffset) -- | Null 'FStat' value. nullFStat :: FStat nullFStat = (-1, -1, -1) -- | Reload model data type. data ReloadModel = ReloadNotify -- ^ We are using notifications | ReloadPoll Int -- ^ We are using polling deriving (Eq, Show) -- | Server state data type. data ServerState = ServerState { reloadModel :: ReloadModel , reloadTime :: Integer -- ^ Reload time (epoch) in microseconds , reloadFStat :: FStat } -- | Maximum no-reload poll rounds before reverting to inotify. maxIdlePollRounds :: Int maxIdlePollRounds = 3 -- | Reload timeout in microseconds. watchInterval :: Int watchInterval = C.confdConfigReloadTimeout * 1000000 -- | Ratelimit timeout in microseconds. pollInterval :: Int pollInterval = C.confdConfigReloadRatelimit -- | Ratelimit timeout in microseconds, as an 'Integer'. reloadRatelimit :: Integer reloadRatelimit = fromIntegral C.confdConfigReloadRatelimit -- | Initial poll round. initialPoll :: ReloadModel initialPoll = ReloadPoll 0 -- | Reload status data type. data ConfigReload = ConfigToDate -- ^ No need to reload | ConfigReloaded -- ^ Configuration reloaded | ConfigIOError -- ^ Error during configuration reload deriving (Eq) -- * Configuration handling -- ** Helper functions -- | Helper function for logging transition into polling mode. moveToPolling :: String -> INotify -> FilePath -> (Result ConfigData -> IO ()) -> MVar ServerState -> IO ReloadModel moveToPolling msg inotify path save_fn mstate = do logInfo $ "Moving to polling mode: " ++ msg let inotiaction = addNotifier inotify path save_fn mstate _ <- forkIO $ onPollTimer inotiaction path save_fn mstate return initialPoll -- | Helper function for logging transition into inotify mode. moveToNotify :: IO ReloadModel moveToNotify = do logInfo "Moving to inotify mode" return ReloadNotify -- ** Configuration loading -- | (Re)loads the configuration. updateConfig :: FilePath -> (Result ConfigData -> IO ()) -> IO () updateConfig path save_fn = do newcfg <- loadConfig path let !newdata = case newcfg of Ok !cfg -> Ok cfg Bad _ -> Bad "Cannot load configuration" save_fn newdata case newcfg of Ok cfg -> logInfo ("Loaded new config, serial " ++ show (configSerial cfg)) Bad msg -> logError $ "Failed to load config: " ++ msg return () -- | Wrapper over 'updateConfig' that handles IO errors. safeUpdateConfig :: FilePath -> FStat -> (Result ConfigData -> IO ()) -> IO (FStat, ConfigReload) safeUpdateConfig path oldfstat save_fn = Control.Exception.catch (do nt <- needsReload oldfstat path case nt of Nothing -> return (oldfstat, ConfigToDate) Just nt' -> do updateConfig path save_fn return (nt', ConfigReloaded) ) (\e -> do let msg = "Failure during configuration update: " ++ show (e::IOError) save_fn $ Bad msg return (nullFStat, ConfigIOError) ) -- | Computes the file cache data from a FileStatus structure. buildFileStatus :: FileStatus -> FStat buildFileStatus ofs = let modt = modificationTime ofs inum = fileID ofs fsize = fileSize ofs in (modt, inum, fsize) -- | Wrapper over 'buildFileStatus'. This reads the data from the -- filesystem and then builds our cache structure. getFStat :: FilePath -> IO FStat getFStat p = liftM buildFileStatus (getFileStatus p) -- | Check if the file needs reloading needsReload :: FStat -> FilePath -> IO (Maybe FStat) needsReload oldstat path = do newstat <- getFStat path return $ if newstat /= oldstat then Just newstat else Nothing -- ** Watcher threads -- $watcher -- We have three threads/functions that can mutate the server state: -- -- 1. the long-interval watcher ('onWatcherTimer') -- -- 2. the polling watcher ('onPollTimer') -- -- 3. the inotify event handler ('onInotify') -- -- All of these will mutate the server state under 'modifyMVar' or -- 'modifyMVar_', so that server transitions are more or less -- atomic. The inotify handler remains active during polling mode, but -- checks for polling mode and doesn't do anything in this case (this -- check is needed even if we would unregister the event handler due -- to how events are serialised). -- | Long-interval reload watcher. -- -- This is on top of the inotify-based triggered reload. onWatcherTimer :: IO Bool -> FilePath -> (Result ConfigData -> IO ()) -> MVar ServerState -> IO () onWatcherTimer inotiaction path save_fn state = do threadDelay watchInterval logDebug "Watcher timer fired" modifyMVar_ state (onWatcherInner path save_fn) _ <- inotiaction onWatcherTimer inotiaction path save_fn state -- | Inner onWatcher handler. -- -- This mutates the server state under a modifyMVar_ call. It never -- changes the reload model, just does a safety reload and tried to -- re-establish the inotify watcher. onWatcherInner :: FilePath -> (Result ConfigData -> IO ()) -> ServerState -> IO ServerState onWatcherInner path save_fn state = do (newfstat, _) <- safeUpdateConfig path (reloadFStat state) save_fn return state { reloadFStat = newfstat } -- | Short-interval (polling) reload watcher. -- -- This is only active when we're in polling mode; it will -- automatically exit when it detects that the state has changed to -- notification. onPollTimer :: IO Bool -> FilePath -> (Result ConfigData -> IO ()) -> MVar ServerState -> IO () onPollTimer inotiaction path save_fn state = do threadDelay pollInterval logDebug "Poll timer fired" continue <- modifyMVar state (onPollInner inotiaction path save_fn) if continue then onPollTimer inotiaction path save_fn state else logDebug "Inotify watch active, polling thread exiting" -- | Inner onPoll handler. -- -- This again mutates the state under a modifyMVar call, and also -- returns whether the thread should continue or not. onPollInner :: IO Bool -> FilePath -> (Result ConfigData -> IO ()) -> ServerState -> IO (ServerState, Bool) onPollInner _ _ _ state@(ServerState { reloadModel = ReloadNotify } ) = return (state, False) onPollInner inotiaction path save_fn state@(ServerState { reloadModel = ReloadPoll pround } ) = do (newfstat, reload) <- safeUpdateConfig path (reloadFStat state) save_fn let state' = state { reloadFStat = newfstat } -- compute new poll model based on reload data; however, failure to -- re-establish the inotifier means we stay on polling newmode <- case reload of ConfigToDate -> if pround >= maxIdlePollRounds then do -- try to switch to notify result <- inotiaction if result then moveToNotify else return initialPoll else return (ReloadPoll (pround + 1)) _ -> return initialPoll let continue = case newmode of ReloadNotify -> False _ -> True return (state' { reloadModel = newmode }, continue) -- the following hint is because hlint doesn't understand our const -- (return False) is so that we can give a signature to 'e' {-# ANN addNotifier "HLint: ignore Evaluate" #-} -- | Setup inotify watcher. -- -- This tries to setup the watch descriptor; in case of any IO errors, -- it will return False. addNotifier :: INotify -> FilePath -> (Result ConfigData -> IO ()) -> MVar ServerState -> IO Bool addNotifier inotify path save_fn mstate = Control.Exception.catch (addWatch inotify [CloseWrite] path (onInotify inotify path save_fn mstate) >> return True) (\e -> const (return False) (e::IOError)) -- | Inotify event handler. onInotify :: INotify -> String -> (Result ConfigData -> IO ()) -> MVar ServerState -> Event -> IO () onInotify inotify path save_fn mstate Ignored = do logDebug "File lost, trying to re-establish notifier" modifyMVar_ mstate $ \state -> do result <- addNotifier inotify path save_fn mstate (newfstat, _) <- safeUpdateConfig path (reloadFStat state) save_fn let state' = state { reloadFStat = newfstat } if result then return state' -- keep notify else do mode <- moveToPolling "cannot re-establish inotify watch" inotify path save_fn mstate return state' { reloadModel = mode } onInotify inotify path save_fn mstate _ = modifyMVar_ mstate $ \state -> if reloadModel state == ReloadNotify then do ctime <- getCurrentTimeUSec (newfstat, _) <- safeUpdateConfig path (reloadFStat state) save_fn let state' = state { reloadFStat = newfstat, reloadTime = ctime } if abs (reloadTime state - ctime) < reloadRatelimit then do mode <- moveToPolling "too many reloads" inotify path save_fn mstate return state' { reloadModel = mode } else return state' else return state initConfigReader :: (Result ConfigData -> a) -> IORef a -> IO () initConfigReader cfg_transform ioref = do let save_fn = writeIORef ioref . cfg_transform -- Inotify setup inotify <- initINotify -- try to load the configuration, if possible conf_file <- Path.clusterConfFile (fstat, reloaded) <- safeUpdateConfig conf_file nullFStat save_fn ctime <- getCurrentTime statemvar <- newMVar $ ServerState ReloadNotify ctime fstat let inotiaction = addNotifier inotify conf_file save_fn statemvar has_inotify <- if reloaded == ConfigReloaded then inotiaction else return False if has_inotify then logInfo "Starting up in inotify mode" else do -- inotify was not enabled, we need to update the reload model logInfo "Starting up in polling mode" modifyMVar_ statemvar (\state -> return state { reloadModel = initialPoll }) -- fork the timeout timer _ <- forkIO $ onWatcherTimer inotiaction conf_file save_fn statemvar -- fork the polling timer unless has_inotify $ do _ <- forkIO $ onPollTimer inotiaction conf_file save_fn statemvar return ()
narurien/ganeti-ceph
src/Ganeti/ConfigReader.hs
gpl-2.0
11,914
0
16
2,884
2,345
1,206
1,139
199
5
{-# LANGUAGE DeriveGeneric #-} module StandOff.AttributesMap ( AttributesMap , AttributeMap(..) , ValueMap , Attribute(..) , mapExternal , serializeXml , specialAttrs , parseMapping , updSplitNumbers ) where -- | This module provides types and functions for mapping features -- (attributes) of external markup to XML attributes. The aim is to -- plug in an arbitrary mapping definition for serializing to -- arbitrary attributes. -- -- No processing is done on the attribute values. The features come -- from 'attributes' of markup that is an instance of 'ToAttributes'. -- Further processing of attribute values can be done with -- X-technologies in postprocessing. -- -- There are also special attributes produced by this module. See -- 'specialAttrs'. import qualified Data.Map as Map import Data.Map ((!)) import Data.Maybe import Control.Monad import Data.Monoid import qualified Data.Yaml as Y import qualified Data.Aeson as J import GHC.Generics import Data.Traversable import StandOff.External -- * Types for mapping features of external markup to XML attributes -- | An mapping of attributes provided by external markup that -- implements the class 'ToAttributes'. The mapping is done by the -- keys of both 'Map.Map's. type AttributesMap = Map.Map String AttributeMap -- | A record holding full qualified names etc and a 'ValueMap'. data AttributeMap = AttributeMap { attrm_prefix :: Maybe String , attrm_ns :: Maybe String , attrm_name :: String , attrm_values :: Maybe ValueMap } deriving (Eq, Show, Generic) -- | Mapping of values of external markup to some other values. type ValueMap = Map.Map String String -- | An attribute that was mapped from the external markup's -- attributes. data Attribute = Attribute { attr_prefix :: Maybe String , attr_ns :: Maybe String , attr_name :: String , attr_value :: String } deriving (Eq, Show) -- * Parser for mappings in YAML instance Y.FromJSON AttributeMap where parseJSON = J.genericParseJSON $ J.defaultOptions { J.fieldLabelModifier = drop 6 } -- | Parse 'AttributesMap' from file. parseMapping :: FilePath -> IO (Either Y.ParseException AttributesMap) parseMapping = Y.decodeFileEither -- | Debugging: USAGE: -- stack runghc src/StandOff/AttributesMap.hs main :: IO () main = parseMapping "utils/mappings/som-tei.yaml" >>= print -- * Do the mapping -- | 'mapExternal' does the work of mapping attributes of external -- markup through an 'AttributesMap'. mapExternal :: AttributesMap -> ExternalAttributes -> [Attribute] mapExternal mapping external = map (\(k, v) -> toAttr (mapping ! k) v) $ Map.toList $ Map.restrictKeys external keys where keys = Map.keysSet mapping toAttr m v = Attribute { attr_prefix = attrm_prefix m , attr_ns = attrm_ns m , attr_name = attrm_name m , attr_value = fromMaybe v $ join $ fmap (Map.lookup v) $ attrm_values m } -- | Serialize an 'Attribute' to XML. serializeXml :: Attribute -> String serializeXml attr = attr_name attr <> "=\"" <> (escape $ attr_value attr) <> "\"" where escape = id -- TODO: escape quotes -- * Generating special features or attributes -- | Update a map of external attributes with special attributes -- generated by standoff-tools. E.g. this adds compound identifiers -- from the markup identifier and the split number, which can be used -- in TEI's @prev attribute for discontinous markup. specialAttrs :: IdentifiableSplit a => a -> ExternalAttributes -> ExternalAttributes specialAttrs tag = appendNamespace tag . appendPrevId tag . appendSplitId tag -- | This adds the special attribute "__standoff_special__splitId" -- which can be used as @xml:id. appendSplitId :: IdentifiableSplit a => a -> ExternalAttributes -> ExternalAttributes appendSplitId tag attrs = Map.insert "__standoff_special__splitId" (splitIdValue (markupId tag) (splitNum tag)) attrs -- | This adds the special attribute "__standoff_special__prevId" -- which can be used as TEI's @prev. appendPrevId :: IdentifiableSplit a => a -> ExternalAttributes -> ExternalAttributes appendPrevId tag attrs | fmap (>0) (splitNum tag) == (Just True) = Map.insert "__standoff_special__prevId" ("#" <> splitIdValue (markupId tag) (fmap (\x -> x - 1) $ splitNum tag)) attrs | otherwise = attrs splitIdValue :: Maybe String -> Maybe Int -> String splitIdValue Nothing _ = "unknown" splitIdValue (Just mid) Nothing = mid splitIdValue (Just mid) (Just 0) = mid splitIdValue (Just mid) (Just i) = mid <> "-" <> (show i) -- | This adds the special attribute "__standoff_special__ns" with the -- fixed value "unknown" which can be used to add a namespace to the -- inserted element. appendNamespace :: a -> ExternalAttributes -> ExternalAttributes appendNamespace _ attrs = Map.insert "__standoff_special__ns" "unknown" attrs -- * Update split numbers. -- | Update splits with split numbers starting from zero. This works -- if all the splits generated by splitting processe are passed in. updSplitNumbers :: IdentifiableSplit a => [a] -> [a] updSplitNumbers = snd . mapAccumL countSplits Map.empty where countSplits :: IdentifiableSplit a => Map.Map String Int -> a -> (Map.Map String Int, a) countSplits mp tg = ((,) <$> snd <*> (updSplitNum tg . fromMaybe 0 . fst) ) $ Map.insertLookupWithKey (const (+)) (fromMaybe "unknown" $ markupId tg) 1 mp
lueck/standoff-tools
src/StandOff/AttributesMap.hs
gpl-3.0
5,391
0
15
967
1,099
602
497
82
1
import Data.Char import Data.List.Split import Handy import qualified Data.Map as Map import Data.List import System.IO inputTraits = "20266440 22220150 30270160 36237440 22060560 34064556 31271563\ \ 10064563 10060440 33262544 32267543 34462440 34672141 33462141\ \ 34462040 31467562 10060440 33264544 31066145 10061554 30271563\ \ 10062570 32271564 31267143 312270" inputMedia = "7VQ[UF!,C5FCf>4@Vg1-+EVO7ATVTsEZf(6+DlBHD/!lu/g*`-+DGm>BOPpl+EVNE@q]e!F(\ \ HJ&+=Cc0G&MMDBlmo6+CT.u+DGF18K_PXA0>T.+EqaHCh+Z-Ec5Dq@Vg<4BOQ'q+EVNE@V$Z\ \ :0Hb:S+EMHD@;]TuAThX&+EV:.DBO%7AU,DBDfol,+E2@>@UW_^Gp$U1@;]^h+D,Y*EHPi1F\ \ DQ4T+A!\\lBkq9&D09o6@j#u/Bk(g!BlbD*F`Lo,Cj@.BCh7$rBl7Q+FDi:=ALnsGBPDN1@ps\ \ 6tG%#E:+Co&&ASu$mDJ()1DBNeA+Dl%8A0>;uA0>u-AKZ&.FEM#6Bl@l38K_GY+CfP7Eb0-1\ \ Cj@.;DD!&'+CT+0DfB9*+EVNE@;^@4BPD?s+CT.u+Dbb5FCf>4FDi:1+EqO1AKZ/)EbT*,Gp\ \ %$;+Dl7BBk&b<9lG)pCj@.;FCh\\!*@ps1++A!]\ \ \"@<?!m+EMI<+EM47GB4m9F`\\a\ \ 9D^)/g*_.Ch[Zr+D,P1A1eurF" histogram :: (Ord k, Foldable t) => t k -> Map.Map k Integer histogram = foldl' (\a v -> Map.insertWith (+) v 1 a) Map.empty writeBinary :: FilePath -> String -> IO () writeBinary fileName = withBinaryFile fileName WriteMode . flip hPutStr
xkollar/handy-haskell
other/okc-NBTheRain/Main.hs
gpl-3.0
1,320
2
9
246
164
83
81
12
1
a -> a
hmemcpy/milewski-ctfp-pdf
src/content/1.10/code/haskell/snippet26.hs
gpl-3.0
6
1
5
2
10
3
7
-1
-1
module Sites.FeyWinds ( feyWinds ) where import Control.Monad import Data.Maybe (catMaybes) import Network.HTTP.Types.URI (decodePathSegments) import Pipes import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.UTF8 as US import qualified Data.List as DL import qualified Data.Text as T -- Local imports import Types import Sites.Util import Interpreter -- Tagsoup import Text.HTML.TagSoup hiding (parseTags, renderTags) import Text.HTML.TagSoup.Fast -- -- Fey Winds -- rootPage = "http://feywinds.com/" feyWinds = Comic { comicName = "Fey Winds" , seedPage = rootPage ++ "comic.html" , seedCache = Always , pageParse = feyWindsProxy , cookies = [] } feyWindsProxy :: Pipe ReplyType FetchType IO () feyWindsProxy = runWebFetchT $ do debug "Parsing index page" idx <- parseTagsT . BL.toStrict <$> fetchSeedpage -- Filtered down what we want let idx' = filterAny [ (~== "<a>") , (\a -> isTagText a && not (T.isPrefixOf (T.pack "\n") (fromTagText a)) && not (T.isPrefixOf (T.pack "- ") (fromTagText a)) && not ((T.isPrefixOf (T.pack " ") (fromTagText a))) ) ] $ takeWhile (~/= "</blockquote>") $ DL.tail $ dropWhile (~/= "<blockquote>") $ DL.tail $ dropWhile (~/= "<blockquote>") idx let pages = buildTreeUrl idx' forM_ pages (\(url, ct) -> do debug "Parsing image page" debug url page <- parseTagsT . BL.toStrict <$> fetchWebpage [(rootPage ++ url, Always)] let img = fromAttrib (T.pack "src") $ head $ filter (~== "<img>") $ takeWhile (~/= "</blockquote>") $ DL.tail $ dropWhile (~/= "<blockquote>") page debug img fetchImage (rootPage ++ "comic/" ++ T.unpack img) (ct{ctFileName = Just $ last $ decodePathSegments $ US.fromString $ T.unpack img}) ) buildTreeUrl :: [Tag T.Text] -> [(Url, ComicTag)] buildTreeUrl xs = catMaybes $ snd $ DL.mapAccumL accum (T.pack "", 0, T.pack "") xs where accum (vol, chpNum, chp) x | isTagText x && T.isPrefixOf (T.pack "Archive") (fromTagText x) = ((T.pack "Fey Winds", chpNum, chp), Nothing) | isTagText x && T.isPrefixOf (T.pack "Prologue") (fromTagText x) = ((vol, 0, snd $ parseChp $ fromTagText x), Nothing) | isTagText x && T.isPrefixOf (T.pack "Chapter") (fromTagText x) = ((vol, fst $ parseChp $ fromTagText x, snd $ parseChp $ fromTagText x), Nothing) | isTagText x && T.isPrefixOf (T.pack "Mini Comics") (fromTagText x) = ((T.init $ fromTagText x, 0, T.pack ""), Nothing) | isTagText x && T.isPrefixOf (T.pack "Other Comics") (fromTagText x) = ((T.init $ T.init $ fromTagText x, 0, T.pack ""), Nothing) | x ~== "<a>" = ((vol, chpNum, chp), Just (toCT vol chpNum chp $ fromAttrib (T.pack "href") x)) | otherwise = ((vol, chpNum, chp), Nothing) toCT :: T.Text -> Integer -> T.Text -> T.Text -> (Url, ComicTag) toCT vol chpNum chp url | chp == (T.pack "") = (T.unpack url, ComicTag (T.pack "Fey Winds") (Just vol) Nothing Nothing Nothing) | otherwise = (T.unpack url, ComicTag (T.pack "Fey Winds") (Just vol) Nothing (Just $ UnitTag [StandAlone $ Digit chpNum Nothing Nothing Nothing] (Just chp)) Nothing) parseChp :: T.Text -> (Integer, T.Text) parseChp t | (T.isPrefixOf (T.pack "Prologue") t) = (0, T.strip $ DL.last $ T.split (== ':') t) | otherwise = (read $ T.unpack $ T.takeWhile (/= ':') $ T.drop (length "Chapter ") t, T.strip $ DL.last $ T.split (== ':') t)
pharaun/hComicFetcher
src/Sites/FeyWinds.hs
gpl-3.0
3,874
0
28
1,145
1,430
753
677
70
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Reseller.Subscriptions.Insert -- 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) -- -- Creates or transfer a subscription. Create a subscription for a -- customer\'s account that you ordered using the [Order a new customer -- account](\/admin-sdk\/reseller\/v1\/reference\/customers\/insert.html) -- method. For more information about creating a subscription for different -- payment plans, see [manage -- subscriptions](\/admin-sdk\/reseller\/v1\/how-tos\/manage_subscriptions#create_subscription).\\ -- If you did not order the customer\'s account using the customer insert -- method, use the customer\'s \`customerAuthToken\` when creating a -- subscription for that customer. If transferring a G Suite subscription -- with an associated Google Drive or Google Vault subscription, use the -- [batch operation](\/admin-sdk\/reseller\/v1\/how-tos\/batch.html) to -- transfer all of these subscriptions. For more information, see how to -- [transfer -- subscriptions](\/admin-sdk\/reseller\/v1\/how-tos\/manage_subscriptions#transfer_a_subscription). -- -- /See:/ <https://developers.google.com/google-apps/reseller/ Google Workspace Reseller API Reference> for @reseller.subscriptions.insert@. module Network.Google.Resource.Reseller.Subscriptions.Insert ( -- * REST Resource SubscriptionsInsertResource -- * Creating a Request , subscriptionsInsert , SubscriptionsInsert -- * Request Lenses , siXgafv , siUploadProtocol , siAccessToken , siUploadType , siPayload , siCustomerId , siCustomerAuthToken , siCallback ) where import Network.Google.AppsReseller.Types import Network.Google.Prelude -- | A resource alias for @reseller.subscriptions.insert@ method which the -- 'SubscriptionsInsert' request conforms to. type SubscriptionsInsertResource = "apps" :> "reseller" :> "v1" :> "customers" :> Capture "customerId" Text :> "subscriptions" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "customerAuthToken" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Subscription :> Post '[JSON] Subscription -- | Creates or transfer a subscription. Create a subscription for a -- customer\'s account that you ordered using the [Order a new customer -- account](\/admin-sdk\/reseller\/v1\/reference\/customers\/insert.html) -- method. For more information about creating a subscription for different -- payment plans, see [manage -- subscriptions](\/admin-sdk\/reseller\/v1\/how-tos\/manage_subscriptions#create_subscription).\\ -- If you did not order the customer\'s account using the customer insert -- method, use the customer\'s \`customerAuthToken\` when creating a -- subscription for that customer. If transferring a G Suite subscription -- with an associated Google Drive or Google Vault subscription, use the -- [batch operation](\/admin-sdk\/reseller\/v1\/how-tos\/batch.html) to -- transfer all of these subscriptions. For more information, see how to -- [transfer -- subscriptions](\/admin-sdk\/reseller\/v1\/how-tos\/manage_subscriptions#transfer_a_subscription). -- -- /See:/ 'subscriptionsInsert' smart constructor. data SubscriptionsInsert = SubscriptionsInsert' { _siXgafv :: !(Maybe Xgafv) , _siUploadProtocol :: !(Maybe Text) , _siAccessToken :: !(Maybe Text) , _siUploadType :: !(Maybe Text) , _siPayload :: !Subscription , _siCustomerId :: !Text , _siCustomerAuthToken :: !(Maybe Text) , _siCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SubscriptionsInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'siXgafv' -- -- * 'siUploadProtocol' -- -- * 'siAccessToken' -- -- * 'siUploadType' -- -- * 'siPayload' -- -- * 'siCustomerId' -- -- * 'siCustomerAuthToken' -- -- * 'siCallback' subscriptionsInsert :: Subscription -- ^ 'siPayload' -> Text -- ^ 'siCustomerId' -> SubscriptionsInsert subscriptionsInsert pSiPayload_ pSiCustomerId_ = SubscriptionsInsert' { _siXgafv = Nothing , _siUploadProtocol = Nothing , _siAccessToken = Nothing , _siUploadType = Nothing , _siPayload = pSiPayload_ , _siCustomerId = pSiCustomerId_ , _siCustomerAuthToken = Nothing , _siCallback = Nothing } -- | V1 error format. siXgafv :: Lens' SubscriptionsInsert (Maybe Xgafv) siXgafv = lens _siXgafv (\ s a -> s{_siXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). siUploadProtocol :: Lens' SubscriptionsInsert (Maybe Text) siUploadProtocol = lens _siUploadProtocol (\ s a -> s{_siUploadProtocol = a}) -- | OAuth access token. siAccessToken :: Lens' SubscriptionsInsert (Maybe Text) siAccessToken = lens _siAccessToken (\ s a -> s{_siAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). siUploadType :: Lens' SubscriptionsInsert (Maybe Text) siUploadType = lens _siUploadType (\ s a -> s{_siUploadType = a}) -- | Multipart request metadata. siPayload :: Lens' SubscriptionsInsert Subscription siPayload = lens _siPayload (\ s a -> s{_siPayload = a}) -- | Either the customer\'s primary domain name or the customer\'s unique -- identifier. If using the domain name, we do not recommend using a -- \`customerId\` as a key for persistent data. If the domain name for a -- \`customerId\` is changed, the Google system automatically updates. siCustomerId :: Lens' SubscriptionsInsert Text siCustomerId = lens _siCustomerId (\ s a -> s{_siCustomerId = a}) -- | The \`customerAuthToken\` query string is required when creating a -- resold account that transfers a direct customer\'s subscription or -- transfers another reseller customer\'s subscription to your reseller -- management. This is a hexadecimal authentication token needed to -- complete the subscription transfer. For more information, see the -- administrator help center. siCustomerAuthToken :: Lens' SubscriptionsInsert (Maybe Text) siCustomerAuthToken = lens _siCustomerAuthToken (\ s a -> s{_siCustomerAuthToken = a}) -- | JSONP siCallback :: Lens' SubscriptionsInsert (Maybe Text) siCallback = lens _siCallback (\ s a -> s{_siCallback = a}) instance GoogleRequest SubscriptionsInsert where type Rs SubscriptionsInsert = Subscription type Scopes SubscriptionsInsert = '["https://www.googleapis.com/auth/apps.order"] requestClient SubscriptionsInsert'{..} = go _siCustomerId _siXgafv _siUploadProtocol _siAccessToken _siUploadType _siCustomerAuthToken _siCallback (Just AltJSON) _siPayload appsResellerService where go = buildClient (Proxy :: Proxy SubscriptionsInsertResource) mempty
brendanhay/gogol
gogol-apps-reseller/gen/Network/Google/Resource/Reseller/Subscriptions/Insert.hs
mpl-2.0
7,965
0
21
1,665
904
538
366
127
1
{-# LANGUAGE OverloadedStrings #-} module Sparkle.Handlers where import Data.Acid (AcidState) import Happstack.Server import Web.Routes (RouteT) import Web.Routes.Happstack () import Sparkle.Common import Sparkle.Routes import Sparkle.Templates import Sparkle.Types type SparkleM a = RouteT Sitemap (ReaderT (AcidState Project) (ServerPartT IO)) a homePage :: SparkleM Response homePage = do proj <- queryP QueryProject plain <- queryString (lookText' "plain") <|> pure "" let render | plain == "true" = planTemplate . view projTasks | otherwise = pageTemplate ok . toResponse $ render proj
lfairy/sparkle
Sparkle/Handlers.hs
agpl-3.0
632
0
13
119
190
98
92
19
1
{-# LANGUAGE Safe #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-| Module : Data.PolyMap.Storage.List Copyright : (c) 2015 David Farrell License : PublicDomain Stability : unstable Portability : non-portable (GHC extensions) Storage instance for lists. -} module Data.PolyMap.Storage.List ( ) where import Data.PolyMap.Storage instance Storage [] a where singleton x = [x] lookupIndex k xs = f 0 xs where f _ [] = Nothing f i (x:xs) | x == k = Just i | otherwise = f (i + 1) xs lookupElem i xs | i < 0 = Nothing | otherwise = f i xs where f _ [] = Nothing f 0 (x:_) = Just x f i (_:xs) = f (i - 1) xs
shockkolate/hs-polymap
src/Data/PolyMap/Storage/List.hs
unlicense
784
0
11
271
221
113
108
19
0
{-# LANGUAGE MultiParamTypeClasses #-} -- | Lift operations that lift up values from database to domain. module Lycopene.Database.Relational.Lift where import Data.Maybe (fromMaybe) import Data.UUID (fromString) import Lycopene.Database (Persist) import qualified Lycopene.Database.Relational.Project as Project import qualified Lycopene.Core as Core class LiftCore a b where liftC :: a -> Maybe b -- instance (LiftCore a b) => LiftCore [a] [b] where -- liftC = fmap liftC instance LiftCore Project.Project Core.Project where liftC p = Just $ Core.Project { Core.projectId = Project.projectId p , Core.projectName = Project.name p , Core.projectDescription = Project.description p , Core.projectStatus = liftC $ Project.status p } instance LiftCore Integer Core.ProjectStatus where liftC 0 = Just Core.Inactive liftC 1 = Just Core.Active
utky/lycopene
src/Lycopene/Database/Relational/Lift.hs
apache-2.0
955
0
11
230
207
116
91
18
0
module System.IO.FileSystem where import System.IO.Exception import System.IO.UV.Internal import System.IO.UV.Exception import Foreign.Ptr import Foreign.C import Data.CBytes scandir :: CBytes -> IO [(CBytes, UVDirEntType)] scandir path = withCBytes path $ \ p -> withResource (initUVReq uV_FS) $ \ req -> do uvFSScandir nullPtr req p False go req where go req = do withResource initUVDirEnt $ \ ent -> do r <- uv_fs_scandir_next req ent if r == uV_EOF then return [] else if r < 0 then do throwUVIfMinus_ $ return r return [] else do (path, typ) <- peekUVDirEnt ent path' <- fromCString path rest <- go req return ((path', typ) : rest)
winterland1989/stdio
System/IO/FileSystem.hs
bsd-3-clause
875
0
20
341
261
133
128
26
3
{-# LANGUAGE OverloadedStrings #-} module Language.Whippet.Parser.FunctionSpec where import Control.Lens import Control.Lens.Extras import Control.Monad (when) import Data.Text (Text) import Language.Whippet.Parser.Lenses import Language.Whippet.Parser.ParseUtils import Language.Whippet.Parser.Types import Language.Whippet.PPrint import Test.Hspec main :: IO () main = hspec spec spec :: Spec spec = do describe "parsing a function signature" $ do let whenParsesToSig result assertions = do it "parses to a function signature" $ result `shouldSatisfy` is (_Right._AstDecl._DecFunSig) when (is _Right result) assertions fnType' :: ParsedAst -> Text fnType' ast = ast ^. _Right._AstDecl._DecFunSig.functionSigType.pprint' fnName :: ParsedAst -> Text fnName ast = ast ^. _Right._AstDecl._DecFunSig.functionSigIdent.pprint' describe "unary type signature" $ do result <- parseFile "UnitFunSig.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "unit" it "has the expected type signature" $ fnType' result `shouldBe` "Unit" describe "binary type signature" $ do result <- parseFile "IdentityFunSig.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "identity" it "has the expected type signature" $ fnType' result `shouldBe` "(a -> a)" describe "ternary type signature" $ do result <- parseFile "ConstFunSig.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "const" it "has the expected type signature" $ fnType' result `shouldBe` "(a -> (b -> a))" describe "type signature with paranthesised identifier" $ do result <- parseFile "FunctionTyParens.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "const" it "has the expected type signature" $ fnType' result `shouldBe` "(a -> (b -> a))" describe "type signature with type constructor parameter" $ do result <- parseFile "FunctionTyCtor.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "getOpt" it "has the expected type signature" $ fnType' result `shouldBe` "(a -> (Option a -> a))" describe "type signature with function type parameter" $ do result <- parseFile "ListMapFun.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "map" it "has the expected type signature" $ fnType' result `shouldBe` "((a -> b) -> (List a -> List b))" describe "type signature with structural type as input" $ do result <- parseFile "StructuralTypeParameterInput.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "first" it "has the expected type signature" $ fnType' result `shouldBe` "({fst: A, snd: B} -> A)" describe "type signature with structural type as output" $ do result <- parseFile "StructuralTypeParameterOutput.whippet" whenParsesToSig result $ do it "has the expected identifier" $ fnName result `shouldBe` "box" it "has the expected type signature" $ fnType' result `shouldBe` "(A -> {unpack: A})" describe "type signature with existential quantifier" $ do result <- parseFile "TypeSignatureWithQuantifier.whippet" whenParsesToSig result $ it "has the expected type signature" $ fnType' result `shouldBe` "(forall a. ((forall s. ST s a) -> a))" describe "type signature with constraint" $ do result <- parseFile "TypeSignatureWithConstraint.whippet" whenParsesToSig result $ it "has the expected type signature" $ fnType' result `shouldBe` "((Eq a) => (a -> (a -> Bool)))" describe "type signature with multiple constraints" $ do result <- parseFile "TypeSignatureWithMultipleConstraints.whippet" whenParsesToSig result $ it "has the expected type signature" $ fnType' result `shouldBe` "((Eq a, Show a) => a)" describe "function definitions" $ do let whenParsesToFn result assertions = do it "parses to a function signature" $ result `shouldSatisfy` is (_Right._AstDecl._DecFun) when (is _Right result) assertions fnParams :: ParsedAst -> [FnParam ()] fnParams ast = ast ^. _Right._AstDecl._DecFun.functionParams param :: Text -> FnParam () param n = FnParam (ident n) Nothing param' :: Text -> Type () -> FnParam () param' n = FnParam (ident n) . Just fnType :: ParsedAst -> [Type ()] fnType ast = ast ^.. _Right._AstDecl._DecFun.functionType._Just fnType' :: ParsedAst -> Text fnType' ast = ast ^. _Right._AstDecl._DecFun.functionType._Just.pprint' fnName :: ParsedAst -> Text fnName ast = ast ^. _Right._AstDecl._DecFun.functionIdent.pprint' fnBody :: ParsedAst -> [Expr ()] fnBody ast = ast ^.. _Right._AstDecl._DecFun.functionBody describe "simple function" $ do result <- parseFile "IdentityFun.whippet" whenParsesToFn result $ do it "has the expected identifier" $ fnName result `shouldBe` "identity" it "has the expected parameters" $ fnParams result `shouldBe` [param "x"] it "has the expected body" $ fnBody result `shouldBe` [var "x"] describe "simple function with type parameters" $ do result <- parseFile "IdentityFunWithType.whippet" whenParsesToFn result $ do it "has the expected identifier" $ fnName result `shouldBe` "identity" it "has the expected parameters" $ fnParams result `shouldBe` [param' "x" (tyVar "a")] it "has the expected body" $ fnBody result `shouldBe` [var "x"] describe "simple function with result type annotation" $ do result <- parseFile "IdentityFunWithResultType.whippet" whenParsesToFn result $ do it "has the expected identifier" $ fnName result `shouldBe` "identity" it "has the expected parameters" $ fnParams result `shouldBe` [param "x"] it "has the expected result type" $ fnType result `shouldBe` [tyVar "a"] it "has the expected body" $ fnBody result `shouldBe` [var "x"] describe "functions with pattern matching" $ do describe "example 1" $ do result <- parseFile "FunWithPatternMatching1.whippet" it "should parse" $ result `shouldSatisfy` is _Right describe "example 2" $ do result <- parseFile "FunWithPatternMatching2.whippet" it "should parse" $ result `shouldSatisfy` is _Right
chrisbarrett/whippet
test/Language/Whippet/Parser/FunctionSpec.hs
bsd-3-clause
8,265
0
20
3,082
1,634
765
869
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Test.PGType ( TestPGColumnType(..) , TestPGExactType(..) , TestPGType(..) , spec ) where import Data.Char (toLower) import Data.List (intercalate) import Data.Proxy (Proxy(..)) import Database.PostgreSQL.Simple.Bind.Parser import Database.PostgreSQL.Simple.Bind.Representation (PGTypeClass(..)) import Test.Hspec (Spec, describe) import Test.QuickCheck (Gen, Arbitrary(..), oneof, arbitrarySizedNatural, listOf, elements) import Test.Common (PGSql(..)) import Test.Utils (propParsingWorks) import Test.PGIdentifier (TestPGIdentifier(..), TestPGQualifiedIdentifier(..)) import Test.PGConstant (TestPGConstant(..)) newtype TestPGColumnType = TestPGColumnType String deriving (Show) instance Arbitrary TestPGColumnType where arbitrary = TestPGColumnType <$> do tableName <- render <$> (arbitrary :: Gen TestPGIdentifier) columnName <- render <$> (arbitrary :: Gen TestPGIdentifier) return $ concat [tableName, ".", columnName, "%type"] instance PGSql TestPGColumnType where render (TestPGColumnType s) = s data TestPGExactType = TestPGExactType { tpgetName :: String , tpgetModifiers :: [String] , tpgetTimeZone :: String , tpgetDimensions :: String } deriving (Show) instance Arbitrary TestPGExactType where arbitrary = do tpgetName <- arbitraryTypeName tpgetModifiers <- listOf arbitraryTypeModifier tpgetTimeZone <- if (map toLower tpgetName) `elem` ["timestamp", "time"] then arbitraryTimeZone else return "" tpgetDimensions <- arbitraryDimensions return $ TestPGExactType {..} where arbitraryTypeName = oneof [ elements $ [ "double precision" , "bit varying" , "character varying" , "timestamptz" , "timestamp" , "timetz" , "time"] ++ (map ("interval" ++) . ("":) . (map (' ':)) $ [ "year to month" , "day to hour" , "day to minute" , "day to second" , "hour to minute" , "hour to second" , "minute to second" , "year" , "month" , "day" , "hour" , "minute" , "second"]) , (render <$> (arbitrary :: Gen TestPGIdentifier))] arbitraryTypeModifier = oneof [ render <$> (arbitrary :: Gen TestPGConstant) , render <$> (arbitrary :: Gen TestPGQualifiedIdentifier)] arbitraryTimeZone = elements ["with time zone", "without time zone", ""] arbitraryDimensions = oneof [ return "array" , ("array " ++) <$> dimension , concat <$> listOf dimension] where dimension = oneof [ show <$> (arbitrarySizedNatural :: Gen Int) , return "" ] >>= \d -> return . concat $ ["[", d, "]"] shrink (TestPGExactType n m t d) = [ TestPGExactType n m' t' d' | m' <- if null m then [] else [[], m] , t' <- shrinkString t , d' <- shrinkString d , (m /= m' || t /= t' || d /= d')] where shrinkString s = if (null s) then [s] else ["", s] instance PGSql TestPGExactType where render (TestPGExactType {..}) = intercalate " " . filter (not . null) $ [ tpgetName , if (not . null $ tpgetModifiers) then "(" ++ (intercalate "," tpgetModifiers) ++ ")" else "" , tpgetTimeZone , tpgetDimensions] newtype TestPGType = TestPGType String deriving (Show, Eq) instance Arbitrary TestPGType where arbitrary = TestPGType <$> oneof [ render <$> (arbitrary :: Gen TestPGColumnType) , render <$> (arbitrary :: Gen TestPGExactType)] instance PGSql TestPGType where render (TestPGType s) = s instance PGTypeClass TestPGType where mergeTypes ts ts' = if ts == ts' || ((length ts' > 1) && ts == [recordType]) then Just ts' else Nothing where recordType = TestPGType "record" spec :: Spec spec = do describe "pgColumnType" $ do propParsingWorks pgColumnType (Proxy :: Proxy TestPGColumnType) describe "pgExactType" $ do propParsingWorks pgExactType (Proxy :: Proxy TestPGExactType) describe "pgType" $ do propParsingWorks pgType (Proxy :: Proxy TestPGType)
zohl/postgresql-simple-bind
tests/Test/PGType.hs
bsd-3-clause
4,609
0
16
1,204
1,226
689
537
123
1
{-# language CPP #-} -- | = Name -- -- VK_NV_compute_shader_derivatives - device extension -- -- == VK_NV_compute_shader_derivatives -- -- [__Name String__] -- @VK_NV_compute_shader_derivatives@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 202 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ -- -- [__Contact__] -- -- - Pat Brown -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_NV_compute_shader_derivatives] @nvpbrown%0A<<Here describe the issue or question you have about the VK_NV_compute_shader_derivatives extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2018-07-19 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - This extension requires -- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_compute_shader_derivatives.html SPV_NV_compute_shader_derivatives> -- -- - This extension provides API support for -- <https://github.com/KhronosGroup/GLSL/blob/master/extensions/nv/GLSL_NV_compute_shader_derivatives.txt GL_NV_compute_shader_derivatives> -- -- [__Contributors__] -- -- - Pat Brown, NVIDIA -- -- == Description -- -- This extension adds Vulkan support for the -- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/NV/SPV_NV_compute_shader_derivatives.html SPV_NV_compute_shader_derivatives> -- SPIR-V extension. -- -- The SPIR-V extension provides two new execution modes, both of which -- allow compute shaders to use built-ins that evaluate compute derivatives -- explicitly or implicitly. Derivatives will be computed via differencing -- over a 2x2 group of shader invocations. The @DerivativeGroupQuadsNV@ -- execution mode assembles shader invocations into 2x2 groups, where each -- group has x and y coordinates of the local invocation ID of the form -- (2m+{0,1}, 2n+{0,1}). The @DerivativeGroupLinearNV@ execution mode -- assembles shader invocations into 2x2 groups, where each group has local -- invocation index values of the form 4m+{0,1,2,3}. -- -- == New Structures -- -- - Extending -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2', -- 'Vulkan.Core10.Device.DeviceCreateInfo': -- -- - 'PhysicalDeviceComputeShaderDerivativesFeaturesNV' -- -- == New Enum Constants -- -- - 'NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME' -- -- - 'NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV' -- -- == New SPIR-V Capability -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirvenv-capabilities-table-ComputeDerivativeGroupQuadsNV ComputeDerivativeGroupQuadsNV> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirvenv-capabilities-table-ComputeDerivativeGroupLinearNV ComputeDerivativeGroupLinearNV> -- -- == Issues -- -- (1) Should we specify that the groups of four shader invocations used -- for derivatives in a compute shader are the same groups of four -- invocations that form a “quad” in shader subgroups? -- -- __RESOLVED__: Yes. -- -- == Examples -- -- None. -- -- == Version History -- -- - Revision 1, 2018-07-19 (Pat Brown) -- -- - Initial draft -- -- == See Also -- -- 'PhysicalDeviceComputeShaderDerivativesFeaturesNV' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_NV_compute_shader_derivatives Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_NV_compute_shader_derivatives ( PhysicalDeviceComputeShaderDerivativesFeaturesNV(..) , NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION , pattern NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION , NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME , pattern NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME ) where import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import Foreign.Ptr (Ptr) import Data.Kind (Type) import Vulkan.Core10.FundamentalTypes (bool32ToBool) import Vulkan.Core10.FundamentalTypes (boolToBool32) import Vulkan.Core10.FundamentalTypes (Bool32) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV)) -- | VkPhysicalDeviceComputeShaderDerivativesFeaturesNV - Structure -- describing compute shader derivative features that can be supported by -- an implementation -- -- = Members -- -- This structure describes the following features: -- -- = Description -- -- See -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#shaders-scope-quad Quad shader scope> -- for more information. -- -- If the @VkPhysicalDeviceComputeShaderDerivativesFeaturesNVfeatures@. -- structure is included in the @pNext@ chain of the -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2' -- structure passed to -- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceFeatures2', -- it is filled in to indicate whether each corresponding feature is -- supported. @VkPhysicalDeviceComputeShaderDerivativesFeaturesNVfeatures@. -- /can/ also be used in the @pNext@ chain of -- 'Vulkan.Core10.Device.DeviceCreateInfo' to selectively enable these -- features. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_NV_compute_shader_derivatives VK_NV_compute_shader_derivatives>, -- 'Vulkan.Core10.FundamentalTypes.Bool32', -- 'Vulkan.Core10.Enums.StructureType.StructureType' data PhysicalDeviceComputeShaderDerivativesFeaturesNV = PhysicalDeviceComputeShaderDerivativesFeaturesNV { -- | #features-computeDerivativeGroupQuads# @computeDerivativeGroupQuads@ -- indicates that the implementation supports the -- @ComputeDerivativeGroupQuadsNV@ SPIR-V capability. computeDerivativeGroupQuads :: Bool , -- | #features-computeDerivativeGroupLinear# @computeDerivativeGroupLinear@ -- indicates that the implementation supports the -- @ComputeDerivativeGroupLinearNV@ SPIR-V capability. computeDerivativeGroupLinear :: Bool } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (PhysicalDeviceComputeShaderDerivativesFeaturesNV) #endif deriving instance Show PhysicalDeviceComputeShaderDerivativesFeaturesNV instance ToCStruct PhysicalDeviceComputeShaderDerivativesFeaturesNV where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p PhysicalDeviceComputeShaderDerivativesFeaturesNV{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (computeDerivativeGroupQuads)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (computeDerivativeGroupLinear)) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_COMPUTE_SHADER_DERIVATIVES_FEATURES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero)) poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero)) f instance FromCStruct PhysicalDeviceComputeShaderDerivativesFeaturesNV where peekCStruct p = do computeDerivativeGroupQuads <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32)) computeDerivativeGroupLinear <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32)) pure $ PhysicalDeviceComputeShaderDerivativesFeaturesNV (bool32ToBool computeDerivativeGroupQuads) (bool32ToBool computeDerivativeGroupLinear) instance Storable PhysicalDeviceComputeShaderDerivativesFeaturesNV where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero PhysicalDeviceComputeShaderDerivativesFeaturesNV where zero = PhysicalDeviceComputeShaderDerivativesFeaturesNV zero zero type NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION" pattern NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION :: forall a . Integral a => a pattern NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION = 1 type NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME = "VK_NV_compute_shader_derivatives" -- No documentation found for TopLevel "VK_NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME" pattern NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME = "VK_NV_compute_shader_derivatives"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_NV_compute_shader_derivatives.hs
bsd-3-clause
10,074
0
14
1,489
1,112
694
418
-1
-1
{-# LANGUAGE RecordWildCards #-} module Day4 where import Data.Char import Data.List import Data.List.Split import Lib data Room = Room { name :: String , sector :: Int , checksum :: String } deriving (Show) input :: IO String input = readFile "day4" parse :: String -> Room parse s = Room name sector (init after) where [before, after] = splitOn "[" s nameSector = splitOn "-" before name = concat $ init nameSector sector = read $ last nameSector load :: String -> [Room] load = map parse . lines countLex :: (Char, Int) -> (Char, Int) -> Ordering countLex (a, ac) (b, bc) = if ac == bc then compare a b else compare bc ac isReal :: Room -> Bool isReal Room{..} = checksum' == checksum where checksum' = take 5 . map fst . sortBy countLex $ freq name solve1 :: [Room] -> Int solve1 = sum . map sector . filter isReal shift :: Int -> Char -> Char shift n c = c' where c' = chr $ ((ord c - ord 'a' + n ) `mod` 26) + ord 'a' rotate :: Room -> Room rotate room@Room{..} = room{name = rotated} where rotated = map (shift sector) $ name solve2 :: [Room] -> Maybe Room solve2 = find (\r -> name r == target) . map rotate . filter isReal where target = "northpoleobjectstorage"
mbernat/aoc16-haskell
src/Day4.hs
bsd-3-clause
1,249
0
14
307
519
277
242
37
2
{- | Module : $Header$ Description : Parse a string to a propositional Formula Copyright : (c) Till Theis License : MIT Maintainer : Till Theis <theis.till@gmail.com> Stability : experimental Portability : portable Parse a string to a propositional Formula. -} module PropositionalLogic.Parser (formula) where import PropositionalLogic.Logic import Data.Char (toLower, isSpace, isAlpha) import Data.Function (on) import Data.List (isPrefixOf) import Control.Monad (liftM, liftM2) -- * Exports -- | Translate a string to a 'Formula'. If it can't be translated the function -- returns the position of the first error and a message describing the problem. formula :: String -> Either (Int, String) (Formula Fancy) formula s = case runParser tokenize s of Right ([], ts) -> case runParser parse ts of Right ([], f) -> Right f Right (t:_, _) -> Left (position t, "parser: input not exhausted") Left ([], msg) -> Left (-1, msg) Left (t:_, msg) -> Left (position t, msg) Right (s', _) -> Left (length s - length s', "tokenizer: input not exhausted") Left (s', msg) -> Left (length s - length s', "tokenizer: " ++ msg) -- * Library Code -- I had to create my own parsing library because UHC can't compile Cabal -- packages to Javascript. -- The following functions mostly resemble the the ones from Parsec -- (<http://hackage.haskell.org/package/parsec>) -- | The Parser type parameterized over the input stream element type @s@ and -- the return type a. A parser takes the input and produces either an error -- message together with the original input or a return value together with the -- not yet consumed input. newtype Parser s a = Parser { runParser :: [s] -> Either ([s], String) ([s], a) } parserError s msg = Left (s, msg) parserAccept s a = Right (s, a) instance Monad (Parser s) where p >>= f = Parser $ \s -> case runParser p s of Right (s', a) -> runParser (f a) s' Left l -> Left l return = Parser . flip parserAccept fail = Parser . flip parserError (<|>) :: Parser s a -> Parser s a -> Parser s a p1 <|> p2 = Parser $ \s -> runParser p1 s `or` runParser p2 s where (Left _) `or` b = b a `or` _ = a eof :: Parser s () eof = Parser go where go [] = parserAccept [] () go s = parserError s "eof" many :: Parser s a -> Parser s [a] many p = many1 p <|> return [] many1 :: Parser s a -> Parser s [a] many1 p = liftM2 (:) p (many p) many2 :: Parser s a -> Parser s [a] many2 p = liftM2 (:) p (many1 p) oneOf :: Eq s => [s] -> Parser s s oneOf elems = satisfy (`elem` elems) satisfy :: (s -> Bool) -> Parser s s satisfy p = Parser go where go (x:xs) | p x = parserAccept xs x go s = parserError s "not satisfied" lookAhead :: Parser s a -> Parser s a lookAhead p = Parser $ \s -> either (parserError s . snd) (parserAccept s . snd) (runParser p s) choice :: [Parser s a] -> Parser s a choice = foldr1 (<|>) -- * Scanning data TokenID = TTok | FTok | SpaceTok | LParTok | RParTok | SymTok | NotTok | AndTok | OrTok | ImplTok | EqTok | ErrTok deriving (Show, Eq) data Token = Token { tid :: TokenID, position :: Position, match :: String } deriving (Show, Eq) type Position = Int tokenParser :: TokenID -> Parser Char String -> Parser Char Token tokenParser t p = p >>= \match -> return $ Token t 0 match tokenParsers = [ tokenParser SpaceTok $ many1 (satisfy isSpace) , tokenParser TTok $ stringIgnoreCase "1" , tokenParser FTok $ stringIgnoreCase "0" , tokenParser SymTok $ many2 (satisfy isAlpha) , tokenParser SymTok $ singleCharSymbol , tokenParser LParTok $ stringIgnoreCase "(" , tokenParser RParTok $ stringIgnoreCase ")" , tokenParser NotTok $ liftM return $ oneOf "!¬" , tokenParser AndTok $ liftM return $ oneOf "^∧" , tokenParser OrTok $ liftM return $ oneOf "v∨" , tokenParser EqTok $ stringIgnoreCase "<->" , tokenParser ImplTok $ stringIgnoreCase "->" , tokenParser ErrTok $ liftM return (satisfy (const True)) ] singleCharSymbol = do match <- satisfy (\c -> isAlpha c && c /= 'v') -- v is "or" operator lookAhead $ (satisfy (not . isAlpha) >> return ()) <|> eof return $ match:"" tokenize :: Parser Char [Token] tokenize = do rawTokens <- many1 $ choice tokenParsers eof return $ updatePositions rawTokens updatePositions :: [Token] -> [Token] updatePositions = go 0 where go offs (Token tid _ match : ts) = Token tid offs match : go (offs + length match) ts go _ _ = [] stringIgnoreCase :: String -> Parser Char String stringIgnoreCase str = Parser $ \input -> if str `isPrefixOfIgnoreCase` input then uncurry parserAccept $ swap $ splitAt (length str) input else parserError input str where isPrefixOfIgnoreCase = isPrefixOf `on` toLowerString toLowerString = map toLower swap (a, b) = (b, a) -- * Parsing type FParser = Parser Token (Formula Fancy) token :: TokenID -> Parser Token Token token t = satisfy $ (==) t . tid parse :: Parser Token (Formula Fancy) parse = Parser $ runParser pFormula . withoutSpaces where withoutSpaces = filter ((/=) SpaceTok . tid) parens :: Parser Token a -> Parser Token a parens p = do token LParTok a <- p token RParTok return a andEOF :: Parser s a -> Parser s a andEOF p = do a <- p eof return a formulaParsers = [pConnective, pNegation, pTrue, pFalse, pSymbol] pFormula :: FParser pFormula = choice $ map andEOF formulaParsers pSubFormula :: FParser pSubFormula = choice [pTrue, pFalse, pSymbol, pNegation, choice $ map parens formulaParsers] pTrue :: FParser pTrue = token TTok >> return T pFalse :: FParser pFalse = token FTok >> return F pSymbol :: FParser pSymbol = token SymTok >>= return . Symbol . match pNegation :: FParser pNegation = token NotTok >> pSubFormula >>= return . Negation associativeParsers = [ token AndTok >> return Conjunction , token OrTok >> return Disjunction ] rightAssociativeParsers = [ token ImplTok >> return Implication , token EqTok >> return Equivalence ] pAssociative :: FParser pAssociative = do f <- pSubFormula op <- choice associativeParsers g <- pAssociative <|> pSubFormula return $ f `op` g pRightAssociative :: FParser pRightAssociative = do f <- pAssociative <|> pSubFormula op <- choice rightAssociativeParsers g <- pRightAssociative <|> pAssociative <|> pSubFormula return $ f `op` g pConnective :: FParser pConnective = pRightAssociative <|> pAssociative <|> pSubFormula
tilltheis/propositional-logic
src/PropositionalLogic/Parser.hs
bsd-3-clause
6,623
0
13
1,546
2,272
1,168
1,104
141
6
{-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Control.Applicative import Control.Monad import qualified Data.ByteString.Lazy as BL import Data.Csv import Data.Char import Data.Time.Calendar import Data.Time.LocalTime import qualified Data.Vector as V import System.Environment (getArgs, getProgName) main :: IO () main = do args <- getArgs if null args then do progName <- getProgName putStrLn $ "usage: " ++ progName ++ " <csvfile>" else bloodprint $ head args bloodprint :: FilePath -> IO () bloodprint filename = do let removeLine = BL.tail . BL.dropWhile (/= fromIntegral (ord '\n')) removeThreeLines = removeLine . removeLine . removeLine csv <- fmap removeThreeLines $ BL.readFile filename case decodeWith (defaultDecodeOptions { decDelimiter = fromIntegral (ord ';') }) csv of Left err -> putStrLn err Right v -> V.forM_ v $ \ bpmRaw -> print $ bpmRawToBpm bpmRaw data BloodPressureMeasurementRaw = BPMRaw { date :: String , time :: String , sys :: Integer , dia :: Integer , pul :: Integer } instance FromRecord BloodPressureMeasurementRaw where parseRecord v | V.length v >= 5 = BPMRaw <$> v .! 0 <*> v .! 1 <*> v .! 2 <*> v .! 3 <*> v .! 4 | otherwise = mzero data BloodPressureMeasurement = BPM { datetime :: LocalTime , systolic :: Integer , diastolic :: Integer , pulse :: Integer } deriving Show bpmRawToBpm :: BloodPressureMeasurementRaw -> BloodPressureMeasurement bpmRawToBpm (BPMRaw d t sy di pu) = BPM mkLocalTime sy di pu where mkLocalTime :: LocalTime mkLocalTime = LocalTime (fromGregorian (read (d' !! 2)) (read (d' !! 1)) (read (head d'))) (TimeOfDay (read (head t')) (read (t' !! 1)) (read (t' !! 2))) breaks :: Char -> String -> [String] breaks c [] = [] breaks c str = let (f, r') = break (==c) str in f : breaks c (tail r') d' = breaks '.' d t' = breaks ':' t
obcode/bloodprint
src/BloodPrint.hs
bsd-3-clause
2,231
0
16
724
708
373
335
64
2
module Main where import Test.HUnit hiding (path) import TestUtil import Database.TokyoCabinet.FDB import Data.Maybe (catMaybes, fromJust) import Data.List (sort) import Control.Monad dbname :: String dbname = "foo.tcf" withOpenedFDB :: String -> (FDB -> IO a) -> IO () withOpenedFDB name action = do h <- new open h name [OREADER, OWRITER, OCREAT] res <- action h close h return () test_ecode = withoutFile dbname $ \fn -> do h <- new open h fn [OREADER] ecode h >>= (ENOFILE @=?) test_new_delete = do fdb <- new delete fdb test_open_close = withoutFile dbname $ \fn -> do fdb <- new not `fmap` open fdb fn [OREADER] @? "file does not exist" open fdb fn [OREADER, OWRITER, OCREAT] @? "open" close fdb @? "close" not `fmap` close fdb @? "cannot close closed file" test_putxx = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do put fdb "1" "bar" get fdb "1" >>= (Just "bar" @=?) putkeep fdb "1" "baz" get fdb "1" >>= (Just "bar" @=?) putcat fdb "1" "baz" get fdb "1" >>= (Just "barbaz" @=?) test_out = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do put fdb "1" "bar" get fdb "1" >>= (Just "bar" @=?) out fdb "1" @? "out succeeded" get fdb "1" >>= ((Nothing :: Maybe String) @=?) test_put_get = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do put fdb "2" "foo" put fdb "3" "bar" put fdb "4" "baz" put fdb IDNEXT "hoge" put fdb IDPREV "fuga" get fdb "2" >>= (Just "foo" @=?) get fdb "3" >>= (Just "bar" @=?) get fdb "4" >>= (Just "baz" @=?) get fdb (5 :: Int) >>= (Just "hoge" @=?) get fdb (1 :: Int) >>= (Just "fuga" @=?) put fdb IDMAX "max" put fdb IDMIN "min" get fdb (5 :: Int) >>= (Just "max" @=?) get fdb (1 :: Int) >>= (Just "min" @=?) test_iterate = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do let keys = [1, 2, 3] :: [Int] vals = ["foo", "bar", "baz"] zipWithM_ (put fdb) keys vals iterinit fdb keys' <- sequence $ replicate (length keys) (iternext fdb) (sort $ catMaybes keys') @?= (sort keys) iternext fdb >>= ((Nothing :: Maybe String) @=?) test_vsiz = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do put fdb "123" "bar" vsiz fdb "123" >>= (Just 3 @=?) vsiz fdb "234" >>= ((Nothing :: Maybe Int) @=?) test_range = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do zipWithM_ (put fdb) ([1..10] :: [Int]) ([100, 200..1000] :: [Int]) range fdb (2 :: Int) (5 :: Int) (-1) >>= (([2..5] :: [Int]) @=?) range fdb IDMIN IDMAX (-1) >>= (([1..10] :: [Int]) @=?) range fdb IDMIN IDMAX 2 >>= (([1..2] :: [Int]) @=?) test_fwmkeys = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do zipWithM_ (put fdb) ([1..10] :: [Int]) ([100, 200..1000] :: [Int]) fwmkeys fdb "[min,max]" 10 >>= ((map show [1..10]) @=?) test_addint = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do let ini = 32 :: Int put fdb "10" ini get fdb "10" >>= (Just ini @=?) addint fdb "10" 3 get fdb "10" >>= (Just (ini+3) @=?) addint fdb "20" 1 >>= (Just 1 @=?) put fdb "20" "foo" addint fdb "20" 1 >>= (Nothing @=?) test_adddouble = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do let ini = 0.003 :: Double put fdb "1" ini get fdb "1" >>= (Just ini @=?) adddouble fdb "1" 0.3 (get fdb "1" >>= (isIn (ini+0.3))) @? "isIn" adddouble fdb "2" 0.5 >>= (Just 0.5 @=?) put fdb "2" "foo" adddouble fdb "2" 1.2 >>= (Nothing @=?) where margin = 1e-30 isIn :: Double -> (Maybe Double) -> IO Bool isIn expected (Just actual) = let diff = expected - actual in return $ abs diff <= margin test_vanish = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> do put fdb "1" "111" put fdb "2" "222" put fdb "3" "333" rnum fdb >>= (3 @=?) vanish fdb rnum fdb >>= (0 @=?) test_copy = withoutFile dbname $ \fns -> withoutFile "bar.tcf" $ \fnd -> withOpenedFDB fns $ \fdb -> do put fdb "1" "bar" copy fdb fnd close fdb open fdb fnd [OREADER] get fdb "1" >>= (Just "bar" @=?) test_path = withoutFile dbname $ \fn -> withOpenedFDB fn $ \fdb -> path fdb >>= (Just dbname @=?) test_util = withoutFile dbname $ \fn -> do fdb <- new tune fdb 0 100000000 @? "tune" open fdb fn [OREADER, OWRITER, OCREAT] path fdb >>= (Just fn @=?) rnum fdb >>= (0 @=?) ((> 0) `fmap` fsiz fdb) @? "fsiz" sync fdb @? "sync" put fdb (1 :: Int) "dummy record" optimize fdb 0 0 @? "optimize" close fdb tests = test [ "new delete" ~: test_new_delete , "ecode" ~: test_ecode , "open close" ~: test_open_close , "put get" ~: test_put_get , "out" ~: test_out , "putxx" ~: test_putxx , "copy" ~: test_copy , "range" ~: test_range , "fwmkeys" ~: test_fwmkeys , "path" ~: test_path , "addint" ~: test_addint , "adddouble" ~: test_adddouble , "util" ~: test_util , "vsiz" ~: test_vsiz , "vanish" ~: test_vanish , "iterate" ~: test_iterate ] main = runTestTT tests
tom-lpsd/tokyocabinet-haskell
tests/FDBTest.hs
bsd-3-clause
5,943
0
17
2,159
2,240
1,122
1,118
174
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. module Duckling.Email.FR.Tests ( tests ) where import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Email.FR.Corpus import Duckling.Testing.Asserts tests :: TestTree tests = testGroup "Email Tests" [ makeCorpusTest [This Email] corpus ]
rfranek/duckling
tests/Duckling/Email/FR/Tests.hs
bsd-3-clause
584
0
9
96
77
49
28
10
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section{Haskell abstract syntax definition} This module glues together the pieces of the Haskell abstract syntax, which is declared in the various \tr{Hs*} modules. This module, therefore, is almost nothing but re-exporting. -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} module HsSyn ( module HsBinds, module HsDecls, module HsExpr, module HsImpExp, module HsLit, module HsPat, module HsTypes, module HsUtils, module HsDoc, module PlaceHolder, Fixity, HsModule(..) ) where -- friends: import HsDecls import HsBinds import HsExpr import HsImpExp import HsLit import PlaceHolder import HsPat import HsTypes import BasicTypes ( Fixity, WarningTxt ) import HsUtils import HsDoc -- others: import OccName ( HasOccName ) import Outputable import SrcLoc import Module ( ModuleName ) -- libraries: import Data.Data hiding ( Fixity ) -- | All we actually declare here is the top-level structure for a module. data HsModule name = HsModule { hsmodName :: Maybe (Located ModuleName), -- ^ @Nothing@: \"module X where\" is omitted (in which case the next -- field is Nothing too) hsmodExports :: Maybe (Located [LIE name]), -- ^ Export list -- -- - @Nothing@: export list omitted, so export everything -- -- - @Just []@: export /nothing/ -- -- - @Just [...]@: as you would expect... -- -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen' -- ,'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation hsmodImports :: [LImportDecl name], -- ^ We snaffle interesting stuff out of the imported interfaces early -- on, adding that info to TyDecls/etc; so this list is often empty, -- downstream. hsmodDecls :: [LHsDecl name], -- ^ Type, class, value, and interface signature decls hsmodDeprecMessage :: Maybe (Located WarningTxt), -- ^ reason\/explanation for warning/deprecation of this module -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen' -- ,'ApiAnnotation.AnnClose' -- -- For details on above see note [Api annotations] in ApiAnnotation hsmodHaddockModHeader :: Maybe LHsDocString -- ^ Haddock module info and description, unparsed -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen' -- ,'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation } -- ^ 'ApiAnnotation.AnnKeywordId's -- -- - 'ApiAnnotation.AnnModule','ApiAnnotation.AnnWhere' -- -- - 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnClose' for explicit braces and semi around -- hsmodImports,hsmodDecls if this style is used. -- For details on above see note [Api annotations] in ApiAnnotation deriving instance (DataId name) => Data (HsModule name) instance (OutputableBndr name, HasOccName name) => Outputable (HsModule name) where ppr (HsModule Nothing _ imports decls _ mbDoc) = pp_mb mbDoc $$ pp_nonnull imports $$ pp_nonnull decls ppr (HsModule (Just name) exports imports decls deprec mbDoc) = vcat [ pp_mb mbDoc, case exports of Nothing -> pp_header (text "where") Just es -> vcat [ pp_header lparen, nest 8 (fsep (punctuate comma (map ppr (unLoc es)))), nest 4 (text ") where") ], pp_nonnull imports, pp_nonnull decls ] where pp_header rest = case deprec of Nothing -> pp_modname <+> rest Just d -> vcat [ pp_modname, ppr d, rest ] pp_modname = text "module" <+> ppr name pp_mb :: Outputable t => Maybe t -> SDoc pp_mb (Just x) = ppr x pp_mb Nothing = empty pp_nonnull :: Outputable t => [t] -> SDoc pp_nonnull [] = empty pp_nonnull xs = vcat (map ppr xs)
vikraman/ghc
compiler/hsSyn/HsSyn.hs
bsd-3-clause
4,636
0
21
1,448
662
381
281
69
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Model.Db ( createTables , tagNameExists , listTags -- * Todos , queryTodo , saveTodo , listTodos , removeTodoTag , addTodoTag -- * Notes , queryNote , saveNote , listNotes , addNoteTag , removeNoteTag , TodoId(..) , NoteId(..) ) where import Control.Applicative import Control.Monad import Data.Int (Int64) import Data.Maybe (fromJust, listToMaybe) import qualified Data.Text as T import Database.SQLite.Simple import Model.Types data TagType = TagTodo | TagNote instance FromRow Tag where fromRow = Tag <$> field <*> field instance FromRow Todo where fromRow = Todo <$> fmap (Just . TodoId) field <*> field <*> field <*> field <*> pure [] instance FromRow Note where fromRow = Note <$> fmap (Just . NoteId) field <*> field <*> field <*> pure [] tableExists :: Connection -> String -> IO Bool tableExists conn tblName = do r <- query conn "SELECT name FROM sqlite_master WHERE type='table' AND name=?" (Only tblName) case r of [Only (_ :: String)] -> return True _ -> return False tagMapTableName :: TagType -> T.Text tagMapTableName TagTodo = "todo_tag_map" tagMapTableName TagNote = "note_tag_map" createTagMapTable :: Connection -> TagType -> IO () createTagMapTable conn ty = execute_ conn (Query $ T.concat [ "CREATE TABLE ", tagMapTableName ty, " (" , "object_id INTEGER, " , "tag_id INTEGER)" ]) -- | Create the necessary database tables, if not already initialized. createTables :: Connection -> IO () createTables conn = do -- Note: for a bigger app, you probably want to create a 'version' -- table too and use it to keep track of schema version and -- implement your schema upgrade procedure here. schemaCreated <- tableExists conn "todos" unless schemaCreated $ do execute_ conn "BEGIN" execute_ conn (Query $ T.concat [ "CREATE TABLE todos (" , "id INTEGER PRIMARY KEY, " , "user_id INTEGER NOT NULL, " , "saved_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, " , "activates_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP, " , "text TEXT, " , "done BOOLEAN)"]) createTagMapTable conn TagTodo createTagMapTable conn TagNote execute_ conn (Query $ T.concat [ "CREATE TABLE notes (" , "id INTEGER PRIMARY KEY, " , "user_id INTEGER NOT NULL, " , "title TEXT, " , "saved_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL, " , "text TEXT)"]) execute_ conn (Query $ T.concat [ "CREATE TABLE tags (" , "id INTEGER PRIMARY KEY," , "user_id INTEGER," , "tag TEXT," , "UNIQUE(user_id, tag))" ]) execute_ conn "COMMIT" -- | User already has created a tag with the given name? tagNameExists :: Connection -> User -> T.Text -> IO Bool tagNameExists conn (User uid _) tag = do [Only nRows] <- query conn "SELECT count(*) FROM tags WHERE user_id = ? AND tag = ?" (uid, tag) :: IO [Only Int] return $ nRows /= 0 -- | Is a Tag already associated with a given Todo item isObjectTagged :: Connection -> TagType -> Int64 -> Tag -> IO Bool isObjectTagged conn tagType oid tag = do let q = Query $ T.concat [ "SELECT count(*) FROM " , tagMapTableName tagType , " WHERE object_id = ? AND tag_id = ?" ] [Only nRows] <- query conn q (oid, tagId tag) :: IO [Only Int] return $ nRows /= 0 listObjectTags :: Connection -> TagType -> Int64 -> IO [Tag] listObjectTags conn tagType oid = query conn (Query $ T.concat [ "SELECT tags.id,tags.tag FROM tags, ", tagMapTableName tagType, " AS tmap " , " WHERE tmap.object_id = ? AND tmap.tag_id = tags.id" ]) (Only oid) -- | Assign a Tag to a given Object tagObject :: Connection -> TagType -> Int64 -> Tag -> IO [Tag] tagObject conn tagType oid tag = do tagAlreadySet <- isObjectTagged conn tagType oid tag unless tagAlreadySet $ execute conn (Query $ T.concat ["INSERT INTO ", tagMapTableName tagType, " (object_id, tag_id) VALUES (?,?)"]) (oid, tagId tag) listObjectTags conn tagType oid -- | Remove a Tag from a given Object untagObject :: Connection -> TagType -> Int64 -> Tag -> IO [Tag] untagObject conn tagType oid tag = do execute conn (Query $ T.concat ["DELETE FROM ", tagMapTableName tagType, " WHERE object_id = ? AND tag_id = ?"]) (oid, tagId tag) listObjectTags conn tagType oid -- | Look for a Tag by its name -- Note: use only if you know the tag exists tagByName :: Connection -> User -> T.Text -> IO Tag tagByName conn (User uid _) tag = do [t] <- query conn "SELECT id,tag FROM tags WHERE user_id = ? and tag = ?" (uid, tag) return t -- | Create a new tag newTag :: Connection -> User -> T.Text -> IO Tag newTag conn user@(User uid _) t = do tagExists <- tagNameExists conn user t if not tagExists then do execute conn "INSERT INTO tags (user_id, tag) VALUES (?, ?)" (uid, t) rowId <- lastInsertRowId conn return $ Tag rowId t else tagByName conn user t listTodoTags :: Connection -> TodoId -> IO [Tag] listTodoTags c (TodoId todo) = listObjectTags c TagTodo todo -- | Retrieve a user's list of todos listTodos' :: Connection -> User -> Maybe TodoFilter -> Maybe TodoId -> IO [Todo] listTodos' conn (User uid _) listFilter todoId_ = do let fields = "id, text, done, activates_on" todos <- case todoId_ of Nothing -> case listFilter of Just (TodoFilter includeDone (Just activationDate)) -> let q = Query $ T.concat [ "SELECT ", fields, " FROM todos " , "WHERE user_id = ? " , "AND ((activates_on IS NULL) OR (activates_on <= ?)) " , "AND ((done = 0) OR (done = ?))" ] in query conn q (uid, activationDate, includeDone) Just (TodoFilter includeDone Nothing) -> let q = Query $ T.concat [ "SELECT ", fields, " FROM todos " , "WHERE user_id = ? " , "AND ((done = 0) OR (done = ?))" ] in query conn q (uid, includeDone) Nothing -> query conn "SELECT id,text,done,activates_on FROM todos WHERE user_id = ?" (Only uid) Just (TodoId tid) -> query conn "SELECT id,text,done,activates_on FROM todos WHERE (user_id = ? AND id = ?)" (uid, tid) mapM queryTags todos where queryTags todo = do tags <- listTodoTags conn (fromJust . todoId $ todo) return $ todo { todoTags = tags } listTodos :: Connection -> User -> Maybe TodoFilter -> IO [Todo] listTodos c u f = listTodos' c u f Nothing queryTodo :: Connection -> User -> TodoId -> IO (Maybe Todo) queryTodo conn user todoId_ = listToMaybe <$> listTodos' conn user Nothing (Just todoId_) -- | Save or update a todo saveTodo :: Connection -> User -> Todo -> IO Todo saveTodo conn user@(User uid _) t = maybe newTodo updateTodo (todoId t) where newTodo = do execute conn "INSERT INTO todos (user_id,text,done,activates_on) VALUES (?,?,?,?)" (uid, todoText t, todoDone t, todoActivatesOn t) rowId <- lastInsertRowId conn return $ t { todoId = Just . TodoId $ rowId } updateTodo tid = do let q = Query $ T.concat [ "UPDATE todos SET " , "text = ?, done = ?, activates_on = ? " , "WHERE (user_id = ? AND id = ?)" ] execute conn q (todoText t, todoDone t, todoActivatesOn t, uid, unTodoId tid) fromJust <$> queryTodo conn user tid addTodoTag :: Connection -> User -> TodoId -> T.Text -> IO [Tag] addTodoTag c user (TodoId todo) text = newTag c user text >>= tagObject c TagTodo todo removeTodoTag :: Connection -> TodoId -> Tag -> IO [Tag] removeTodoTag c (TodoId todo) = untagObject c TagTodo todo addNoteTag :: Connection -> User -> NoteId -> T.Text -> IO [Tag] addNoteTag c user (NoteId note) text = newTag c user text >>= tagObject c TagNote note removeNoteTag :: Connection -> NoteId -> Tag -> IO [Tag] removeNoteTag c (NoteId note) = untagObject c TagNote note listNoteTags :: Connection -> NoteId -> IO [Tag] listNoteTags c (NoteId note) = listObjectTags c TagNote note -- | Retrieve a user's list of notes listNotes' :: Connection -> User -> Maybe NoteId -> IO [Note] listNotes' conn (User uid _) id_ = do notes <- case id_ of Nothing -> query conn "SELECT id,title,text FROM notes WHERE user_id = ?" (Only uid) Just (NoteId nid) -> query conn "SELECT id,title,text FROM notes WHERE (user_id = ? AND id = ?)" (uid, nid) mapM queryTags notes where queryTags note = do tags <- listNoteTags conn (fromJust . noteId $ note) return $ note { noteTags = tags } listNotes :: Connection -> User -> IO [Note] listNotes c u = listNotes' c u Nothing queryNote :: Connection -> User -> NoteId -> IO (Maybe Note) queryNote conn user noteId_ = listToMaybe <$> listNotes' conn user (Just noteId_) -- | Save or update a note saveNote :: Connection -> User -> Note -> IO Note saveNote conn user@(User uid _) n = maybe insert update (noteId n) where insert = do execute conn "INSERT INTO notes (user_id,title,text) VALUES (?,?,?)" (uid, noteTitle n, noteText n) rowId <- lastInsertRowId conn return $ n { noteId = Just . NoteId $ rowId } update nid = do execute conn "UPDATE notes SET title = ?, text = ? WHERE (user_id = ? AND id = ?)" (noteTitle n, noteText n, uid, unNoteId nid) fromJust <$> queryNote conn user nid -- | Retrieve a user's list of tags listTags :: Connection -> User -> IO [Tag] listTags conn (User uid _) = query conn "SELECT id,tag FROM tags WHERE user_id = ?" (Only uid)
nurpax/hstodo
src/Model/Db.hs
bsd-3-clause
10,302
0
20
3,042
2,741
1,387
1,354
217
4
{-| Module : Export.LatexGenerator Description : Contains functions for creating LaTeX text. -} module Export.LatexGenerator (generateTex) where import Text.LaTeX import Text.LaTeX.Packages.Graphicx import Text.LaTeX.Packages.Fancyhdr import Text.LaTeX.Packages.Geometry -- | Create a TEX file named texName that includes all of the images in -- imageNames generateTex :: [String] -> String -> IO () generateTex imageNames texName = execLaTeXT (buildTex imageNames) >>= renderFile texName -- | Combine the preamble and the document text into a single block of latex -- code. The document text contains code to insert all of the images in -- imageNames. buildTex :: Monad m => [String] -> LaTeXT_ m buildTex imageNames = do preamble document (body imageNames) -- | Defines documentclass and packages used. preamble :: Monad m => LaTeXT_ m preamble = do documentclass [] article usepackage [] graphicx usepackage [] geometry applyGeometry [GLandscape True, GWidth (In 9)] let mySettings = defaultHdrSettings {leftHeader = "Graph and Timetables", rightHeader = "courseography.cdf.toronto.edu"} applyHdrSettings mySettings raw "\\pagenumbering{gobble}" -- | Adds an includegraphics command for each image in imageNames. If an empty -- list of imageNames was provided, the body will be empty. body :: Monad m => [String] -> LaTeXT_ m body [] = "" body (imageName:imageNames) = do center $ includegraphics [IGWidth (CustomMeasure linewidth)] imageName body imageNames
hermish/courseography
app/Export/LatexGenerator.hs
gpl-3.0
1,528
0
12
273
324
165
159
26
1
module S06_Ex3 where {- Module : S06_Ex3 Description : Series 06 of the Functionnal and Logic Programming course at UniFR Author : Sylvain Julmy Email : sylvain.julmy(at)unifr.ch -} import Data.Char -- Tests import import qualified Test.HUnit as T import Text.Show.Functions -- to show <function> import Text.Format -- type declaration type State = Int type Code = String type Transition = (State,Char -> Bool,State) data StateMachine = StateMachine State [State] [Transition] deriving (Show) data Token = Token StateMachine Code deriving (Show) -- Tokens definition t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16 :: Token t1 = Token (StateMachine 0 [1] [(0,\c -> c == '{',1)]) "begin_block" t2 = Token (StateMachine 0 [1] [(0,\c -> c == '}',1)]) "end_block" t3 = Token (StateMachine 0 [1] [(0,\c -> c == '(',1)]) "begin_par" t4 = Token (StateMachine 0 [1] [(0,\c -> c == ')',1)]) "end_par" t5 = Token (StateMachine 0 [1] [(0,\c -> c == ';',1)]) "semicolon" t6 = Token (StateMachine 0 [2] [ (0,\c -> c == '=',1), (1,\c -> c == '=',2)]) "op_eg" t7 = Token (StateMachine 0 [1] [(0,\c -> c == '=',1)]) "op_affect" t8 = Token (StateMachine 0 [1] [(0,\c -> c == '+',1)]) "op_add" t9 = Token (StateMachine 0 [1] [(0,\c -> c == '-',1)]) "op_minus" t10 = Token (StateMachine 0 [1] [(0,\c -> c == '*',1)]) "op_mult" t11 = Token (StateMachine 0 [1] [(0,\c -> c == '/',1)]) "op_div" t12 = Token ( StateMachine 0 [3] [ (0,\c -> c == 'i',1), (1,\c -> c == 'n',2), (2,\c -> c == 't',3)]) "type_int" t13 = Token ( StateMachine 0 [2] [ (0,\c -> c == 'i',1), (1,\c -> c == 'f',2)]) "cond" t14 = Token ( StateMachine 0 [5] [ (0,\c -> c == 'w',1), (1,\c -> c == 'h',2), (2,\c -> c == 'i',3), (3,\c -> c == 'l',4), (4,\c -> c == 'e',5)]) "loop" t15 = Token ( StateMachine 0 [1] [ (0,isDigit,1), (1,isDigit,1)]) "value_int" t16 = Token ( StateMachine 0 [1] [ (0,\c -> isIdentHead c, 1), (1,\c -> isIdentBody c,1)]) "ident" where isIdentHead c = (elem c az) || (elem c (map toUpper az)) || c == '_' isIdentBody c = isIdentHead c || (isDigit c) az = "abcdefghijklmnopqrstuvwxyz" tokens = [t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,t11,t12,t13,t14,t15,t16] -- Ex3.2 recognizedFromState :: String -> Token -> (Code,String,String) recognizedFromState str tk = recognizedFromState' 0 str "" tk recognizedFromState' :: State -> String -> String -> Token -> (Code,String,String) recognizedFromState' _ [] acc (Token _ code) = (code,acc,"") recognizedFromState' crtState crtString@(c:cs) acc tk@(Token stateMachine@(StateMachine _ _ transitions) code) | ns == -1 = if isFinalState crtState stateMachine then (code,acc,crtString) else ("","",crtString) | otherwise = recognizedFromState' ns cs (acc ++ [c]) tk where ns = nextState crtState c stateMachine -- Ex3.3 getNextRecognizedToken :: String -> [Token] -> (Code,String,String) getNextRecognizedToken text [] = ("","",text) getNextRecognizedToken text tokens = inner text tokens ("","",text) where inner :: String -> [Token] -> (Code,String,String) -> (Code,String,String) inner _ [] acc = acc inner text (tk:tks) acc@(_,crtRecognizedString,_) = case (recognizedFromState text tk) of n@(_, txt, _) -> if (length txt) > (length crtRecognizedString) then inner text tks n else inner text tks acc lexAnalyse :: String -> [Token] -> [Code] lexAnalyse str tokens = inner (trim str) [] where inner :: String -> [Code] -> [Code] inner "" acc = acc inner crtStr acc = case (getNextRecognizedToken crtStr tokens) of (_,"",_) -> acc (code,_,rest) -> inner (trim rest) (acc ++ [code]) -- remove the first spaces of a String trim :: String -> String trim "" = "" trim str@(c:cs) | isSpace c = trim cs | otherwise = str isFinalState :: Int -> StateMachine -> Bool isFinalState crtState (StateMachine _ finalStates _) = elem crtState finalStates nextState :: State -> Char -> StateMachine -> State nextState crtState c (StateMachine _ _ transitions) = applyTransitions transitions where applyTransitions :: [Transition] -> State applyTransitions [] = -1 applyTransitions ((start,predicat,end):xs) | start == crtState && predicat c = end | otherwise = applyTransitions xs -- Test utils assertLexAnalyse :: String -> [Code] -> T.Assertion assertLexAnalyse str code = T.assertEqual (format "lexAnalyse {str} == {code}") (lexAnalyse str tokens) (code) -- Test test_lexAnalyse = T.TestCase (do assertLexAnalyse "int a;" ["type_int", "ident", "semicolon"] assertLexAnalyse "int b;" ["type_int", "ident", "semicolon"] assertLexAnalyse "intxy = 2;" ["ident","op_affect","value_int","semicolon"] assertLexAnalyse "toto=3;" ["ident","op_affect","value_int","semicolon"] ) tests = T.TestList [ T.TestLabel "test lexAnalyse" test_lexAnalyse] main = do T.runTestTT tests
SnipyJulmy/mcs_notes_and_resume
fun-and-log-prog/exercices/s06/s06_Julmy_Sylvain/ex3.hs
lgpl-3.0
5,128
0
13
1,174
2,164
1,227
937
106
3
module Handler.Verify ( getVerifyR ) where import Import import Yesod.Auth getVerifyR :: Handler RepHtml getVerifyR = do maid <- maybeAuthId defaultLayout [whamlet| <p>Your current auth ID: #{show maid} $maybe _ <- maid <p> <a href=@{AuthR LogoutR}>Logout $nothing <p> <a href=@{AuthR LoginR}>Go to the login page |]
ChrisSwires/One
Handler/Verify.hs
bsd-2-clause
356
0
7
85
49
28
21
-1
-1
module Kennitala (kennitala,gildKennitala,kennitöluHafi,vartölu, dagur,mánuður,ár,raðtala,vartala,öld, Aðili(Einstaklingur,Lögaðili), mánaðardagar,hlaupár) where import Text.Read import Control.Applicative import Data.Traversable data Kennitala = Kennitala { daggildi :: Int, mánuður :: Int, ár :: Int, raðtala :: Int, vartala :: Int, öld :: Int } dagur :: Kennitala -> Int dagur (Kennitala daggildi _ _ _ _ _) = if daggildi > 31 then daggildi - 40 else daggildi data Aðili = Einstaklingur | Lögaðili deriving (Show, Eq) kennitöluHafi :: Kennitala -> Aðili kennitöluHafi kt = if dagur kt == daggildi kt then Einstaklingur else Lögaðili -- Listi af tveimur seinustu stöfum tölu. -- Nú eða núlli og tölunni, ef talan er minni en 10. tveggjaStafaTala :: Int -> [Int] tveggjaStafaTala t = [t `div` 10, t `mod` 10] instance Show Kennitala where show (Kennitala daggildi mánuður ár raðtala vartala öld) = (show =<< tveggjaStafaTala =<< [daggildi,mánuður,ár]) ++ "-" ++ (show =<< tveggjaStafaTala raðtala) ++ (show =<< [vartala,öld]) -- 20 ≤ raðtala, svo fyrri tölustafurinn er aldrei núll => show raðtala == (show =<< tveggjaStafaTala raðtala) isRight (Left _) = False isRight (Right _) = True gildKennitala :: String -> Bool gildKennitala = isRight . kennitala breytaVillu :: (a -> b) -> Either a r -> Either b r breytaVillu f = either (Left . f) Right x & f = f x krefjast :: (a -> Bool) -> String -> a -> Either String a krefjast skilyrði melding x = if skilyrði x then Right x else Left melding tala :: String -> (Int -> Bool) -> Char -> Char -> String -> Either String Int tala heiti skilyrði a b melding = (readEither [a,b] & breytaVillu (const $ heiti ++ " má einungis innihalda tölustafi") >>= krefjast skilyrði melding) & breytaVillu (++ ", ekki " ++ [a,b] ++ ".") tölustaf :: String -> Char -> Either String Int tölustaf heiti a = let gildi = fromEnum a - fromEnum '0' in if gildi > 9 then Left $ heiti ++ " á að vera tölustafur, ekki " ++ [a] ++ "." else Right gildi bæði :: (a -> Bool) -> (a -> Bool) -> a -> Bool bæði = liftA2 (&&) kennitala :: String -> Either String Kennitala kennitala [dagtugur,dags,mántugur,mán,áratugur,árs,nr1,nr2,vartala,öld] = Kennitala <$> tala "Dagsetning" (0 <) dagtugur dags "Daggildi má mest vera 31 fyrir einstaklinga en minnst 41 fyrir félög. Daggildi má vera margt að 71" <*> tala "Mánuður" (bæði (0 <) (<= 12)) mántugur mán "Mánuðirnir eru tólf" <*> tala "Ártal" (0 <) áratugur árs "Ár má tákna með hvaða jákvæðu, tveggja stafa tölu sem er" <*> tala "Númer" (0 <=) nr1 nr2 "Raðtala er allt niður í 00, en oftast frá 20" <*> tölustaf "Vartala" vartala <*> tölustaf "Öld" öld >>= (\kt -> let dagar = mánaðardagar (ár kt) (mánuður kt) in krefjast (\kt -> dagur kt <= dagar) ("Dagar í " ++ show (mánuður kt) ++ ". mánuði eru " ++ show dagar ++ " talsins, ekki " ++ show (dagur kt)) kt) >>= \kt -> vartölu [dagtugur,dags,mántugur,mán,áratugur,árs,nr1,nr2] >>= maybe (Left "Þessi kennitala getur ekki verið rétt. Hún á sér ekki vartölu.") (\útreiknuð -> if útreiknuð == vartala then Right kt else Left $ "Einhver fyrstu níu stafanna í kennitölunni er rangur. Níundi stafurinn ætti að vera " ++ [útreiknuð] ++ " en ekki " ++ [vartala] ++ " ef fyrstu átta stafirnir eru rétir.") -- Bandstrik má vera á milli 6. og 7. stafs kennitala (dagtug:dag:mántug:mánuð:áratug:ár':'-':rest) = kennitala (dagtug:dag:mántug:mánuð:áratug:ár':rest) kennitala _ = Left $ "Kennitala þarf að vera 10 tölustafir, að frátöldu valfrjálsu bandstriki." -- Flestar 8 tölustafa runur eiga sér vartölu. -- Stundum kemst út reiknuð vartala ekki fyrir í einum tölustaf. -- Þá skilar eftirfarandi fall Nothing. -- Það þýðir að kennitala getur ekki byrjað á tilteknu 8 tölustafa rununni. -- Annaðhvort var runan rangt slegin inn, eða Þjóðskrá verður að velja nýtt númer. -- Ef út reiknuð vartala kemst fyrir, þá skilar fallið Just henni. vartöluFastar = 3:2:[7,6..2] vartölu :: String -> Either String (Maybe Char) vartölu strengur = if length strengur /= 8 then Left "Vartala reiknast ekki nema af fyrstu 8 stöfum kennitölu." else do listi <- traverse (tölustaf "Tölustafur") strengur :: Either String [Int] let niðurstaða = 11 - ((sum $ zipWith (*) vartöluFastar listi) `mod` 11) return . fmap (toEnum . (fromEnum '0' +)) $ if niðurstaða == 11 then Just 0 else if niðurstaða == 10 then Nothing else Just niðurstaða divisibleBy :: Int -> Int -> Bool a `divisibleBy` b = a `rem` b == 0 -- (=>) :: Bool -> Bool -> Bool -- True => False = False -- _ => _ = True hlaupár :: Int -> Bool hlaupár ár = ár `divisibleBy` 4 -- && (ár `divisibleBy` 100) `implies` (ár `divisibleBy` 400) mánaðardagar :: Int -> Int -> Int mánaðardagar ár mánuður = case mánuður of 02 -> if hlaupár ár then 29 else 28 04 -> 30 06 -> 30 08 -> 30 11 -> 30 _ -> 31
bjorsig/Kennitala
hsKennitala/Kennitala.hs
bsd-2-clause
5,522
32
20
1,383
1,688
892
796
101
7
------------------------------------------------------------------------------- -- This program runs fib and sumEuler separately and sequentially -- to allow us to compute how long each individual function takes -- to execute. module Main where import System.Time import Control.Parallel import System.Mem ------------------------------------------------------------------------------- fib :: Int -> Int fib 0 = 0 fib 1 = 1 fib n = fib (n-1) + fib (n-2) ------------------------------------------------------------------------------- mkList :: Int -> [Int] mkList n = [1..n-1] ------------------------------------------------------------------------------- relprime :: Int -> Int -> Bool relprime x y = gcd x y == 1 ------------------------------------------------------------------------------- euler :: Int -> Int euler n = length (filter (relprime n) (mkList n)) ------------------------------------------------------------------------------- sumEuler :: Int -> Int sumEuler = sum . (map euler) . mkList ------------------------------------------------------------------------------- sumFibEuler :: Int -> Int -> Int sumFibEuler a b = fib a + sumEuler b ------------------------------------------------------------------------------- result1 :: Int result1 = fib 38 result2 :: Int result2 = sumEuler 5300 ------------------------------------------------------------------------------- secDiff :: ClockTime -> ClockTime -> Float secDiff (TOD secs1 psecs1) (TOD secs2 psecs2) = fromInteger (psecs2 - psecs1) / 1e12 + fromInteger (secs2 - secs1) ------------------------------------------------------------------------------- main :: IO () main = do putStrLn "SumEuler0 (sequential)" performGC t0 <- getClockTime pseq result1 (return ()) t1 <- getClockTime putStrLn ("fib time: " ++ show (secDiff t0 t1)) t2 <- getClockTime pseq result2 (return ()) t3 <- getClockTime putStrLn ("sumEuler time: " ++ show (secDiff t2 t3)) -------------------------------------------------------------------------------
ml9951/ThreadScope
papers/haskell_symposium_2009/sumEuler/SumEuler0.hs
bsd-3-clause
2,163
0
12
385
477
245
232
37
1
{-# LANGUAGE BangPatterns, Rank2Types #-} module Math.Probably.Fitting where import Numeric.FAD fit :: (Ord a, Floating a) => (forall tag. b -> [Dual tag a] -> Dual tag a) -> [(b,a)] -> [a] -> [[a]] fit g pts p0 = let ss args = sum $ map (\(t,y)-> (g t args - lift y)**2) pts in argminNaiveGradient ss p0 --expDecay :: (Floating a) => a -> [a] -> a expDecay1 [t, a, tau, s0] = a*exp(-t*tau)+s0 --expDecay :: (Fractional a, Ord a, Floating a) => Double -> (forall tag. [Dual tag a] -> Dual tag a) expDecay :: (Floating b, Real a) => a -> [b] -> b expDecay t [a, tau, s0] = a*exp(-(realToFrac t)/tau)+s0 gaussFun x [mean, sd] = let factor = (recip $ sd*sqrt (2*pi)) in factor * (exp . negate $ (((x-mean)**2)/(2*sd**2))) fitFun :: [a] -> (b -> [a] -> a) -> (b->a) fitFun pars f = \t->f t pars --pars= (!!201) $ fit expDecay (pts) [100, 2, 20] in -- FunSeg 0 30 $ fitFun pars expDecay
glutamate/probably
Math/Probably/Fitting.hs
bsd-3-clause
943
0
16
232
437
238
199
13
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE DisambiguateRecordFields #-} module Verify.Graphics.Vty.Image ( module Verify.Graphics.Vty.Image , module Graphics.Vty.Image ) where import Verify.Graphics.Vty.Attributes import Graphics.Vty.Image import Graphics.Vty.Image.Internal import Verify data UnitImage = UnitImage Char Image instance Arbitrary UnitImage where arbitrary = do SingleColumnChar c <- arbitrary a <- arbitrary return $ UnitImage c (char a c) instance Show UnitImage where show (UnitImage c _) = "UnitImage " ++ show c data DefaultImage = DefaultImage Image instance Show DefaultImage where show (DefaultImage i) = "DefaultImage (" ++ show i ++ ") " ++ show (imageWidth i, imageHeight i) instance Arbitrary DefaultImage where arbitrary = do i <- return $ char defAttr 'X' return $ DefaultImage i data SingleRowSingleAttrImage = SingleRowSingleAttrImage { expectedAttr :: Attr , expectedColumns :: Int , rowImage :: Image } instance Show SingleRowSingleAttrImage where show (SingleRowSingleAttrImage attr columns image) = "SingleRowSingleAttrImage (" ++ show attr ++ ") " ++ show columns ++ " ( " ++ show image ++ " )" newtype WidthResize = WidthResize (Image -> (Image, Int)) instance Arbitrary WidthResize where arbitrary = do WidthResize f <- arbitrary w <- choose (1,64) oneof $ map (return . WidthResize) [ \i -> (i, imageWidth i) , \i -> (resizeWidth w $ fst $ f i, w) , \i -> let i' = fst $ f i in (cropLeft w i', min (imageWidth i') w) , \i -> let i' = fst $ f i in (cropRight w i', min (imageWidth i') w) ] newtype HeightResize = HeightResize (Image -> (Image, Int)) instance Arbitrary HeightResize where arbitrary = do HeightResize f <- arbitrary h <- choose (1,64) oneof $ map (return . HeightResize) [ \i -> (i, imageHeight i) , \i -> (resizeHeight h $ fst $ f i, h) , \i -> let i' = fst $ f i in (cropTop h i', min (imageHeight i') h) , \i -> let i' = fst $ f i in (cropBottom h i', min (imageHeight i') h) ] newtype ImageResize = ImageResize (Image -> (Image, (Int, Int))) instance Arbitrary ImageResize where arbitrary = oneof [ return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , return $! ImageResize $! \i -> (i, (imageWidth i, imageHeight i)) , do ImageResize f <- arbitrary WidthResize g <- arbitrary return $! ImageResize $! \i -> let (i0, (_, outHeight)) = f i gI = g i0 in (fst gI, (snd gI, outHeight)) , do ImageResize f <- arbitrary HeightResize g <- arbitrary return $! ImageResize $! \i -> let (i0, (outWidth, _)) = f i gI = g i0 in (fst gI, (outWidth, snd gI)) ] instance Arbitrary SingleRowSingleAttrImage where arbitrary = do -- The text must contain at least one character. Otherwise the -- image simplifies to the IdImage which has a height of 0. If -- this is to represent a single row then the height must be 1 singleColumnRowText <- Verify.resize 16 (listOf1 arbitrary) a <- arbitrary let outImage = horizCat $ [char a c | SingleColumnChar c <- singleColumnRowText] outWidth = length singleColumnRowText return $ SingleRowSingleAttrImage a outWidth outImage data SingleRowTwoAttrImage = SingleRowTwoAttrImage { part0 :: SingleRowSingleAttrImage , part1 :: SingleRowSingleAttrImage , joinImage :: Image } deriving Show instance Arbitrary SingleRowTwoAttrImage where arbitrary = do p0 <- arbitrary p1 <- arbitrary return $ SingleRowTwoAttrImage p0 p1 (rowImage p0 <|> rowImage p1) data SingleAttrSingleSpanStack = SingleAttrSingleSpanStack { stackImage :: Image , stackSourceImages :: [SingleRowSingleAttrImage] , stackWidth :: Int , stackHeight :: Int } deriving Show instance Arbitrary SingleAttrSingleSpanStack where arbitrary = do imageList <- Verify.resize 16 (listOf1 arbitrary) return $ mkSingleAttrSingleSpanStack imageList shrink s = do imageList <- shrink $ stackSourceImages s if null imageList then [] else return $ mkSingleAttrSingleSpanStack imageList mkSingleAttrSingleSpanStack imageList = let image = vertCat [ i | SingleRowSingleAttrImage { rowImage = i } <- imageList ] in SingleAttrSingleSpanStack image imageList (maximum $ map expectedColumns imageList) (toEnum $ length imageList) instance Arbitrary Image where arbitrary = oneof [ return EmptyImage , do SingleAttrSingleSpanStack {stackImage} <- Verify.resize 8 arbitrary ImageResize f <- Verify.resize 2 arbitrary return $! fst $! f stackImage , do SingleAttrSingleSpanStack {stackImage} <- Verify.resize 8 arbitrary ImageResize f <- Verify.resize 2 arbitrary return $! fst $! f stackImage , do i0 <- arbitrary i1 <- arbitrary let i = i0 <|> i1 ImageResize f <- Verify.resize 2 arbitrary return $! fst $! f i , do i0 <- arbitrary i1 <- arbitrary let i = i0 <-> i1 ImageResize f <- Verify.resize 2 arbitrary return $! fst $! f i ] {- shrink i@(HorizJoin {partLeft, partRight}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) !partLeft' <- shrink partLeft !partRight' <- shrink partRight [i_alt, partLeft' <|> partRight'] shrink i@(VertJoin {partTop, partBottom}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) !partTop' <- shrink partTop !partBottom' <- shrink partBottom [i_alt, partTop' <-> partBottom'] shrink i@(CropRight {croppedImage, outputWidth}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) [i_alt, croppedImage] shrink i@(CropLeft {croppedImage, leftSkip, outputWidth}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) [i_alt, croppedImage] shrink i@(CropBottom {croppedImage, outputHeight}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) [i_alt, croppedImage] shrink i@(CropTop {croppedImage, topSkip, outputHeight}) = do let !i_alt = backgroundFill (imageWidth i) (imageHeight i) [i_alt, croppedImage] shrink i = [emptyImage, backgroundFill (imageWidth i) (imageHeight i)] -} data CropOperation = CropFromLeft | CropFromRight | CropFromTop | CropFromBottom deriving (Eq, Show) instance Arbitrary CropOperation where arbitrary = oneof $ map return [CropFromLeft, CropFromRight, CropFromTop, CropFromBottom] data Translation = Translation Image (Int, Int) Image deriving (Eq, Show) instance Arbitrary Translation where arbitrary = do i <- arbitrary x <- arbitrary `suchThat` (> 0) y <- arbitrary `suchThat` (> 0) let i' = translate x y i return $ Translation i (x,y) i'
jtdaugherty/vty
test/Verify/Graphics/Vty/Image.hs
bsd-3-clause
7,815
0
17
2,313
2,015
1,039
976
154
1
{-# LANGUAGE CPP #-} module Network.Wai.Handler.Warp.Date ( withDateCache , GMTDate ) where import Control.AutoUpdate (defaultUpdateSettings, updateAction, mkAutoUpdate) import Data.ByteString import Network.HTTP.Date #if WINDOWS import Data.Time (UTCTime, getCurrentTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Foreign.C.Types (CTime(..)) #else import System.Posix (epochTime) #endif -- | The type of the Date header value. type GMTDate = ByteString -- | Creating 'DateCache' and executing the action. withDateCache :: (IO GMTDate -> IO a) -> IO a withDateCache action = initialize >>= action initialize :: IO (IO GMTDate) initialize = mkAutoUpdate defaultUpdateSettings { updateAction = formatHTTPDate <$> getCurrentHTTPDate } #ifdef WINDOWS uToH :: UTCTime -> HTTPDate uToH = epochTimeToHTTPDate . CTime . truncate . utcTimeToPOSIXSeconds getCurrentHTTPDate :: IO HTTPDate getCurrentHTTPDate = uToH <$> getCurrentTime #else getCurrentHTTPDate :: IO HTTPDate getCurrentHTTPDate = epochTimeToHTTPDate <$> epochTime #endif
creichert/wai
warp/Network/Wai/Handler/Warp/Date.hs
mit
1,115
0
8
198
213
127
86
16
1
---------------------------------------------------------------------------- -- -- Pretty-printing of Cmm as (a superset of) C-- -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- -- -- This is where we walk over CmmNode emitting an external representation, -- suitable for parsing, in a syntax strongly reminiscent of C--. This -- is the "External Core" for the Cmm layer. -- -- As such, this should be a well-defined syntax: we want it to look nice. -- Thus, we try wherever possible to use syntax defined in [1], -- "The C-- Reference Manual", http://www.cminusminus.org/. We differ -- slightly, in some cases. For one, we use I8 .. I64 for types, rather -- than C--'s bits8 .. bits64. -- -- We try to ensure that all information available in the abstract -- syntax is reproduced, or reproducible, in the concrete syntax. -- Data that is not in printed out can be reconstructed according to -- conventions used in the pretty printer. There are at least two such -- cases: -- 1) if a value has wordRep type, the type is not appended in the -- output. -- 2) MachOps that operate over wordRep type are printed in a -- C-style, rather than as their internal MachRep name. -- -- These conventions produce much more readable Cmm output. -- -- A useful example pass over Cmm is in nativeGen/MachCodeGen.hs {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE GADTs, TypeFamilies, FlexibleContexts #-} module PprCmm ( module PprCmmDecl , module PprCmmExpr ) where import BlockId () import CLabel import Cmm import CmmUtils import FastString import Outputable import PprCmmDecl import PprCmmExpr import Util import BasicTypes import Compiler.Hoopl import Data.List import Prelude hiding (succ) ------------------------------------------------- -- Outputable instances instance Outputable CmmStackInfo where ppr = pprStackInfo instance Outputable CmmTopInfo where ppr = pprTopInfo instance Outputable (CmmNode e x) where ppr = pprNode instance Outputable Convention where ppr = pprConvention instance Outputable ForeignConvention where ppr = pprForeignConvention instance Outputable ForeignTarget where ppr = pprForeignTarget instance Outputable CmmReturnInfo where ppr = pprReturnInfo instance Outputable (Block CmmNode C C) where ppr = pprBlock instance Outputable (Block CmmNode C O) where ppr = pprBlock instance Outputable (Block CmmNode O C) where ppr = pprBlock instance Outputable (Block CmmNode O O) where ppr = pprBlock instance Outputable (Graph CmmNode e x) where ppr = pprGraph instance Outputable CmmGraph where ppr = pprCmmGraph ---------------------------------------------------------- -- Outputting types Cmm contains pprStackInfo :: CmmStackInfo -> SDoc pprStackInfo (StackInfo {arg_space=arg_space, updfr_space=updfr_space}) = ptext (sLit "arg_space: ") <> ppr arg_space <+> ptext (sLit "updfr_space: ") <> ppr updfr_space pprTopInfo :: CmmTopInfo -> SDoc pprTopInfo (TopInfo {info_tbls=info_tbl, stack_info=stack_info}) = vcat [ptext (sLit "info_tbl: ") <> ppr info_tbl, ptext (sLit "stack_info: ") <> ppr stack_info] ---------------------------------------------------------- -- Outputting blocks and graphs pprBlock :: IndexedCO x SDoc SDoc ~ SDoc => Block CmmNode e x -> IndexedCO e SDoc SDoc pprBlock block = foldBlockNodesB3 ( ($$) . ppr , ($$) . (nest 4) . ppr , ($$) . (nest 4) . ppr ) block empty pprGraph :: Graph CmmNode e x -> SDoc pprGraph GNil = empty pprGraph (GUnit block) = ppr block pprGraph (GMany entry body exit) = text "{" $$ nest 2 (pprMaybeO entry $$ (vcat $ map ppr $ bodyToBlockList body) $$ pprMaybeO exit) $$ text "}" where pprMaybeO :: Outputable (Block CmmNode e x) => MaybeO ex (Block CmmNode e x) -> SDoc pprMaybeO NothingO = empty pprMaybeO (JustO block) = ppr block pprCmmGraph :: CmmGraph -> SDoc pprCmmGraph g = text "{" <> text "offset" $$ nest 2 (vcat $ map ppr blocks) $$ text "}" where blocks = postorderDfs g --------------------------------------------- -- Outputting CmmNode and types which it contains pprConvention :: Convention -> SDoc pprConvention (NativeNodeCall {}) = text "<native-node-call-convention>" pprConvention (NativeDirectCall {}) = text "<native-direct-call-convention>" pprConvention (NativeReturn {}) = text "<native-ret-convention>" pprConvention Slow = text "<slow-convention>" pprConvention GC = text "<gc-convention>" pprForeignConvention :: ForeignConvention -> SDoc pprForeignConvention (ForeignConvention c args res ret) = doubleQuotes (ppr c) <+> text "arg hints: " <+> ppr args <+> text " result hints: " <+> ppr res <+> ppr ret pprReturnInfo :: CmmReturnInfo -> SDoc pprReturnInfo CmmMayReturn = empty pprReturnInfo CmmNeverReturns = ptext (sLit "never returns") pprForeignTarget :: ForeignTarget -> SDoc pprForeignTarget (ForeignTarget fn c) = ppr c <+> ppr_target fn where ppr_target :: CmmExpr -> SDoc ppr_target t@(CmmLit _) = ppr t ppr_target fn' = parens (ppr fn') pprForeignTarget (PrimTarget op) -- HACK: We're just using a ForeignLabel to get this printed, the label -- might not really be foreign. = ppr (CmmLabel (mkForeignLabel (mkFastString (show op)) Nothing ForeignLabelInThisPackage IsFunction)) pprNode :: CmmNode e x -> SDoc pprNode node = pp_node <+> pp_debug where pp_node :: SDoc pp_node = case node of -- label: CmmEntry id -> ppr id <> colon -- // text CmmComment s -> text "//" <+> ftext s -- reg = expr; CmmAssign reg expr -> ppr reg <+> equals <+> ppr expr <> semi -- rep[lv] = expr; CmmStore lv expr -> rep <> brackets(ppr lv) <+> equals <+> ppr expr <> semi where rep = sdocWithDynFlags $ \dflags -> ppr ( cmmExprType dflags expr ) -- call "ccall" foo(x, y)[r1, r2]; -- ToDo ppr volatile CmmUnsafeForeignCall target results args -> hsep [ ppUnless (null results) $ parens (commafy $ map ppr results) <+> equals, ptext $ sLit "call", ppr target <> parens (commafy $ map ppr args) <> semi] -- goto label; CmmBranch ident -> ptext (sLit "goto") <+> ppr ident <> semi -- if (expr) goto t; else goto f; CmmCondBranch expr t f -> hsep [ ptext (sLit "if") , parens(ppr expr) , ptext (sLit "goto") , ppr t <> semi , ptext (sLit "else goto") , ppr f <> semi ] CmmSwitch expr maybe_ids -> hang (hcat [ ptext (sLit "switch [0 .. ") , int (length maybe_ids - 1) , ptext (sLit "] ") , if isTrivialCmmExpr expr then ppr expr else parens (ppr expr) , ptext (sLit " {") ]) 4 (vcat ( map caseify pairs )) $$ rbrace where pairs = groupBy snds (zip [0 .. ] maybe_ids ) snds a b = (snd a) == (snd b) caseify ixs@((_,Nothing):_) = ptext (sLit "/* impossible: ") <> hcat (intersperse comma (map (int.fst) ixs)) <> ptext (sLit " */") caseify as = let (is,ids) = unzip as in hsep [ ptext (sLit "case") , hcat (punctuate comma (map int is)) , ptext (sLit ": goto") , ppr (head [ id | Just id <- ids]) <> semi ] CmmCall tgt k regs out res updfr_off -> hcat [ ptext (sLit "call"), space , pprFun tgt, parens (interpp'SP regs), space , returns <+> ptext (sLit "args: ") <> ppr out <> comma <+> ptext (sLit "res: ") <> ppr res <> comma <+> ptext (sLit "upd: ") <> ppr updfr_off , semi ] where pprFun f@(CmmLit _) = ppr f pprFun f = parens (ppr f) returns | Just r <- k = ptext (sLit "returns to") <+> ppr r <> comma | otherwise = empty CmmForeignCall {tgt=t, res=rs, args=as, succ=s, ret_args=a, ret_off=u, intrbl=i} -> hcat $ if i then [ptext (sLit "interruptible"), space] else [] ++ [ ptext (sLit "foreign call"), space , ppr t, ptext (sLit "(...)"), space , ptext (sLit "returns to") <+> ppr s <+> ptext (sLit "args:") <+> parens (ppr as) <+> ptext (sLit "ress:") <+> parens (ppr rs) , ptext (sLit "ret_args:") <+> ppr a , ptext (sLit "ret_off:") <+> ppr u , semi ] pp_debug :: SDoc pp_debug = if not debugIsOn then empty else case node of CmmEntry {} -> empty -- Looks terrible with text " // CmmEntry" CmmComment {} -> empty -- Looks also terrible with text " // CmmComment" CmmAssign {} -> text " // CmmAssign" CmmStore {} -> text " // CmmStore" CmmUnsafeForeignCall {} -> text " // CmmUnsafeForeignCall" CmmBranch {} -> text " // CmmBranch" CmmCondBranch {} -> text " // CmmCondBranch" CmmSwitch {} -> text " // CmmSwitch" CmmCall {} -> text " // CmmCall" CmmForeignCall {} -> text " // CmmForeignCall" commafy :: [SDoc] -> SDoc commafy xs = hsep $ punctuate comma xs
lukexi/ghc-7.8-arm64
compiler/cmm/PprCmm.hs
bsd-3-clause
10,036
0
23
3,137
2,516
1,287
1,229
179
24
{-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses, PatternGuards #-} ---------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.BorderResize -- Copyright : (c) Jan Vornberger 2009 -- License : BSD3-style (see LICENSE) -- -- Maintainer : jan.vornberger@informatik.uni-oldenburg.de -- Stability : unstable -- Portability : not portable -- -- This layout modifier will allow to resize windows by dragging their -- borders with the mouse. However, it only works in layouts or modified -- layouts that react to the 'SetGeometry' message. -- "XMonad.Layout.WindowArranger" can be used to create such a setup, -- but it is probably must useful in a floating layout such as -- "XMonad.Layout.PositionStoreFloat" with which it has been mainly tested. -- See the documentation of PositionStoreFloat for a typical usage example. -- ----------------------------------------------------------------------------- module XMonad.Layout.BorderResize ( -- * Usage -- $usage borderResize , BorderResize (..) , RectWithBorders, BorderInfo, ) where import XMonad import XMonad.Layout.Decoration import XMonad.Layout.WindowArranger import XMonad.Util.XUtils import Control.Monad(when) import qualified Data.Map as M -- $usage -- You can use this module with the following in your -- @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.BorderResize -- > myLayout = borderResize (... layout setup that reacts to SetGeometry ...) -- > main = xmonad defaultConfig { layoutHook = myLayout } -- type BorderBlueprint = (Rectangle, Glyph, BorderType) data BorderType = RightSideBorder | LeftSideBorder | TopSideBorder | BottomSideBorder deriving (Show, Read, Eq) data BorderInfo = BI { bWin :: Window, bRect :: Rectangle, bType :: BorderType } deriving (Show, Read) type RectWithBorders = (Rectangle, [BorderInfo]) data BorderResize a = BR (M.Map Window RectWithBorders) deriving (Show, Read) brBorderSize :: Dimension brBorderSize = 2 borderResize :: l a -> ModifiedLayout BorderResize l a borderResize = ModifiedLayout (BR M.empty) instance LayoutModifier BorderResize Window where redoLayout _ _ Nothing wrs = return (wrs, Nothing) redoLayout (BR wrsLastTime) _ _ wrs = do let correctOrder = map fst wrs wrsCurrent = M.fromList wrs wrsGone = M.difference wrsLastTime wrsCurrent wrsAppeared = M.difference wrsCurrent wrsLastTime wrsStillThere = M.intersectionWith testIfUnchanged wrsLastTime wrsCurrent handleGone wrsGone wrsCreated <- handleAppeared wrsAppeared let wrsChanged = handleStillThere wrsStillThere wrsThisTime = M.union wrsChanged wrsCreated return (compileWrs wrsThisTime correctOrder, Just $ BR wrsThisTime) -- What we return is the original wrs with the new border -- windows inserted at the correct positions - this way, the core -- will restack the borders correctly. -- We also return information about our borders, so that we -- can handle events that they receive and destroy them when -- they are no longer needed. where testIfUnchanged entry@(rLastTime, _) rCurrent = if rLastTime == rCurrent then (Nothing, entry) else (Just rCurrent, entry) handleMess (BR wrsLastTime) m | Just e <- fromMessage m :: Maybe Event = handleResize (createBorderLookupTable wrsLastTime) e >> return Nothing | Just _ <- fromMessage m :: Maybe LayoutMessages = handleGone wrsLastTime >> return (Just $ BR M.empty) handleMess _ _ = return Nothing compileWrs :: M.Map Window RectWithBorders -> [Window] -> [(Window, Rectangle)] compileWrs wrsThisTime correctOrder = let wrs = reorder (M.toList wrsThisTime) correctOrder in concat $ map compileWr wrs compileWr :: (Window, RectWithBorders) -> [(Window, Rectangle)] compileWr (w, (r, borderInfos)) = let borderWrs = for borderInfos $ \bi -> (bWin bi, bRect bi) in borderWrs ++ [(w, r)] handleGone :: M.Map Window RectWithBorders -> X () handleGone wrsGone = mapM_ deleteWindow borderWins where borderWins = map bWin . concat . map snd . M.elems $ wrsGone handleAppeared :: M.Map Window Rectangle -> X (M.Map Window RectWithBorders) handleAppeared wrsAppeared = do let wrs = M.toList wrsAppeared wrsCreated <- mapM handleSingleAppeared wrs return $ M.fromList wrsCreated handleSingleAppeared :: (Window, Rectangle) -> X (Window, RectWithBorders) handleSingleAppeared (w, r) = do let borderBlueprints = prepareBorders r borderInfos <- mapM createBorder borderBlueprints return (w, (r, borderInfos)) handleStillThere :: M.Map Window (Maybe Rectangle, RectWithBorders) -> M.Map Window RectWithBorders handleStillThere wrsStillThere = M.map handleSingleStillThere wrsStillThere handleSingleStillThere :: (Maybe Rectangle, RectWithBorders) -> RectWithBorders handleSingleStillThere (Nothing, entry) = entry handleSingleStillThere (Just rCurrent, (_, borderInfos)) = (rCurrent, updatedBorderInfos) where changedBorderBlueprints = prepareBorders rCurrent updatedBorderInfos = map updateBorderInfo . zip borderInfos $ changedBorderBlueprints -- assuming that the four borders are always in the same order updateBorderInfo :: (BorderInfo, BorderBlueprint) -> BorderInfo updateBorderInfo (borderInfo, (r, _, _)) = borderInfo { bRect = r } createBorderLookupTable :: M.Map Window RectWithBorders -> [(Window, (BorderType, Window, Rectangle))] createBorderLookupTable wrsLastTime = concat $ map processSingleEntry $ M.toList wrsLastTime where processSingleEntry :: (Window, RectWithBorders) -> [(Window, (BorderType, Window, Rectangle))] processSingleEntry (w, (r, borderInfos)) = for borderInfos $ \bi -> (bWin bi, (bType bi, w, r)) prepareBorders :: Rectangle -> [BorderBlueprint] prepareBorders (Rectangle x y wh ht) = [((Rectangle (x + fi wh - fi brBorderSize) y brBorderSize ht), xC_right_side , RightSideBorder), ((Rectangle x y brBorderSize ht) , xC_left_side , LeftSideBorder), ((Rectangle x y wh brBorderSize) , xC_top_side , TopSideBorder), ((Rectangle x (y + fi ht - fi brBorderSize) wh brBorderSize), xC_bottom_side, BottomSideBorder) ] handleResize :: [(Window, (BorderType, Window, Rectangle))] -> Event -> X () handleResize borders ButtonEvent { ev_window = ew, ev_event_type = et } | et == buttonPress, Just edge <- lookup ew borders = case edge of (RightSideBorder, hostWin, (Rectangle hx hy _ hht)) -> mouseDrag (\x _ -> do let nwh = max 1 $ fi (x - hx) rect = Rectangle hx hy nwh hht focus hostWin when (x - hx > 0) $ sendMessage (SetGeometry rect)) (focus hostWin) (LeftSideBorder, hostWin, (Rectangle hx hy hwh hht)) -> mouseDrag (\x _ -> do let nx = max 0 $ min (hx + fi hwh) $ x nwh = max 1 $ hwh + fi (hx - x) rect = Rectangle nx hy nwh hht focus hostWin when (x < hx + fi hwh) $ sendMessage (SetGeometry rect)) (focus hostWin) (TopSideBorder, hostWin, (Rectangle hx hy hwh hht)) -> mouseDrag (\_ y -> do let ny = max 0 $ min (hy + fi hht) $ y nht = max 1 $ hht + fi (hy - y) rect = Rectangle hx ny hwh nht focus hostWin when (y < hy + fi hht) $ sendMessage (SetGeometry rect)) (focus hostWin) (BottomSideBorder, hostWin, (Rectangle hx hy hwh _)) -> mouseDrag (\_ y -> do let nht = max 1 $ fi (y - hy) rect = Rectangle hx hy hwh nht focus hostWin when (y - hy > 0) $ sendMessage (SetGeometry rect)) (focus hostWin) handleResize _ _ = return () createBorder :: BorderBlueprint -> X (BorderInfo) createBorder (borderRect, borderCursor, borderType) = do borderWin <- createInputWindow borderCursor borderRect return BI { bWin = borderWin, bRect = borderRect, bType = borderType } createInputWindow :: Glyph -> Rectangle -> X Window createInputWindow cursorGlyph r = withDisplay $ \d -> do win <- mkInputWindow d r io $ selectInput d win (exposureMask .|. buttonPressMask) cursor <- io $ createFontCursor d cursorGlyph io $ defineCursor d win cursor io $ freeCursor d cursor showWindow win return win mkInputWindow :: Display -> Rectangle -> X Window mkInputWindow d (Rectangle x y w h) = do rw <- asks theRoot let screen = defaultScreenOfDisplay d visual = defaultVisualOfScreen screen attrmask = cWOverrideRedirect io $ allocaSetWindowAttributes $ \attributes -> do set_override_redirect attributes True createWindow d rw x y w h 0 0 inputOnly visual attrmask attributes for :: [a] -> (a -> b) -> [b] for = flip map reorder :: (Eq a) => [(a, b)] -> [a] -> [(a, b)] reorder wrs order = let ordered = concat $ map (pickElem wrs) order rest = filter (\(w, _) -> not (w `elem` order)) wrs in ordered ++ rest where pickElem list e = case (lookup e list) of Just result -> [(e, result)] Nothing -> []
markus1189/xmonad-contrib-710
XMonad/Layout/BorderResize.hs
bsd-3-clause
9,965
2
22
2,827
2,686
1,410
1,276
154
4
{-# LANGUAGE ScopedTypeVariables #-} -- You can set the following VERBOSE environment variable to control -- the verbosity of the output generated by this module. module PackageTests.PackageTester ( PackageSpec(..) , SuiteConfig(..) , Success(..) , Result(..) -- * Running cabal commands , cabal_configure , cabal_build , cabal_haddock , cabal_test , cabal_bench , cabal_install , cabal_register , unregister , compileSetup , run -- * Test helpers , assertConfigureSucceeded , assertBuildSucceeded , assertBuildFailed , assertHaddockSucceeded , assertTestSucceeded , assertTestFailed , assertInstallSucceeded , assertRegisterSucceeded , assertRegisterFailed , assertOutputContains , assertOutputDoesNotContain ) where import qualified Control.Exception.Extensible as E import Control.Monad import qualified Data.ByteString.Char8 as C import Data.List import Data.Maybe import System.Directory (canonicalizePath, doesFileExist) import System.Environment (getEnv) import System.Exit (ExitCode(ExitSuccess)) import System.FilePath import System.IO (hIsEOF, hGetChar, hClose) import System.IO.Error (isDoesNotExistError) import System.Process (runProcess, waitForProcess) import Test.Tasty.HUnit (Assertion, assertFailure) import Distribution.Compat.CreatePipe (createPipe) import Distribution.Simple.BuildPaths (exeExtension) import Distribution.Simple.Compiler (PackageDBStack, PackageDB(..)) import Distribution.Simple.Program.Run (getEffectiveEnvironment) import Distribution.Simple.Utils (printRawCommandAndArgsAndEnv) import Distribution.ReadE (readEOrFail) import Distribution.Verbosity (Verbosity, flagToVerbosity, normal) data PackageSpec = PackageSpec { directory :: FilePath , distPref :: Maybe FilePath , configOpts :: [String] } data SuiteConfig = SuiteConfig { ghcPath :: FilePath , ghcPkgPath :: FilePath , cabalDistPref :: FilePath , inplaceSpec :: PackageSpec , packageDBStack :: PackageDBStack } data Success = Failure | ConfigureSuccess | BuildSuccess | HaddockSuccess | InstallSuccess | RegisterSuccess | TestSuccess | BenchSuccess deriving (Eq, Show) data Result = Result { successful :: Bool , success :: Success , outputText :: String } deriving Show nullResult :: Result nullResult = Result True Failure "" ------------------------------------------------------------------------ -- * Running cabal commands recordRun :: (String, ExitCode, String) -> Success -> Result -> Result recordRun (cmd, exitCode, exeOutput) thisSucc res = res { successful = successful res && exitCode == ExitSuccess , success = if exitCode == ExitSuccess then thisSucc else success res , outputText = (if null $ outputText res then "" else outputText res ++ "\n") ++ cmd ++ "\n" ++ exeOutput } cabal_configure :: SuiteConfig -> PackageSpec -> IO Result cabal_configure config spec = do res <- doCabalConfigure config spec record spec res return res doCabalConfigure :: SuiteConfig -> PackageSpec -> IO Result doCabalConfigure config spec = do cleanResult@(_, _, _) <- cabal config spec [] ["clean"] requireSuccess cleanResult res <- cabal config spec [] -- Use the package dbs from when we configured cabal rather than any -- defaults. (["configure", "--user", "-w", ghcPath config, "--package-db=clear"] ++ packageDBParams (packageDBStack config) ++ configOpts spec) return $ recordRun res ConfigureSuccess nullResult packageDBParams :: PackageDBStack -> [String] packageDBParams = map (("--package-db=" ++) . convert) where convert :: PackageDB -> String convert GlobalPackageDB = "global" convert UserPackageDB = "user" convert (SpecificPackageDB path) = path doCabalBuild :: SuiteConfig -> PackageSpec -> IO Result doCabalBuild config spec = do configResult <- doCabalConfigure config spec if successful configResult then do res <- cabal config spec [] ["build", "-v"] return $ recordRun res BuildSuccess configResult else return configResult cabal_build :: SuiteConfig -> PackageSpec -> IO Result cabal_build config spec = do res <- doCabalBuild config spec record spec res return res cabal_haddock :: SuiteConfig -> PackageSpec -> [String] -> IO Result cabal_haddock config spec extraArgs = do res <- doCabalHaddock config spec extraArgs record spec res return res doCabalHaddock :: SuiteConfig -> PackageSpec -> [String] -> IO Result doCabalHaddock config spec extraArgs = do configResult <- doCabalConfigure config spec if successful configResult then do res <- cabal config spec [] ("haddock" : extraArgs) return $ recordRun res HaddockSuccess configResult else return configResult unregister :: SuiteConfig -> String -> IO () unregister config libraryName = do res@(_, _, output) <- run Nothing (ghcPkgPath config) [] ["unregister", "--user", libraryName] if "cannot find package" `isInfixOf` output then return () else requireSuccess res -- | Install this library in the user area cabal_install :: SuiteConfig -> PackageSpec -> IO Result cabal_install config spec = do buildResult <- doCabalBuild config spec res <- if successful buildResult then do res <- cabal config spec [] ["install"] return $ recordRun res InstallSuccess buildResult else return buildResult record spec res return res cabal_register :: SuiteConfig -> PackageSpec -> [String] -> IO Result cabal_register config spec extraArgs = do res <- doCabalRegister config spec extraArgs record spec res return res doCabalRegister :: SuiteConfig -> PackageSpec -> [String] -> IO Result doCabalRegister config spec extraArgs = do configResult <- doCabalConfigure config spec if successful configResult then do buildResult <- doCabalBuild config spec if successful buildResult then do res <- cabal config spec [] ("register" : extraArgs) return $ recordRun res RegisterSuccess configResult else return buildResult else return configResult cabal_test :: SuiteConfig -> PackageSpec -> [(String, Maybe String)] -> [String] -> IO Result cabal_test config spec envOverrides extraArgs = do res <- cabal config spec envOverrides ("test" : extraArgs) let r = recordRun res TestSuccess nullResult record spec r return r cabal_bench :: SuiteConfig -> PackageSpec -> [String] -> IO Result cabal_bench config spec extraArgs = do res <- cabal config spec [] ("bench" : extraArgs) let r = recordRun res BenchSuccess nullResult record spec r return r compileSetup :: SuiteConfig -> FilePath -> IO () compileSetup config packageDir = do r <- run (Just $ packageDir) (ghcPath config) [] [ "--make" -- HPC causes trouble -- see #1012 -- , "-fhpc" , "-package-conf " ++ (cabalDistPref config) </> "package.conf.inplace" , "Setup.hs" ] requireSuccess r -- | Returns the command that was issued, the return code, and the output text. cabal :: SuiteConfig -> PackageSpec -> [(String, Maybe String)] -- ^ environment variable overrides -> [String] -- ^ extra arguments -> IO (String, ExitCode, String) cabal config spec envOverrides cabalArgs_ = do let cabalArgs = case distPref spec of Nothing -> cabalArgs_ Just dist -> ("--builddir=" ++ dist) : cabalArgs_ customSetup <- doesFileExist (directory spec </> "Setup.hs") if customSetup then do compileSetup config (directory spec) path <- canonicalizePath $ directory spec </> "Setup" run (Just $ directory spec) path envOverrides cabalArgs else do -- Use shared Setup executable (only for Simple build types). path <- canonicalizePath "Setup" run (Just $ directory spec) path envOverrides cabalArgs -- | Returns the command that was issued, the return code, and the output text run :: Maybe FilePath -> String -> [(String, Maybe String)] -> [String] -> IO (String, ExitCode, String) run cwd path envOverrides args = do verbosity <- getVerbosity -- path is relative to the current directory; canonicalizePath makes it -- absolute, so that runProcess will find it even when changing directory. path' <- do pathExists <- doesFileExist path canonicalizePath (if pathExists then path else path <.> exeExtension) menv <- getEffectiveEnvironment envOverrides printRawCommandAndArgsAndEnv verbosity path' args menv (readh, writeh) <- createPipe pid <- runProcess path' args cwd menv Nothing (Just writeh) (Just writeh) -- fork off a thread to start consuming the output out <- suckH [] readh hClose readh -- wait for the program to terminate exitcode <- waitForProcess pid let fullCmd = unwords (path' : args) return ("\"" ++ fullCmd ++ "\" in " ++ fromMaybe "" cwd, exitcode, out) where suckH output h = do eof <- hIsEOF h if eof then return (reverse output) else do c <- hGetChar h suckH (c:output) h requireSuccess :: (String, ExitCode, String) -> IO () requireSuccess (cmd, exitCode, output) = unless (exitCode == ExitSuccess) $ assertFailure $ "Command " ++ cmd ++ " failed.\n" ++ "output: " ++ output record :: PackageSpec -> Result -> IO () record spec res = do C.writeFile (directory spec </> "test-log.txt") (C.pack $ outputText res) ------------------------------------------------------------------------ -- * Test helpers assertConfigureSucceeded :: Result -> Assertion assertConfigureSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup configure\' should succeed\n" ++ " output: " ++ outputText result assertBuildSucceeded :: Result -> Assertion assertBuildSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup build\' should succeed\n" ++ " output: " ++ outputText result assertBuildFailed :: Result -> Assertion assertBuildFailed result = when (successful result) $ assertFailure $ "expected: \'setup build\' should fail\n" ++ " output: " ++ outputText result assertHaddockSucceeded :: Result -> Assertion assertHaddockSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup haddock\' should succeed\n" ++ " output: " ++ outputText result assertTestSucceeded :: Result -> Assertion assertTestSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup test\' should succeed\n" ++ " output: " ++ outputText result assertTestFailed :: Result -> Assertion assertTestFailed result = when (successful result) $ assertFailure $ "expected: \'setup test\' should fail\n" ++ " output: " ++ outputText result assertInstallSucceeded :: Result -> Assertion assertInstallSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup install\' should succeed\n" ++ " output: " ++ outputText result assertRegisterSucceeded :: Result -> Assertion assertRegisterSucceeded result = unless (successful result) $ assertFailure $ "expected: \'setup register\' should succeed\n" ++ " output: " ++ outputText result assertRegisterFailed :: Result -> Assertion assertRegisterFailed result = when (successful result) $ assertFailure $ "expected: \'setup register\' should fail\n" ++ " output: " ++ outputText result assertOutputContains :: String -> Result -> Assertion assertOutputContains needle result = unless (needle `isInfixOf` (concatOutput output)) $ assertFailure $ " expected: " ++ needle ++ "\n" ++ " in output: " ++ output ++ "" where output = outputText result assertOutputDoesNotContain :: String -> Result -> Assertion assertOutputDoesNotContain needle result = when (needle `isInfixOf` (concatOutput output)) $ assertFailure $ "unexpected: " ++ needle ++ " in output: " ++ output where output = outputText result -- | Replace line breaks with spaces, correctly handling "\r\n". concatOutput :: String -> String concatOutput = unwords . lines . filter ((/=) '\r') ------------------------------------------------------------------------ -- Verbosity lookupEnv :: String -> IO (Maybe String) lookupEnv name = (fmap Just $ getEnv name) `E.catch` \ (e :: IOError) -> if isDoesNotExistError e then return Nothing else E.throw e -- TODO: Convert to a "-v" flag instead. getVerbosity :: IO Verbosity getVerbosity = do maybe normal (readEOrFail flagToVerbosity) `fmap` lookupEnv "VERBOSE"
enolan/cabal
Cabal/tests/PackageTests/PackageTester.hs
bsd-3-clause
13,245
0
16
3,160
3,274
1,692
1,582
298
3
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE LiberalTypeSynonyms #-} {-# LANGUAGE ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Main (properties) -- Copyright : (C) 2012-14 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- This module provides a set of QuickCheck properties that can be run through -- test-framework to validate a number of expected behaviors of the library. ----------------------------------------------------------------------------- module Main where import Control.Applicative import Control.Lens import Test.QuickCheck import Test.QuickCheck.Function import Test.Framework.TH import Test.Framework.Providers.QuickCheck2 import Data.Char (isAlphaNum, isAscii, toUpper) import Data.Text.Strict.Lens import Data.Maybe import Data.List.Lens import Data.Functor.Compose import Numeric (showHex, showOct, showSigned) import Numeric.Lens import Control.Lens.Properties (isIso, isLens, isPrism, isSetter, isTraversal) -- an illegal lens bad :: Lens' (Int,Int) Int bad f (a,b) = (,) b <$> f a badIso :: Iso' Int Bool badIso = iso even fromEnum -- Control.Lens.Type prop_1 = isLens (_1 :: Lens' (Int,Double,()) Int) prop_2 = isLens (_2 :: Lens' (Int,Bool) Bool) prop_3 = isLens (_3 :: Lens' (Int,Bool,()) ()) prop_4 = isLens (_4 :: Lens' (Int,Bool,(),Maybe Int) (Maybe Int)) prop_5 = isLens (_5 :: Lens' ((),(),(),(),Int) Int) prop_2_2 = isLens (_2._2 :: Lens' (Int,(Int,Bool),Double) Bool) -- prop_illegal_lens = expectFailure $ isLens bad -- prop_illegal_traversal = expectFailure $ isTraversal bad -- prop_illegal_setter = expectFailure $ isSetter bad -- prop_illegal_iso = expectFailure $ isIso badIso -- Control.Lens.Setter prop_mapped = isSetter (mapped :: Setter' [Int] Int) prop_mapped_mapped = isSetter (mapped.mapped :: Setter' [Maybe Int] Int) prop_both = isTraversal (both :: Traversal' (Int,Int) Int) prop_traverseLeft = isTraversal (_Left :: Traversal' (Either Int Bool) Int) prop_traverseRight = isTraversal (_Right :: Traversal' (Either Int Bool) Bool) prop_simple = isIso (simple :: Iso' Int Int) --prop_enum = isIso (enum :: Iso' Int Char) prop__Left = isPrism (_Left :: Prism' (Either Int Bool) Int) prop__Right = isPrism (_Right :: Prism' (Either Int Bool) Bool) prop__Just = isPrism (_Just :: Prism' (Maybe Int) Int) -- Data.List.Lens prop_prefixed s = isPrism (prefixed s :: Prism' String String) -- Data.Text.Lens prop_text s = s^.packed.from packed == s --prop_text = isIso packed -- Numeric.Lens prop_base_show (n :: Integer) = conjoin [ show n == n ^. re (base 10) , showSigned showOct 0 n "" == n ^. re (base 8) , showSigned showHex 0 n "" == n ^. re (base 16) ] prop_base_read (n :: Integer) = conjoin [ show n ^? base 10 == Just n , showSigned showOct 0 n "" ^? base 8 == Just n , showSigned showHex 0 n "" ^? base 16 == Just n , map toUpper (showSigned showHex 0 n "") ^? base 16 == Just n ] prop_base_readFail (s :: String) = forAll (choose (2,36)) $ \b -> not isValid ==> s ^? base b == Nothing where isValid = (not . null) sPos && all isValidChar sPos sPos = case s of { ('-':s') -> s'; _ -> s } isValidChar c = isAscii c && isAlphaNum c main :: IO () main = $defaultMainGenerator
rpglover64/lens
tests/properties.hs
bsd-3-clause
4,134
0
11
1,223
1,065
582
483
-1
-1
<?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="en-GB"> <title>Passive Scan Rules | ZAP Extension</title> <maps> <homeID>top</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>
kamiNaranjo/zap-extensions
src/org/zaproxy/zap/extension/pscanrules/resources/help/helpset.hs
apache-2.0
992
82
67
173
425
217
208
-1
-1
{-# LANGUAGE Safe #-} -- | This module contains functions and data used for building -- a game of TicTacToe. module Game.TicTacToe where import Data.Array (Array, listArray, (//), elems, (!), indices) import Data.List (transpose, find, nub) import Data.List.Split (chunksOf) import Data.Maybe (isJust, fromJust, isNothing) -- | Representation of the current state of the game. data GameState = GameState { player :: Player , board :: Board , phase :: GamePhase } deriving Show -- | Representation of the current phase the game is in. data GamePhase = InProgress | Won Player | Draw deriving (Eq, Show) -- | Representation of each player in the game. data Player = X | O deriving (Show, Eq, Enum) -- | Replacement for default Enum's succ -- allowing for Player values to wrap. succWrap :: Player -> Player succWrap O = X succWrap p = succ p -- | The representation of the squares of the TicTacToe board. type Board = Array Position Square -- | Representation of a square of the board. -- A square either has Nothing on it or single -- player's piece. type Square = Maybe Player -- | Coordinate type for board positions. type Position = (Int, Int) -- | A blank game state representing the initial -- state of a game of TicTacToe. newGame :: GameState newGame = GameState X emptyBoard InProgress -- | A 3x3 array of Squares representing a board with -- no pieces placed on it. emptyBoard :: Board emptyBoard = listArray ((1,1),(3,3)) . replicate 9 $ Nothing -- | This operator attempts to place a player's piece -- on the board and returns the updated game state -- if it succeeds. (/?/) :: GameState -> Position -> Maybe GameState gs /?/ p | validPosition = Just . updateGamePhase $ gs { board = board gs // [(p, Just $ player gs)] , player = succWrap $ player gs } | otherwise = Nothing where validPosition = inProgress gs -- game in progress && (elem p . indices $ board gs) -- position is on board && isNothing (board gs ! p) -- square not taken -- | Evaluates a GameState to determine what the next game state -- should be based on its board state. updateGamePhase :: GameState -> GameState updateGamePhase gameState = case maybeFullRows gameState of Just xs -> gameState { phase = Won . fromJust . head $ xs } Nothing -> if boardFull gameState then gameState { phase = Draw } else gameState { phase = InProgress } where boardFull = notElem Nothing . elems . board maybeFullRows = find full . rows . board toLists = chunksOf 3 . elems full xs = (length . nub) xs == 1 && (isJust . head) xs rows b = toLists b ++ (transpose . toLists) b ++ diagonals b diagonals b = [ [b ! (1,1), b ! (2,2), b ! (3,3)] , [b ! (3,1), b ! (2,2), b ! (1,3)] ] -- | Determines if the game is currently in progress or not. inProgress :: GameState -> Bool inProgress (GameState _ _ InProgress) = True inProgress _ = False
Wollw/TicTacToe-HS
src/Game/TicTacToe.hs
isc
3,241
0
13
960
775
439
336
-1
-1
module Game.Callbacks where import Graphics.UI.GLUT import Data.IORef import Coroutine import Game.DeltaClock import Game.Keyboard import Game.Game (Game) import Game.Rendering type ClockRef = IORef DeltaClock type GameRef = IORef Game type KeyboardRef = IORef Keyboard type CallbackRefs = (ClockRef, KeyboardRef, GameRef) display :: CallbackRefs -> DisplayCallback display (cr, kb, gr) = do clear [ColorBuffer] keyboard <- get kb game <- get gr delta <- getDelta cr let (rects, nextGame) = runC game (keyboard, delta) writeIORef gr nextGame mapM_ renderShape rects flush postRedisplay Nothing handleKeyboard :: CallbackRefs -> KeyboardMouseCallback handleKeyboard (_, kb, _) k ks _ _ = modifyIORef kb (handleKeyEvent k ks)
sgrif/haskell-game
Game/Callbacks.hs
mit
752
0
11
128
251
132
119
25
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Applicative import Snap.Core import Snap.Util.FileServe import Snap.Http.Server import Snap.Util.FileUploads import qualified Data.Enumerator.List as EL import Control.Monad (liftM) import Control.Applicative ((<$>)) import qualified Data.ByteString.UTF8 as BS8 (toString, fromString) import qualified Data.ByteString as BS (readFile, ByteString(..), pack, writeFile, concat) import Control.Monad.IO.Class (liftIO) import Data.Text.Encoding (encodeUtf8) import qualified Data.Text as T (pack) import System.Directory (getDirectoryContents, getCurrentDirectory) import System.FilePath.Posix ((</>)) import RawRGB main :: IO () main = quickHttpServe site site :: Snap () site = ifTop (method GET homeHandler) <|> -- / dir "static" (serveDirectory ".") <|> -- /static/FILE route [ ("picCount", picInfoHandler) , ("upload" , uploadHandler) , ("convert", convertHandler) -- ("instagram/:user", instagramHandler) ] homeHandler :: Snap () homeHandler = writeBS "#This is my first Snap Server!" picInfoHandler :: Snap () picInfoHandler = do content <- liftIO $ getCurrentDirectory >>= \fp -> getDirectoryContents (fp </> "raw") let elements = filter (`notElem` [".", ".."]) content let elementsf = map (\x -> '#' : x ++ "\n") elements writeBS $ encodeUtf8 $ T.pack $ '#' : show ((length elements) - 1) ++ '\n' : concat elementsf convertHandler :: Snap () convertHandler = do elements <- liftIO $ do convertJpgDirToBMP "jpg" "raw" convertBmpDirToTxt "raw" "raw" removeWithExtentionAt "raw" ".bmp" filter (`notElem` [".", ".."]) <$> getDirectoryContents "raw" writeBS $ encodeUtf8 $ T.pack $ '#' : show (length elements) uploadHandler :: Snap () uploadHandler = method POST uploadPost <|> error405 uploadPost :: Snap () uploadPost = do --files <- handleMultipart defaultUploadPolicy $ \part -> do -- content <- liftM BS.concat EL.consume -- return (part, content) --saveFiles files mcount <- getPostParam "count" mbs <- getPostParam "bytestring" case (mcount, mbs) of (Just count, Just bs) -> do liftIO $ putStrLn $ BS8.toString count -- let name = BS8.toString count -- saveFile ((undefined, bs), name) -- liftIO $ jpgToBMP (name ++ ".jpg") (_) -> return () -- saveFiles :: [(PartInfo, ByteString)] -> Snap () -- saveFiles fs = mapM_ saveFile (zip fs [0..]) saveFile :: ((PartInfo, BS.ByteString), String) -> Snap () saveFile ((_, bs), count) = liftIO $ BS.writeFile (count ++ ".jpg") bs error405 = genericError 405 "Method Not Allowed" genericError :: Int -> String -> Snap () genericError c s = do modifyResponse $ setResponseStatus c $ BS8.fromString s writeText $ T.pack ((show c) ++ " - " ++ s) r <- getResponse finishWith r -- instagramHandler :: Snap () -- instagramHandler = do -- user <- getParam "user" -- let url = "http://iconosquare.com/feed/" ++ (BS8.toString (fromJust user)) -- urls <- liftIO (getUserPics url) -- mapM_ writeText urls --maybe (writeBS "must specify echo/param in URL") -- writeBS -- param
cirquit/Personal-Repository
Haskell/arduino-webserver/app/Main.hs
mit
3,301
0
14
746
846
465
381
62
2
import Data.List (permutations) import Data.Set (fromList, elems, union) main = do print $ sum $ elems $ fromList ((products s144) ++ (products s234)) where products splitter = [c | (a, b, c) <- map splitter ps, a*b==c] s144 ([x1, x2, x3, x4, x5, x6, x7, x8, x9]) = ( x1, ((x2*10+x3)*10+x4)*10+x5, ((x6*10+x7)*10+x8)*10+x9) s234 ([x1, x2, x3, x4, x5, x6, x7, x8, x9]) = (x1*10+x2, (x3*10+x4)*10+x5, ((x6*10+x7)*10+x8)*10+x9) ps = permutations [1..9]
dpieroux/euler
0/0032.hs
mit
501
0
15
121
340
191
149
8
1
import System.Environment import Data.List --import Data.Maybe import AStar import Parser import NPuzzle import Heuristics main :: IO () main = do args <- getArgs if length args /= 1 then putStrLn "Usage: ./graphi file/path" else do content <- readFile (head args) case parseGrid (head args) content of Left err -> print err Right grid -> do putStr content putStrLn "--solution--" let goal = generateGoal $ intRoot $ length grid let path = aStarSearch expand cost (manhattan goal) (== goal) (toArray grid) putStr $ maybe "No path available\n" showPath path showPath :: [Grid] -> String showPath = foldl' (\str state -> str ++ showGrid state ++ "\n") "" intRoot :: Int -> Int intRoot = truncate . sqrt . (fromIntegral :: Int -> Double)
Shakadak/n-puzzle
Main.hs
mit
960
0
20
348
279
138
141
23
3
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Tests.GB2.Primitive where import Test.Framework import GB2.Primitive import GB2.Geometry import Control.Applicative -- ##################################### -- Vector Tests -- ##################################### -- ##### QuickCheck ##### -- ##### HUnit ##### -- # Normals test_normal_sphere1 = assertEqual (Vector 1 0 0) (primitiveNormal (Sphere 10 (Vector 0 0 0)) (Vector 10 0 0)) test_normal_sphere2 = assertEqual (Vector 0 0 1) (primitiveNormal (Sphere 10 (Vector 1 2 3)) (Vector 1 2 13)) test_normal_sphere3 = assertEqual (Vector 0 (-1) 0) (primitiveNormal (Sphere 10 (Vector (-7) 23 12)) (Vector (-7) 20 12)) test_normal_triangle = assertEqual (Vector 0 0 1) (primitiveNormal (Triangle (Vector 0 0 0) (Vector 1 0 0) (Vector 0 1 0)) undefined) -- # Intersection Primitives simpleSphere = Sphere 10 (Vector 1 0 0) test_interect_sphere = assertEqual (Just 10) ( rayPrimitiveIntersectDistance (Ray (Vector 1 0 0) (Vector 0 0 1)) simpleSphere) -- fails because intersection is < 0 test_interect_sphere_fail = assertEqual (Nothing) ( rayPrimitiveIntersectDistance (Ray (Vector 100 0 0) (Vector 0 0 1)) simpleSphere) -- fails because not intersection test_interect_sphere_fail2 = assertEqual (Nothing) ( rayPrimitiveIntersectDistance (Ray (Vector 12 0 0) (Vector 0 0 1)) simpleSphere) test_intersect_triangle = assertEqual (Just 10) ( rayPrimitiveIntersectDistance (Ray (Vector 0.2 0.2 (-10)) (Vector 0 0 1)) (Triangle (Vector 0 0 0) (Vector 1 0 0) (Vector 0 1 0)) ) -- fails because no intersection test_intersect_triangle_fail = assertEqual Nothing ( rayPrimitiveIntersectDistance (Ray (Vector (-5) 0.2 (-10)) (Vector 0 0 1)) (Triangle (Vector 0 0 0) (Vector 1 0 0) (Vector 0 1 0)) ) -- fails because it < 0 test_intersect_triangle_fail2 = assertEqual Nothing ( rayPrimitiveIntersectDistance (Ray (Vector 0.2 0.2 1) (Vector 0 0 1)) (Triangle (Vector 0 0 0) (Vector 1 0 0) (Vector 0 1 0)) )
gbataille/halray
test/Tests/GB2/Primitive.hs
mit
2,326
0
13
675
739
383
356
35
1
{-# LANGUAGE BangPatterns #-} module Geometry.Randomish ( randomishPoints , randomishInts , randomishDoubles) where import Data.Word import qualified Data.Vector.Generic as G import qualified Data.Vector.Unboxed.Mutable as MV import qualified Data.Vector.Unboxed as V -- | Some uniformly distributed points randomishPoints :: Int -- ^ seed -> Int -- ^ number of points -> Float -- ^ minimum coordinate -> Float -- ^ maximum coordinate -> V.Vector (Float, Float) randomishPoints seed' n pointMin pointMax = let pts = randomishFloats (n*2) pointMin pointMax seed' xs = G.slice 0 n pts ys = G.slice n n pts in V.zip xs ys -- | Use the "minimal standard" Lehmer generator to quickly generate some random -- numbers with reasonable statistical properties. By "reasonable" we mean good -- enough for games and test data, but not cryptography or anything where the -- quality of the randomness really matters. -- -- From "Random Number Generators: Good ones are hard to find" -- Stephen K. Park and Keith W. Miller. -- Communications of the ACM, Oct 1988, Volume 31, Number 10. -- randomishInts :: Int -- Length of vector. -> Int -- Minumum value in output. -> Int -- Maximum value in output. -> Int -- Random seed. -> V.Vector Int -- Vector of random numbers. randomishInts !len !valMin' !valMax' !seed' = let -- a magic number (don't change it) multiplier :: Word64 multiplier = 16807 -- a merzenne prime (don't change it) modulus :: Word64 modulus = 2^(31 :: Integer) - 1 -- if the seed is 0 all the numbers in the sequence are also 0. seed | seed' == 0 = 1 | otherwise = seed' !valMin = fromIntegral valMin' !valMax = fromIntegral valMax' + 1 !range = valMax - valMin {-# INLINE f #-} f x = multiplier * x `mod` modulus in G.create $ do vec <- MV.new len let go !ix !x | ix == len = return () | otherwise = do let x' = f x MV.write vec ix $ fromIntegral $ (x `mod` range) + valMin go (ix + 1) x' go 0 (f $ f $ f $ fromIntegral seed) return vec -- | Generate some randomish doubles with terrible statistical properties. -- This is good enough for test data, but not much else. randomishDoubles :: Int -- Length of vector -> Double -- Minimum value in output -> Double -- Maximum value in output -> Int -- Random seed. -> V.Vector Double -- Vector of randomish doubles. randomishDoubles !len !valMin !valMax !seed = let range = valMax - valMin mx = 2^(30 :: Integer) - 1 mxf = fromIntegral mx ints = randomishInts len 0 mx seed in V.map (\n -> valMin + (fromIntegral n / mxf) * range) ints -- | Generate some randomish doubles with terrible statistical properties. -- This is good enough for test data, but not much else. randomishFloats :: Int -- Length of vector -> Float -- Minimum value in output -> Float -- Maximum value in output -> Int -- Random seed. -> V.Vector Float -- Vector of randomish doubles. randomishFloats !len !valMin !valMax !seed = let range = valMax - valMin mx = 2^(30 :: Integer) - 1 mxf = fromIntegral mx ints = randomishInts len 0 mx seed in V.map (\n -> valMin + (fromIntegral n / mxf) * range) ints
gscalzo/HaskellTheHardWay
gloss-try/gloss-master/gloss-examples/picture/Visibility/Geometry/Randomish.hs
mit
3,236
116
11
762
749
432
317
75
1
module Problem9 where main :: IO () main = print $ head [a*b*(1000 - a - b) | b <- [1..499], a <- [1..b-1], a^2 + b^2 == (1000 - a - b)^2]
DevJac/haskell-project-euler
src/Problem9.hs
mit
213
0
13
107
113
60
53
6
1
module H99.Q1to10 ( tests1to10, encode ) where import Test.Tasty import Test.Tasty.HUnit as HU --import Test.HUnit.Tools (assertRaises) {-| Problem 1. Find the last element of a list. -} myLast :: [a] -> a myLast [] = error "No such element" myLast (x:[]) = x myLast (_:xs) = myLast xs problem1 :: TestTree problem1 = testGroup "Problem 1" [ testCase "myLast [1,2,3,4]" $ myLast [1,2,3,4] @?= 4 , testCase "myLast ['x','y','z']" $ myLast "xyz" @?= 'z' ] {-| Problem 2. Find the last but one element of a list. -} myButLast :: [a] -> a myButLast [] = error "No such element" myButLast [x] = error "No such element" myButLast [x, y] = x myButLast (x:xs) = myButLast xs problem2 :: TestTree problem2 = testGroup "Problem 2" [ testCase "myButLast [1,2,3,4]" $ myButLast [1,2,3,4] @?= 3 , testCase "myButLast ['a'..'z']" $ myButLast ['a'..'z'] @?= 'y' --, testCase "myButLast []" $ -- assertRaises "should throw" (Exception "No such element") $ evaluate myButLast [] ] {-| Problem 3. Find the K'th element of a list. The first element in the list is number 1. -} elementAt :: [a] -> Int -> a elementAt [] _ = error "No such element" elementAt (x:xs) 1 = x elementAt (x:xs) n = elementAt xs (n - 1) problem3 :: TestTree problem3 = testGroup "Problem 3" [ testCase "elementAt [1,2,3] 2" $ elementAt [1,2,3] 2 @?= 2 , testCase "elementAt \"haskell\" 5" $ elementAt "haskell" 5 @?= 'e' ] {-| Problem 4. Find the number of elements of a list. -} myLength :: [a] -> Int myLength [] = 0 myLength (_:xs) = 1 + myLength xs problem4 :: TestTree problem4 = testGroup "Problem 4" [ testCase "myLength [123, 456, 789]" $ myLength [123, 456, 789] @?= 3 , testCase "myLength \"Hello, world!\"" $ myLength "Hello, world!" @?= 13 ] {-| Problem 5. Reverse a list. -} myReverse :: [a] -> [a] myReverse [] = [] myReverse (x:xs) = myReverse xs ++ [x] problem5 :: TestTree problem5 = testGroup "Problem 5" [ testCase "myReverse \"A man, a plan, a canal, panama!\"" $ myReverse "A man, a plan, a canal, panama!" @?= "!amanap ,lanac a ,nalp a ,nam A" , testCase "myReverse [1,2,3,4]" $ myReverse [1,2,3,4] @?= [4,3,2,1] ] {-| Problem 6. Find the number of elements of a list. -} isPalindrome :: (Eq a) => [a] -> Bool isPalindrome xs = xs == myReverse xs problem6 :: TestTree problem6 = testGroup "Problem 6" [ testCase "isPalindrome [1,2,3]" $ isPalindrome [1,2,3] @?= False , testCase "isPalindrome \"madamimadam\"" $ isPalindrome "madamimadam" @?= True , testCase "isPalindrome [1,2,4,8,16,8,4,2,1]" $ isPalindrome [1,2,4,8,16,8,4,2,1] @?= True , testCase "isPalindrome []" $ isPalindrome ([] :: [Int]) @?= True , testCase "isPalindrome [1]" $ isPalindrome [1] @?= True ] {-| Problem 7. Flatten a nested list structure. -} data NestedList a = Elem a | List [NestedList a] flatten :: NestedList a -> [a] flatten (Elem x) = [x] flatten (List xs) = foldl (\accu x -> accu ++ flatten x) [] xs problem7 :: TestTree problem7 = testGroup "Problem 7" [ testCase "flatten (Elem 5)" $ flatten (Elem 5) @?= [5] , testCase "flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])" $ flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]]) @?= [1,2,3,4,5] , testCase "flatten (List [])" $ flatten (List [] :: NestedList Char) @?= [] ] {-| Problem 8. Eliminate consecutive duplicates of list elements. -} compress :: (Eq a) => [a] -> [a] compress [] = [] compress (x:[]) = [x] compress (fst:sec:rest) | fst == sec = remaining | otherwise = fst : remaining where remaining = compress $ sec : rest problem8 :: TestTree problem8 = testGroup "Problem 8" [ testCase "compress \"aaaabccaadeeee\"" $ compress "aaaabccaadeeee" @?= "abcade" , testCase "compress [1]" $ compress [1] @?= [1] , testCase "compress []" $ compress ([] :: [Int]) @?= [] ] {-| Problem 9. Pack consecutive duplicates of list elements into sublists. If a list contains repeated elements they should be placed in separate sublists. -} pack :: (Eq a) => [a] -> [[a]] pack xs = foldr grp [[]] xs where grp e [[]] = [[e]] grp e (curList@(h:t):ys) | h == e = (e:curList):ys | otherwise = [e]:curList:ys problem9 :: TestTree problem9 = testGroup "Problem 9" [ testCase "pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']" $ pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] @?= ["aaaa","b","cc","aa","d","eeee"] , testCase "pack [1]" $ pack [1] @?= [[1]] , testCase "pack []" $ pack ([] :: [Int]) @?= [[]] ] {-| Problem 10. Run-length encoding of a list. Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E. -} encode :: (Eq a) => [a] -> [(Int, a)] encode xs = [ (myLength l, h) | l@(h:t) <- pack xs] problem10 :: TestTree problem10 = testGroup "Problem 10" [ testCase "encode ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']" $ encode ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e'] @?= [(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')] , testCase "encode [1]" $ encode [1] @?= [(1, 1)] , testCase "encode []" $ encode ([] :: [Int]) @?= [] ] tests1to10 :: TestTree tests1to10 = testGroup "Q1 - 10" [ problem1, problem2, problem3, problem4, problem5, problem6, problem7, problem8, problem9, problem10 ]
izmailoff/haskell-h99
src/H99/Q1to10.hs
mit
7,445
0
17
3,060
1,887
1,032
855
115
2
{-# LANGUAGE OverloadedStrings #-} module Gradebot where import qualified Data.Map as M import Control.Applicative import qualified Data.ByteString.Lazy as BL import Data.Csv import qualified Data.Vector as V import Data.Maybe import Data.Either.Unwrap import Data.List type Code = String data CodeBlock = CodeBlock { cb_code :: Code, cb_comment :: Maybe String } deriving (Show) data GradeRecord = GradeRecord { gr_name :: String , gr_Ambiguity :: Maybe String , gr_Code_1 :: Maybe String , gr_Code_2 :: Maybe String , gr_Code_3 :: Maybe String , gr_Code_4 :: Maybe String , gr_Code_5 :: Maybe String , gr_Code_6 :: Maybe String , gr_Code_7 :: Maybe String , gr_CC_1 :: Maybe String , gr_CC_2 :: Maybe String , gr_CC_3 :: Maybe String , gr_CC_4 :: Maybe String , gr_CC_5 :: Maybe String , gr_CC_6 :: Maybe String , gr_CC_7 :: Maybe String , gr_Misc_Comment :: Maybe String } deriving (Show) data IndivCode = IndivCode { ic_code :: Code , ic_title :: String , ic_text :: String , ic_points :: Double , ic_qnum :: Int } deriving (Show) type GMap = M.Map Code IndivCode data Student = Student { studentName :: String , studentID :: Int } deriving (Show) data QFeedback = QFeedback { questionNum :: Int , questionCodes :: [CodeBlock] , questionMiscComment :: Maybe String , questionAmbiguity :: Maybe String } deriving (Show) data SFeedback = SFeedback { sf_student :: Student, sf_qfeedback :: [QFeedback] } deriving (Show) ---------------------------------------- -- parsing gradeRecords instance FromNamedRecord GradeRecord where parseNamedRecord r = GradeRecord <$> r .: "Name" <*> r .: "Ambiguity" <*> r .: "Code_1" <*> r .: "Code_2" <*> r .: "Code_3" <*> r .: "Code_4" <*> r .: "Code_5" <*> r .: "Code_6" <*> r .: "Code_7" <*> r .: "CC_1" <*> r .: "CC_2" <*> r .: "CC_3" <*> r .: "CC_4" <*> r .: "CC_5" <*> r .: "CC_6" <*> r .: "CC_7" <*> r .: "Misc_Comment" parseFname :: BL.ByteString -> Either String [GradeRecord] parseFname csvData = case decodeByName csvData of Left err -> Left err Right (_, v) -> Right (V.toList v) makeCodeTuples :: GradeRecord -> [CodeBlock] makeCodeTuples gri = cb_list where cb_raw = [(gr_Code_1 gri, gr_CC_1 gri), (gr_Code_2 gri, gr_CC_2 gri), (gr_Code_3 gri, gr_CC_3 gri), (gr_Code_4 gri, gr_CC_4 gri), (gr_Code_5 gri, gr_CC_5 gri), (gr_Code_6 gri, gr_CC_6 gri), (gr_Code_7 gri, gr_CC_7 gri)] has_code = filter (\a -> isJust $ fst a) cb_raw filtered = map (\a -> (fromJust $ fst a, snd a) ) has_code cb_list = map (\(a,b) -> CodeBlock a b) filtered makeQF :: GradeRecord -> Int -> QFeedback makeQF gri qnum = qf where qf = QFeedback qnum (makeCodeTuples gri) (gr_Misc_Comment gri) (gr_Ambiguity gri) makeStudent :: GradeRecord -> Student makeStudent gri = Student (gr_name gri) 123456 processGR :: GradeRecord -> Int -> SFeedback processGR gri qnum = SFeedback (makeStudent gri) [(makeQF gri qnum)] addQF :: SFeedback -> QFeedback -> SFeedback addQF sf qf = sf { sf_qfeedback = qf : sf_qfeedback sf } -------------------------------------------------------------------------------- stringifyCodeBlockHelper :: CodeBlock -> String stringifyCodeBlockHelper cb = out where out = "CODE: " ++ (cb_code cb) ++ " COMMENT: " ++ (fromMaybe "NONE" (cb_comment cb)) stringifyCodeBlock :: [CodeBlock] -> [String] stringifyCodeBlock codes | n == 0 = [] | otherwise = out where n = length codes out = map stringifyCodeBlockHelper codes codeLookupWithDefault :: [CodeBlock] -> GMap -> [IndivCode] codeLookupWithDefault codes myGMap = indivs where codelist = map (\cb -> cb_code cb) codes indivlist = map (\cb -> M.lookup cb myGMap) codelist indivs = map (fromMaybe defaultIndivCode) indivlist ---------------------------------------- -- fix this to work for multiple questions makeReport :: SFeedback -> Int -> String makeReport sf qn = rstr where st = sf_student sf qf = sf_qfeedback sf !! 0 codes = questionCodes qf l1 = "STUDENT: " ++ studentName st l2 = "QUESTION: " ++ show qn l3 = "N CODES: " ++ show (length codes) l4 = unlines $ stringifyCodeBlock codes rstr = unlines [l1, l2, l3, l4] ---------------------------------------- showIC :: IndivCode -> String showIC ic = str where l1 = " CODE DESCR: " ++ ic_code ic l2 = " TITLE: " ++ ic_title ic l3 = " TEXT: " ++ ic_text ic l4 = " POINTS: " ++ show (ic_points ic) l5 = " QNUM: " ++ show (ic_qnum ic) str = unlines [l1, l2, l3, l4, l5] showICfancy :: CodeBlock -> IndivCode -> String showICfancy cb ic = str where l1 = " CODE DESCR: " ++ ic_code ic l2 = " " ++ ic_title ic l3 = " " ++ ic_text ic l4 = " POINTS: " ++ show (ic_points ic) cstr = fromMaybe "" (cb_comment cb) l5 = if cstr == "" then "" else (" COMMENT: " ++ cstr) -- l5 = " COMMENT: " ++ str = unlines [l1,l2, l3, l4, l5] makeCodeReport :: SFeedback -> GMap -> String makeCodeReport sf myGMap = rstr where st = sf_student sf qf = sf_qfeedback sf !! 0 codes = questionCodes qf iclist = codeLookupWithDefault codes myGMap rstr = unlines $ map showIC iclist makeCodeReport_Q :: QFeedback -> GMap -> String makeCodeReport_Q qf myGMap = rstr where codes = questionCodes qf l1 = "Question: " ++ show (questionNum qf) iclist = codeLookupWithDefault codes myGMap rstr = unlines $ (++) [l1] (zipWith showICfancy codes iclist) outerReport :: [GradeRecord] -> Int -> GMap -> String outerReport grlist qnum myGMap = out where sflist = map (\a -> processGR a qnum) grlist outlist = map (\a -> makeReport a qnum) sflist codereplist = map (\a -> makeCodeReport a myGMap) sflist seplist = replicate (length outlist) "--------------------------------------------------------------------------------" out = unlines $ merge [outlist, codereplist, seplist] make_full_SF :: [([GradeRecord],Int)] -> [SFeedback] make_full_SF gr_list = sf_out where process gr_i qnum = map (\a -> processGR a qnum) gr_i sf_list = map (\(g,i) -> process g i) gr_list sf_out = mergeSFLists sf_list -- studentReport takes the list of parsed GradeRecords, and the -- mapping per question -- and the code mapping, and returns a report of the form: -- -- STUDENT: -- -Q1, Q2 studentReport :: SFeedback -> GMap -> String studentReport sf myGMap = out where st = sf_student sf l0 = "--------------------------------------------------------------------------------" l1 = "STUDENT: " ++ studentName st qf_list = sf_qfeedback sf l2 = unlines $ map (\a -> indivQuestionReport a myGMap) qf_list l3 = groupQuestionReport qf_list myGMap out = unlines [l0, l1, l2, l3] indivQuestionReport :: QFeedback -> GMap -> String indivQuestionReport = makeCodeReport_Q groupQuestionReport :: [QFeedback] -> GMap -> String groupQuestionReport qf_list myGMap = rstr where allcodes = map (\q -> codeLookupWithDefault (questionCodes q) myGMap) qf_list sum_pts icl = sum $ map ic_points icl points_per_q = map sum_pts allcodes l1 = "Total deductions: " ++ show (sum $ points_per_q) rstr = l1 ---------------------------------------- instance FromNamedRecord IndivCode where parseNamedRecord r = IndivCode <$> r .: "Code" <*> r .: "Title" <*> r .: "Text" <*> r .: "Points" <*> r .: "Qnum" parseCodeFile :: BL.ByteString -> Either String [IndivCode] parseCodeFile codeData = case decodeByName codeData of Left err -> Left err Right (_, v) -> Right (V.toList v) makeGMap :: [IndivCode] -> GMap makeGMap iclist = themap where mylist = map (\a -> ic_code a) iclist themap = M.fromList $ zip mylist iclist merge = concat . transpose defaultIndivCode = IndivCode "INVALID LOOKUP" "--" "--" (-99.0) 0 -- merge2parlist :: [SFeedback] -> [SFeedback] -> SFeedback -- merge2parlist a b = ab -- where -- n = length a -- ab = map (\i -> addQF (a !! i) (sf_qfeedback (b !! i))) [0..(n-1)] -- this merges the SF, taking care to merge their lists mergeSF :: SFeedback -> SFeedback -> SFeedback mergeSF a b = a { sf_qfeedback = (sf_qfeedback a) ++ (sf_qfeedback b) } -- assumes that this length > 1, and that all lists have the same length mergeSFLists :: [[SFeedback]] -> [SFeedback] mergeSFLists sfl = sf_final where sf_first = head sfl n = length sf_first per_student_lists = map (\i -> (fmap (!! i) sfl)) [0..(n-1)] widemerge x = foldl mergeSF (head x) (tail x) sf_final = map widemerge per_student_lists ---------------------------------------- main :: IO () main = do csvData <- BL.readFile "graded-1-export.csv" let glist = parseFname csvData let gr1 = fromRight glist csvData <- BL.readFile "graded-2-export.csv" let glist2 = parseFname csvData let gr2 = fromRight glist2 csvData <- BL.readFile "graded-3-export.csv" let glist3 = parseFname csvData let gr3 = fromRight glist3 csvData <- BL.readFile "graded-4-export.csv" let glist4 = parseFname csvData let gr4 = fromRight glist4 codeData <- BL.readFile "full-error-codes-v2.csv" let codeObj = parseCodeFile codeData let myGMap = makeGMap (fromRight codeObj) let gr_list = [(gr1,1), (gr2,2), (gr3,3), (gr4,4)] let x = make_full_SF gr_list let strs = map (\student -> studentReport student myGMap) x let fname = "final-report.txt" writeFile fname (unlines strs) print "Done" -- parseCodes :: String -> GMap -- parseCodes fname = gmap -- where -- case glist of -- Left err -> putStrLn err -- Right grs -> print $ outerReport grs 1 myGMap -- case glist2 of -- Left err -> putStrLn err -- Right grs -> print $ outerReport grs 3 myGMap -- case glist3 of -- Left err -> putStrLn err -- Right grs -> print $ outerReport grs 3 myGMap -- case glist4 of -- Left err -> putStrLn err -- Right grs -> print $ outerReport grs 4 myGMap
stephenjbarr/gradebot
Gradebot.hs
mit
10,608
0
39
2,800
3,019
1,605
1,414
213
2
-- Problems/Problem027.hs module Problems.Problem027 (p27) where import Helpers.Primes main = print p27 p27 :: Int p27 = snd $ maximum $ map calcConsecutives combinations where calcConsecutives (a,b) = (consecutives 0 (a,b),a * b) combinations :: [(Int,Int)] combinations = [(a,b) | a <- [-999..999], b <- (takeWhile (< 1000) primeNumbers)] consecutives :: Int -> (Int,Int) -> Int consecutives n (a,b) | isPrime (n ^ 2 + a * n + b) = consecutives (n + 1) (a,b) | otherwise = n
Sgoettschkes/learning
haskell/ProjectEuler/src/Problems/Problem027.hs
mit
494
0
13
97
238
132
106
12
1
{-# LANGUAGE OverloadedStrings #-} import Control.Concurrent (threadDelay) import Control.Monad import Control.Monad.IO.Class (liftIO, MonadIO) import Control.Monad.Trans (lift) import Control.Monad.Trans.Reader import Data.Aeson import Data.Maybe import Data.Time import Data.Time.Clock.POSIX import Data.Text import Data.Text.Encoding import Database.MongoDB import Network.HTTP.Conduit hiding (host) import System.Environment (getArgs) import qualified Data.Bson as Bson (Document) import qualified Data.ByteString.Char8 as StrictC8 import qualified LastFm import Config apiCallDelay :: Int apiCallDelay = 1000000 `div` 5 -- 1 / 5 sec in microseconds url = "http://ws.audioscrobbler.com/2.0/" data CrawlerEnv = CrawlerEnv { lastCrawlTimestamp :: Maybe Int, lastFmUser :: String, httpManager :: Manager, mongoPipe :: Pipe, runConfig :: Config } type Crawler = ReaderT CrawlerEnv IO runMongoAction :: Action IO a -> Crawler a runMongoAction action = do (CrawlerEnv _ _ _ mongoPipe cfg) <- ask let databaseName = dbName cfg liftIO $ access mongoPipe master databaseName action toByteString :: Int -> StrictC8.ByteString toByteString = StrictC8.pack . show logPagingStatus page pages = putStrLn $ "Fetched page " ++ show page ++ " / " ++ show pages logError page code msg = putStrLn $ "Error fetching page " ++ show page ++ "\n" ++ "Error code " ++ show code ++ "\n" ++ "Message " ++ unpack msg requestWithParams :: Text -> Int -> String -> Int -> Maybe Int -> Request -> Request requestWithParams key items user page from request = setQueryString params request where params = [("method", Just "user.getrecenttracks"), ("user", Just (StrictC8.pack user)), ("limit", Just (toByteString items)), ("api_key", Just (encodeUtf8 key)), ("format", Just "json"), ("page", Just (toByteString page)), ("from", fmap toByteString from)] fetchTracks :: Int -> Crawler (Maybe LastFm.Response) fetchTracks page = do (CrawlerEnv lastCrawled lastFmUser manager _ (Config key _ _ _ _ _ items _)) <- ask let scrobblesSince = fmap (+ 1) lastCrawled request <- fmap (requestWithParams key items lastFmUser page scrobblesSince) $ parseUrl url response <- httpLbs request manager return $ decode $ responseBody response handleError :: Int -> Int -> Text -> Crawler () handleError page code msg = errorOutput >> recentTracks page where errorOutput = lift $ logError page code msg >> putStrLn "Retrying..." persist :: [LastFm.Track] -> Crawler [Database.MongoDB.Value] persist tracks = do (CrawlerEnv _ _ _ _ cfg) <- ask let databaseName = dbName cfg let insertAction = insertMany databaseName $ fmap LastFm.toDocument tracks runMongoAction insertAction handleResponse :: LastFm.RecentTracks -> Crawler () handleResponse tracks = do persist $ LastFm.timestampedScrobbles tracks let (page, pages) = LastFm.paging tracks lift $ logPagingStatus page pages if page > 1 then recentTracks $ page - 1 else return () recentTracks :: Int -> Crawler () recentTracks 0 = return () recentTracks page = do response <- fetchTracks page lift $ threadDelay apiCallDelay case response of Nothing -> return () Just (LastFm.Error code msg _) -> handleError page code msg Just (LastFm.RecentTracksResponse tracks) -> handleResponse tracks latestScrobbleTimestamp :: Pipe -> Text -> IO (Maybe Int) latestScrobbleTimestamp mongoPipe databaseName = do let run = access mongoPipe master databaseName let latestScrobbleAction = findOne (select [] databaseName) {sort = ["scrobbledAt" =: (-1 :: Int)]} latestScrobbleDocument <- run latestScrobbleAction let latestScrobbleTime = fmap (at "scrobbledAt") latestScrobbleDocument :: Maybe UTCTime return $ fmap (round . utcTimeToPOSIXSeconds) latestScrobbleTime numberOfPages :: Crawler Int numberOfPages = fetchTracks 1 >>= \response -> case response of Just (LastFm.RecentTracksResponse tracks) -> return $ (snd . LastFm.paging) tracks _ -> return 0 crawl = numberOfPages >>= recentTracks main = readConfig >>= \cfg -> do let user = Config.lastFmUser cfg let mongoHost = unpack $ mongoServer cfg let mongoPort = Config.port cfg mongoPipe <- connect $ Host mongoHost mongoPort let db = dbName cfg access mongoPipe master db $ auth (Config.user cfg) (password cfg) lastCrawled <- latestScrobbleTimestamp mongoPipe db manager <- newManager tlsManagerSettings let env = CrawlerEnv lastCrawled user manager mongoPipe cfg liftIO $ runReaderT crawl env close mongoPipe
jliuhtonen/lastfm-dump
src/Main.hs
mit
4,747
4
19
1,004
1,501
754
747
108
3
module Main where import qualified Data.Text as T import qualified Data.Text.IO as TIO import TopStrings main :: IO () main = TIO.getContents >>= printTopStrings . topStrings . T.lines
spoj/mwtools
app/usc.hs
mit
188
0
8
31
55
34
21
6
1
{-# LANGUAGE OverlappingInstances #-} -- |This module provides an open union of functors. module Data.Union ( Union , Member , inj , prj , decomp , trivial ) where import Data.Maybe import Data.Typeable import Unsafe.Coerce (unsafeCoerce) -- |`Union` is an open sum of functors -- A value of type `Union` r a is a value f a for some f that is a member of the r list -- Since direct construction is not safe you have to use `inj` to create a value. data Union (r :: [* -> *]) (a :: *) where Union :: (Functor f, Typeable f) => f a -> Union r a instance Functor (Union r) where fmap f (Union fa) = Union (fmap f fa) -- |The `Member` type clas denotes that f is a member of type list r class Member (f :: * -> *) (r :: [* -> *]) where instance Member h (h ': t) instance (Member x t) => Member x (h ': t) -- |Smart constructor for `Union`. Injects the functor into any union -- of which the said functor is a member. Please note that only the -- type constructor need be a `Typeable`. inj :: (Typeable f, Functor f, Member f r) => f a -> Union r a inj = Union -- |Project a `Union` into a specific functor. prj :: (Typeable f, Member f r) => Union r a -> Maybe (f a) prj (Union d) = res where availableType = typeOf1 d wantedType = typeOf1 $ fromJust res res = if availableType == wantedType then Just $ unsafeCoerce d else Nothing -- |Decompose a `Union`. Similar to `prj` but gives you a -- `Union` instance without the functor f in type if projection fails. decomp :: (Typeable f) => Union (f ': r) a -> Either (f a) (Union r a) decomp u@(Union d) = maybe (Right $ Union d) Left $ prj u -- |A `Union` of one functor can only be that. Safe cast. trivial :: (Typeable f) => Union '[f] a -> f a trivial = fromJust . prj
edofic/effect-handlers
src/Data/Union.hs
mit
1,755
0
9
388
513
278
235
-1
-1
-- Filter Module module Lib.Filter where import Network.PFQ.Lang.Prelude import Network.PFQ.Lang.Default filterFunction = par ip ip
pfq/PFQ
user/pfq-lang/examples/Lib/Filter.hs
gpl-2.0
139
0
5
22
31
20
11
4
1
{- | Module : $Header$ Description : Tree-based implementation of 'Graph' and 'DynGraph' using Data.Map Copyright : (c) Martin Erwig, Christian Maeder and Uni Bremen 1999-2006 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable Tree-based implementation of 'Graph' and 'DynGraph' using Data.IntMap instead of Data.Graph.Inductive.Internal.FiniteMap -} module Common.Lib.Graph ( Gr(..) , GrContext(..) , unsafeConstructGr , decomposeGr , getPaths , getAllPathsTo , getPathsTo , getLEdges , Common.Lib.Graph.delLEdge , insLEdge , delLNode , labelNode , getNewNode , rmIsolated ) where import Data.Graph.Inductive.Graph as Graph import qualified Data.IntMap as Map import Data.List -- | the graph type constructor newtype Gr a b = Gr { convertToMap :: Map.IntMap (GrContext a b) } data GrContext a b = GrContext { nodeLabel :: a , nodeSuccs :: Map.IntMap [b] , loops :: [b] , nodePreds :: Map.IntMap [b] } unsafeConstructGr :: Map.IntMap (GrContext a b) -> Gr a b unsafeConstructGr = Gr instance (Show a, Show b) => Show (Gr a b) where show (Gr g) = showGraph g instance Graph Gr where empty = Gr Map.empty isEmpty (Gr g) = Map.null g match = matchGr mkGraph vs es = (insEdges es . insNodes vs) empty labNodes = map (\ (v, c) -> (v, nodeLabel c)) . Map.toList . convertToMap -- more efficient versions of derived class members matchAny g = case Map.keys $ convertToMap g of [] -> error "Match Exception, Empty Graph" h : _ -> let (Just c, g') = matchGr h g in (c, g') noNodes (Gr g) = Map.size g nodeRange (Gr g) = case Map.keys g of [] -> (0, -1) ks@(h : _) -> (h, last ks) labEdges = concatMap (\ (v, cw) -> map (\ (l, w) -> (v, w, l)) $ mkLoops v (loops cw) ++ mkAdj (nodeSuccs cw)) . Map.toList . convertToMap instance DynGraph Gr where (p, v, l, s) & gr = let mkMap = foldr (\ (e, w) -> Map.insertWith (++) w [e]) Map.empty pm = mkMap p sm = mkMap s in composeGr v GrContext { nodeLabel = l , nodeSuccs = Map.delete v sm , loops = Map.findWithDefault [] v pm ++ Map.findWithDefault [] v sm , nodePreds = Map.delete v pm } gr showGraph :: (Show a, Show b) => Map.IntMap (GrContext a b) -> String showGraph = unlines . map (\ (v, c) -> shows v ": " ++ show (nodeLabel c) ++ showLinks ((case loops c of [] -> [] l -> [(v, l)]) ++ Map.toList (nodeSuccs c))) . Map.toList showLinks :: Show b => [(Node, [b])] -> String showLinks = concatMap $ \ (v, l) -> " - " ++ intercalate ", " (map show l) ++ " -> " ++ shows v ";" mkLoops :: Node -> [b] -> Adj b mkLoops v = map (\ e -> (e, v)) mkAdj :: Map.IntMap [b] -> Adj b mkAdj = concatMap (\ (w, l) -> map (\ e -> (e, w)) l) . Map.toList {- here cyclic edges are omitted as predecessors, thus they only count as outgoing and not as ingoing! Therefore it is enough that only successors are filtered during deletions. -} matchGr :: Node -> Gr a b -> Decomp Gr a b matchGr v gr = case decomposeGr v gr of Nothing -> (Nothing, gr) Just (c, rg) -> (Just ( mkAdj $ nodePreds c , v , nodeLabel c , mkLoops v (loops c) ++ mkAdj (nodeSuccs c)), rg) decomposeGr :: Node -> Gr a b -> Maybe (GrContext a b, Gr a b) decomposeGr v (Gr g) = case Map.lookup v g of Nothing -> Nothing Just c -> let g1 = Map.delete v g g2 = updAdj g1 (nodeSuccs c) $ clearPred v g3 = updAdj g2 (nodePreds c) $ clearSucc v in Just (c, Gr g3) addSuccs :: Node -> [b] -> GrContext a b -> GrContext a b addSuccs v ls c = c { nodeSuccs = Map.insert v ls $ nodeSuccs c } addPreds :: Node -> [b] -> GrContext a b -> GrContext a b addPreds v ls c = c { nodePreds = Map.insert v ls $ nodePreds c } clearSucc :: Node -> [b] -> GrContext a b -> GrContext a b clearSucc v _ c = c { nodeSuccs = Map.delete v $ nodeSuccs c } clearPred :: Node -> [b] -> GrContext a b -> GrContext a b clearPred v _ c = c { nodePreds = Map.delete v $ nodePreds c } updAdj :: Map.IntMap (GrContext a b) -> Map.IntMap [b] -> ([b] -> GrContext a b -> GrContext a b) -> Map.IntMap (GrContext a b) updAdj g m f = Map.foldWithKey (\ v -> updGrContext v . f) g m updGrContext :: Node -> (GrContext a b -> GrContext a b) -> Map.IntMap (GrContext a b) -> Map.IntMap (GrContext a b) updGrContext v f r = case Map.lookup v r of Nothing -> error $ "Common.Lib.Graph.updGrContext no node: " ++ show v Just c -> Map.insert v (f c) r composeGr :: Node -> GrContext a b -> Gr a b -> Gr a b composeGr v c (Gr g) = let g1 = updAdj g (nodePreds c) $ addSuccs v g2 = updAdj g1 (nodeSuccs c) $ addPreds v g3 = Map.insert v c g2 in if Map.member v g then error $ "Common.Lib.Graph.composeGr no node: " ++ show v else Gr g3 -- | compute the possible cycle free paths from a start node getPaths :: Node -> Gr a b -> [[LEdge b]] getPaths src gr = case decomposeGr src gr of Just (c, ng) -> Map.foldWithKey (\ nxt lbls l -> l ++ map (\ b -> [(src, nxt, b)]) lbls ++ concatMap (\ p -> map (\ b -> (src, nxt, b) : p) lbls) (getPaths nxt ng)) [] $ nodeSuccs c Nothing -> error $ "Common.Lib.Graph.getPaths no node: " ++ show src -- | compute the possible cycle free reversed paths from a start node getAllPathsTo :: Node -> Gr a b -> [[LEdge b]] getAllPathsTo tgt gr = case decomposeGr tgt gr of Just (c, ng) -> Map.foldWithKey (\ nxt lbls l -> l ++ map (\ b -> [(nxt, tgt, b)]) lbls ++ concatMap (\ p -> map (\ b -> (nxt, tgt, b) : p) lbls) (getAllPathsTo nxt ng)) [] $ nodePreds c Nothing -> error $ "Common.Lib.Graph.getAllPathsTo no node: " ++ show tgt -- | compute the possible cycle free paths from a start node to a target node. getPathsTo :: Node -> Node -> Gr a b -> [[LEdge b]] getPathsTo src tgt gr = case decomposeGr src gr of Just (c, ng) -> let s = nodeSuccs c in Map.foldWithKey (\ nxt lbls -> (++ concatMap (\ p -> map (\ b -> (src, nxt, b) : p) lbls) (getPathsTo nxt tgt ng))) (map (\ lbl -> [(src, tgt, lbl)]) $ Map.findWithDefault [] tgt s) (Map.delete tgt s) Nothing -> error $ "Common.Lib.Graph.getPathsTo no node: " ++ show src -- | get all the edge labels between two nodes getLEdges :: Node -> Node -> Gr a b -> [b] getLEdges v w (Gr m) = let err = "Common.Lib.Graph.getLEdges: no node " in case Map.lookup v m of Just c -> if v == w then loops c else Map.findWithDefault (if Map.member w m then [] else error $ err ++ show w) w $ nodeSuccs c Nothing -> error $ err ++ show v showEdge :: Node -> Node -> String showEdge v w = show v ++ " -> " ++ show w -- | delete a labeled edge from a graph delLEdge :: (b -> b -> Ordering) -> LEdge b -> Gr a b -> Gr a b delLEdge cmp (v, w, l) (Gr m) = let e = showEdge v w err = "Common.Lib.Graph.delLEdge " in case Map.lookup v m of Just c -> let sm = nodeSuccs c b = v == w ls = if b then loops c else Map.findWithDefault [] w sm in case partition (\ k -> cmp k l == EQ) ls of ([], _) -> error $ err ++ "no edge: " ++ e ([_], rs) -> if b then Gr $ Map.insert v c { loops = rs } m else Gr $ updGrContext w ((if null rs then clearPred else addPreds) v rs) $ Map.insert v c { nodeSuccs = if null rs then Map.delete w sm else Map.insert w rs sm } m _ -> error $ err ++ "multiple edges: " ++ e Nothing -> error $ err ++ "no node: " ++ show v ++ " for edge: " ++ e -- | insert a labeled edge into a graph, returns False if edge exists insLEdge :: Bool -> (b -> b -> Ordering) -> LEdge b -> Gr a b -> (Gr a b, Bool) insLEdge failIfExist cmp (v, w, l) gr@(Gr m) = let e = showEdge v w err = "Common.Lib.Graph.insLEdge " in case Map.lookup v m of Just c -> let sm = nodeSuccs c b = v == w ls = if b then loops c else Map.findWithDefault [] w sm ns = insertBy cmp l ls in if any (\ k -> cmp k l == EQ) ls then if failIfExist then error $ err ++ "multiple edges: " ++ e else (gr, False) else (if b then Gr $ Map.insert v c { loops = ns } m else Gr $ updGrContext w (addPreds v ns) $ Map.insert v c { nodeSuccs = Map.insert w ns sm } m, True) Nothing -> error $ err ++ "no node: " ++ show v ++ " for edge: " ++ e isIsolated :: GrContext a b -> Bool isIsolated c = Map.null (nodeSuccs c) && Map.null (nodePreds c) -- | delete a labeled node delLNode :: (a -> a -> Bool) -> LNode a -> Gr a b -> Gr a b delLNode eq (v, l) (Gr m) = let err = "Common.Lib.Graph.delLNode: node " ++ show v in case Map.lookup v m of Just c -> if isIsolated c && null (loops c) then if eq l $ nodeLabel c then Gr (Map.delete v m) else error $ err ++ " has a different label" else error $ err ++ " has remaining edges" Nothing -> error $ err ++ " is missing" -- | sets the node with new label and returns the new graph and the old label labelNode :: LNode a -> Gr a b -> (Gr a b, a) labelNode (v, l) (Gr m) = case Map.lookup v m of Just c -> (Gr $ Map.insert v (c { nodeLabel = l }) m, nodeLabel c) Nothing -> error $ "Common.Lib.Graph.labelNode no node: " ++ show v -- | returns one new node id for the given graph getNewNode :: Gr a b -> Node getNewNode g = case newNodes 1 g of [n] -> n _ -> error "Common.Lib.Graph.getNewNode" -- | remove isolated nodes without edges rmIsolated :: Gr a b -> Gr a b rmIsolated (Gr m) = Gr $ Map.filter (not . isIsolated) m
nevrenato/Hets_Fork
Common/Lib/Graph.hs
gpl-2.0
9,857
0
23
2,814
4,003
2,066
1,937
203
8
{-# LANGUAGE OverloadedStrings #-} -- Copyright (C) 2010-2011 John Millikin <jmillikin@gmail.com> -- -- 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 3 of the License, or -- 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, see <http://www.gnu.org/licenses/>. module Network.Protocol.XMPP.Client ( runClient , bindJID ) where import Control.Monad ((>=>)) import Control.Monad.Error (throwError) import Control.Monad.Trans (liftIO) import Data.ByteString (ByteString) import Data.Text (Text) import Network (connectTo) import qualified System.IO as IO import qualified Network.Protocol.XMPP.Client.Authentication as A import qualified Network.Protocol.XMPP.Connections as C import qualified Network.Protocol.XMPP.Client.Features as F import qualified Network.Protocol.XMPP.Handle as H import qualified Network.Protocol.XMPP.JID as J import qualified Network.Protocol.XMPP.Monad as M import qualified Network.Protocol.XMPP.XML as X import Network.Protocol.XMPP.ErrorT import Network.Protocol.XMPP.Stanza runClient :: C.Server -> J.JID -- ^ Client JID -> Text -- ^ Username -> Text -- ^ Password -> M.XMPP a -> IO (Either M.Error a) runClient server jid username password xmpp = do -- Open a TCP connection let C.Server sjid host port = server rawHandle <- connectTo host port IO.hSetBuffering rawHandle IO.NoBuffering let handle = H.PlainHandle rawHandle -- Open the initial stream and authenticate M.startXMPP handle "jabber:client" $ do features <- newStream sjid tryTLS sjid features $ \tlsFeatures -> do let mechanisms = authenticationMechanisms tlsFeatures A.authenticate mechanisms jid sjid username password M.restartXMPP Nothing (newStream sjid >> xmpp) newStream :: J.JID -> M.XMPP [F.Feature] newStream jid = do M.putBytes (C.xmlHeader "jabber:client" jid) void (M.readEvents C.startOfStream) F.parseFeatures `fmap` M.getElement tryTLS :: J.JID -> [F.Feature] -> ([F.Feature] -> M.XMPP a) -> M.XMPP a tryTLS sjid features m | not (streamSupportsTLS features) = m features | otherwise = do M.putElement xmlStartTLS void M.getElement h <- M.getHandle eitherTLS <- liftIO (runErrorT (H.startTLS h)) case eitherTLS of Left err -> throwError (M.TransportError err) Right tls -> M.restartXMPP (Just tls) (newStream sjid >>= m) authenticationMechanisms :: [F.Feature] -> [ByteString] authenticationMechanisms = step where step [] = [] step (f:fs) = case f of (F.FeatureSASL ms) -> ms _ -> step fs -- | Send a @\<bind\>@ message for the given 'J.JID', returning the server's reply. In -- most cases the reply will be the same as the input. However, if the input has no -- 'J.Resource', the returned 'J.JID' will contain a generated 'J.Resource'. -- -- Clients must bind a 'J.JID' before sending any 'Stanza's. bindJID :: J.JID -> M.XMPP J.JID bindJID jid = do -- Bind M.putStanza (bindStanza (J.jidResource jid)) bindResult <- M.getStanza let getJID = X.elementChildren >=> X.isNamed "{urn:ietf:params:xml:ns:xmpp-bind}jid" >=> X.elementNodes >=> X.isContent >=> return . X.contentText let maybeJID = do iq <- case bindResult of ReceivedIQ x -> Just x _ -> Nothing payload <- iqPayload iq case getJID payload of [] -> Nothing (str:_) -> J.parseJID str returnedJID <- case maybeJID of Just x -> return x Nothing -> throwError (M.InvalidBindResult bindResult) -- Session M.putStanza sessionStanza void M.getStanza M.putStanza (emptyPresence PresenceAvailable) void M.getStanza return returnedJID bindStanza :: Maybe J.Resource -> IQ bindStanza resource = (emptyIQ IQSet) { iqPayload = Just payload } where payload = X.element "{urn:ietf:params:xml:ns:xmpp-bind}bind" [] requested requested = case fmap J.strResource resource of Nothing -> [] Just x -> [X.NodeElement (X.element "resource" [] [X.NodeContent (X.ContentText x)])] sessionStanza :: IQ sessionStanza = (emptyIQ IQSet) { iqPayload = Just payload } where payload = X.element "{urn:ietf:params:xml:ns:xmpp-session}session" [] [] streamSupportsTLS :: [F.Feature] -> Bool streamSupportsTLS = any isStartTLS where isStartTLS (F.FeatureStartTLS _) = True isStartTLS _ = False xmlStartTLS :: X.Element xmlStartTLS = X.element "{urn:ietf:params:xml:ns:xmpp-tls}starttls" [] [] void :: Monad m => m a -> m () void m = m >> return ()
jmillikin/haskell-xmpp
lib/Network/Protocol/XMPP/Client.hs
gpl-3.0
4,939
23
18
942
1,334
692
642
-1
-1
import Data.DotsAndBoxes.Test.General import Control.Monad import System.Exit import Test.HUnit main :: IO () main = do -- propSuccess <- runPropTests -- unless propSuccess exitFailure hunitResult <- runTestTT testGroup unless (errors hunitResult == 0 && failures hunitResult == 0) exitFailure
mcapodici/dotsandboxes
test/Spec.hs
gpl-3.0
309
1
12
53
82
41
41
8
1
{-# OPTIONS_GHC -Wall #-} module Main where import Analysis import GrammarFilters import Test.HUnit isAmbiguousSentence :: String -> Bool isAmbiguousSentence = (isSingleSentence `andAlso` (isAmbiguous)) testBasicSentence :: Test testBasicSentence = TestCase $ assertBool "Basic sentence" (isWellFormed "my dogs found a yellow ball.") testPrepositionalPhraseUnambig :: Test testPrepositionalPhraseUnambig = TestCase $ assertBool "Unambiguous prepositional phrase" (isWellFormed "the dog in my yard eats a carrot.") testPrepositionalPhraseAmbig :: Test testPrepositionalPhraseAmbig = TestCase $ assertBool "Ambiguous prepositional phrase" (isAmbiguousSentence "the dog eats a carrot in my refrigerator.") testInfinitive :: Test testInfinitive = TestCase $ assertBool "Infinitive should be a valid, unambiguous object" (isWellFormed "I love to run.") testConjugation1 :: Test testConjugation1 = TestCase $ assertBool "Conjugation: third person singular" (isWellFormed "my dog likes to run.") testConjugation2 :: Test testConjugation2 = TestCase $ assertBool "Conjugation: third person plural" (isWellFormed "my dogs like to run.") testConjugation3 :: Test testConjugation3 = TestCase $ assertBool "Conjugation: incorrect third person singular" (not . isSingleSentence $ "my dog like to run.") testConjugation4 :: Test testConjugation4 = TestCase $ assertBool "Conjugation: incorrect third person plural" (not . isSingleSentence $ "my dogs likes to run.") testPluralNouns :: Test testPluralNouns = TestCase $ assertBool "Nouns ending in S have plurals with ES" (isWellFormed "bushes like classes.") testVerbEsConjugation :: Test testVerbEsConjugation = TestCase $ assertBool "Verbs ending in S have plurals with ES" (isWellFormed "he fusses." && isWellFormed "he catches the ball.") testNounConjugation :: Test testNounConjugation = TestCase $ assertBool "Nouns can be conjoined" (isSingleSentence "the dog and cat play in the yard.") testWhen :: Test testWhen = TestCase $ assertBool "Sentences can be conjoined" (isWellFormed "the dogs ran after the blue ball when I threw it.") testPredicateConjunction :: Test testPredicateConjunction = TestCase $ assertBool "Predicates can be conjoined" (isWellFormed "the dogs eat carrots and chew the blue ball.") testPrepPhraseConjunction :: Test testPrepPhraseConjunction = TestCase $ assertBool "Prepositional phrases can be conjoined" (isWellFormed "the dogs eat in the yard and with me.") testAdjectiveConjunction :: Test testAdjectiveConjunction = TestCase $ assertBool "Adjectives can be conjoined" (isWellFormed "I like the blue and yellow ball.") testPastTense :: Test testPastTense = TestCase $ assertBool "Larger texts can be parsed, past tense is supported" (isText $ "Zac and Sam went to the store because they wanted food. Zac " ++ "wanted ham. Sam wanted chips and dip.") testUnusualVerbs :: Test testUnusualVerbs = TestCase $ assertBool "Unusual verbs conjugate correctly." (isText $ "I do it. you do it. he does it. we do it. they do it. I did it. " ++ "I am it. you are it. he is it. we are it. they are it. I was it. " ++ "you were it. he was it. we were it. they were it.") testSentenceAsQuestion :: Test testSentenceAsQuestion = TestCase $ assertBool "Sentences can be considered questions" (isWellFormed "they like the blue and yellow balls?") testQuestionAsking :: Test testQuestionAsking = TestCase $ assertBool "Basic question syntax is supported" (isText $ "do I play in the yard? do you play in the yard? does he play in " ++ "the yard and did they play in the yard? do you want to build a " ++ "snowman?") testIesPluralNouns :: Test testIesPluralNouns = TestCase $ assertBool "Adjectives can be conjoined" (isWellFormed "my baby likes the babies!") testIsEsPluralNouns :: Test testIsEsPluralNouns = TestCase $ assertBool "Is->Es plural nouns" (isWellFormed "my analysis fits with your analyses.") testLesMiserables :: Test testLesMiserables = TestCase $ assertBool "Lyrics of On My Own from Les Mis" (isText "the city goes to bed and I can live inside my head.") testDanglingPrepositions :: Test testDanglingPrepositions = TestCase $ assertBool "Dangling prepositions can be parsed" (isAmbiguousSentence "the store I went to had the carrots I longed for.") testContractions :: Test testContractions = TestCase $ assertBool "Contractions can be parsed" (isText "I'm in the yard. you're inside my head. I wouldn't've lived.") main :: IO Counts main = runTestTT $ TestList [ testBasicSentence , testPrepositionalPhraseUnambig , testPrepositionalPhraseAmbig , testInfinitive , testConjugation1 , testConjugation2 , testConjugation3 , testConjugation4 , testPluralNouns , testVerbEsConjugation , testNounConjugation , testWhen , testPredicateConjunction , testPrepPhraseConjunction , testAdjectiveConjunction , testPastTense , testUnusualVerbs , testSentenceAsQuestion , testQuestionAsking , testIesPluralNouns , testIsEsPluralNouns , testLesMiserables , testDanglingPrepositions , testContractions ]
penguinland/nlp
IntegrationTest.hs
gpl-3.0
6,048
0
10
1,772
774
419
355
139
1
module EngineTypes where import Tiles import Foreign.C.Types import SDL import Vector (Mat) import Control.Concurrent data Avatar = Avatar { plPos :: (Int,Int) , plTiles :: [TileStack] , direct :: Direction } data Sys = Sys { width :: Int , height :: Int , randSeed :: Int , flagMVar :: MVar Bool , boxMVar :: MVar ([Mat [TileStack]]) } data Chunk = Chunk { chType :: ChunkType , canPos :: (Int,Int) , chLand :: Mat [TileStack] , canvasSize :: (Int,Int) , chunkSize :: Int , chunkNbr :: Int } data World = World { sys :: Sys , screen :: Renderer , tileset :: Texture , chunk :: Chunk , chunks :: [Chunk] , player :: Avatar } data Direction = Lefty | Righty| Up | Down | Stop deriving Show type Seed = Int
eniac314/wizzard
src/EngineTypes.hs
gpl-3.0
1,080
0
13
510
261
165
96
28
0
module Handler.ProductSpec (spec) where import TestImport spec :: Spec spec = withApp $ do describe "getProductR" $ do error "Spec not implemented: getProductR" describe "postProductR" $ do error "Spec not implemented: postProductR" describe "putProductR" $ do error "Spec not implemented: putProductR" describe "deleteProductR" $ do error "Spec not implemented: deleteProductR"
Southern-Exposure-Seed-Exchange/Order-Manager-Prototypes
yesod/test/Handler/ProductSpec.hs
gpl-3.0
437
0
11
108
92
41
51
12
1
module Problem041 (answer) where import NumUtil (genPanDigitNumbers) import Primes (isPrime) answer :: Int answer = maximum $ filter isPrime (concatMap (uncurry genPanDigitNumbers) range) where range = zip (repeat 1) [2..9]
geekingfrog/project-euler
Problem041.hs
gpl-3.0
228
0
10
34
81
45
36
6
1
{-# LANGUAGE FlexibleContexts #-} module Mudblood.Contrib.MG.Guilds.Common ( spell, hands, unhands ) where import Data.String.Utils import Data.Maybe import Mudblood import Mudblood.Contrib.MG.State spell :: (MBMonad m u, Has R_Common u) => String -> m () spell sp = do focus <- getU' R_Common mgFocus let final = replace "%f" (fromMaybe "" focus) sp echoA $ (toAS "> ") <++> (setFg Yellow $ toAS final) send final hands :: (MBMonad m u, Has R_Common u) => Int -> m () hands n = do shield <- getU' R_Common mgShieldName case n of 1 -> send "steck waffe weg" 2 -> send $ "zieh " ++ shield ++ " aus\nsteck waffe weg" _ -> return () unhands :: (MBMonad m u, Has R_Common u) => m () unhands = do shield <- getU' R_Common mgShieldName send "zueck waffe" send $ "trage " ++ shield
talanis85/mudblood
src/Mudblood/Contrib/MG/Guilds/Common.hs
gpl-3.0
850
0
12
215
316
159
157
25
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} module Wat where import Data.List import Data.Char import Data.Time import Data.Tuple import Data.Maybe import Control.Applicative import Data.Semigroup import Data.Monoid hiding ((<>)) import Test.QuickCheck import Test.QuickCheck.Checkers import qualified Test.QuickCheck.Classes import Control.Exception import Control.Monad (join) data DayOfWeek = Mon | Tue | Wen | Thu | Fri | Sat | Sun deriving (Show) instance Eq DayOfWeek where (==) Mon Mon = True (==) Tue Tue = True (==) Wen Wen = True (==) Thu Thu = True (==) Fri Fri = True (==) Sat Sat = True (==) Sun Sun = True (==) _ _ = False instance Ord DayOfWeek where compare Fri Fri = EQ compare Fri _ = GT compare _ Fri = LT compare _ _ = EQ class Numberish a where fromNumber :: Integer -> a toNumber :: a -> Integer newtype Age = Age Integer deriving (Eq, Show) instance Numberish Age where fromNumber = Age toNumber (Age n) = n newtype Year = Year Integer deriving (Eq, Show) instance Numberish Year where fromNumber = Year toNumber (Year n) = n sumN :: Numberish a => a -> a -> a sumN a a' = fromNumber summed where inta = toNumber a inta' = toNumber a' summed = inta + inta' data Mood = Blah | Woot deriving (Show, Eq) settleDown x = if x == Woot then Blah else x type Sub = String type Verb = String type Obj = String data Sentence = Sentence Sub Verb Obj deriving (Eq, Show) s1 = Sentence "dogs" "drool" s2 = Sentence "julle" "loves" "dogs" data Rocks = Rocks String deriving (Eq, Show) data Yeah = Yeah Bool deriving (Eq, Show) data Papu = Papu Rocks Yeah deriving (Eq, Show) equalityForall :: Papu -> Papu -> Bool equalityForall p p' = p == p' -- comparePapus :: Papu -> Papu -> Bool -- comparePapus p p' = p > p' f :: RealFrac a => a f = 1.0 freud :: Int -> Int freud x = x myX :: Num a => a myX = 1 sigmund :: Integral a => a -> a sigmund x = myX jung :: [Int] -> Int jung = minimum mySort :: String -> String mySort = sort signifier :: String -> Char signifier xs = head (mySort xs) arith :: Num b => (a -> b) -> Integer -> a -> b arith f int a = fromInteger int + f a bindExp :: Integer -> String bindExp x = let y = 5 in let z = y + x in "the integer was: " ++ show x ++ " and y was: " ++ show y ++ " and z was: " ++ show z numbers x | x < 0 = -1 | x == 0 = 0 | x > 0 =1 pal xs | xs == reverse xs = True | otherwise = False foldBool3 :: a -> a -> Bool -> a foldBool3 x y b = if b then x else y foldBool4 x y b | b = x | not b = y foldBool5 x y True = x foldBool5 x y False = y roundTrip :: (Show a, Read b) => a -> b roundTrip a = read (show a) main = do print (roundTrip 4 :: Int) print 4 ff True = 0 ff False = error "haha" myWords :: String -> [String] myWords str = myW str [] where myW [] acc = reverse acc myW s acc = let word = takeWhile (/=' ') s wordl = length word (_, rest) = splitAt wordl s rest' = dropWhile (==' ') rest in myW rest' (word:acc) myZip :: [a] -> [b] -> [(a,b)] myZip [] _ = [] myZip _ [] = [] myZip (a:as) (b:bs) = (a,b): myZip as bs myZipWith :: (a->b->c) -> [a] -> [b] -> [c] myZipWith f [] _ = [] myZipWith f _ [] = [] myZipWith f (a:as) (b:bs) = f a b : myZipWith f as bs myZip1 :: [a] -> [b] -> [(a,b)] myZip1 = myZipWith (,) myAnd :: [Bool] -> Bool myAnd = foldr (&&) True --myAnd (x:xs) = x && myAnd xs myAny :: (a->Bool) -> [a] -> Bool myAny f = foldr ((||).f) False --myAny f [] = False --myAny f (x:xs) = f x || myAny f xs myOr :: [Bool] -> Bool myOr = myAny id myElem :: Eq a => a -> [a] -> Bool myElem e = any (e==) squish :: [[a]] -> [a] squish [] = [] squish (as:ass) = as ++ squish ass squishMap :: (a -> [b]) -> [a] -> [b] squishMap f = foldr ((++).f) [] squishAgain :: [[a]] -> [a] squishAgain = squishMap id myMaximumBy :: (a->a->Ordering) -> [a] -> a myMaximumBy f [] = undefined myMaximumBy f (x:xs) = myMaximumBy' f x xs where myMaximumBy' f m [] = m myMaximumBy' f m (x:xs) = case f m x of LT -> myMaximumBy' f x xs _ -> myMaximumBy' f m xs myMaximum :: (Ord a) => [a] -> a myMaximum = myMaximumBy compare myMinimumBy :: (a->a->Ordering) -> [a] -> a myMinimumBy f = myMaximumBy $ flip f myMinimum :: (Ord a) => [a] -> a myMinimum = myMinimumBy compare data DatabaseItem = DbString String | DbNumber Integer | DbDate UTCTime deriving (Eq, Ord, Show) theDatabase :: [DatabaseItem] theDatabase = [ DbDate (UTCTime (fromGregorian 1911 5 1) (secondsToDiffTime 34123)), DbNumber 9001, DbString "Hello, world!", DbDate (UTCTime (fromGregorian 1921 5 1) (secondsToDiffTime 34123)) ] filterDbDate :: [DatabaseItem] -> [UTCTime] filterDbDate = foldr getDate [] where getDate (DbDate d) acc = d:acc getDate _ acc = acc filterDbNumber :: [DatabaseItem] -> [Integer] filterDbNumber = foldr getNumber [] where getNumber (DbNumber x) acc = x:acc getNumber _ acc = acc mostRecent :: [DatabaseItem] -> UTCTime mostRecent = maximum.filterDbDate -- OR m x = maximum $ filterDbDate x sumDb :: [DatabaseItem] -> Integer sumDb = foldr summy 0 where summy (DbNumber x) acc = x + acc summy _ acc = acc avgDb :: [DatabaseItem] -> Double avgDb db = let all = fromIntegral $ sumDb db l = fromIntegral $ length db in all/l myMap :: (a -> b) -> [a] -> [b] myMap f = foldr ((:).f) [] newtype Goats = Goats Int deriving Show class TooMany a where tooMany :: a -> Bool instance TooMany Int where tooMany n = n>42 instance TooMany Goats where tooMany (Goats n) = n>43 instance TooMany (Int, String) where tooMany (int, _) = int>43 instance TooMany (Int, Int) where tooMany (a,b) = tooMany $ a+b instance (Num a, TooMany a) => TooMany (a,a) where tooMany (a,b) = False data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) deriving (Eq, Ord, Show) insert' :: Ord a => a -> BinaryTree a -> BinaryTree a insert' b Leaf = Node Leaf b Leaf insert' b (Node left a right) | b > a = Node left a (insert' b right) | b < a = Node (insert' b left) a right | b == a = Node left a right mapTree :: (a->b) -> BinaryTree a -> BinaryTree b mapTree _ Leaf = Leaf mapTree f (Node left a right) = Node (mapTree f left) (f a) (mapTree f right) preOrder :: BinaryTree a -> [a] preOrder Leaf = [] preOrder (Node left a right) = [a] ++ preOrder left ++ preOrder right inOrder :: BinaryTree a -> [a] inOrder Leaf = [] inOrder (Node left a right) = inOrder left ++ [a] ++ inOrder right postOrder :: BinaryTree a -> [a] postOrder Leaf = [] postOrder (Node left a right) = postOrder left ++ postOrder right ++ [a] foldTree :: (a->b->b) -> b -> BinaryTree a -> b foldTree _ acc Leaf = acc foldTree f acc (Node left a right) = let l = foldTree f acc left r = foldTree f l right in f a r vigenere :: String -> String -> String vigenere str key = let repeat = div (length str) (length key) + 1 vigenere' "" key = "" vigenere' (' ':str) key = ' ' : vigenere' str key vigenere' (c:str) (k:key) = (chr $ mod (ord c + ord k - 65 - 65) 26 + 65) : vigenere' str key in vigenere' str (concat $ replicate repeat key) isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool isSubsequenceOf a b = and [x `elem` b | x <- a] capitalizeWord :: String -> String capitalizeWord str@(x:xs) | ord x >= 65 && ord x <= 90 = str | otherwise = chr (ord x - 32) : xs type Digit = Char type Presses = Int data DaPhone = DaPhone [(Digit, String)] dataphone :: DaPhone dataphone = DaPhone [('2',"abc2"),('3',"def3"),('4',"ghi4"),('5',"jkl5"),('6',"mno6"),('7',"pqrs7"),('8',"tuv8"),('9',"wxyz9"),('0'," 0")] convo :: [String] convo = ["Wanna play 20 questions", "Ya", "U 1st haha", "Lol ok. Have u ever tasted alcohol lol", "Lol ya", "Wow ur cool haha. Ur turn", "Ok. Do u think I am pretty Lol", "Lol ya", "Haha thanks just making sure rofl ur turn"] reverseTaps :: DaPhone -> Char -> [(Digit, Presses)] reverseTaps phone char | isUpper char = [('*', 1), lookkey phone (toLower char)] | otherwise = [lookkey phone char] lookkey :: DaPhone -> Char -> (Digit, Presses) lookkey (DaPhone ((digit,str):tl)) char = case elemIndex char str of Nothing -> lookkey (DaPhone tl) char Just idx -> (digit, idx+1) cellPhonesDead :: DaPhone -> String -> [(Digit, Presses)] cellPhonesDead phone = foldMap (reverseTaps phone) fingerTaps :: [(Digit, Presses)] -> Presses fingerTaps = foldr (\(_,press) acc -> acc + press) 0 mostPopularLetter :: String -> Char mostPopularLetter str = let pairs = foldr (\c acc -> case lookup c acc of Nothing -> (c, 1) : acc Just rep -> insert (c,rep+1) $ delete (c,rep) acc) [] str in fst $ maximumBy (\(_,rep1) (_,rep2) -> compare rep1 rep2) pairs -- Hutton's Razor data Expr = Lit Integer | Add Expr Expr eval :: Expr -> Integer eval (Lit int) = int eval (Add exp1 exp2) = eval exp1 + eval exp2 printExpr :: Expr -> String printExpr (Lit int) = show int printExpr (Add exp1 exp2) = printExpr exp1 ++ " + " ++ printExpr exp2 notThe :: String -> Maybe String notThe "the" = Nothing notThe s = Just s replaceThe :: String -> String replaceThe str = unwords $ (fromMaybe "a" . notThe) <$> words str -- unwords $ fmap (fromMaybe "a" . notThe) $ words str countTheBeforeVowel :: String -> Integer countTheBeforeVowel str = let count' acc [] = acc count' acc ("the" : ('a':_) : rest) = count' (acc+1) rest count' acc ("the" : ('e':_) : rest) = count' (acc+1) rest count' acc ("the" : ('i':_) : rest) = count' (acc+1) rest count' acc ("the" : ('o':_) : rest) = count' (acc+1) rest count' acc ("the" : ('u':_) : rest) = count' (acc+1) rest count' acc (_:t) = count' acc t in count' 0 $ words str countVowels :: String -> Integer countVowels str = let countV' acc [] = acc countV' acc ('a':rest) = countV' (acc+1) rest countV' acc ('e':rest) = countV' (acc+1) rest countV' acc ('i':rest) = countV' (acc+1) rest countV' acc ('o':rest) = countV' (acc+1) rest countV' acc ('u':rest) = countV' (acc+1) rest countV' acc (_:t) = countV' acc t in countV' 0 str newtype Word' = Word' String deriving (Eq, Show) vowels = "aeiou" mkWord :: String -> Maybe Word' mkWord str = let mk' tup [] = tup mk' tup (' ':rest) = mk' tup rest mk' (vo,cn) ('a':rest) = mk' (vo+1,cn) rest mk' (vo,cn) ('e':rest) = mk' (vo+1,cn) rest mk' (vo,cn) ('i':rest) = mk' (vo+1,cn) rest mk' (vo,cn) ('o':rest) = mk' (vo+1,cn) rest mk' (vo,cn) ('u':rest) = mk' (vo+1,cn) rest mk' (vo,cn) (_:rest) = mk' (vo,cn+1) rest (v,c) = mk' (0,0) str in if v < c then Just $ Word' str else Nothing data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 :: Integer natToInteger (Succ nat) = 1 + natToInteger nat integerToNat :: Integer -> Maybe Nat integerToNat int | int < 0 = Nothing | int >= 0 = Just $ itn int where itn 0 = Zero itn i = Succ (itn $ i-1) isJust1 :: Maybe a -> Bool isJust1 (Just _) = True isJust1 Nothing = False isNothing1 :: Maybe a -> Bool isNothing1 = not.isJust1 maybee :: b -> (a->b) -> Maybe a -> b maybee b f Nothing = b maybee b f (Just a) = f a fromMaybe1 :: a -> Maybe a -> a fromMaybe1 a Nothing = a fromMaybe1 _ (Just a) = a listToMaybe1 :: [a] -> Maybe a listToMaybe1 [] = Nothing listToMaybe1 (x:_) = Just x maybeToList :: Maybe a -> [a] maybeToList Nothing = [] maybeToList (Just a) = [a] catMaybes1 :: [Maybe a] -> [a] catMaybes1 mybs = [x | Just x <- mybs] flipMaybe :: [Maybe a] -> Maybe [a] flipMaybe [] = Just [] flipMaybe (Nothing:_) = Nothing flipMaybe (Just a : rest) = case flipMaybe rest of Nothing -> Nothing Just as -> Just $ a:as lefts' :: [Either a b] -> [a] lefts' = let f (Left a) bcc = a:bcc f (Right b) bcc = bcc in foldr f [] rights' :: [Either a b] -> [b] rights' = let f (Left a) bcc = bcc f (Right b) bcc = b:bcc in foldr f [] partitionEithers' :: [Either a b] -> ([a], [b]) partitionEithers' = let f (Left a) (as,bs) = (a:as,bs) f (Right b) (as,bs) = (as,b:bs) in foldr f ([],[]) eitherMaybe' :: (b -> c) -> Either a b -> Maybe c eitherMaybe' f (Left a) = Nothing eitherMaybe' f (Right b) = Just $ f b either' :: (a -> c) -> (b -> c) -> Either a b -> c either' fa fb (Left a) = fa a either' fa fb (Right b) = fb b eitherMaybe1' :: (b -> c) -> Either a b -> Maybe c eitherMaybe1' f = either' (const Nothing) (Just . f) myIterate :: (a -> a) -> a -> [a] myIterate f fir = fir : myIterate f (f fir) myUnfoldr :: (b -> Maybe (a, b)) -> b -> [a] myUnfoldr f b = case f b of Nothing -> [] Just (a1,b1) -> a1 : myUnfoldr f b1 betterIterate :: (a -> a) -> a -> [a] betterIterate f = myUnfoldr (\a -> Just (a, f a)) unfoldB :: (a -> Maybe (a,b,a)) -> a -> BinaryTree b unfoldB f a = case f a of Nothing -> Leaf Just (al,b,ar) -> Node (unfoldB f al) b (unfoldB f ar) treeBuild :: Integer -> BinaryTree Integer treeBuild n | n<0 = Leaf | otherwise = unfoldB f' 0 where f' x | x == n = Nothing | otherwise = Just (x+1,x,x+1) data Optional a = Nada | Only a deriving (Eq, Show) instance (Arbitrary a) => Arbitrary (Optional a) where arbitrary = frequency [(1, return Nada), (1, Only <$> arbitrary)] instance (Eq a) => EqProp (Optional a) where (=-=) = eq instance Functor Optional where fmap f Nada = Nada fmap f (Only a) = Only $ f a -- CH15, MONOID, SEMIGROUP instance Monoid a => Monoid (Optional a) where mempty = Nada mappend Nada Nada = Nada mappend (Only x) Nada = Only x mappend Nada (Only x) = Only x mappend (Only a) (Only b) = Only $ mappend a b instance Foldable Optional where foldMap f Nada = mempty foldMap f (Only a) = f a -- CH21, TRAVERSABLE instance Traversable Optional where traverse f (Only a) = Only <$> f a traverse f Nada = pure Nada --let trigger = undefined :: Optional (Int, Int, [Int]) --quickBatch (Test.QuickCheck.Classes.traversable trigger) newtype First' a = First' { getFirst' :: Optional a} deriving (Eq, Show) instance Monoid (First' a) where mempty = First' { getFirst' = Nada} mappend (First' Nada) (First' b) = First' b mappend (First' a) _ = First' a firstGen' :: Arbitrary a => Gen (First' a) firstGen' = do a <- arbitrary elements [First' Nada, First' (Only a)] instance (Arbitrary a) => Arbitrary (First' a) where -- arbitrary = firstGen' arbitrary = do a <- arbitrary elements [First' Nada, First' (Only a)] firstMappend :: First' a -> First' a -> First' a firstMappend = mappend type FirstMappend = First' String -> First' String -> First' String -> Bool type FstId = First' String -> Bool semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool semigroupAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c) monoidLeftIdentity :: (Eq m, Monoid m, Semigroup m) => m -> Bool monoidLeftIdentity a = (mempty <> a) == a monoidRightIdentity :: (Eq m, Monoid m, Semigroup m) => m -> Bool monoidRightIdentity a = (a <> mempty) == a data Trivial = Trivial deriving (Eq, Show) instance Semigroup Trivial where _ <> _ = Trivial instance Arbitrary Trivial where arbitrary = return Trivial type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool instance Monoid Trivial where mempty = Trivial mappend = (<>) newtype Identity a = Identity a deriving (Eq, Show, Ord) instance (Semigroup a) => Semigroup (Identity a) where (Identity a) <> (Identity b) = Identity $ a <> b instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do a <- arbitrary return $ Identity a type IdentityAssoc a = Identity a -> Identity a -> Identity a -> Bool instance (Semigroup a, Monoid a) => Monoid (Identity a) where mempty = Identity mempty mappend = (<>) instance Functor Identity where fmap g (Identity a) = Identity (g a) instance Applicative Identity where pure = Identity Identity f <*> Identity a = Identity $ f a instance Monad Identity where return = pure Identity a >>= f = f a instance (Eq a) => EqProp (Identity a) where (=-=) = eq instance Foldable Identity where foldMap f (Identity a) = f a -- CH21, TRAVERSABLE instance Traversable Identity where traverse f (Identity a) = Identity <$> f a --let trigger = undefined :: Identity (Int, Int, [Int]) --quickBatch (Test.QuickCheck.Classes.traversable trigger) data Pair a = Pair a a deriving (Eq, Show) instance (Arbitrary a) => Arbitrary (Pair a) where arbitrary = do a <- arbitrary b <- arbitrary return $ Pair a b instance Functor Pair where fmap g (Pair x y) = Pair (g x) (g y) instance Applicative Pair where pure a = Pair a a Pair f f1 <*> Pair a a1 = Pair (f a) (f1 a1) instance (Eq a) => EqProp (Pair a) where (=-=) = eq --quickBatch $ Test.QuickCheck.Classes.applicative(Pair ("b", "w", 1) ("b", "w", 1)) data Two a b = Two a b deriving (Eq, Show) instance (Semigroup a, Semigroup b) => Semigroup (Two a b) where (Two a b) <> (Two c d) = Two (a <> c) (b <> d) instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where arbitrary = do a <- arbitrary b <- arbitrary return $ Two a b type TwoAssoc a b = Two a b -> Two a b -> Two a b -> Bool instance (Monoid a, Monoid b, Semigroup a, Semigroup b) => Monoid (Two a b) where mempty = Two mempty mempty mappend = (<>) instance Functor (Two a) where fmap g (Two a b) = Two a $ g b instance (Monoid a, Semigroup a) => Applicative (Two a) where pure = Two mempty Two a0 f <*> Two a1 b = Two (a0 <> a1) (f b) instance (Eq a, Eq b) => EqProp (Two a b) where (=-=) = eq --quickBatch $ applicative (undefined :: Two String (Int, Double, Char)) instance Foldable (Two a) where foldMap f (Two a b) = f b data Three' a b = Three' a b b deriving (Eq, Show) instance Functor (Three' a) where fmap g (Three' a b0 b1) = Three' a (g b0) (g b1) instance (Arbitrary a, Arbitrary b) => Arbitrary (Three' a b) where arbitrary = do a <- arbitrary b0 <- arbitrary b1 <- arbitrary return $ Three' a b0 b1 instance (Monoid a, Semigroup a) => Applicative (Three' a) where pure b = Three' mempty b b Three' a0 f0 f1 <*> Three' a1 b0 b1 = Three' (a0 <> a1) (f0 b0) (f1 b1) instance (Eq a, Eq b) => EqProp (Three' a b) where (=-=) = eq --quickBatch $ applicative (undefined :: Three' String (Int, Double, Char)) instance Foldable (Three' a) where foldMap f (Three' a b0 b1) = f b0 `mappend` f b1 instance Traversable (Three' a) where traverse f (Three' a b0 b1) = liftA2 (Three' a) (f b0) (f b1) newtype BoolConj = BoolConj Bool deriving (Eq, Show) instance Semigroup BoolConj where (BoolConj True) <> (BoolConj True) = BoolConj True _ <> _ = BoolConj False instance Arbitrary BoolConj where arbitrary = elements [BoolConj True, BoolConj False] type BoolConjAssoc = BoolConj -> BoolConj -> BoolConj -> Bool instance Monoid BoolConj where mempty = BoolConj True mappend = (<>) newtype BoolDisj = BoolDisj Bool deriving (Eq, Show) instance Semigroup BoolDisj where (BoolDisj False) <> (BoolDisj False) = BoolDisj False _ <> _ = BoolDisj True instance Arbitrary BoolDisj where arbitrary = elements [BoolDisj True, BoolDisj False] type BoolDisjAssoc = BoolDisj -> BoolDisj -> BoolDisj -> Bool instance Monoid BoolDisj where mempty = BoolDisj False mappend = (<>) data Or a b = Fst a | Snd b deriving (Eq, Show) instance Semigroup (Or a b) where (Snd a) <> _ = Snd a _ <> (Snd b) = Snd b (Fst a) <> (Fst b) = Fst b instance (Arbitrary a, Arbitrary b) => Arbitrary (Or a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [Fst a, Snd b] type OrAssoc a b = Or a b -> Or a b -> Or a b -> Bool newtype Combine a b = Combine { unCombine :: a -> b } instance (Semigroup b) => Semigroup (Combine a b) where (Combine f) <> (Combine g) = Combine $ \x -> f x <> g x instance (Monoid b, Semigroup b) => Monoid (Combine a b) where mempty = Combine $ const mempty mappend = (<>) newtype Comp a = Comp { unComp :: a -> a } instance Semigroup (Comp a) where (Comp f) <> (Comp g) = Comp $ f.g instance Monoid (Comp a) where mempty = Comp id mappend = (<>) data Validation a b = Failur a | Succss b deriving (Eq, Show) instance Functor (Validation a) where fmap f (Failur a) = Failur a fmap f (Succss b) = Succss $ f b instance (Semigroup a) => Semigroup (Validation a b) where (Succss b) <> _ = Succss b (Failur a) <> (Succss b) = Succss b (Failur a0) <> (Failur a1) = Failur $ a0 <> a1 instance (Semigroup a) => Applicative (Validation a) where pure = Succss Succss f <*> Succss b = Succss $ f b Failur a <*> Failur b = Failur $ a <> b Failur a <*> _ = Failur a _ <*> Failur a = Failur a instance (Eq a, Eq b) => EqProp (Validation a b) where (=-=) = eq instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [Failur a, Succss b] --quickBatch $ Test.QuickCheck.Classes.applicative (Failur ("b",[3],"c")) type ValidationAssoc a b = Validation a b -> Validation a b -> Validation a b -> Bool newtype AccumulateRight a b = AccumulateRight (Validation a b) deriving (Eq, Show) instance (Semigroup b) => Semigroup (AccumulateRight a b) where (AccumulateRight (Succss b0)) <> (AccumulateRight (Succss b1)) = AccumulateRight $ Succss $ b0 <> b1 (AccumulateRight (Failur a)) <> (AccumulateRight (Succss b)) = AccumulateRight $ Failur a _ <> (AccumulateRight (Failur a)) = AccumulateRight $ Failur a instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateRight a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [AccumulateRight $ Failur a, AccumulateRight $ Succss b] type AccmuRAssoc a b = AccumulateRight a b -> AccumulateRight a b -> AccumulateRight a b -> Bool newtype AccumulateBoth a b = AccumulateBoth (Validation a b) deriving (Eq, Show) instance (Semigroup a, Semigroup b) => Semigroup (AccumulateBoth a b) where (AccumulateBoth (Failur a0)) <> (AccumulateBoth (Failur a1)) = AccumulateBoth $ Failur $ a0 <> a1 (AccumulateBoth (Succss b0)) <> (AccumulateBoth (Succss b1)) = AccumulateBoth $ Succss $ b0 <> b1 (AccumulateBoth (Failur a)) <> (AccumulateBoth (Succss b)) = AccumulateBoth $ Failur a (AccumulateBoth (Succss b)) <> (AccumulateBoth (Failur a)) = AccumulateBoth $ Failur a instance (Arbitrary a , Arbitrary b) => Arbitrary (AccumulateBoth a b) where arbitrary = do a <- arbitrary b <- arbitrary elements [AccumulateBoth $ Failur a, AccumulateBoth $ Failur b] type AccmuBoAssoc a b = AccumulateBoth a b -> AccumulateBoth a b -> AccumulateBoth a b -> Bool newtype Mem s a = Mem { runMem :: s -> (a,s) } instance (Monoid a, Semigroup a) => Monoid (Mem s a) where mempty = Mem $ \s -> (mempty, s) mappend = (<>) instance (Semigroup a) => Semigroup (Mem s a) where (Mem f) <> (Mem g) = Mem $ \x -> let (a0, s0) = f x (a1, _) = g x a' = a0 <> a1 (_, s') = g s0 in (a', s') functorIdentity :: (Functor f, Eq (f a)) => f a -> Bool functorIdentity f = fmap id f == f functorCompose :: (Eq (f c), Functor f) => (a -> b) -> (b -> c) -> f a -> Bool functorCompose f g x = fmap g (fmap f x) == fmap (g . f) x data Possibly a = LolNope | Yeppers a deriving (Eq, Show) instance Functor Possibly where fmap g (Yeppers a) = Yeppers $ g a fmap g LolNope = LolNope -- P 663 data Quant a b = Finace | Desk a | Bloor b deriving (Eq, Show) instance Functor (Quant a) where fmap g (Bloor b) = Bloor $ g b fmap _ Finace = Finace fmap _ (Desk a) = Desk a data K a b = K a deriving (Eq, Show) instance Functor (K a) where fmap g (K a) = K a newtype Flip f a b = Flip (f b a) deriving (Eq, Show) instance Functor (Flip K a) where fmap g (Flip (K b)) = Flip $ K (g b) data EvilGoateeConst a b = GoatyConst b deriving (Eq, Show) instance Functor (EvilGoateeConst a) where fmap g (GoatyConst b) = GoatyConst $ g b data LiftItOut f a = LiftItOut (f a) deriving (Eq, Show) instance (Functor f) => Functor (LiftItOut f) where fmap g (LiftItOut fa) = LiftItOut $ fmap g fa data Parappa f g a = DaWrappa (f a) (g a) deriving (Eq, Show) instance (Functor f, Functor g) => Functor (Parappa f g) where fmap g (DaWrappa fa ga) = DaWrappa (fmap g fa) (fmap g ga) data IgnoreOne f g a b = IgnoringSomething (f a) (g b) deriving (Eq, Show) instance (Functor g) => Functor (IgnoreOne f g a) where fmap g (IgnoringSomething fa gb) = IgnoringSomething fa (fmap g gb) data Notorious g o a t = Notorious (g o) (g a) (g t) deriving (Eq, Show) instance (Functor g) => Functor (Notorious g o a) where fmap g (Notorious go ga gt) = Notorious go ga $ fmap g gt data List a = Nil | Cons a (List a) deriving (Eq, Show) instance (Arbitrary a) => Arbitrary (List a) where arbitrary = frequency [(9,liftA2 Cons arbitrary arbitrary),(1,return Nil)] -- OR Cons <$> arbitrary <*> arbitrary -- instance Monoid (List a) where -- mempty = Nil -- mappend = append instance Functor List where fmap g Nil = Nil fmap g (Cons a tail) = Cons (g a) $ fmap g tail instance Applicative List where pure a = Cons a Nil Nil <*> _ = Nil _ <*> Nil = Nil funcs <*> vals = concat' $ fmap flatmapFn funcs where flatmapFn f = flatMap (pure.f) vals -- OR with explicit pattern matching -- Cons f restf <*> vals = -- (f <$> vals) `append` (restf <*> vals) instance Monad List where return = pure -- does not work: join $ f <$> list (>>=) = flip flatMap -- OR -- list >>= f = flatMap f list -- OR -- Nil >>= f = Nil -- Cons a rest >>= f = f a `append` (rest >>= f) instance (Eq a) => EqProp (List a) where (=-=) = eq -- xs =-= ys = xs' `eq` ys' where -- xs' = take' 3000 xs -- ys' = take' 3000 ys instance Foldable List where foldMap f Nil = mempty foldMap f (Cons h t) = f h `mappend` foldMap f t instance Traversable List where traverse f Nil = pure Nil traverse f (Cons h t) = liftA2 Cons (f h) (traverse f t) append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x $ xs `append` ys fold :: (a -> b -> b) -> b -> List a -> b fold _ b Nil = b fold f b (Cons h t) = f h (fold f b t) concat' :: List (List a) -> List a concat' = fold append Nil flatMap :: (a -> List b) -> List a -> List b flatMap f as = concat' $ f <$> as take' :: Int -> List a -> List a take' _ Nil = Nil take' n (Cons a tail) | n <= 0 = Nil | otherwise = Cons a $ take' (n-1) tail repeatList :: a -> List a repeatList x = Cons x $ repeatList x newtype ZipList' a = ZipList' (List a) deriving (Eq, Show) instance Functor ZipList' where fmap f (ZipList' xs) = ZipList' $ fmap f xs instance Applicative ZipList' where pure a = ZipList' $ repeatList a ZipList' funcs <*> ZipList' vals = ZipList' $ zip' funcs vals where zip' _ Nil = Nil zip' Nil _ = Nil zip' (Cons f ft) (Cons v vt) = Cons (f v) $ zip' ft vt instance (Eq a) => EqProp (ZipList' a) where xs =-= ys = xs' `eq` ys' where xs' = let (ZipList' l) = xs in take' 3000 l ys' = let (ZipList' l) = ys in take' 3000 l instance (Arbitrary a) => Arbitrary (ZipList' a) where arbitrary = ZipList' <$> arbitrary --quickBatch $ Test.QuickCheck.Classes.applicative (ZipList' (Cons ("b", "w", 1) Nil)) bench f = do start <- getCurrentTime evaluate f end <- getCurrentTime print (diffUTCTime end start) data GoatLord a = NoGoat | OneGoat a | MoreGoats (GoatLord a) (GoatLord a) (GoatLord a) deriving (Eq, Show) instance Functor GoatLord where fmap g NoGoat = NoGoat fmap g (OneGoat a) = OneGoat $ g a fmap g (MoreGoats a1 a2 a3) = MoreGoats (fmap g a1) (fmap g a2) (fmap g a3) data TalkToMe a = Halt | Print String a | Read {getTalk :: String -> a} instance Functor TalkToMe where fmap g Halt = Halt fmap g (Print str a) = Print str $ g a fmap g (Read fsa) = Read $ g.fsa --getTalk (fmap (+1) (fmap (*4) (Read length))) "ffff" --getTalk (fmap (+1).(*4) (Read length)) "ffff" --getF (fmap id (Read length )) "ffff" -- P686 newtype Constant a b = Constant {getConstant :: a} deriving (Eq, Show, Ord) instance (Arbitrary a) => Arbitrary (Constant a b) where arbitrary = Constant <$> arbitrary instance Functor (Constant a) where fmap g (Constant a) = Constant a instance (Semigroup a, Monoid a) => Applicative (Constant a) where pure _ = Constant mempty Constant a0 <*> Constant a1 = Constant $ a0 <> a1 instance Foldable (Constant a) where foldMap f ta = mempty instance (Eq a, Eq b) => EqProp (Constant a b) where (=-=) = eq -- CH21, TRAVERSABLE instance Traversable (Constant a) where traverse f (Constant a) = pure $ Constant a --let trigger = undefined :: Constant Int (Int, Int, [Int]) --quickBatch (Test.QuickCheck.Classes.traversable trigger) -- P751 data Sum1 a b = First1 a | Second1 b deriving (Eq, Show) instance Functor (Sum1 a) where fmap f (First1 a) = First1 a fmap f (Second1 b) = Second1 $ f b instance Applicative (Sum1 a) where pure = Second1 First1 a <*> _ = First1 a Second1 f <*> r = fmap f r instance Monad (Sum1 a) where return = pure First1 a >>= _ = First1 a Second1 b >>= f = f b -- P763 data Nope a = NopeDotJpg deriving (Eq, Show) instance Functor Nope where fmap g NopeDotJpg = NopeDotJpg instance Applicative Nope where pure _ = NopeDotJpg NopeDotJpg <*> NopeDotJpg = NopeDotJpg instance Monad Nope where return = pure NopeDotJpg >>= f = NopeDotJpg instance Arbitrary (Nope a) where arbitrary = return NopeDotJpg instance EqProp (Nope a) where (=-=) = eq data PhhhbbtttEither b a = LeftP a | RightP b deriving (Eq, Show) instance Functor (PhhhbbtttEither b) where fmap f (RightP b) = RightP b fmap f (LeftP a) = LeftP $ f a instance Applicative (PhhhbbtttEither b) where pure = LeftP --LeftP f <*> LeftP b = LeftP $ f b RightP b <*> _ = RightP b LeftP f <*> r = fmap f r instance Monad (PhhhbbtttEither b) where return = pure LeftP a >>= f = f a RightP b >>= _ = RightP b instance (Arbitrary b, Arbitrary a) => Arbitrary (PhhhbbtttEither b a) where arbitrary = do a <- arbitrary b <- arbitrary elements [LeftP a, RightP b] instance (Eq b, Eq a) => EqProp (PhhhbbtttEither b a) where (=-=) = eq --do --let trigger = undefined :: Nope (Int, String, Int) --quickBatch $ functor trigger --quickBatch $ applicative trigger --quickBatch $ monad trigger -- P 809 sum' :: (Foldable t, Num a) => t a -> a sum' xs = getSum $ foldMap Sum xs product' :: (Foldable t, Num a) => t a -> a product' xs = getProduct $ foldMap Product xs elem' :: (Foldable t, Eq a) => a -> t a -> Bool elem' a xs = getAny $ foldMap (Any . (a==)) xs minimum' :: (Foldable t, Ord a) => t a -> Maybe a minimum' = foldr f Nothing where f a Nothing = Just a f a (Just b) | a < b = Just a | otherwise = Just b maximum' :: (Foldable t, Ord a) => t a -> Maybe a maximum' = foldr f Nothing where f a Nothing = Just a f a (Just b) | a > b = Just a | otherwise = Just b null' :: (Foldable t) => t a -> Bool --null' xs = not.getAny $ foldMap (const $ Any True) xs null' xs = getAll $ foldMap (const $ All False) xs length' :: (Foldable t) => t a -> Int length' xs = getSum $ foldMap (const $ Sum 1) xs toList' :: (Foldable t) => t a -> [a] toList' = foldMap (:[]) fold' :: (Foldable t, Monoid m) => t m -> m fold' = foldMap id foldMap' :: (Foldable t, Monoid m) => (a->m) -> t a -> m foldMap' f = foldr (\a b -> f a `mappend` b) mempty filterF :: (Applicative f, Foldable t, Monoid (f a)) => (a -> Bool) -> t a -> f a filterF f = foldMap g where g a = if f a then mempty else pure a --filterF odd [1..10] :: [Int] --filterF (>3) [2] :: Maybe (Sum Int) --filterF (<3) [2] :: Maybe (Sum Int) data S n a = S (n a) a deriving (Eq, Show) instance (Eq a, Eq (n a)) => EqProp (S n a) where (=-=) = eq instance (Arbitrary a, CoArbitrary a, Arbitrary (n a)) => Arbitrary (S n a) where arbitrary = do n <- arbitrary a <- arbitrary return $ S (n a) a instance (Monoid a, Monoid (n a)) => Monoid (S n a) where mempty = S mempty mempty mappend (S na0 a0) (S na1 a1) = S (na0 `mappend` na1) (a0 `mappend` a1) instance (Functor n) => Functor (S n) where fmap f (S na a) = S (f <$> na) (f a) instance (Applicative n) => Applicative (S n) where pure a = S (pure a) a S nf f <*> S na a = S (nf <*> na) (f a) -- instance (Foldable n, Applicative n) => -- Monad (S n) where -- S n a >>= f = nb1 `mappend` f a where -- nb = f <$> n -- nb1 = foldMap id nb -- FAILED TO WRITE MONAD INSTANCE instance (Foldable n) => Foldable (S n) where foldMap f (S n a) = foldMap f n `mappend` f a instance (Traversable n) => Traversable (S n) where traverse f (S n a) = liftA2 S (traverse f n) (f a) data Tree a = EmptyT | LeafT a | NodeT (Tree a) a (Tree a) deriving (Eq, Show) instance (Eq a) => EqProp (Tree a) where (=-=) = eq instance (Arbitrary a) => Arbitrary (Tree a) where arbitrary = frequency [(2, return EmptyT), (1, LeafT <$> arbitrary), (3, liftA3 NodeT arbitrary arbitrary arbitrary)] instance Functor Tree where fmap f EmptyT = EmptyT fmap f (LeafT a) = LeafT (f a) fmap f (NodeT l a r) = NodeT (f<$>l) (f a) (f<$>r) instance Foldable Tree where foldMap f EmptyT = mempty foldMap f (LeafT a) = f a foldMap f (NodeT l a r) = foldMap f l `mappend` f a `mappend` foldMap f r instance Traversable Tree where traverse f EmptyT = pure EmptyT traverse f (LeafT a) = LeafT <$> f a traverse f (NodeT l a r) = liftA3 NodeT (traverse f l) (f a) (traverse f r) newtype Reader r a = Reader { runReader :: r -> a } instance Functor (Reader r) where fmap f (Reader ra) = Reader $ f.ra instance Applicative (Reader r) where pure :: a -> Reader r a pure = Reader . const -- pure a = Reader $ const a (<*>) :: Reader r (a -> b) -> Reader r a -> Reader r b (Reader rab) <*> (Reader ra) = Reader $ \r -> rab r (ra r) instance Monad (Reader r) where return = pure (>>=) :: Reader r a -> (a -> Reader r b) -> Reader r b Reader ra >>= aRb = Reader $ \r -> (runReader $ aRb (ra r)) r -- join $ Reader $ \r -> aRb (ra r) -- WOW newtype HumanName = HumanName String deriving (Eq, Show) newtype DogName = DogName String deriving (Eq, Show) newtype Address = Address String deriving (Eq, Show) data Person = Person {humanName :: HumanName, dogName :: DogName, address :: Address } deriving (Eq, Show) data Dog = Dog {dogsName :: DogName, dogsAddress :: Address } deriving (Eq, Show) getDogR'' :: Reader Person Dog getDogR'' = Dog <$> Reader dogName <*> Reader address --getDogR'' = Reader $ Dog <$> dogName <*> address --flip TO MATCH TYPES FOR MONAD INSTANCE getDogRM :: Reader Person Dog getDogRM = Reader $ address >>= flip (Dog <$> dogName) --flip :: (a -> b -> c) -> b -> a -> c --(Dog <$> Reader dogName) :: Reader Person (Address -> Dog) --SO NEED TO USE CUSTOM flipReader FOR NESTED Reader BELOW getDogRM' :: Reader Person Dog getDogRM' = Reader address >>= flipReader (Dog <$> Reader dogName) flipReader :: Reader a (b -> c) -> b -> Reader a c flipReader (Reader f) = Reader . flip f --flipReader (Reader f) = \b -> Reader $ flip f b newtype Moi s a = Moi {runMoi :: s -> (a, s)} instance Functor (Moi s) where fmap :: (a -> b) -> Moi s a -> Moi s b f `fmap` Moi g = Moi $ k <$> g where k (a, s) = (f a, s) instance Applicative (Moi s) where pure :: a -> Moi s a pure a = Moi $ \s -> (a, s) (<*>) :: Moi s (a -> b) -> Moi s a -> Moi s b Moi f <*> Moi g = Moi $ \s -> let (ab, s0) = f s (a, s') = g s0 in (ab a, s') instance Monad (Moi s) where return = pure (>>=) :: Moi s a -> (a -> Moi s b) -> Moi s b Moi f >>= g = Moi $ \s -> let (a, s0) = f s in runMoi (g a) s0 getMoi :: Moi s s getMoi = Moi $ \s -> (s, s) putMoi :: s -> Moi s () putMoi s = Moi $ const ((), s) execMoi :: Moi s a -> s -> s execMoi (Moi sa) s = snd $ sa s evalMoi :: Moi s a -> s -> a evalMoi (Moi sa) s = fst $ sa s modifyMoi :: (s -> s) -> Moi s () modifyMoi f = Moi $ \s -> ((), f s)
fxmy/haskell-book-exercise
src/Wat.hs
gpl-3.0
38,325
0
18
10,795
16,613
8,583
8,030
-1
-1
main = do calcThis <- getLine print $ solveRPN calcThis solveRPN :: String -> Double solveRPN = head . foldl foldingFunction [] . words where foldingFunction (x:y:ys) "*" = (y * x):ys foldingFunction (x:y:ys) "+" = (y + x):ys foldingFunction (x:y:ys) "-" = (y - x):ys foldingFunction xs numberString = read numberString:xs
medik/lang-hack
Haskell/LearnYouAHaskell/c10/RPNCalc/RPNCalc.hs
gpl-3.0
363
4
12
92
172
85
87
9
4
{-# OPTIONS_GHC -fno-warn-orphans #-} module Language.PySMEIL.Instances ( Variable (..) ) where import Language.PySMEIL.AST -- TODO: Is there a better way to do this? instance Ord Variable where a `compare` b = s a `compare` s b where s (ParamVar _ i) = "param_" ++ i s (ConstVar _ i) = "const_" ++ i s (BusVar _ i j) = "bus_" ++ i ++ "_" ++ j s (NamedVar _ i) = "name_" ++ i
truls/almique
src/Language/PySMEIL/Instances.hs
gpl-3.0
418
0
10
116
149
80
69
9
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.OSLogin.Types -- 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) -- module Network.Google.OSLogin.Types ( -- * Service Configuration oSLoginService -- * OAuth Scopes , computeScope , cloudPlatformScope -- * PosixAccountOperatingSystemType , PosixAccountOperatingSystemType (..) -- * LoginProFileSSHPublicKeys , LoginProFileSSHPublicKeys , loginProFileSSHPublicKeys , lpfspkAddtional -- * Empty , Empty , empty -- * LoginProFile , LoginProFile , loginProFile , lpfPosixAccounts , lpfSSHPublicKeys , lpfName -- * ImportSSHPublicKeyResponse , ImportSSHPublicKeyResponse , importSSHPublicKeyResponse , ispkrLoginProFile , ispkrDetails -- * SSHPublicKey , SSHPublicKey , sshPublicKey , spkFingerprint , spkKey , spkName , spkExpirationTimeUsec -- * PosixAccount , PosixAccount , posixAccount , paGecos , paUid , paUsername , paShell , paPrimary , paAccountId , paName , paGid , paOperatingSystemType , paSystemId , paHomeDirectory -- * Xgafv , Xgafv (..) ) where import Network.Google.OSLogin.Types.Product import Network.Google.OSLogin.Types.Sum import Network.Google.Prelude -- | Default request referring to version 'v1' of the Cloud OS Login API. This contains the host and root path used as a starting point for constructing service requests. oSLoginService :: ServiceConfig oSLoginService = defaultService (ServiceId "oslogin:v1") "oslogin.googleapis.com" -- | View and manage your Google Compute Engine resources computeScope :: Proxy '["https://www.googleapis.com/auth/compute"] computeScope = Proxy -- | See, edit, configure, and delete your Google Cloud Platform data cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"] cloudPlatformScope = Proxy
brendanhay/gogol
gogol-oslogin/gen/Network/Google/OSLogin/Types.hs
mpl-2.0
2,342
0
7
512
238
163
75
57
1
-- | Round 1A 2015 Problem A. Mushroom Monster -- https://code.google.com/codejam/contest/4224486/dashboard module MushroomMonster where -- constant imports import Text.ParserCombinators.Parsec import Text.Parsec import System.IO (openFile, hClose, hGetContents, hPutStrLn, IOMode(ReadMode), stderr) import Debug.Trace (trace) -- variable imports import qualified Data.Set as S import Data.List (group, sort, sortBy, foldl', foldl1', inits) import Data.Char (ord) import qualified Data.Map as M -- variable Data data TestCase = TestCase Int -- ^ Number of intervals [Int] -- ^ Intervals deriving (Show, Eq, Ord) -- variable implementation solveCase tc@(TestCase n xs) = show c1 ++ " " ++ (show c2) where c1 = case1 xs c2 = case2 xs deltas xs = zipWith (-) xs (tail xs) case1 = sum . filter (>0) . deltas case2 :: [Int] -> Int case2 xs = if rate <= 0 then 0 else sum $ map (min rate) $ init xs where rate = maximum $ deltas xs -- Parser (variable part) parseSingleCase = do n <- parseInt eol xs <- parseInts eol <|> eof return $ TestCase n xs eol :: GenParser Char st () eol = char '\n' >> return () parseIntegral :: Integral a => (String -> a) -> GenParser Char st a parseIntegral rd = rd <$> (plus <|> minus <|> number) where plus = char '+' *> number minus = (:) <$> char '-' <*> number number = many1 digit parseInteger :: GenParser Char st Integer parseInteger = parseIntegral (read :: String -> Integer) parseIntegers :: GenParser Char st [Integer] parseIntegers = parseInteger `sepBy` (char ' ') parseInt :: GenParser Char st Int parseInt = parseIntegral (read :: String -> Int) parseInts :: GenParser Char st [Int] parseInts = parseInt `sepBy` (char ' ') -- -- constant part -- -- Parsing (constant part) -- | First number is number of test cases data TestInput = TestInput Int -- ^ number of 'TestCase's [TestCase] deriving (Show, Ord, Eq) parseTestCases = do numCases <- parseInt eol cases <- count numCases parseSingleCase return $ TestInput numCases cases parseCases :: String -> Either ParseError TestInput parseCases contents = parse parseTestCases "(stdin)" contents -- main runOnContent :: String -> IO () runOnContent content = do let parsed = parseCases content case parsed of Right (TestInput _ cases) -> mapM_ putStrLn (output (solveCases cases)) Left err -> hPutStrLn stderr $ show err where solveCases xs = map solveCase xs consCase n s = "Case #" ++ (show n) ++ ": " ++ s output xs = zipWith consCase [1..] xs -- | command line implementation run = do cs <- getContents runOnContent cs main = run
dirkz/google-code-jam-haskell
practice/src/MushroomMonster.hs
mpl-2.0
2,758
0
14
664
878
466
412
68
2
{-# LANGUAGE QuasiQuotes, FlexibleInstances #-} module Trigger where import Str(str) import Util import Console import Diff import Data.Bits import Debug.Trace triggerList = [str| SELECT n.nspname as "Schema", c.relname AS "Relation", t.tgname AS "Name", tgtype AS "Type", t.tgenabled = 'O' AS enabled, concat (np.nspname, '.', p.proname) AS procedure, pg_get_triggerdef(t.oid) as definition FROM pg_catalog.pg_trigger t JOIN pg_catalog.pg_class c ON t.tgrelid = c.oid JOIN pg_catalog.pg_namespace n ON c.relnamespace = n.oid JOIN pg_catalog.pg_proc p ON t.tgfoid = p.oid JOIN pg_catalog.pg_namespace np ON p.pronamespace = np.oid WHERE t.tgconstraint = 0 AND n.nspname IN (select * from unnest(current_schemas(false))) ORDER BY 1,2,3 |] data TriggerWhen = After | Before | InsteadOf deriving (Show, Eq) data TriggerWhat = Insert | Delete | Update | Truncate deriving (Show, Eq) data TriggerType = TriggerType TriggerWhen [TriggerWhat] TriggerHow deriving (Show, Eq) data TriggerHow = ForEachRow | ForEachStatement deriving (Show, Eq) mktt x = let w = if testBit x 1 then Before else if testBit x 6 then InsteadOf else After t = map snd $ filter (\(b,z) -> testBit x b) $ [(2,Insert), (3,Delete), (4,Update), (5,Truncate)] h = if testBit x 0 then ForEachRow else ForEachStatement in TriggerType w t h {- tgtype is the type (INSERT, UPDATE) tgattr is which column -} data DbTrigger = DbTrigger { schema :: String, relation :: String, name :: String, triggerType :: TriggerType, enabled :: Bool, procedure :: String, definition :: String } deriving(Show) mkdbt (a:b:c:d:e:f:g:_) = DbTrigger (gs a) (gs b) (gs c) (mktt (gi d)) (gb e) (gs f) (gs g) instance Show (Comparison DbTrigger) where show (Equal x) = concat [sok, showTrigger x, treset] show (LeftOnly a) = concat [azure, [charLeftArrow]," ", showTrigger a, treset] show (RightOnly a) = concat [peach, [charRightArrow], " ", showTrigger a, treset] show (Unequal a b) = concat [nok, showTrigger a, treset, if compareIgnoringWhiteSpace (definition a) (definition b) then "" else concat [setAttr bold,"\n definition differences: \n", treset, concatMap show $ diff (definition a) (definition b)] ] instance Comparable DbTrigger where objCmp a b = if compareIgnoringWhiteSpace (definition a) (definition b) then Equal a else Unequal a b compareTriggers (get1, get2) = do aa <- get1 triggerList -- aac <- get1 viewColumns -- aat <- get1 viewTriggers -- aar <- get1 viewRules bb <- get2 triggerList -- bbc <- get2 viewColumns -- bbt <- get2 viewTriggers -- bbr <- get2 viewRules let a = map mkdbt aa let b = map mkdbt bb let cc = dbCompare a b let cnt = dcount iseq cc putStr $ if fst cnt > 0 then sok ++ show (fst cnt) ++ " matches, " else "" putStrLn $ if snd cnt > 0 then concat [setColor dullRed,show $ snd cnt," differences"] else concat [sok,"no differences"] putStr treset return $ filter (not . iseq) cc showTrigger x = concat [schema x, ".", relation x, "." , name x] instance Ord DbTrigger where compare a b = let hd p = map ($ p) [schema, relation, name] in compare (hd a) (hd b) instance Eq DbTrigger where (==) a b = EQ == compare a b
sourcewave/pg-schema-diff
Trigger.hs
unlicense
3,319
0
14
731
1,060
565
495
48
4
--- (c) Martin Braun, November 2015 --- 101lang is an experimental language --- used to learn the basics of programming --- language design with Haskell --- --- License: Apache 2.0 --- --- file: parser.hs module Parser where import Syntax import Text.ParserCombinators.Parsec {- -- Parsing the expression parseInteger = do sign <- option "" (string "-") number <- many1 digit return $ BlaiseInt (read (sign++number)) parseSymbol = do f <- firstAllowed r <- many (firstAllowed <|> digit) return $ BlaiseSymbol (f:r) where firstAllowed = oneOf "+-*/" <|> letter parseExprAux = (try parseInteger) <|> (try parseSymbol) <|> (try parseList) parseList = do char '(' ; skipMany space x <- parseExprAux `sepEndBy` (many1 space) char ')' return $ BlaiseList x parseExpr = do skipMany space x <- parseExprAux skipMany space ; eof return x parse :: String -> BlaiseResult parse source = case (Text.ParserCombinators.Parsec.parse parseExpr "" source) of Right x -> return x Left e -> throwError $ show e -}
s4ke/101lang
parser.hs
apache-2.0
1,090
0
4
253
22
18
4
3
0
module Main where import Control.Monad (replicateM) import qualified Data.ByteString as BS import Network.Simple.TCP import System.Environment import RL_Glue.Experiment import RL_Glue.Network main = do args <- getArgs let n = read $ head $ args runExperiment (doExperiments n) runExperiments :: Int -> IO () runExperiments n = do putStrLn "Maybe later..." doExperiments :: Int -> (Socket, SockAddr) -> IO () doExperiments n (sock, addr) = do taskSpec <- initExperiment sock putStrLn ("Sent task spec: " ++ show taskSpec) putStrLn "\n----------Running episodes----------" results <- replicateM n (prettyRunEpisode sock 0) let avgResult = (sum results) / (fromIntegral $ length results) putStrLn $ "Average result: " ++ show avgResult cleanupExperiment sock prettyRunEpisode :: Socket -> Int -> IO Double prettyRunEpisode sock steps = do terminal <- runEpisode sock steps totalSteps <- getNumSteps sock totalReward <- getReturn sock putStrLn $ "Ran for " ++ show totalSteps ++ " steps.\tGot a reward of " ++ show totalReward return totalReward
rhofour/PlayingAtari
src/SimpleExperiment.hs
apache-2.0
1,083
0
13
193
342
165
177
30
1
module Lambda.Reduce ( -- * Normal-order beta reduction reduce ) where import Control.Monad ( MonadPlus , guard ) import Lambda.Deconstruct import Lambda.Term {- | Normal-order beta reduction (capture-avoiding substitution). If the input term is not a beta redex, this produces 'A.empty'. A beta redex is an @App x y@ where @x@ is a lambda abstraction or a beta redex. Note that there is a beta redex that reduces to itself such as @(\\ x -> x x) (\\ x -> x x)@. Redex is an acronym for /red/ucible /ex/pression. -} reduce :: (MonadPlus m, Term t) => t -> m t reduce t = app (lam pure pure) pure t |> (\ ((name, body), arg) -> substitute name arg body) <|> (app pure pure t >>= \ (fun, arg) -> mkApp <$> reduce fun <*> pure arg) -- | Capture-avoiding substitution. substitute :: (Term t) => String -> t -> t -> t substitute name replacement = subst where subst term = varNamed name term |> const replacement <|> app pure pure term |> (\ (fun, arg) -> mkApp (subst fun) (subst arg)) <|> lamNotNamed name term |> (\ (n, body) -> mkLam n (subst body)) <!> term varNamed name_ t = do n <- var t guard (n == name_) pure () lamNotNamed name_ t = do (n, body) <- lam pure pure t guard (n /= name_) pure (n, body)
edom/ptt
src/Lambda/Reduce.hs
apache-2.0
1,403
0
15
429
403
209
194
28
1
module Codec.JVM (module X) where import Codec.JVM.ASM as X import Codec.JVM.Class as X import Codec.JVM.Types as X import Codec.JVM.ASM.Code as X import Codec.JVM.ASM.Code.Types as X hiding (BranchType(..))
rahulmutt/codec-jvm
src/Codec/JVM.hs
apache-2.0
209
0
6
28
65
48
17
6
0
module NLP.Crubadan (readCrData) where import qualified Data.Map as M import qualified Data.Text as T import Text.ParserCombinators.Parsec import NLP.General import NLP.Freq readCrData :: String -> IO (FreqList TriGram) readCrData fpath = do s <- readFile fpath let ngs = (fmap M.fromList . parse triGramFile "err") s return (case ngs of Right fm -> FreqList fm Left e -> error (show e)) triGramFile :: GenParser Char st [(TriGram, Frequency)] triGramFile = do result <- many line eof return result line = do a <- noneOf "\n " b <- noneOf "\n " c <- noneOf "\n " char ' ' freq <- many (noneOf "\n") char '\n' return (TriGram (toTok a) (toTok b) (toTok c), read freq)
RoboNickBot/nlp-libs
src/NLP/Crubadan.hs
bsd-2-clause
813
0
14
261
299
145
154
24
2
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} module CLaSH.GHC.LoadInterfaceFiles (loadExternalExprs) where -- External Modules import Data.Either (partitionEithers) import Data.List (elemIndex, partition) import Data.Maybe (isJust, isNothing) -- GHC API import qualified BasicTypes import CLaSH.GHC.Compat.Outputable (showPpr, showSDoc) import qualified Class import qualified CoreFVs import qualified CoreSyn import qualified GHC import qualified Id import qualified IdInfo import qualified IfaceSyn import qualified LoadIface import qualified Maybes import qualified MkCore import qualified MonadUtils import qualified Name import Outputable (text) import qualified TcIface import qualified TcRnMonad import qualified TcRnTypes import qualified UniqFM import qualified Var import qualified VarSet -- Internal Modules import CLaSH.Util (curLoc, traceIf) runIfl :: GHC.GhcMonad m => GHC.Module -> TcRnTypes.IfL a -> m a runIfl modName action = do hscEnv <- GHC.getSession let localEnv = TcRnTypes.IfLclEnv modName (text "runIfl") UniqFM.emptyUFM UniqFM.emptyUFM let globalEnv = TcRnTypes.IfGblEnv Nothing MonadUtils.liftIO $ TcRnMonad.initTcRnIf 'r' hscEnv globalEnv localEnv action loadDecl :: IfaceSyn.IfaceDecl -> TcRnTypes.IfL GHC.TyThing loadDecl = TcIface.tcIfaceDecl False loadIface :: GHC.Module -> TcRnTypes.IfL (Maybe GHC.ModIface) loadIface foundMod = do ifaceFailM <- LoadIface.findAndReadIface (Outputable.text "loadIface") foundMod False case ifaceFailM of Maybes.Succeeded (modInfo,_) -> return (Just modInfo) Maybes.Failed msg -> traceIf True ($(curLoc) ++ "Failed to load interface for module: " ++ showPpr foundMod ++ "\nReason: " ++ showSDoc msg) $ return Nothing loadExternalExprs :: GHC.GhcMonad m => [CoreSyn.CoreExpr] -> [CoreSyn.CoreBndr] -> m ( [(CoreSyn.CoreBndr,CoreSyn.CoreExpr)] -- Binders , [(CoreSyn.CoreBndr,Int)] -- Class Ops , [CoreSyn.CoreBndr] -- Unlocatable ) loadExternalExprs [] _ = return ([],[],[]) loadExternalExprs (expr:exprs) visited = do let fvs = VarSet.varSetElems $ CoreFVs.exprSomeFreeVars (\v -> Var.isId v && isNothing (Id.isDataConId_maybe v) && v `notElem` visited ) expr let (clsOps,fvs') = partition (isJust . Id.isClassOpId_maybe) fvs (locatedExprs,unlocated) <- fmap partitionEithers $ mapM loadExprFromIface fvs' let visited' = concat [ map fst locatedExprs , unlocated , clsOps , visited ] (locatedExprs', clsOps', unlocated') <- loadExternalExprs (exprs ++ map snd locatedExprs) visited' let clsOps'' = map ( \v -> flip (maybe (error $ $(curLoc) ++ "Not a class op")) (Id.isClassOpId_maybe v) $ \c -> let clsIds = Class.classAllSelIds c in maybe (error $ $(curLoc) ++ "Index not found") (v,) (elemIndex v clsIds) ) clsOps return ( locatedExprs ++ locatedExprs' , clsOps'' ++ clsOps' , unlocated ++ unlocated' ) loadExprFromIface :: GHC.GhcMonad m => CoreSyn.CoreBndr -> m (Either (CoreSyn.CoreBndr,CoreSyn.CoreExpr) CoreSyn.CoreBndr ) loadExprFromIface bndr = do let moduleM = Name.nameModule_maybe $ Var.varName bndr case moduleM of Just nameMod -> runIfl nameMod $ do ifaceM <- loadIface nameMod case ifaceM of Nothing -> return (Right bndr) Just iface -> do let decls = map snd (GHC.mi_decls iface) let nameFun = GHC.getOccName $ Var.varName bndr let declM = filter ((== nameFun) . IfaceSyn.ifName) decls case declM of [namedDecl] -> do tyThing <- loadDecl namedDecl return $ loadExprFromTyThing bndr tyThing _ -> return (Right bndr) Nothing -> return (Right bndr) loadExprFromTyThing :: CoreSyn.CoreBndr -> GHC.TyThing -> Either (CoreSyn.CoreBndr,CoreSyn.CoreExpr) -- Located Binder CoreSyn.CoreBndr -- unlocatable Var loadExprFromTyThing bndr tyThing = case tyThing of GHC.AnId _id | Var.isId _id -> let unfolding = IdInfo.unfoldingInfo $ Var.idInfo _id inlineInfo = IdInfo.inlinePragInfo $ Var.idInfo _id in case unfolding of (CoreSyn.CoreUnfolding {}) -> case (BasicTypes.inl_inline inlineInfo,BasicTypes.inl_act inlineInfo) of (BasicTypes.NoInline,BasicTypes.AlwaysActive) -> Right bndr (BasicTypes.NoInline,BasicTypes.NeverActive) -> Right bndr (BasicTypes.NoInline,_) -> Left (bndr, CoreSyn.unfoldingTemplate unfolding) _ -> Left (bndr, CoreSyn.unfoldingTemplate unfolding) (CoreSyn.DFunUnfolding dfbndrs dc es) -> let dcApp = MkCore.mkCoreConApps dc es dfExpr = MkCore.mkCoreLams dfbndrs dcApp in Left (bndr,dfExpr) _ -> Right bndr _ -> Right bndr
christiaanb/clash-compiler
clash-ghc/src-ghc/CLaSH/GHC/LoadInterfaceFiles.hs
bsd-2-clause
5,462
0
24
1,616
1,477
765
712
127
7
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE FlexibleContexts #-} module Data.CRF.Chain2.Generic.Model ( FeatGen (..) , FeatSel , selectPresent , selectHidden , Model (..) , mkModel , Core (..) , core , withCore , phi , index , presentFeats , hiddenFeats , obFeatsOn , trFeatsOn , onWord , onTransition , lbNum , lbOn , lbIxs ) where import Control.Applicative ((<$>), (<*>)) import Data.Maybe (maybeToList) import Data.Binary (Binary, put, get) import Data.Vector.Binary () import qualified Data.Set as S import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Number.LogFloat as L import Data.CRF.Chain2.Generic.Internal import Data.CRF.Chain2.Generic.FeatMap -- | Feature generation specification. data FeatGen o t f = FeatGen { obFeats :: o -> t -> [f] , trFeats1 :: t -> [f] , trFeats2 :: t -> t -> [f] , trFeats3 :: t -> t -> t -> [f] } -- | A conditional random field. data Model m o t f = Model { values :: U.Vector Double , ixMap :: m f , featGen :: FeatGen o t f } -- | A core of the model with no feature generation function. -- Unlike the 'Model', the core can be serialized. data Core m f = Core { valuesC :: U.Vector Double , ixMapC :: m f } instance Binary (m f) => Binary (Core m f) where put Core{..} = put valuesC >> put ixMapC get = Core <$> get <*> get -- | Extract the model core. core :: Model m o t f -> Core m f core Model{..} = Core values ixMap -- | Construct model with the given core and feature generation function. withCore :: Core m f -> FeatGen o t f -> Model m o t f withCore Core{..} ftGen = Model valuesC ixMapC ftGen -- | Features present in the dataset element together with corresponding -- occurence probabilities. presentFeats :: FeatGen o t f -> Xs o t -> Ys t -> [(f, L.LogFloat)] presentFeats fg xs ys = concat [ obFs i ++ trFs i | i <- [0 .. V.length xs - 1] ] where obFs i = [ (ft, L.logFloat pr) | o <- unX (xs V.! i) , (u, pr) <- unY (ys V.! i) , ft <- obFeats fg o u ] trFs 0 = [ (ft, L.logFloat pr) | (u, pr) <- unY (ys V.! 0) , ft <- trFeats1 fg u ] trFs 1 = [ (ft, L.logFloat pr1 * L.logFloat pr2) | (u, pr1) <- unY (ys V.! 1) , (v, pr2) <- unY (ys V.! 0) , ft <- trFeats2 fg u v ] trFs i = [ (ft, L.logFloat pr1 * L.logFloat pr2 * L.logFloat pr3) | (u, pr1) <- unY (ys V.! i) , (v, pr2) <- unY (ys V.! (i-1)) , (w, pr3) <- unY (ys V.! (i-2)) , ft <- trFeats3 fg u v w ] -- | Features hidden in the dataset element. hiddenFeats :: FeatGen o t f -> Xs o t -> [f] hiddenFeats fg xs = obFs ++ trFs where obFs = concat [ obFeatsOn fg xs i u | i <- [0 .. V.length xs - 1] , u <- lbIxs xs i ] trFs = concat [ trFeatsOn fg xs i u v w | i <- [0 .. V.length xs - 1] , u <- lbIxs xs i , v <- lbIxs xs $ i - 1 , w <- lbIxs xs $ i - 2 ] -- | A feature selection function type. type FeatSel o t f = FeatGen o t f -> Xs o t -> Ys t -> [f] -- | The 'presentFeats' adapted to fit feature selection specs. selectPresent :: FeatSel o t f selectPresent fg xs = map fst . presentFeats fg xs -- | The 'hiddenFeats' adapted to fit feature selection specs. selectHidden :: FeatSel o t f selectHidden fg xs _ = hiddenFeats fg xs mkModel :: (Ord f, FeatMap m f) => FeatGen o t f -> FeatSel o t f -> [(Xs o t, Ys t)] -> Model m o t f mkModel fg ftSel dataset = Model { values = U.replicate (S.size fs) 0.0 , ixMap = let featIxs = map FeatIx [0..] featLst = S.toList fs in mkFeatMap (zip featLst featIxs) , featGen = fg } where fs = S.fromList $ concatMap select dataset select = uncurry (ftSel fg) -- | Potential assigned to the feature -- exponential of the -- corresonding parameter. phi :: FeatMap m f => Model m o t f -> f -> L.LogFloat phi Model{..} ft = case featIndex ft ixMap of Just ix -> L.logToLogFloat (values U.! unFeatIx ix) Nothing -> L.logToLogFloat (0 :: Float) {-# INLINE phi #-} -- | Index of the feature. index :: FeatMap m f => Model m o t f -> f -> Maybe FeatIx index Model{..} ft = featIndex ft ixMap {-# INLINE index #-} obFeatsOn :: FeatGen o t f -> Xs o t -> Int -> LbIx -> [f] obFeatsOn featGen xs i u = concat [ feats ob e | e <- lbs , ob <- unX (xs V.! i) ] where feats = obFeats featGen lbs = maybeToList (lbOn xs i u) {-# INLINE obFeatsOn #-} trFeatsOn :: FeatGen o t f -> Xs o t -> Int -> LbIx -> LbIx -> LbIx -> [f] trFeatsOn featGen xs i u' v' w' = doIt a b c where a = lbOn xs i u' b = lbOn xs (i - 1) v' c = lbOn xs (i - 2) w' doIt (Just u) (Just v) (Just w) = trFeats3 featGen u v w doIt (Just u) (Just v) _ = trFeats2 featGen u v doIt (Just u) _ _ = trFeats1 featGen u doIt _ _ _ = [] {-# INLINE trFeatsOn #-} onWord :: FeatMap m f => Model m o t f -> Xs o t -> Int -> LbIx -> L.LogFloat onWord crf xs i u = product . map (phi crf) $ obFeatsOn (featGen crf) xs i u {-# INLINE onWord #-} onTransition :: FeatMap m f => Model m o t f -> Xs o t -> Int -> LbIx -> LbIx -> LbIx -> L.LogFloat onTransition crf xs i u w v = product . map (phi crf) $ trFeatsOn (featGen crf) xs i u w v {-# INLINE onTransition #-}
kawu/crf-chain2-generic
Data/CRF/Chain2/Generic/Model.hs
bsd-2-clause
5,446
0
14
1,600
2,211
1,165
1,046
146
4
-- | Peer proceeses {-# LANGUAGE ScopedTypeVariables, BangPatterns #-} module Process.Peer ( -- * Interface Process.Peer.start -- * Tests , Process.Peer.testSuite ) where import Control.Applicative import Control.Concurrent import Control.Concurrent.STM import Control.DeepSeq import Control.Exception import Control.Monad.State import Control.Monad.Reader import Prelude hiding (log) import Data.Array import Data.Bits import qualified Data.ByteString as B import Data.Function (on) import qualified Data.PieceSet as PS import Data.Maybe import Data.Monoid(Monoid(..), Last(..)) import Data.Set as S hiding (map, foldl) import Data.Time.Clock import Data.Word import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit hiding (Path, Test, assert) import Channels import Digest import Crypto import Process import Process.FS import Process.PieceMgr import RateCalc as RC import Process.Status import qualified Process.ChokeMgr as ChokeMgr (RateTVar, PeerRateInfo(..)) import Process.Timer import Supervisor import Torrent import qualified Protocol.BCode as BCode (decode, encode, extendedP, extendedV, extendedMsg, extendedRReq) import Protocol.Wire import Version import qualified Process.Peer.Sender as Sender import qualified Process.Peer.SenderQ as SenderQ import qualified Process.Peer.Receiver as Receiver -- INTERFACE ---------------------------------------------------------------------- start :: ConnectedPeer -> Port -> [Capabilities] -> MgrChannel -> ChokeMgr.RateTVar -> PieceMgrChannel -> FSPChannel -> TVar [PStat] -> PieceMap -> Int -> InfoHash -> IO Children start connP port caps pMgrC rtv pieceMgrC fsC stv pm nPieces ih = do queueC <- newTChanIO senderMV <- newEmptyTMVarIO receiverC <- newTChanIO return [Worker $ Sender.start connP senderMV, Worker $ SenderQ.start caps queueC senderMV receiverC fsC, Worker $ Receiver.start connP receiverC, Worker $ peerP port caps pMgrC rtv pieceMgrC pm nPieces queueC receiverC stv ih] -- INTERNAL FUNCTIONS ---------------------------------------------------------------------- data CF = CF { myPort :: Port , inCh :: TChan MsgTy , outCh :: TChan SenderQ.SenderQMsg , peerMgrCh :: MgrChannel , pieceMgrCh :: PieceMgrChannel , statTV :: TVar [PStat] , rateTV :: ChokeMgr.RateTVar , pcInfoHash :: InfoHash , pieceMap :: !PieceMap , piecesDoneTV :: TMVar [PieceNum] , haveTV :: TMVar [PieceNum] , grabBlockTV :: TMVar Blocks , extConf :: ExtensionConfig } instance Logging CF where logName _ = "Process.Peer" data ST = ST { weChoke :: !Bool -- ^ True if we are choking the peer , weInterested :: !Bool -- ^ True if we are interested in the peer , blockQueue :: !(S.Set (PieceNum, Block)) -- ^ Blocks queued at the peer , peerChoke :: !Bool -- ^ Is the peer choking us? True if yes , peerInterested :: !Bool -- ^ True if the peer is interested , peerPieces :: !(PS.PieceSet) -- ^ List of pieces the peer has access to , missingPieces :: !Int -- ^ Tracks the number of pieces the peer misses before seeding , upRate :: !Rate -- ^ Upload rate towards the peer (estimated) , downRate :: !Rate -- ^ Download rate from the peer (estimated) , runningEndgame :: !Bool -- ^ True if we are in endgame , lastMsg :: !Int -- ^ Ticks from last Message , lastPieceMsg :: !Int -- ^ Ticks from last Piece Message , interestingPieces :: !(S.Set PieceNum) -- ^ peer pieces we are interested in , lastPn :: !PieceNum } data ExtensionConfig = ExtensionConfig { handleHaveAll :: Last (Process CF ST ()) , handleHaveNone :: Last (Process CF ST ()) , handleBitfield :: Last (BitField -> Process CF ST ()) , handleSuggest :: Last (PieceNum -> Process CF ST ()) , handleAllowedFast :: Last (PieceNum -> Process CF ST ()) , handleRejectRequest :: Last (PieceNum -> Block -> Process CF ST ()) , handleExtendedMsg :: Last (Word8 -> B.ByteString -> Process CF ST ()) , handleRequestMsg :: Last (PieceNum -> Block -> Process CF ST ()) , handleChokeMsg :: Last (Process CF ST ()) , handleCancelMsg :: Last (PieceNum -> Block -> Process CF ST ()) , handlePieceMsg :: Last (PieceNum -> Int -> B.ByteString -> Process CF ST ()) , sendExtendedMsg :: Last (Process CF ST ()) } emptyExtensionConfig :: ExtensionConfig emptyExtensionConfig = ExtensionConfig mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty mempty appendEConfig :: ExtensionConfig -> ExtensionConfig -> ExtensionConfig appendEConfig a b = ExtensionConfig { handleHaveAll = app handleHaveAll a b , handleHaveNone = app handleHaveNone a b , handleBitfield = app handleBitfield a b , handleSuggest = app handleSuggest a b , handleAllowedFast = app handleAllowedFast a b , handleRejectRequest = app handleRejectRequest a b , handleExtendedMsg = app handleExtendedMsg a b , handleRequestMsg = app handleRequestMsg a b , handleChokeMsg = app handleChokeMsg a b , handleCancelMsg = app handleCancelMsg a b , handlePieceMsg = app handlePieceMsg a b , sendExtendedMsg = app sendExtendedMsg a b } where app f = mappend `on` f instance Monoid ExtensionConfig where mempty = emptyExtensionConfig mappend = appendEConfig -- | Constructor for 'Last' values. ljust :: a -> Last a ljust = Last . Just -- | Deconstructor for 'Last' values. fromLJ :: (ExtensionConfig -> Last a) -- ^ Field to access. -> ExtensionConfig -- ^ Default to use. -> a fromLJ f cfg = case f cfg of Last Nothing -> fromLJ f extensionBase Last (Just a) -> a extensionBase :: ExtensionConfig extensionBase = ExtensionConfig (ljust errorHaveAll) (ljust errorHaveNone) (ljust bitfieldMsg) (ljust errorSuggest) (ljust errorAllowedFast) (ljust errorRejectRequest) (ljust errorExtendedMsg) (ljust requestMsg) (ljust chokeMsg) (ljust cancelBlock) (ljust pieceMsg) (ljust noExtendedMsg) fastExtension :: ExtensionConfig fastExtension = ExtensionConfig (ljust haveAllMsg) (ljust haveNoneMsg) (ljust bitfieldMsg) (ljust ignoreSuggest) (ljust ignoreAllowedFast) (ljust rejectMsg) mempty (ljust requestFastMsg) (ljust fastChokeMsg) (ljust fastCancelBlock) (ljust fastPieceMsg) mempty extendedMsgExtension :: ExtensionConfig extendedMsgExtension = ExtensionConfig mempty mempty mempty mempty mempty mempty (ljust extendedMsg) mempty mempty mempty mempty (ljust outputExtendedMsg) noExtendedMsg :: Process CF ST () noExtendedMsg = return () -- Deliberately ignore the extended message outputExtendedMsg :: Process CF ST () outputExtendedMsg = do P p <- asks myPort outChan $ SenderQ.SenderQM $ ExtendedMsg 0 (em p) where em p = BCode.encode (BCode.extendedMsg (fromIntegral p) ("Combinatorrent " ++ Version.version) 250) -- 250 is what most other clients default to. ignoreSuggest :: PieceNum -> Process CF ST () ignoreSuggest _ = debugP "Ignoring SUGGEST message" ignoreAllowedFast :: PieceNum -> Process CF ST () ignoreAllowedFast _ = debugP "Ignoring ALLOWEDFAST message" errorHaveAll :: Process CF ST () errorHaveAll = do errorP "Received a HAVEALL, but the extension is not enabled" stopP errorHaveNone :: Process CF ST () errorHaveNone = do errorP "Received a HAVENONE, but the extension is not enabled" stopP errorSuggest :: PieceNum -> Process CF ST () errorSuggest _ = do errorP "Received a SUGGEST PIECE, but the extension is not enabled" stopP errorAllowedFast :: PieceNum -> Process CF ST () errorAllowedFast _ = do errorP "Received a ALLOWEDFAST, but the extension is not enabled" stopP errorRejectRequest :: PieceNum -> Block -> Process CF ST () errorRejectRequest _ _ = do errorP "Received a REJECT REQUEST, but the extension is not enabled" stopP errorExtendedMsg :: Word8 -> B.ByteString -> Process CF ST () errorExtendedMsg _ _ = do errorP "Received an EXTENDED MESSAGE, but the extension is not enabled" stopP peerP :: Port -> [Capabilities] -> MgrChannel -> ChokeMgr.RateTVar -> PieceMgrChannel -> PieceMap -> Int -> TChan SenderQ.SenderQMsg -> TChan MsgTy -> TVar [PStat] -> InfoHash -> SupervisorChannel -> IO ThreadId peerP port caps pMgrC rtv pieceMgrC pm nPieces outBound inBound stv ih supC = do ct <- getCurrentTime pdtmv <- newEmptyTMVarIO havetv <- newEmptyTMVarIO gbtmv <- newEmptyTMVarIO pieceSet <- PS.new nPieces let cs = configCapabilities caps spawnP (CF port inBound outBound pMgrC pieceMgrC stv rtv ih pm pdtmv havetv gbtmv cs) (ST True False S.empty True False pieceSet nPieces (RC.new ct) (RC.new ct) False 0 0 S.empty 0) (cleanupP (startup nPieces) (defaultStopHandler supC) cleanup) configCapabilities :: [Capabilities] -> ExtensionConfig configCapabilities caps = mconcat [ if Fast `elem` caps then fastExtension else mempty, if Extended `elem` caps then extendedMsgExtension else mempty] startup :: Int -> Process CF ST () startup nPieces = do tid <- liftIO $ myThreadId pmc <- asks peerMgrCh ih <- asks pcInfoHash ich <- asks inCh liftIO . atomically $ writeTChan pmc $ Connect ih tid ich pieces <- getPiecesDone outChan $ SenderQ.SenderQM $ BitField (constructBitField nPieces pieces) -- eventually handle extended messaging asks extConf >>= fromLJ sendExtendedMsg -- Install the StatusP timer _ <- registerSTM 5 ich TimerTick eventLoop cleanup :: Process CF ST () cleanup = do t <- liftIO myThreadId pieces <- gets peerPieces >>= PS.toList ch2 <- asks peerMgrCh msgPieceMgr (PeerUnhave pieces) liftIO . atomically $ writeTChan ch2 (Disconnect t) readInCh :: Process CF ST MsgTy readInCh = do inb <- asks inCh liftIO . atomically $ readTChan inb eventLoop :: Process CF ST () eventLoop = do ty <- readInCh case ty of FromPeer (msg, sz) -> peerMsg msg sz TimerTick -> {-# SCC "timerTick" #-} timerTick FromSenderQ l -> {-# SCC "fromSender" #-} (do s <- get let !u = RC.update l $ upRate s put $! s { upRate = u}) FromChokeMgr m -> {-# SCC "chokeMgrMsg" #-} chokeMgrMsg m eventLoop -- | Return a list of pieces which are currently done by us getPiecesDone :: Process CF ST [PieceNum] getPiecesDone = do c <- asks piecesDoneTV msgPieceMgr (GetDone c) liftIO $ do atomically $ takeTMVar c trackInterestRemove :: PieceNum -> Process CF ST () trackInterestRemove pn = do im <- gets interestingPieces let !ns = S.delete pn im if S.null ns then do modify (\db -> db { interestingPieces = S.empty, weInterested = False }) debugP "We are not interested" outChan $ SenderQ.SenderQM NotInterested else modify (\db -> db { interestingPieces = ns }) trackInterestAdd :: [PieceNum] -> Process CF ST () trackInterestAdd pns = do c <- asks haveTV msgPieceMgr (PeerHave pns c) interesting <- liftIO . atomically $ takeTMVar c set <- gets interestingPieces let !ns = upd interesting set if S.null ns then modify (\db -> db { interestingPieces = S.empty }) else do modify (\db -> db { interestingPieces = ns, weInterested = True }) debugP "We are interested" outChan $ SenderQ.SenderQM Interested where upd is set = foldl (flip S.insert) set is -- | Process an event from the Choke Manager chokeMgrMsg :: PeerChokeMsg -> Process CF ST () chokeMgrMsg msg = do case msg of PieceCompleted pn -> do debugP "Telling about Piece Completion" outChan $ SenderQ.SenderQM $ Have pn trackInterestRemove pn ChokePeer -> do choking <- gets weChoke when (not choking) (do t <- liftIO myThreadId debugP $ "Pid " ++ show t ++ " choking" outChan $ SenderQ.SenderOChoke modify (\s -> s {weChoke = True})) UnchokePeer -> do choking <- gets weChoke when choking (do t <- liftIO myThreadId debugP $ "Pid " ++ show t ++ " unchoking" outChan $ SenderQ.SenderQM Unchoke modify (\s -> s {weChoke = False})) CancelBlock pn blk -> do cf <- asks extConf fromLJ handleCancelMsg cf pn blk data ExtendedInfo = ExtendedInfo { _extP :: Maybe Word16 , _extV :: Maybe String , _extReqq :: Maybe Integer } deriving Show extendedMsg :: Word8 -> B.ByteString -> Process CF ST () extendedMsg 0 bs = case BCode.decode bs of Left _err -> do infoP "Peer sent wrong BCoded dictionary extended msg" stopP Right bc -> let inf = ExtendedInfo (BCode.extendedP bc) (BCode.extendedV bc) (BCode.extendedRReq bc) in do infoP $ "Peer Extended handshake: " ++ show inf infoP $ show bc extendedMsg _ _ = do errorP "Unknown extended message type received" stopP cancelBlock :: PieceNum -> Block -> Process CF ST () cancelBlock pn blk = do s <- get put $! s { blockQueue = S.delete (pn, blk) $ blockQueue s } outChan $ SenderQ.SenderQRequestPrune pn blk fastCancelBlock :: PieceNum -> Block -> Process CF ST () fastCancelBlock pn blk = do bq <- gets blockQueue when (S.member (pn, blk) bq) $ outChan $ SenderQ.SenderQRequestPrune pn blk checkKeepAlive :: Process CF ST () checkKeepAlive = do lm <- gets lastMsg if lm >= 24 then do outChan $ SenderQ.SenderQM KeepAlive else let !inc = succ lm in modify (\st -> st { lastMsg = inc }) isSnubbed :: Process CF ST Bool isSnubbed = do -- 6 * 5 seconds is 30 lpm <- gets lastPieceMsg if lpm > 6 then return True else do let !inc = succ lpm modify (\st -> st { lastPieceMsg = inc }) return False -- A Timer event handles a number of different status updates. One towards the -- Choke Manager so it has a information about whom to choke and unchoke - and -- one towards the status process to keep track of uploaded and downloaded -- stuff. timerTick :: Process CF ST () timerTick = do checkKeepAlive inC <- asks inCh _ <- registerSTM 5 inC TimerTick (nur, ndr) <- timerTickChokeMgr timerTickStatus nur ndr -- Tell the ChokeMgr about our progress timerTickChokeMgr :: Process CF ST (Rate, Rate) timerTickChokeMgr = {-# SCC "timerTickChokeMgr" #-} do mTid <- liftIO myThreadId ur <- gets upRate dr <- gets downRate t <- liftIO $ getCurrentTime let (up, nur) = RC.extractRate t ur (down, ndr) = RC.extractRate t dr infoP $ "Peer has rates up/down: " ++ show up ++ "/" ++ show down i <- gets peerInterested seed <- isASeeder snub <- isSnubbed pchoke <- gets peerChoke rtv <- asks rateTV let peerInfo = (mTid, ChokeMgr.PRI { ChokeMgr.peerUpRate = up, ChokeMgr.peerDownRate = down, ChokeMgr.peerInterested = i, ChokeMgr.peerSeeding = seed, ChokeMgr.peerSnubs = snub, ChokeMgr.peerChokingUs = pchoke }) liftIO . atomically $ do q <- readTVar rtv writeTVar rtv (peerInfo : q) return (nur, ndr) -- Tell the Status Process about our progress timerTickStatus :: RC.Rate -> RC.Rate -> Process CF ST () timerTickStatus nur ndr = {-# SCC "timerTickStatus" #-} do let (upCnt, nuRate) = RC.extractCount $ nur (downCnt, ndRate) = RC.extractCount $ ndr stv <- asks statTV ih <- asks pcInfoHash liftIO .atomically $ do q <- readTVar stv writeTVar stv (PStat { pInfoHash = ih , pUploaded = fromIntegral upCnt , pDownloaded = fromIntegral downCnt } : q) modify (\s -> s { upRate = nuRate, downRate = ndRate }) chokeMsg :: Process CF ST () chokeMsg = do putbackBlocks s <- get put $! s { peerChoke = True } fastChokeMsg :: Process CF ST () fastChokeMsg = do s <- get put $! s { peerChoke = True} unchokeMsg :: Process CF ST () unchokeMsg = do s <- get put $! s { peerChoke = False } fillBlocks -- | Process an Message from the peer in the other end of the socket. peerMsg :: Message -> Int -> Process CF ST () peerMsg msg sz = do modify (\s -> s { downRate = RC.update sz $ downRate s}) case msg of KeepAlive -> {-# SCC "KeepAlive" #-} return () Choke -> {-# SCC "Choke" #-} asks extConf >>= fromLJ handleChokeMsg Unchoke -> {-# SCC "Unchoke" #-} unchokeMsg Interested -> {-# SCC "Interested" #-} modify (\s -> s { peerInterested = True }) NotInterested -> {-# SCC "NotInterested" #-} modify (\s -> s { peerInterested = False }) Have pn -> {-# SCC "Have" #-} haveMsg pn BitField bf -> {-# SCC "Bitfield" #-} bitfieldMsg bf Request pn blk -> {-# SCC "Request" #-} do cf <- asks extConf fromLJ handleRequestMsg cf pn blk Piece n os bs -> {-# SCC "Piece" #-} do cf <- asks extConf fromLJ handlePieceMsg cf n os bs modify (\st -> st { lastPieceMsg = 0 }) fillBlocks Cancel pn blk -> {-# SCC "Cancel" #-} cancelMsg pn blk Port _ -> return () -- No DHT yet, silently ignore HaveAll -> {-# SCC "HaveAll" #-} fromLJ handleHaveAll =<< asks extConf HaveNone -> fromLJ handleHaveNone =<< asks extConf Suggest pn -> do cf <- asks extConf fromLJ handleSuggest cf pn AllowedFast pn -> do cf <- asks extConf fromLJ handleAllowedFast cf pn RejectRequest pn blk -> do cf <- asks extConf fromLJ handleRejectRequest cf pn blk ExtendedMsg idx bs -> do cf <- asks extConf fromLJ handleExtendedMsg cf idx bs -- | Put back blocks for other peer processes to grab. This is done whenever -- the peer chokes us, or if we die by an unknown cause. putbackBlocks :: Process CF ST () putbackBlocks = do blks <- gets blockQueue msgPieceMgr (PutbackBlocks (S.toList blks)) modify (\s -> s { blockQueue = S.empty }) -- | Process a HAVE message from the peer. Note we also update interest as a side effect haveMsg :: PieceNum -> Process CF ST () haveMsg pn = do pm <- asks pieceMap let (lo, hi) = bounds pm if pn >= lo && pn <= hi then do PS.insert pn =<< gets peerPieces debugP $ "Peer has pn: " ++ show pn trackInterestAdd [pn] decMissingCounter 1 fillBlocks else do warningP "Unknown Piece" stopP -- True if the peer is a seeder isASeeder :: Process CF ST Bool isASeeder = do sdr <- gets missingPieces return $! sdr == 0 -- Decrease the counter of missing pieces for the peer decMissingCounter :: Int -> Process CF ST () decMissingCounter n = do modify (\s -> s { missingPieces = missingPieces s - n}) m <- gets missingPieces when (m == 0) assertSeeder -- Assert that the peer is a seeder assertSeeder :: Process CF ST () assertSeeder = do ok <- liftM2 (==) (gets peerPieces >>= PS.size) (succ . snd . bounds <$> asks pieceMap) assert ok (return ()) -- | Process a BITFIELD message from the peer. Side effect: Consider Interest. bitfieldMsg :: BitField -> Process CF ST () bitfieldMsg bf = do pieces <- gets peerPieces piecesNull <- PS.null pieces if piecesNull -- TODO: Don't trust the bitfield then do nPieces <- succ . snd . bounds <$> asks pieceMap pp <- createPeerPieces nPieces bf modify (\s -> s { peerPieces = pp }) peerLs <- PS.toList pp trackInterestAdd peerLs decMissingCounter (length peerLs) else do infoP "Got out of band Bitfield request, dying" stopP haveAllNoneMsg :: String -> Bool -> Process CF ST () haveAllNoneMsg ty a = do pieces <- gets peerPieces piecesNull <- PS.null pieces if piecesNull then do nPieces <- succ . snd . bounds <$> asks pieceMap pp <- createAllPieces nPieces a modify (\s -> s { peerPieces = pp}) peerLs <- PS.toList pp trackInterestAdd peerLs decMissingCounter (length peerLs) else do infoP $ "Got out of band " ++ ty ++ " request, dying" stopP haveNoneMsg :: Process CF ST () haveNoneMsg = haveAllNoneMsg "HaveNone" False haveAllMsg :: Process CF ST () haveAllMsg = haveAllNoneMsg "HaveAll" True -- | Process a request message from the Peer requestMsg :: PieceNum -> Block -> Process CF ST () requestMsg pn blk = do choking <- gets weChoke unless choking (do debugP $ "Peer requested: " ++ show pn ++ "(" ++ show blk ++ ")" outChan $ SenderQ.SenderQPiece pn blk) requestFastMsg :: PieceNum -> Block -> Process CF ST () requestFastMsg pn blk = do choking <- gets weChoke debugP $ "Peer fastRequested: " ++ show pn ++ "(" ++ show blk ++ ")" if choking then outChan $ SenderQ.SenderQM (RejectRequest pn blk) else outChan $ SenderQ.SenderQPiece pn blk -- | Handle a Piece Message incoming from the peer pieceMsg :: PieceNum -> Int -> B.ByteString -> Process CF ST () pieceMsg pn offs bs = pieceMsg' pn offs bs >> return () fastPieceMsg :: PieceNum -> Int -> B.ByteString -> Process CF ST () fastPieceMsg pn offs bs = do r <- pieceMsg' pn offs bs unless r (do infoP "Peer sent out-of-band piece we did not request, closing" stopP) pieceMsg' :: PieceNum -> Int -> B.ByteString -> Process CF ST Bool pieceMsg' n os bs = do let sz = B.length bs blk = Block os sz e = (n, blk) q <- gets blockQueue -- When e is not a member, the piece may be stray, so ignore it. -- Perhaps print something here. if S.member e q then do storeBlock n blk bs bq <- gets blockQueue >>= return . S.delete e s <- get bq `deepseq` put $! s { blockQueue = bq } return True else return False rejectMsg :: PieceNum -> Block -> Process CF ST () rejectMsg pn blk = do let e = (pn, blk) q <- gets blockQueue if S.member e q then do msgPieceMgr (PutbackBlocks [e]) s <- get put $! s { blockQueue = S.delete e q } else do infoP "Peer rejected piece/block we never requested, stopping" stopP -- | Handle a cancel message from the peer cancelMsg :: PieceNum -> Block -> Process CF ST () cancelMsg n blk = outChan $ SenderQ.SenderQCancel n blk -- | Try to fill up the block queue at the peer. The reason we pipeline a -- number of blocks is to get around the line delay present on the internet. fillBlocks :: Process CF ST () fillBlocks = do choked <- gets peerChoke interested <- gets weInterested when (not choked && interested) checkWatermark -- | check the current Watermark level. If we are below the lower one, then -- fill till the upper one. This in turn keeps the pipeline of pieces full as -- long as the peer is interested in talking to us. -- TODO: Decide on a queue size based on the current download rate. checkWatermark :: Process CF ST () checkWatermark = do q <- gets blockQueue eg <- gets runningEndgame let sz = S.size q mark = if eg then endgameLoMark else loMark when (sz < mark) (do toQueue <- grabBlocks (hiMark - sz) queuePieces toQueue) -- These three values are chosen rather arbitrarily at the moment. loMark :: Int loMark = 5 hiMark :: Int hiMark = 25 -- Low mark when running in endgame mode endgameLoMark :: Int endgameLoMark = 1 -- | Queue up pieces for retrieval at the Peer queuePieces :: [(PieceNum, Block)] -> Process CF ST () queuePieces toQueue = {-# SCC "queuePieces" #-} do s <- get let bq = blockQueue s unless (Prelude.null toQueue) $ updateLastPnCache (head toQueue) q <- forM toQueue (\(p, b) -> do if S.member (p, b) bq then return Nothing -- Ignore pieces which are already in queue else do outChan $ SenderQ.SenderQM $ Request p b return $ Just (p, b)) put $! s { blockQueue = S.union bq (S.fromList $ catMaybes q) } where updateLastPnCache (pn, _) = modify (\s -> s { lastPn = pn }) -- | Tell the PieceManager to store the given block storeBlock :: PieceNum -> Block -> B.ByteString -> Process CF ST () storeBlock n blk bs = msgPieceMgr (StoreBlock n blk bs) -- | The call @grabBlocks n@ will attempt to grab (up to) @n@ blocks from the -- piece Manager for request at the peer. grabBlocks :: Int -> Process CF ST [(PieceNum, Block)] grabBlocks n = do c <- asks grabBlockTV ps <- gets peerPieces lpn <- gets lastPn msgPieceMgr (GrabBlocks n ps c lpn) blks <- liftIO $ do atomically $ takeTMVar c case blks of Leech bs -> return bs Endgame bs -> modify (\s -> s { runningEndgame = True }) >> return bs createAllPieces :: MonadIO m => Int -> Bool -> m PS.PieceSet createAllPieces n False = PS.fromList n [] createAllPieces n True = PS.fromList n [0..(n-1)] createPeerPieces :: MonadIO m => Int -> B.ByteString -> m PS.PieceSet createPeerPieces nPieces = PS.fromList nPieces . map fromIntegral . concat . decodeBytes 0 . B.unpack where decodeByte :: Int -> Word8 -> [Maybe Int] decodeByte soFar w = let dBit n = if testBit w (7-n) then Just (n+soFar) else Nothing in fmap dBit [0..7] decodeBytes _ [] = [] decodeBytes soFar (w : ws) = catMaybes (decodeByte soFar w) : decodeBytes (soFar + 8) ws -- | Send a message on a chan from the process queue outChan :: SenderQ.SenderQMsg -> Process CF ST () outChan qm = do modify (\st -> st { lastMsg = 0 }) ch <- asks outCh liftIO . atomically $ writeTChan ch qm msgPieceMgr :: PieceMgrMsg -> Process CF ST () msgPieceMgr m = do pmc <- asks pieceMgrCh {-# SCC "Channel_Write" #-} liftIO . atomically $ writeTChan pmc m -- IP address is given in host byte-order allowedFast :: Word32 -> InfoHash -> Int -> Int -> IO [Word32] allowedFast ip ihash sz n = generate n [] x [] where -- Take pieces from the generated ones and refill when it is exhausted. -- While taking pieces, kill duplicates generate 0 pcs _ _ = return $ reverse pcs generate k pcs hsh (p : rest) | p `elem` pcs = generate k pcs hsh rest | otherwise = generate (k-1) (p : pcs) hsh rest generate k pcs hsh [] = do let nhsh = Digest.digestBS hsh generate k pcs nhsh (genPieces nhsh) genPieces hash | B.null hash = [] | otherwise = let (h, rest) = B.splitAt 4 hash bytes :: [Word32] bytes = [fromIntegral z `shiftL` s | (z, s) <- zip (B.unpack h) [24,16,8,0]] ntohl = fromIntegral . sum in ((ntohl bytes) `mod` fromIntegral sz) : genPieces rest -- To prevent a Peer to reconnect, obtain a new IP and thus new FAST-set pieces, we mask out -- the lower bits ipBytes = B.pack $ map fromIntegral [ (ip .&. 0xFF000000) `shiftR` 24 , (ip .&. 0x00FF0000) `shiftR` 16 , (ip .&. 0x0000FF00) `shiftR` 8 , 0 ] x = B.concat [ipBytes, ihash] testSuite :: Test testSuite = testGroup "Process/Peer" [ testCase "AllowedFast" testAllowedFast ] testAllowedFast :: Assertion testAllowedFast = do pcs <- allowedFast (ip32 [80,4,4,200]) tHash 1313 7 assertEqual "Test1" [1059,431,808,1217,287,376,1188] pcs pcs' <- allowedFast (ip32 [80,4,4,200]) tHash 1313 9 assertEqual "Test2" [1059,431,808,1217,287,376,1188,353,508] pcs' where ip32 :: [Int] -> Word32 ip32 bytes = fromIntegral $ sum [b `shiftL` s | (b, s) <- zip bytes [24,16,8,0]] tHash :: B.ByteString tHash = B.pack $ take 20 (repeat 0xaa)
rethab/combinatorrent
src/Process/Peer.hs
bsd-2-clause
30,335
1
20
9,607
8,471
4,250
4,221
688
17