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
import qualified Data.ByteString as B import Control.Monad import Microbench import Commit main = microbench "commit parsing" parseOneCommit where parseOneCommit = do text <- B.readFile "testdata/commit" let Right commit = parseCommit text unless (length (commit_parents commit) > 0) $ fail "misparse" return ()
martine/gat
Commit_perftest.hs
gpl-2.0
338
0
15
68
102
49
53
11
1
{-# OPTIONS_GHC -fno-implicit-prelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Tuple -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- The tuple data types, and associated functions. -- ----------------------------------------------------------------------------- module Data.Tuple ( fst -- :: (a,b) -> a , snd -- :: (a,b) -> a , curry -- :: ((a, b) -> c) -> a -> b -> c , uncurry -- :: (a -> b -> c) -> ((a, b) -> c) ) where default () -- Double isn't available yet -- --------------------------------------------------------------------------- -- Standard functions over tuples
kaoskorobase/mescaline
resources/hugs/packages/base/Data/Tuple.hs
gpl-3.0
1,095
0
4
402
45
37
8
7
0
module Graphics.Forensics.Analyser.Demosaic where import Prelude hiding (zipWith3) import Graphics.Forensics.Algorithms.Convolve import Graphics.Forensics.Analyser import Graphics.Forensics.Color import Graphics.Forensics.Image import Graphics.Forensics.Report import Graphics.Forensics.Utilities (zipWith3) import Data.Array.Repa (DIM2, (:.)(..), computeP, computeUnboxedP) import qualified Data.Array.Repa as Repa analyser :: Analyser ByteImage analyser = Analyser { analyse = demosaicAnalyse , name = "demosaic" , author = "Moritz Roth" , version = readVersion "1.0" } highpass :: Stencil DIM2 Float highpass = [stencil2| 0 1 0 1 -4 1 0 1 0 |] demosaicAnalyse :: ByteImage -> Analysis () demosaicAnalyse !img = task "Demosaic analysis" 4 $ do let fImg = byteToFloatImage img {-Convole the float image with a highpass filter-} let conv = return . convolveS Clamp highpass let rmap = computeUnboxedP . flip Repa.map fImg r <- conv =<< rmap channelRed step g <- conv =<< rmap channelGreen step b <- conv =<< rmap channelBlue step {-Merge the convolved channels into the result image-} result <- computeP $ zipWith3 fromRGBValues r g b reportInfo "Output: image demosaic analysis." $ reportImage (floatToByteImage result)
Purview/purview
src/Graphics/Forensics/Analyser/Demosaic.hs
gpl-3.0
1,317
0
13
262
329
179
150
-1
-1
module Main where import Command import Hardware1 import Hardware2 main = do run start run stop print $ getInfo start print $ getInfo stop run rotate print ""
graninas/Haskell-Algorithms
Tests/Types/Test.hs
gpl-3.0
197
0
8
66
62
28
34
11
1
{-# LANGUAGE FlexibleContexts #-} module Data.Cellular where import Data.Subset import Data.DecidableSubset import Data.Maybe import Data.Monoid import Data.List import Data.Function.MemoM import Control.Monad.Identity newtype CellularT m g a = Cellular { delta :: (g -> m a) -> m a } -- This type is quite annoying: we would like to have m (g -> a) -- but, at the same time, still be able to have local side effects. stepM :: (Monoid g, Monad m) => CellularT m g a -> (g -> m a) -> (g -> m a) stepM cell init g = delta cell $ init . (g <>) runM :: (Monoid g, Ord g, Monad m) => CellularT m g a -> (g -> m a) -> [g -> m a] runM cell = iterate (memoM . stepM cell) -- Obviously, we can have pure Cellular. And they are Actually a lot -- easier to run: type Cellular g a = CellularT Identity g a -- run :: (Monoid g, Ord g, MonadMemo g a Identity) => Cellular g a -> (g -> a) -> [g -> a] run cell = fmap (runIdentity .) . runM cell . (Identity .) -- A PreCellular is a Cellular automata whose behaviour we only -- observe on a subset of the whole Monoid data PreCellularT m s g a = PreCellular { decidableSubset :: DecidableSubset s g , cellular :: CellularT m g a } stepPM :: (Monoid g, Monad m) => PreCellularT m s g a -> (g -> m a) -> (s -> m a) -> (s -> m a) stepPM (PreCellular dec cell) dflt initS = stepM cell initG . embed (subset dec) where initG g = maybe (dflt g) initS $ decide dec g runPM :: (Monoid g, Ord s, Monad m) => PreCellularT m s g a -> (Either s g -> m a) -> [s -> m a] runPM cell init = iterate (memoM . stepPM cell (init . Right)) (init . Left)
gallais/potpourri
haskell/cellular/Data/Cellular.hs
gpl-3.0
1,626
0
11
387
578
308
270
26
1
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ViewPatterns #-} -- | -- Copyright : (c) 2010-2012 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Portability : GHC only -- -- A monad for writing constraint reduction steps together with basic steps -- for inserting nodes, edges, actions, and equations and applying -- substitutions. module Theory.Constraint.Solver.Reduction ( -- * The constraint 'Reduction' monad Reduction , execReduction , runReduction -- ** Change management , ChangeIndicator(..) , whenChanged , applyChangeList , whileChanging -- ** Accessing the 'ProofContext' , getProofContext , getMaudeHandle -- ** Inserting nodes, edges, and atoms , labelNodeId , insertFreshNode , insertFreshNodeConc , insertGoal , insertAtom , insertEdges , insertChain , insertAction , insertLess , insertFormula , reducibleFormula -- ** Goal management , markGoalAsSolved , removeSolvedSplitGoals -- ** Substitution application , substSystem , substNodes , substEdges , substLastAtom , substLessAtoms , substFormulas , substSolvedFormulas -- ** Solving equalities , SplitStrategy(..) , solveNodeIdEqs , solveTermEqs , solveFactEqs , solveRuleEqs , solveSubstEqs -- ** Conjunction with another constraint 'System' , conjoinSystem -- ** Convenience export , module Logic.Connectives ) where import Debug.Trace import Prelude hiding (id, (.)) import qualified Data.Foldable as F import qualified Data.Map as M import qualified Data.Set as S import qualified Data.ByteString.Char8 as BC import Data.List (mapAccumL) import Safe import Control.Basics import Control.Category import Control.Monad.Bind import Control.Monad.Disj import Control.Monad.Reader import Control.Monad.State (StateT, execStateT, gets, runStateT) import Text.PrettyPrint.Class import Extension.Data.Label import Extension.Data.Monoid (Monoid(..)) import Extension.Prelude import Logic.Connectives import Theory.Constraint.Solver.Contradictions -- import Theory.Constraint.Solver.Types import Theory.Constraint.System import Theory.Model ------------------------------------------------------------------------------ -- The constraint reduction monad ------------------------------------------------------------------------------ -- | A constraint reduction step. Its state is the current constraint system, -- it can generate fresh names, split over cases, and access the proof -- context. type Reduction = StateT System (FreshT (DisjT (Reader ProofContext))) -- Executing reductions ----------------------- -- | Run a constraint reduction. Returns a list of constraint systems whose -- combined solutions are equal to the solutions of the given system. This -- property is obviously not enforced, but it must be respected by all -- functions of type 'Reduction'. runReduction :: Reduction a -> ProofContext -> System -> FreshState -> Disj ((a, System), FreshState) runReduction m ctxt se fs = Disj $ (`runReader` ctxt) $ runDisjT $ (`runFreshT` fs) $ runStateT m se -- | Run a constraint reduction returning only the updated constraint systems -- and the new freshness states. execReduction :: Reduction a -> ProofContext -> System -> FreshState -> Disj (System, FreshState) execReduction m ctxt se fs = Disj $ (`runReader` ctxt) . runDisjT . (`runFreshT` fs) $ execStateT m se -- Change management -------------------- -- | Indicate whether the constraint system was changed or not. data ChangeIndicator = Unchanged | Changed deriving( Eq, Ord, Show ) instance Monoid ChangeIndicator where mempty = Unchanged Changed `mappend` _ = Changed _ `mappend` Changed = Changed Unchanged `mappend` Unchanged = Unchanged -- | Return 'True' iff there was a change. wasChanged :: ChangeIndicator -> Bool wasChanged Changed = True wasChanged Unchanged = False -- | Only apply a monadic action, if there has been a change. whenChanged :: Monad m => ChangeIndicator -> m () -> m () whenChanged = when . wasChanged -- | Apply a list of changes to the proof state. applyChangeList :: [Reduction ()] -> Reduction ChangeIndicator applyChangeList [] = return Unchanged applyChangeList changes = sequence_ changes >> return Changed -- | Execute a 'Reduction' as long as it results in changes. Indicate whether -- at least one change was performed. whileChanging :: Reduction ChangeIndicator -> Reduction ChangeIndicator whileChanging reduction = go Unchanged where go indicator = do indicator' <- reduction case indicator' of Unchanged -> return indicator Changed -> go indicator' -- Accessing the proof context ------------------------------ -- | Retrieve the 'ProofContext'. getProofContext :: Reduction ProofContext getProofContext = ask -- | Retrieve the 'MaudeHandle' from the 'ProofContext'. getMaudeHandle :: Reduction MaudeHandle getMaudeHandle = askM pcMaudeHandle -- Inserting (fresh) nodes into the constraint system ----------------------------------------------------- -- | Insert a fresh rule node labelled with a fresh instance of one of the -- rules and return one of the conclusions. insertFreshNodeConc :: [RuleAC] -> Reduction (RuleACInst, NodeConc, LNFact) insertFreshNodeConc rules = do (i, ru) <- insertFreshNode rules (v, fa) <- disjunctionOfList $ enumConcs ru return (ru, (i, v), fa) -- | Insert a fresh rule node labelled with a fresh instance of one of the rules -- and solve it's 'Fr', 'In', and 'KU' premises immediatly. insertFreshNode :: [RuleAC] -> Reduction (NodeId, RuleACInst) insertFreshNode rules = do i <- freshLVar "vr" LSortNode (,) i <$> labelNodeId i rules -- | Label a node-id with a fresh instance of one of the rules and -- solve it's 'Fr', 'In', and 'KU' premises immediatly. -- -- PRE: Node must not yet be labelled with a rule. labelNodeId :: NodeId -> [RuleAC] -> Reduction RuleACInst labelNodeId = \i rules -> do (ru, mrconstrs) <- importRule =<< disjunctionOfList rules solveRuleConstraints mrconstrs modM sNodes (M.insert i ru) exploitPrems i ru return ru where -- | Import a rule with all its variables renamed to fresh variables. importRule ru = someRuleACInst ru `evalBindT` noBindings mkISendRuleAC m = return $ Rule (IntrInfo (ISendRule)) [kuFact m] [inFact m] [kLogFact m] mkFreshRuleAC m = Rule (ProtoInfo (ProtoRuleACInstInfo FreshRule [])) [] [freshFact m] [] exploitPrems i ru = mapM_ (exploitPrem i ru) (enumPrems ru) exploitPrem i ru (v, fa) = case fa of -- CR-rule *DG2_2* specialized for *In* facts. Fact InFact [m] -> do j <- freshLVar "vf" LSortNode ruKnows <- mkISendRuleAC m modM sNodes (M.insert j ruKnows) modM sEdges (S.insert $ Edge (j, ConcIdx 0) (i, v)) exploitPrems j ruKnows -- CR-rule *DG2_2* specialized for *Fr* facts. Fact FreshFact [m] -> do j <- freshLVar "vf" LSortNode modM sNodes (M.insert j (mkFreshRuleAC m)) unless (isFreshVar m) $ do -- 'm' must be of sort fresh ==> enforce via unification n <- varTerm <$> freshLVar "n" LSortFresh void (solveTermEqs SplitNow [Equal m n]) modM sEdges (S.insert $ Edge (j, ConcIdx 0) (i,v)) -- CR-rule *DG2_{2,u}*: solve a KU-premise by inserting the -- corresponding KU-actions before this node. _ | isKUFact fa -> do j <- freshLVar "vk" LSortNode insertLess j i void (insertAction j fa) -- Store premise goal for later processing using CR-rule *DG2_2* | otherwise -> insertGoal (PremiseG (i,v) fa) (v `elem` breakers) where breakers = ruleInfo (get praciLoopBreakers) (const []) $ get rInfo ru -- | Insert a chain constrain. insertChain :: NodeConc -> NodePrem -> Reduction () insertChain c p = insertGoal (ChainG c p) False -- | Insert an edge constraint. CR-rule *DG1_2* is enforced automatically, -- i.e., the fact equalities are enforced. insertEdges :: [(NodeConc, LNFact, LNFact, NodePrem)] -> Reduction () insertEdges edges = do void (solveFactEqs SplitNow [ Equal fa1 fa2 | (_, fa1, fa2, _) <- edges ]) modM sEdges (\es -> foldr S.insert es [ Edge c p | (c,_,_,p) <- edges]) -- | Insert an 'Action' atom. Ensures that (almost all) trivial *KU* actions -- are solved immediately using rule *S_{at,u,triv}*. We currently avoid -- adding intermediate products. Indicates whether nodes other than the given -- action have been added to the constraint system. -- -- FIXME: Ensure that intermediate products are also solved before stating -- that no rule is applicable. insertAction :: NodeId -> LNFact -> Reduction ChangeIndicator insertAction i fa = do present <- (goal `M.member`) <$> getM sGoals isdiff <- getM sDiffSystem nodePresent <- (i `M.member`) <$> getM sNodes if present then do return Unchanged else do case kFactView fa of Just (UpK, viewTerm2 -> FPair m1 m2) -> do -- In the diff case, add pair rule instead of goal if isdiff then do -- if the node is already present in the graph, do not insert it again. (This can be caused by substitutions applying and changing a goal.) if not nodePresent then do modM sNodes (M.insert i (Rule (IntrInfo (ConstrRule $ BC.pack "pair")) ([(Fact KUFact [m1]),(Fact KUFact [m2])]) ([fa]) ([fa]))) insertGoal goal False markGoalAsSolved "pair" goal requiresKU m1 *> requiresKU m2 *> return Changed else do insertGoal goal False markGoalAsSolved "exists" goal return Changed else do insertGoal goal False requiresKU m1 *> requiresKU m2 *> return Changed Just (UpK, viewTerm2 -> FInv m) -> do -- In the diff case, add inv rule instead of goal if isdiff then do -- if the node is already present in the graph, do not insert it again. (This can be caused by substitutions applying and changing a goal.) if not nodePresent then do modM sNodes (M.insert i (Rule (IntrInfo (ConstrRule $ BC.pack "inv")) ([(Fact KUFact [m])]) ([fa]) ([fa]))) insertGoal goal False markGoalAsSolved "inv" goal requiresKU m *> return Changed else do insertGoal goal False markGoalAsSolved "exists" goal return Changed else do insertGoal goal False requiresKU m *> return Changed Just (UpK, viewTerm2 -> FMult ms) -> do -- In the diff case, add mult rule instead of goal if isdiff then do -- if the node is already present in the graph, do not insert it again. (This can be caused by substitutions applying and changing a goal.) if not nodePresent then do modM sNodes (M.insert i (Rule (IntrInfo (ConstrRule $ BC.pack "mult")) (map (\x -> Fact KUFact [x]) ms) ([fa]) ([fa]))) insertGoal goal False markGoalAsSolved "mult" goal mapM_ requiresKU ms *> return Changed else do insertGoal goal False markGoalAsSolved "exists" goal return Changed else do insertGoal goal False mapM_ requiresKU ms *> return Changed Just (UpK, viewTerm2 -> FUnion ms) -> do -- In the diff case, add union (?) rule instead of goal if isdiff then do -- if the node is already present in the graph, do not insert it again. (This can be caused by substitutions applying and changing a goal.) if not nodePresent then do modM sNodes (M.insert i (Rule (IntrInfo (ConstrRule $ BC.pack "union")) (map (\x -> Fact KUFact [x]) ms) ([fa]) ([fa]))) insertGoal goal False markGoalAsSolved "union" goal mapM_ requiresKU ms *> return Changed else do insertGoal goal False markGoalAsSolved "exists" goal return Changed else do insertGoal goal False mapM_ requiresKU ms *> return Changed _ -> do insertGoal goal False return Unchanged where goal = ActionG i fa -- Here we rely on the fact that the action is new. Otherwise, we might -- loop due to generating new KU-nodes that are merged immediately. requiresKU t = do j <- freshLVar "vk" LSortNode let faKU = kuFact t insertLess j i void (insertAction j faKU) -- | Insert a 'Less' atom. @insertLess i j@ means that *i < j* is added. insertLess :: NodeId -> NodeId -> Reduction () insertLess i j = modM sLessAtoms (S.insert (i, j)) -- | Insert a 'Last' atom and ensure their uniqueness. insertLast :: NodeId -> Reduction ChangeIndicator insertLast i = do lst <- getM sLastAtom case lst of Nothing -> setM sLastAtom (Just i) >> return Unchanged Just j -> solveNodeIdEqs [Equal i j] -- | Insert an atom. Returns 'Changed' if another part of the constraint -- system than the set of actions was changed. insertAtom :: LNAtom -> Reduction ChangeIndicator insertAtom ato = case ato of EqE x y -> solveTermEqs SplitNow [Equal x y] Action i fa -> insertAction (ltermNodeId' i) fa Less i j -> do insertLess (ltermNodeId' i) (ltermNodeId' j) return Unchanged Last i -> insertLast (ltermNodeId' i) -- | Insert a 'Guarded' formula. Ensures that existentials, conjunctions, negated -- last atoms, and negated less atoms, are immediately solved using the rules -- *S_exists*, *S_and*, *S_not,last*, and *S_not,less*. Only the inserted -- formula is marked as solved. Other intermediate formulas are not marked. insertFormula :: LNGuarded -> Reduction () insertFormula = do insert True where insert mark fm = do formulas <- getM sFormulas solvedFormulas <- getM sSolvedFormulas insert' mark formulas solvedFormulas fm insert' mark formulas solvedFormulas fm | fm `S.member` formulas = return () | fm `S.member` solvedFormulas = return () | otherwise = case fm of GAto ato -> do markAsSolved void (insertAtom (bvarToLVar ato)) -- CR-rule *S_∧* GConj fms -> do markAsSolved mapM_ (insert False) (getConj fms) -- Store for later applications of CR-rule *S_∨* GDisj disj -> do modM sFormulas (S.insert fm) insertGoal (DisjG disj) False -- CR-rule *S_∃* GGuarded Ex ss as gf -> do -- must always mark as solved, as we otherwise may repeatedly -- introduce fresh variables. modM sSolvedFormulas $ S.insert fm xs <- mapM (uncurry freshLVar) ss let body = gconj (map GAto as ++ [gf]) insert False (substBound (zip [0..] (reverse xs)) body) -- CR-rule *S_{¬,⋖}* GGuarded All [] [Less i j] gf | gf == gfalse -> do markAsSolved insert False (gdisj [GAto (EqE i j), GAto (Less j i)]) -- CR-rule: FIXME add this rule to paper GGuarded All [] [EqE i@(bltermNodeId -> Just _) j@(bltermNodeId -> Just _) ] gf | gf == gfalse -> do markAsSolved insert False (gdisj [GAto (Less i j), GAto (Less j i)]) -- CR-rule *S_{¬,last}* GGuarded All [] [Last i] gf | gf == gfalse -> do markAsSolved lst <- getM sLastAtom j <- case lst of Nothing -> do j <- freshLVar "last" LSortNode void (insertLast j) return (varTerm (Free j)) Just j -> return (varTerm (Free j)) insert False $ gdisj [ GAto (Less j i), GAto (Less i j) ] -- Guarded All quantification: store for saturation GGuarded All _ _ _ -> modM sFormulas (S.insert fm) where markAsSolved = when mark $ modM sSolvedFormulas $ S.insert fm -- | 'True' iff the formula can be reduced by one of the rules implemented in -- 'insertFormula'. reducibleFormula :: LNGuarded -> Bool reducibleFormula fm = case fm of GAto _ -> True GConj _ -> True GGuarded Ex _ _ _ -> True GGuarded All [] [Less _ _] gf -> gf == gfalse GGuarded All [] [Last _] gf -> gf == gfalse _ -> False -- Goal management ------------------ -- | Combine the status of two goals. combineGoalStatus :: GoalStatus -> GoalStatus -> GoalStatus combineGoalStatus (GoalStatus solved1 age1 loops1) (GoalStatus solved2 age2 loops2) = GoalStatus (solved1 || solved2) (min age1 age2) (loops1 || loops2) -- | Insert a goal and its status with a new age. Merge status if goal exists. insertGoalStatus :: Goal -> GoalStatus -> Reduction () insertGoalStatus goal status = do age <- getM sNextGoalNr modM sGoals $ M.insertWith' combineGoalStatus goal (set gsNr age status) sNextGoalNr =: succ age -- | Insert a 'Goal' and store its age. insertGoal :: Goal -> Bool -> Reduction () insertGoal goal looping = insertGoalStatus goal (GoalStatus False 0 looping) -- | Mark the given goal as solved. markGoalAsSolved :: String -> Goal -> Reduction () markGoalAsSolved how goal = case goal of ActionG _ _ -> updateStatus PremiseG _ fa | isKDFact fa -> modM sGoals $ M.delete goal | otherwise -> updateStatus ChainG _ _ -> modM sGoals $ M.delete goal SplitG _ -> updateStatus DisjG disj -> modM sFormulas (S.delete $ GDisj disj) >> modM sSolvedFormulas (S.insert $ GDisj disj) >> updateStatus where updateStatus = do mayStatus <- M.lookup goal <$> getM sGoals case mayStatus of Just status -> trace (msg status) $ modM sGoals $ M.insert goal $ set gsSolved True status Nothing -> trace ("markGoalAsSolved: inexistent goal " ++ show goal) $ return () msg status = render $ nest 2 $ fsep $ [ text ("solved goal nr. "++ show (get gsNr status)) <-> parens (text how) <> colon , nest 2 (prettyGoal goal) ] removeSolvedSplitGoals :: Reduction () removeSolvedSplitGoals = do goals <- getM sGoals existent <- splitExists <$> getM sEqStore sequence_ [ modM sGoals $ M.delete goal | goal@(SplitG i) <- M.keys goals, not (existent i) ] -- Substitution --------------- -- | Apply the current substitution of the equation store to the remainder of -- the sequent. substSystem :: Reduction ChangeIndicator substSystem = do c1 <- substNodes substEdges substLastAtom substLessAtoms substFormulas substSolvedFormulas substLemmas c2 <- substGoals substNextGoalNr return (c1 <> c2) -- no invariants to maintain here substEdges, substLessAtoms, substLastAtom, substFormulas, substSolvedFormulas, substLemmas, substNextGoalNr :: Reduction () substEdges = substPart sEdges substLessAtoms = substPart sLessAtoms substLastAtom = substPart sLastAtom substFormulas = substPart sFormulas substSolvedFormulas = substPart sSolvedFormulas substLemmas = substPart sLemmas substNextGoalNr = return () -- | Apply the current substitution of the equation store to a part of the -- sequent. This is an internal function. substPart :: Apply a => (System :-> a) -> Reduction () substPart l = do subst <- getM sSubst modM l (apply subst) -- | Apply the current substitution of the equation store the nodes of the -- constraint system. Indicates whether additional equalities were added to -- the equations store. substNodes :: Reduction ChangeIndicator substNodes = substNodeIds <* ((modM sNodes . M.map . apply) =<< getM sSubst) -- | @setNodes nodes@ normalizes the @nodes@ such that node ids are unique and -- then updates the @sNodes@ field of the proof state to the corresponding map. -- Return @True@ iff new equalities have been added to the equation store. setNodes :: [(NodeId, RuleACInst)] -> Reduction ChangeIndicator setNodes nodes0 = do sNodes =: M.fromList nodes if null ruleEqs then return Unchanged else solveRuleEqs SplitLater ruleEqs >> return Changed where -- merge nodes with equal node id (ruleEqs, nodes) = first concat $ unzip $ map merge $ groupSortOn fst nodes0 merge [] = unreachable "setNodes" merge (keep:remove) = (map (Equal (snd keep) . snd) remove, keep) -- | Apply the current substitution of the equation store to the node ids and -- ensure uniqueness of the labels, as required by rule *U_lbl*. Indicates -- whether there where new equalities added to the equations store. substNodeIds :: Reduction ChangeIndicator substNodeIds = whileChanging $ do subst <- getM sSubst nodes <- gets (map (first (apply subst)) . M.toList . get sNodes) setNodes nodes -- | Substitute all goals. Keep the ones with the lower nr. substGoals :: Reduction ChangeIndicator substGoals = do subst <- getM sSubst goals <- M.toList <$> getM sGoals sGoals =: M.empty changes <- forM goals $ \(goal, status) -> case goal of -- Look out for KU-actions that might need to be solved again. ActionG i fa@(kFactView -> Just (UpK, m)) | (isMsgVar m || isProduct m || isUnion m) && (apply subst m /= m) -> insertAction i (apply subst fa) _ -> do modM sGoals $ M.insertWith' combineGoalStatus (apply subst goal) status return Unchanged return (mconcat changes) -- Conjoining two constraint systems ------------------------------------ -- | @conjoinSystem se@ conjoins the logical information in @se@ to the -- constraint system. It assumes that the free variables in @se@ are shared -- with the free variables in the proof state. conjoinSystem :: System -> Reduction () conjoinSystem sys = do kind <- getM sCaseDistKind unless (kind == get sCaseDistKind sys) $ error "conjoinSystem: typing-kind mismatch" joinSets sSolvedFormulas joinSets sLemmas joinSets sEdges F.mapM_ insertLast $ get sLastAtom sys F.mapM_ (uncurry insertLess) $ get sLessAtoms sys -- split-goals are not valid anymore mapM_ (uncurry insertGoalStatus) $ filter (not . isSplitGoal . fst) $ M.toList $ get sGoals sys F.mapM_ insertFormula $ get sFormulas sys -- update nodes _ <- (setNodes . (M.toList (get sNodes sys) ++) . M.toList) =<< getM sNodes -- conjoin equation store eqs <- getM sEqStore let (eqs',splitIds) = (mapAccumL addDisj eqs (map snd . getConj $ get sConjDisjEqs sys)) setM sEqStore eqs' -- add split-goals for all disjunctions of sys mapM_ (`insertGoal` False) $ SplitG <$> splitIds void (solveSubstEqs SplitNow $ get sSubst sys) -- Propagate substitution changes. Ignore change indicator, as it is -- assumed to be 'Changed' by default. void substSystem where joinSets :: Ord a => (System :-> S.Set a) -> Reduction () joinSets proj = modM proj (`S.union` get proj sys) -- Unification via the equation store ------------------------------------- -- | 'SplitStrategy' denotes if the equation store should be split into -- multiple equation stores. data SplitStrategy = SplitNow | SplitLater -- The 'ChangeIndicator' indicates whether at least one non-trivial equality -- was solved. -- | @noContradictoryEqStore@ suceeds iff the equation store is not -- contradictory. noContradictoryEqStore :: Reduction () noContradictoryEqStore = (contradictoryIf . eqsIsFalse) =<< getM sEqStore -- | Add a list of term equalities to the equation store. And -- split resulting disjunction of equations according -- to given split strategy. -- -- Note that updating the remaining parts of the constraint system with the -- substitution has to be performed using a separate call to 'substSystem'. solveTermEqs :: SplitStrategy -> [Equal LNTerm] -> Reduction ChangeIndicator solveTermEqs splitStrat eqs0 = case filter (not . evalEqual) eqs0 of [] -> do return Unchanged eqs1 -> do hnd <- getMaudeHandle se <- gets id (eqs2, maySplitId) <- addEqs hnd eqs1 =<< getM sEqStore setM sEqStore =<< simp hnd (substCreatesNonNormalTerms hnd se) =<< case (maySplitId, splitStrat) of (Just splitId, SplitNow) -> disjunctionOfList $ fromJustNote "solveTermEqs" $ performSplit eqs2 splitId (Just splitId, SplitLater) -> do insertGoal (SplitG splitId) False return eqs2 _ -> return eqs2 noContradictoryEqStore return Changed -- | Add a list of equalities in substitution form to the equation store solveSubstEqs :: SplitStrategy -> LNSubst -> Reduction ChangeIndicator solveSubstEqs split subst = solveTermEqs split [Equal (varTerm v) t | (v, t) <- substToList subst] -- | Add a list of node equalities to the equation store. solveNodeIdEqs :: [Equal NodeId] -> Reduction ChangeIndicator solveNodeIdEqs = solveTermEqs SplitNow . map (fmap varTerm) -- | Add a list of fact equalities to the equation store, if possible. solveFactEqs :: SplitStrategy -> [Equal LNFact] -> Reduction ChangeIndicator solveFactEqs split eqs = do contradictoryIf (not $ all evalEqual $ map (fmap factTag) eqs) solveListEqs (solveTermEqs split) $ map (fmap factTerms) eqs -- | Add a list of rule equalities to the equation store, if possible. solveRuleEqs :: SplitStrategy -> [Equal RuleACInst] -> Reduction ChangeIndicator solveRuleEqs split eqs = do contradictoryIf (not $ all evalEqual $ map (fmap (get rInfo)) eqs) solveListEqs (solveFactEqs split) $ map (fmap (get rConcs)) eqs ++ map (fmap (get rPrems)) eqs ++ map (fmap (get rActs)) eqs -- | Solve a number of equalities between lists interpreted as free terms -- using the given solver for solving the entailed per-element equalities. solveListEqs :: ([Equal a] -> Reduction b) -> [(Equal [a])] -> Reduction b solveListEqs solver eqs = do contradictoryIf (not $ all evalEqual $ map (fmap length) eqs) solver $ concatMap flatten eqs where flatten (Equal l r) = zipWith Equal l r -- | Solve the constraints associated with a rule. solveRuleConstraints :: Maybe RuleACConstrs -> Reduction () solveRuleConstraints (Just eqConstr) = do hnd <- getMaudeHandle (eqs, splitId) <- addRuleVariants eqConstr <$> getM sEqStore insertGoal (SplitG splitId) False -- do not use expensive substCreatesNonNormalTerms here setM sEqStore =<< simp hnd (const (const False)) eqs noContradictoryEqStore solveRuleConstraints Nothing = return ()
ekr/tamarin-prover
lib/theory/src/Theory/Constraint/Solver/Reduction.hs
gpl-3.0
29,399
297
29
9,124
6,287
3,284
3,003
459
14
{-| Module : Fuzzball.Algorithm Description : Implementation of a fuzzy matching algorithm The Fuzzball.Algorithm module implements the actual fuzzy matching algorithm. -} module Fuzzball.Algorithm ( fuzzyMatch , MatchRating(..) ) where -- | The rating of the quality of a fuzzy match data MatchRating = MatchRating { rating :: Int , indexes :: [Int] } deriving (Eq, Ord, Show) -- | Fuzzily match a pattern over a string fuzzyMatch :: String -> String -> Maybe MatchRating fuzzyMatch [] _ = Just . MatchRating 0 $ [] fuzzyMatch _ [] = Nothing fuzzyMatch (p:ps) (c:cs) | p == c = fmap found . fmap push . fuzzyMatch ps $ cs | otherwise = fmap push . fuzzyMatch (p:ps) $ cs where -- Increment the indices push mr@(MatchRating _ indexes) = let indexes' = map (+1) indexes in mr { indexes = indexes' } -- Update the rating and add a new index found mr@(MatchRating rating indexes) = let rating' = rating + if null indexes then 0 else head indexes in mr { rating = rating', indexes = 0:indexes }
froozen/fuzzball
src/Fuzzball/Algorithm.hs
gpl-3.0
1,119
0
13
306
315
167
148
19
2
module Lambda.Types.Either where import Lambda.Variable import Lambda.Engine -- Introduction inl :: Term -> Term inl a = Lambda onleft (Lambda onright (Apply (VarTerm onleft) a)) where onleft = head unusedVars onright = unusedVars !! 1 unusedVars = notUsed $ allVar a inr :: Term -> Term inr b = Lambda onleft (Lambda onright (Apply (VarTerm onright) b)) where onleft = head unusedVars onright = unusedVars !! 1 unusedVars = notUsed $ allVar b -- Elimination reveal :: Term -> Term -> Term -> Term reveal x onleft onright = Apply (Apply x onleft) onright -- Interpretation showEither :: (Term -> String) -> (Term -> String) -> Term -> String showEither showLeft showRight t = let onleft = Variable "onleft" onright = Variable "onright" term = reduceAll $ applyArgs t $ map VarTerm [onleft, onright] in case explode term of (VarTerm x, args) | x == onleft -> let left = applyArgs (head args) (tail args) in "inl(" ++ showLeft left ++ ")" (VarTerm x, args) | x == onright -> let right = applyArgs (head args) (tail args) in "inr(" ++ showRight right ++ ")" _ -> show term
fpoli/lambda
src/Lambda/Types/Either.hs
gpl-3.0
1,384
0
17
503
448
225
223
32
3
{-# LANGUAGE NoImplicitPrelude #-} module My.XMonad.Config.Mods.Amixer (alsaKeys) where import Control.Arrow ((***)) import Data.Function ((.), ($)) import Data.List (map) import Data.Map.Lazy (fromList) import qualified Graphics.X11.ExtraTypes.XF86 as XF86 import XMonad (noModMask) import My.XMonad.Core (KeyConfig, spawn) alsaKeys :: KeyConfig alsaKeys _ = fromList . map ((,) noModMask *** amixer) $ [ (XF86.xF86XK_AudioLowerVolume, "5%-") , (XF86.xF86XK_AudioMute, "toggle") , (XF86.xF86XK_AudioRaiseVolume, "5%+") ] where amixer c = spawn "amixer" ["-q", "set", "Master", c]
xkollar/my-xmonad
src/My/XMonad/Config/Mods/Amixer.hs
gpl-3.0
605
0
11
91
194
121
73
15
1
{-# LANGUAGE ForeignFunctionInterface #-} {----------------------------------------------------------------- (c) 2008-2009 Markus Dittrich This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. 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 Version 3 for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. --------------------------------------------------------------------} -- | definition of additional math and helper functions module ExtraFunctions ( erf , erfc , fact , is_equal , is_equal_with , real_exp , to_int , to_positive_int ) where -- imports import Foreign() import Foreign.C.Types import Prelude -- | use glibc DBL_EPSILON dbl_epsilon :: Double dbl_epsilon = 2.2204460492503131e-16 -- | comparison function for doubles via dbl_epsion is_equal :: Double -> Double -> Bool is_equal x y = abs(x-y) <= abs(x) * dbl_epsilon -- | comparison function for doubles via threshold is_equal_with :: Double -> Double -> Double -> Bool is_equal_with x y th = abs(x-y) <= abs(x) * th -- | function checking if a Double can be interpreted as a non -- negative Integer. We need this since all parsing of numbers -- is done with Doubles but some functions only work for -- non-negative integers such as factorial. -- To check if we are dealing with Double, we convert to an -- Integer via floor and the compare if the numbers are identical. -- If yes, the number seems to be an Integer and we return it, -- otherwise Nothing to_positive_int :: Double -> Maybe Integer to_positive_int x = case (is_equal (fromInteger . floor $ x) x) && (x > 0.0) of True -> Just $ floor x False -> Nothing -- | function checking if a Double can be interpreted as an -- Integer. See is_positive_int for more detail to_int :: Double -> Maybe Integer to_int x = case is_equal (fromInteger . floor $ x) x of True -> Just $ floor x False -> Nothing -- | helper function for defining real powers -- NOTE: We use glibc's pow function since it is more -- precise than implementing it ourselves via, e.g., -- pow a x = exp $ x * log a foreign import ccall "math.h pow" c_pow :: CDouble -> CDouble -> CDouble real_exp :: Double -> Double -> Double real_exp a x = realToFrac $ c_pow (realToFrac a) (realToFrac x) -- | factorial function fact :: Integer -> Integer fact 0 = 1 fact n = n * fact (n-1) -- | error function erf(x) -- we use a recursive solution of the Taylor series expansion erf :: Double -> Double erf x | x == 0.0 = 0.0 -- our recursive alg. loops forever -- in this case | abs(x) > 2.2 = 1.0 - erfc x -- use erfc for numerical accuracy | otherwise = 2.0 / sqrt(pi) * (erf_h x x 1.0) where x_next n = -(x^2) * (2*n-1)/(n * (2*n+1)) erf_h old x_old n = let x_new = x_old * (x_next n) tot = old + x_new in if abs(x_new/tot) < dbl_epsilon then tot else erf_h tot x_new (n+1) -- | complementary error function erfc(x) = 1 - erf(x) -- we use a recursive solution of the continued fraction -- expression of erfc(x) for it superior convergence -- property. Here, we calculate the ith and (i+1)th convergent, (see -- http://archives.math.utk.edu/articles/atuyl/confrac/intro.html) -- and terminate when the relative difference is smaller than a -- certain threshold. erfc :: Double -> Double erfc x | abs(x) < 2.2 = 1.0 - erf(x) -- use erf(x) in [-2.2,2.2] | signum(x) < 0 = 2.0 - erfc(-x) -- continued fraction expansion -- only valid for x > 0 | otherwise = 1/sqrt(pi) * exp(-x^2) * (erfc_h nc1 nc2 dc1 dc2 1.0) where nc1 = 1.0 :: Double -- numerator of 1st convergent nc2 = x :: Double -- numerator of 2nd convergent dc1 = x :: Double -- denominator of 1st convergent dc2 = x^2+0.5 :: Double -- denominator of 2nd convergent erfc_h n1 n2 d1 d2 i = let num_new = n1*i + n2*x denom_new = d1*i + d2*x d_old = n2/d2 d_new = num_new/denom_new in if abs((d_old - d_new)/d_new) < dbl_epsilon then d_new else erfc_h n2 num_new d2 denom_new (i+0.5)
markusle/husky
src/ExtraFunctions.hs
gpl-3.0
4,946
0
15
1,424
941
508
433
64
2
{- - Copyright (C) 2015-2016 Ramakrishnan Muthukrishnan <ram@rkrishnan.org> - - This file is part of FuncTorrent. - - FuncTorrent is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. - - FuncTorrent 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 FuncTorrent; if not, see <http://www.gnu.org/licenses/> -} {-# LANGUAGE OverloadedStrings #-} module FuncTorrent.Metainfo (Info(..), Metainfo(..), torrentToMetainfo ) where import Prelude hiding (lookup) import Data.ByteString.Char8 (ByteString, unpack) import Data.Map as M ((!), lookup) import Data.List (intersperse) import Crypto.Hash.SHA1 (hash) import Data.Maybe (maybeToList) import FuncTorrent.Bencode (BVal(..), encode, decode, bstrToString, bValToInteger) data FileMeta = FileMeta { lengthInBytes :: !Integer , md5sum :: !(Maybe String) , path :: String } deriving (Eq, Show) data Info = Info { pieceLength :: !Integer , pieces :: !ByteString , private :: !(Maybe Integer) , name :: !String , filemeta :: [FileMeta] } deriving (Eq, Show) data Metainfo = Metainfo { info :: !(Maybe Info) , announceList :: ![String] , creationDate :: !(Maybe Integer) , comment :: !(Maybe String) , createdBy :: !(Maybe String) , encoding :: !(Maybe String) , infoHash :: !ByteString } deriving (Eq, Show) bvalToInfo :: BVal -> Maybe Info bvalToInfo (Bdict minfo) = let (Bint pieceLength') = minfo ! "piece length" (Bstr pieces') = minfo ! "pieces" private' = Nothing (Bstr name') = minfo ! "name" -- is the key "files" present? If so, it is a multi-file torrent -- if not, it is a single file torrent. filesIfMulti = lookup "files" minfo partialInfo = Info { pieceLength = pieceLength' , pieces = pieces' , private = private' , name = unpack name' , filemeta = [] } in case filesIfMulti of Nothing -> let (Bint length') = minfo ! "length" filemeta' = FileMeta { lengthInBytes = length' , md5sum = Nothing , path = unpack name' } in Just (partialInfo { filemeta = [filemeta'] }) Just (Blist files) -> mapM toFileMeta files >>= \filemeta' -> Just partialInfo { filemeta = filemeta' } Just _ -> Nothing bvalToInfo _ = Nothing toFileMeta :: BVal -> Maybe FileMeta toFileMeta (Bdict fm) = let (Bint length') = fm ! "length" (Blist pathElems) = fm ! "path" pathStrings = fmap bstrToString pathElems in sequence pathStrings >>= \pathList -> let path' = concat $ intersperse "/" pathList in Just (FileMeta { lengthInBytes = length' , md5sum = Nothing , path = path' }) toFileMeta _ = Nothing mkMetaInfo :: BVal -> Either String Metainfo mkMetaInfo (Bdict minfo) = let info' = bvalToInfo $ minfo ! "info" announce' = lookup "announce" minfo announceList' = lookup "announce-list" minfo creationDate' = lookup "creation date" minfo comment' = lookup "comment" minfo createdBy' = lookup "created by" minfo encoding' = lookup "encoding" minfo in Right Metainfo { info = info' , announceList = maybeToList (announce' >>= bstrToString) ++ getAnnounceList announceList' , creationDate = bValToInteger =<< creationDate' , comment = bstrToString =<< comment' , createdBy = bstrToString =<< createdBy' , encoding = bstrToString =<< encoding' , infoHash = hash . encode $ (minfo ! "info") } mkMetaInfo _ = Left "mkMetaInfo: expect an input dict" getAnnounceList :: Maybe BVal -> [String] getAnnounceList Nothing = [] getAnnounceList (Just (Bint _)) = [] getAnnounceList (Just (Bstr _)) = [] getAnnounceList (Just (Blist l)) = map (\s -> case s of (Bstr s') -> unpack s' (Blist s') -> case s' of [Bstr s''] -> unpack s'' _ -> "" _ -> "") l getAnnounceList (Just (Bdict _)) = [] torrentToMetainfo :: ByteString -> Either String Metainfo torrentToMetainfo s = case decode s of Right d -> mkMetaInfo d Left e -> Left ("Cannot parse the torrent file: " ++ show e)
vu3rdd/functorrent
src/FuncTorrent/Metainfo.hs
gpl-3.0
6,258
0
16
2,811
1,210
650
560
123
4
module Pause where import DataTypes import Graphics.Gloss import Graphics.Gloss.Interface.Pure.Game -- | Update the pause screen. updatePause :: Float -> AsteroidsGame -> AsteroidsGame updatePause seconds game = game -- | Handle the key events on the pause screen. handlePauseKeys :: Event -> AsteroidsGame -> AsteroidsGame --handlePauseKeys (EventKey (Char '1') _ _ _) game = game {gameMode = Single} -- Continue the game as singleplayer mode when press '1' --handlePauseKeys (EventKey (Char '2') _ _ _) game = game {gameMode = Cooperative} -- Continue the game as cooperative mode when press '2' --handlePauseKeys (EventKey (Char '3') _ _ _) game = game {gameMode = Versus} -- Continue the game as versus mode when press '3' handlePauseKeys (EventKey (Char 'q') _ _ _) game = game {gameMode = Menu} -- Return to the menu and quit the game when press 'q' handlePauseKeys (EventKey (Char 'p') Down _ _) game = game {gameMode = (whereFrom game)} handlePauseKeys _ game = game -- | Display the pause screen with some options. pauseRender :: AsteroidsGame -> Picture pauseRender game = color white (pictures [ translate (-350) 280 (text "-------"), translate (-350) 200 (text "| Paused. |"), translate (-350) 120 (text "-------"), --scale (0.4) (0.4) (translate (-800) (100) (text "(1)Continue as SinglePlayer")), --scale (0.4) (0.4) (translate (-800) (-100) (text "(2)Continue as Cooperative")), --scale (0.4) (0.4) (translate (-800) (-300) (text "(3)Continue as Versus")), scale (0.4) (0.4) (translate (-800) (100) (text "(p)Resume")), scale (0.4) (0.4) (translate (-800) (-100) (text "(q)Return to MainMenu")) ])
kareem2048/Asteroids
Pause.hs
gpl-3.0
1,704
0
13
335
327
181
146
18
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} -- Module : Gen.Types.Ann -- Copyright : (c) 2013-2015 Brendan Hay -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : provisional -- Portability : non-portable (GHC extensions) module Gen.Types.Ann where import Control.Comonad import Control.Comonad.Cofree import Control.Lens import Data.Aeson import Data.Function (on) import Data.Hashable import qualified Data.HashSet as Set import Data.Monoid import Data.Text (Text) import qualified Data.Text as Text import Gen.TH import Gen.Types.Id import GHC.Generics (Generic) type Set = Set.HashSet data Direction = Output | Input deriving (Eq, Show, Generic) instance Hashable Direction data Mode = Bi | Uni !Direction deriving (Eq, Show) instance Monoid Mode where mempty = Bi mappend (Uni i) (Uni o) | i == o = Uni o mappend _ _ = Bi data Relation = Relation { _relShared :: !Int -- FIXME: get around to using something more sensible. , _relMode :: !Mode } deriving (Eq, Show) makeClassy ''Relation instance Monoid Relation where mempty = Relation 0 mempty mappend a b = Relation (on add _relShared b a) (on (<>) _relMode b a) where add 0 0 = 2 add 1 0 = 2 add 0 1 = 2 add x y = x + y instance (Functor f, HasRelation a) => HasRelation (Cofree f a) where relation = lens extract (flip (:<) . unwrap) . relation mkRelation :: Maybe Id -> Direction -> Relation mkRelation p = Relation (maybe 0 (const 1) p) . Uni isShared :: HasRelation a => a -> Bool isShared = (> 1) . view relShared isOrphan :: HasRelation a => a -> Bool isOrphan = (== 0) . view relShared data Derive = DEq | DOrd | DRead | DShow | DEnum | DNum | DIntegral | DReal | DRealFrac | DRealFloat | DMonoid | DSemigroup | DIsString | DData | DTypeable | DGeneric deriving (Eq, Ord, Show, Generic) instance Hashable Derive instance FromJSON Derive where parseJSON = gParseJSON' (spinal & ctor %~ (. Text.drop 1)) data Lit = Int | Long | Double | Text | Blob | Time | Bool deriving (Show) data TType = TType Text [Derive] | TLit Lit | TNatural | TStream | TMaybe TType | TSensitive TType | TList TType | TList1 TType | TMap TType TType deriving (Show) data Related = Related { _annId :: Id , _annRelation :: Relation } deriving (Show) makeClassy ''Related instance (Functor f, HasRelated a) => HasRelated (Cofree f a) where related = lens extract (flip (:<) . unwrap) . related instance HasId Related where identifier = view annId instance HasRelation Related where relation = annRelation data Prefixed = Prefixed { _annRelated :: Related , _annPrefix :: Maybe Text } deriving (Show) makeClassy ''Prefixed instance (Functor f, HasPrefixed a) => HasPrefixed (Cofree f a) where prefixed = lens extract (flip (:<) . unwrap) . prefixed instance HasRelation Prefixed where relation = related . relation instance HasRelated Prefixed where related = annRelated instance HasId Prefixed where identifier = view annId data Solved = Solved { _annPrefixed :: Prefixed , _annType :: TType } deriving (Show) makeClassy ''Solved instance (Functor f, HasSolved a) => HasSolved (Cofree f a) where solved = lens extract (flip (:<) . unwrap) . solved instance HasRelation Solved where relation = prefixed . relation instance HasRelated Solved where related = prefixed . related instance HasPrefixed Solved where prefixed = annPrefixed instance HasId Solved where identifier = view annId
fmapfmapfmap/amazonka
gen/src/Gen/Types/Ann.hs
mpl-2.0
4,409
0
11
1,323
1,173
646
527
141
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.CloudSearch.Settings.SearchApplications.List -- 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) -- -- Lists all search applications. **Note:** This API requires an admin -- account to execute. -- -- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.settings.searchapplications.list@. module Network.Google.Resource.CloudSearch.Settings.SearchApplications.List ( -- * REST Resource SettingsSearchApplicationsListResource -- * Creating a Request , settingsSearchApplicationsList , SettingsSearchApplicationsList -- * Request Lenses , ssalXgafv , ssalUploadProtocol , ssalAccessToken , ssalUploadType , ssalDebugOptionsEnableDebugging , ssalPageToken , ssalPageSize , ssalCallback ) where import Network.Google.CloudSearch.Types import Network.Google.Prelude -- | A resource alias for @cloudsearch.settings.searchapplications.list@ method which the -- 'SettingsSearchApplicationsList' request conforms to. type SettingsSearchApplicationsListResource = "v1" :> "settings" :> "searchapplications" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "debugOptions.enableDebugging" Bool :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListSearchApplicationsResponse -- | Lists all search applications. **Note:** This API requires an admin -- account to execute. -- -- /See:/ 'settingsSearchApplicationsList' smart constructor. data SettingsSearchApplicationsList = SettingsSearchApplicationsList' { _ssalXgafv :: !(Maybe Xgafv) , _ssalUploadProtocol :: !(Maybe Text) , _ssalAccessToken :: !(Maybe Text) , _ssalUploadType :: !(Maybe Text) , _ssalDebugOptionsEnableDebugging :: !(Maybe Bool) , _ssalPageToken :: !(Maybe Text) , _ssalPageSize :: !(Maybe (Textual Int32)) , _ssalCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'SettingsSearchApplicationsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ssalXgafv' -- -- * 'ssalUploadProtocol' -- -- * 'ssalAccessToken' -- -- * 'ssalUploadType' -- -- * 'ssalDebugOptionsEnableDebugging' -- -- * 'ssalPageToken' -- -- * 'ssalPageSize' -- -- * 'ssalCallback' settingsSearchApplicationsList :: SettingsSearchApplicationsList settingsSearchApplicationsList = SettingsSearchApplicationsList' { _ssalXgafv = Nothing , _ssalUploadProtocol = Nothing , _ssalAccessToken = Nothing , _ssalUploadType = Nothing , _ssalDebugOptionsEnableDebugging = Nothing , _ssalPageToken = Nothing , _ssalPageSize = Nothing , _ssalCallback = Nothing } -- | V1 error format. ssalXgafv :: Lens' SettingsSearchApplicationsList (Maybe Xgafv) ssalXgafv = lens _ssalXgafv (\ s a -> s{_ssalXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ssalUploadProtocol :: Lens' SettingsSearchApplicationsList (Maybe Text) ssalUploadProtocol = lens _ssalUploadProtocol (\ s a -> s{_ssalUploadProtocol = a}) -- | OAuth access token. ssalAccessToken :: Lens' SettingsSearchApplicationsList (Maybe Text) ssalAccessToken = lens _ssalAccessToken (\ s a -> s{_ssalAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ssalUploadType :: Lens' SettingsSearchApplicationsList (Maybe Text) ssalUploadType = lens _ssalUploadType (\ s a -> s{_ssalUploadType = a}) -- | If you are asked by Google to help with debugging, set this field. -- Otherwise, ignore this field. ssalDebugOptionsEnableDebugging :: Lens' SettingsSearchApplicationsList (Maybe Bool) ssalDebugOptionsEnableDebugging = lens _ssalDebugOptionsEnableDebugging (\ s a -> s{_ssalDebugOptionsEnableDebugging = a}) -- | The next_page_token value returned from a previous List request, if any. -- The default value is 10 ssalPageToken :: Lens' SettingsSearchApplicationsList (Maybe Text) ssalPageToken = lens _ssalPageToken (\ s a -> s{_ssalPageToken = a}) -- | The maximum number of items to return. ssalPageSize :: Lens' SettingsSearchApplicationsList (Maybe Int32) ssalPageSize = lens _ssalPageSize (\ s a -> s{_ssalPageSize = a}) . mapping _Coerce -- | JSONP ssalCallback :: Lens' SettingsSearchApplicationsList (Maybe Text) ssalCallback = lens _ssalCallback (\ s a -> s{_ssalCallback = a}) instance GoogleRequest SettingsSearchApplicationsList where type Rs SettingsSearchApplicationsList = ListSearchApplicationsResponse type Scopes SettingsSearchApplicationsList = '["https://www.googleapis.com/auth/cloud_search", "https://www.googleapis.com/auth/cloud_search.settings", "https://www.googleapis.com/auth/cloud_search.settings.query"] requestClient SettingsSearchApplicationsList'{..} = go _ssalXgafv _ssalUploadProtocol _ssalAccessToken _ssalUploadType _ssalDebugOptionsEnableDebugging _ssalPageToken _ssalPageSize _ssalCallback (Just AltJSON) cloudSearchService where go = buildClient (Proxy :: Proxy SettingsSearchApplicationsListResource) mempty
brendanhay/gogol
gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Settings/SearchApplications/List.hs
mpl-2.0
6,472
0
19
1,439
896
519
377
131
1
{-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Kinesis -- Copyright : (c) 2013-2015 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) -- -- Amazon Kinesis Service API Reference -- -- Amazon Kinesis is a managed service that scales elastically for real -- time processing of streaming big data. -- -- /See:/ <http://docs.aws.amazon.com/kinesis/latest/APIReference/Welcome.html AWS API Reference> module Network.AWS.Kinesis ( -- * Service Configuration kinesis -- * Errors -- $errors -- ** ExpiredIteratorException , _ExpiredIteratorException -- ** InvalidArgumentException , _InvalidArgumentException -- ** ProvisionedThroughputExceededException , _ProvisionedThroughputExceededException -- ** ResourceNotFoundException , _ResourceNotFoundException -- ** LimitExceededException , _LimitExceededException -- ** ResourceInUseException , _ResourceInUseException -- * Waiters -- $waiters -- ** StreamExists , streamExists -- * Operations -- $operations -- ** PutRecord , module Network.AWS.Kinesis.PutRecord -- ** MergeShards , module Network.AWS.Kinesis.MergeShards -- ** GetShardIterator , module Network.AWS.Kinesis.GetShardIterator -- ** GetRecords , module Network.AWS.Kinesis.GetRecords -- ** ListTagsForStream , module Network.AWS.Kinesis.ListTagsForStream -- ** AddTagsToStream , module Network.AWS.Kinesis.AddTagsToStream -- ** PutRecords , module Network.AWS.Kinesis.PutRecords -- ** DeleteStream , module Network.AWS.Kinesis.DeleteStream -- ** RemoveTagsFromStream , module Network.AWS.Kinesis.RemoveTagsFromStream -- ** ListStreams (Paginated) , module Network.AWS.Kinesis.ListStreams -- ** CreateStream , module Network.AWS.Kinesis.CreateStream -- ** SplitShard , module Network.AWS.Kinesis.SplitShard -- ** DescribeStream (Paginated) , module Network.AWS.Kinesis.DescribeStream -- * Types -- ** ShardIteratorType , ShardIteratorType (..) -- ** StreamStatus , StreamStatus (..) -- ** HashKeyRange , HashKeyRange , hashKeyRange , hkrStartingHashKey , hkrEndingHashKey -- ** PutRecordsRequestEntry , PutRecordsRequestEntry , putRecordsRequestEntry , prreExplicitHashKey , prreData , prrePartitionKey -- ** PutRecordsResultEntry , PutRecordsResultEntry , putRecordsResultEntry , prreSequenceNumber , prreErrorCode , prreErrorMessage , prreShardId -- ** Record , Record , record , rApproximateArrivalTimestamp , rSequenceNumber , rData , rPartitionKey -- ** SequenceNumberRange , SequenceNumberRange , sequenceNumberRange , snrEndingSequenceNumber , snrStartingSequenceNumber -- ** Shard , Shard , shard , sAdjacentParentShardId , sParentShardId , sShardId , sHashKeyRange , sSequenceNumberRange -- ** StreamDescription , StreamDescription , streamDescription , sdStreamName , sdStreamARN , sdStreamStatus , sdShards , sdHasMoreShards -- ** Tag , Tag , tag , tagValue , tagKey ) where import Network.AWS.Kinesis.AddTagsToStream import Network.AWS.Kinesis.CreateStream import Network.AWS.Kinesis.DeleteStream import Network.AWS.Kinesis.DescribeStream import Network.AWS.Kinesis.GetRecords import Network.AWS.Kinesis.GetShardIterator import Network.AWS.Kinesis.ListStreams import Network.AWS.Kinesis.ListTagsForStream import Network.AWS.Kinesis.MergeShards import Network.AWS.Kinesis.PutRecord import Network.AWS.Kinesis.PutRecords import Network.AWS.Kinesis.RemoveTagsFromStream import Network.AWS.Kinesis.SplitShard import Network.AWS.Kinesis.Types import Network.AWS.Kinesis.Waiters {- $errors Error matchers are designed for use with the functions provided by <http://hackage.haskell.org/package/lens/docs/Control-Exception-Lens.html Control.Exception.Lens>. This allows catching (and rethrowing) service specific errors returned by 'Kinesis'. -} {- $operations Some AWS operations return results that are incomplete and require subsequent requests in order to obtain the entire result set. The process of sending subsequent requests to continue where a previous request left off is called pagination. For example, the 'ListObjects' operation of Amazon S3 returns up to 1000 objects at a time, and you must send subsequent requests with the appropriate Marker in order to retrieve the next page of results. Operations that have an 'AWSPager' instance can transparently perform subsequent requests, correctly setting Markers and other request facets to iterate through the entire result set of a truncated API operation. Operations which support this have an additional note in the documentation. Many operations have the ability to filter results on the server side. See the individual operation parameters for details. -} {- $waiters Waiters poll by repeatedly sending a request until some remote success condition configured by the 'Wait' specification is fulfilled. The 'Wait' specification determines how many attempts should be made, in addition to delay and retry strategies. -}
olorin/amazonka
amazonka-kinesis/gen/Network/AWS/Kinesis.hs
mpl-2.0
5,708
0
5
1,220
443
329
114
85
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Healthcare.Projects.Locations.DataSets.ConsentStores.ConsentArtifacts.Get -- 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) -- -- Gets the specified Consent artifact. -- -- /See:/ <https://cloud.google.com/healthcare Cloud Healthcare API Reference> for @healthcare.projects.locations.datasets.consentStores.consentArtifacts.get@. module Network.Google.Resource.Healthcare.Projects.Locations.DataSets.ConsentStores.ConsentArtifacts.Get ( -- * REST Resource ProjectsLocationsDataSetsConsentStoresConsentArtifactsGetResource -- * Creating a Request , projectsLocationsDataSetsConsentStoresConsentArtifactsGet , ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet -- * Request Lenses , pldscscagXgafv , pldscscagUploadProtocol , pldscscagAccessToken , pldscscagUploadType , pldscscagName , pldscscagCallback ) where import Network.Google.Healthcare.Types import Network.Google.Prelude -- | A resource alias for @healthcare.projects.locations.datasets.consentStores.consentArtifacts.get@ method which the -- 'ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet' request conforms to. type ProjectsLocationsDataSetsConsentStoresConsentArtifactsGetResource = "v1" :> Capture "name" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ConsentArtifact -- | Gets the specified Consent artifact. -- -- /See:/ 'projectsLocationsDataSetsConsentStoresConsentArtifactsGet' smart constructor. data ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet = ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet' { _pldscscagXgafv :: !(Maybe Xgafv) , _pldscscagUploadProtocol :: !(Maybe Text) , _pldscscagAccessToken :: !(Maybe Text) , _pldscscagUploadType :: !(Maybe Text) , _pldscscagName :: !Text , _pldscscagCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pldscscagXgafv' -- -- * 'pldscscagUploadProtocol' -- -- * 'pldscscagAccessToken' -- -- * 'pldscscagUploadType' -- -- * 'pldscscagName' -- -- * 'pldscscagCallback' projectsLocationsDataSetsConsentStoresConsentArtifactsGet :: Text -- ^ 'pldscscagName' -> ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet projectsLocationsDataSetsConsentStoresConsentArtifactsGet pPldscscagName_ = ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet' { _pldscscagXgafv = Nothing , _pldscscagUploadProtocol = Nothing , _pldscscagAccessToken = Nothing , _pldscscagUploadType = Nothing , _pldscscagName = pPldscscagName_ , _pldscscagCallback = Nothing } -- | V1 error format. pldscscagXgafv :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet (Maybe Xgafv) pldscscagXgafv = lens _pldscscagXgafv (\ s a -> s{_pldscscagXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pldscscagUploadProtocol :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet (Maybe Text) pldscscagUploadProtocol = lens _pldscscagUploadProtocol (\ s a -> s{_pldscscagUploadProtocol = a}) -- | OAuth access token. pldscscagAccessToken :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet (Maybe Text) pldscscagAccessToken = lens _pldscscagAccessToken (\ s a -> s{_pldscscagAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pldscscagUploadType :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet (Maybe Text) pldscscagUploadType = lens _pldscscagUploadType (\ s a -> s{_pldscscagUploadType = a}) -- | Required. The resource name of the Consent artifact to retrieve. pldscscagName :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet Text pldscscagName = lens _pldscscagName (\ s a -> s{_pldscscagName = a}) -- | JSONP pldscscagCallback :: Lens' ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet (Maybe Text) pldscscagCallback = lens _pldscscagCallback (\ s a -> s{_pldscscagCallback = a}) instance GoogleRequest ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet where type Rs ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet = ConsentArtifact type Scopes ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsLocationsDataSetsConsentStoresConsentArtifactsGet'{..} = go _pldscscagName _pldscscagXgafv _pldscscagUploadProtocol _pldscscagAccessToken _pldscscagUploadType _pldscscagCallback (Just AltJSON) healthcareService where go = buildClient (Proxy :: Proxy ProjectsLocationsDataSetsConsentStoresConsentArtifactsGetResource) mempty
brendanhay/gogol
gogol-healthcare/gen/Network/Google/Resource/Healthcare/Projects/Locations/DataSets/ConsentStores/ConsentArtifacts/Get.hs
mpl-2.0
6,125
0
15
1,213
698
409
289
114
1
-- {-# LANGUAGE #-} {-# OPTIONS_GHC -Wall -fno-warn-missing-signatures #-} ---------------------------------------------------------------------- -- | -- Module : Shady.Play.CseTest -- Copyright : (c) Conal Elliott 2009 -- License : AGPLv3 -- -- Maintainer : conal@conal.net -- Stability : experimental -- -- Test new CSE stuff ---------------------------------------------------------------------- module Shady.Play.CseTest where import Prelude hiding ((<*)) -- import Control.Applicative (liftA2) import Data.VectorSpace -- For testing import Text.PrettyPrint.Leijen.DocExpr (Expr,HasExpr(expr)) import Data.Boolean import Shady.Language.Exp -- import Shady.Color -- import Shady.Image import Shady.Complex import Shady.Misc (frac) -- import Shady.Language.Cse import Shady.Language.Share x :: HasExpr a => a -> Expr x = expr type Point = ComplexE R {- xc :: Color -> Expr xc = expr . colorToR4 xp :: Point -> Expr xp = expr . pointToR2 -} q :: FloatE q = Var (var "q") t1,t2 :: FloatE t1 = q + q -- Was @q * (q + q)@, now @let a = q + q in a * a@. What happened? t2 = t1 * t1 c1 = cse t1 t3a = sin q / cos q -- let a = sin(q) in -- let b = cos(q) in -- b + a / b -- t3 = cos q + t3a -- cse => cos(q) + sin(q) / cos(q) t3b = cq + sq / cq where cq = cos q sq = sin q -- cse => let x3 = cos(q) in x3 + sin(q) / x3 -- let a = cos(q) in -- a - 1.0 / a -- t4 = cos q - 1 / cos q -- let a = cos(q) in -- a * (a + sin(q) / a) -- t5 = cos q * t3 -- let a = cos(q) in -- (a + sin(q) / a) * (a - 1.0 / a) -- t6 = t3 * t4 -- let a = cos(q) in -- let b = sin(q) in -- (a + b / a) * (a - 1.0 / a) + (a + b / a) t7 = t6 + t3 -- let a = sin(q) in -- a + (1.0 - a) * (a < 3.0 ? 4.0 : 5.0) -- t8 = let a = sin q in a + (1 - a) * (ifE (a <* 3) 4 5) -- q * sin(q) r = q * sin q -- let a = sin(q) in -- a * (q * a) s = sin q * r -- let a = sin(q) in -- let b = q * a in -- b + a * b t9a = r + s -- let a = sin(q) in -- let b = q * a in -- a * b + b t9b = s + r w = Var (var "w") :: R2E {- bw :: BoolE -> Color bw = boolean white clear ra :: R2E -> Color ra z = bw (z <.> z <* 1) -} stripes (a :+ _) = frac a <* 0.5 a1 :: FloatE a1 = magnitudeSq (t *^ uv) {- a2 :: BoolE a2 = uscale2 t udisk uv a3 :: R4E a3 = colorToR4 $ toColor (uscale2 (cos t) udisk uv) -} t :: FloatE t = Var (var "t") u,v :: FloatE u = Var (var "u") v = Var (var "v") uv :: Point uv = u :+ v ------------- ts = [t1,t2,t3a,t3,t4,t5,t6,t8,t9a,t9b] main = mapM_ (print.expr) ts
conal/shady-gen
src/Shady/Play/CseTest.hs
agpl-3.0
2,583
0
11
723
586
348
238
46
1
{-# LANGUAGE TemplateHaskell #-} module Model.Notification.SQL ( selectNotifyDelivery , selectTargetNotification , selectNotification , selectPartyAuthorizationNotify ) where import qualified Language.Haskell.TH as TH import Has import Model.SQL.Select import Model.Time import Model.Id.Types import Model.Permission.Types import Model.Release.Types import Model.Party.Types import Model.Party.SQL import Model.Volume.Types import Model.Volume.SQL import Model.Container.Types import Model.Segment import Model.Asset.Types import Model.Tag.Types import Model.Tag.SQL import Model.Comment.Types import Model.Notification.Types selectNotifyDelivery :: Selector selectNotifyDelivery = selectMap (TH.VarE 'fromMaybeDelivery `TH.AppE`) $ selectColumn "notify_view" "delivery" makePartyAuthorizationNotice :: (Party, Maybe Permission) -> Delivery -> (Party, Maybe Permission, Delivery) makePartyAuthorizationNotice (p, a) d = (p, a, d) selectPartyAuthorizationNotify :: TH.Name -- ^ 'Identity' -> Selector -- ^ @('Party', Maybe 'Permission', 'Delivery')@ selectPartyAuthorizationNotify ident = selectJoin 'makePartyAuthorizationNotice [ selectPartyAuthorization ident , joinOn "id = target" selectNotifyDelivery ] makeNotification :: Id Notification -> Notice -> Timestamp -> Delivery -> Maybe Permission -> Maybe (Id Container) -> Maybe Segment -> Maybe (Id Asset) -> Maybe Release -> Maybe (Id Comment) -> PartyRow -> Maybe PartyRow -> Maybe VolumeRow -> Maybe Tag -> Account -> Notification makeNotification i n t d e c s a r m w p v g u = Notification i (view u) n t d w p v e c s a r m g notificationRow :: Selector -- ^ @'PartyRow' -> Maybe 'PartyRow' -> Maybe 'VolumeRow' -> Maybe 'Tag' -> 'Account' -> 'Notification'@ notificationRow = selectColumns 'makeNotification "notification" ["id", "notice", "time", "delivered", "permission", "container", "segment", "asset", "release", "comment"] selectTargetNotification :: Selector -- ^ @'Account' -> 'Notification'@ selectTargetNotification = selectJoin '($) [ notificationRow , joinOn "notification.agent = agent.id" $ selectPartyRow `fromAlias` "agent" , maybeJoinOn "notification.party = nparty.id" $ selectPartyRow `fromAlias` "nparty" , maybeJoinOn "notification.volume = volume.id" selectVolumeRow , maybeJoinOn "notification.tag = tag.id" selectTag ] selectNotification :: Selector -- ^ @'Notification'@ selectNotification = selectJoin '($) [ selectTargetNotification , joinOn "notification.target = account.id" selectUserAccount ]
databrary/databrary
src/Model/Notification/SQL.hs
agpl-3.0
2,548
0
19
356
599
339
260
52
1
{-# LANGUAGE GADTs #-} ----------------------------------------------------------------------------- -- Copyright 2018, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : bastiaan.heeren@ou.nl -- Stability : provisional -- Portability : portable (depends on ghc) -- -- Services using JSON notation -- ----------------------------------------------------------------------------- module Ideas.Encoding.NewEncoderJSON (JSONBuilder, builderToJSON, jsonEncoder) where import Control.Applicative hiding (Const) import Data.Char import Data.Maybe import Ideas.Common.Library hiding (exerciseId) import Ideas.Encoding.Encoder hiding (symbol) import Ideas.Encoding.Request import Ideas.Service.State import Ideas.Service.Types hiding (String) import Ideas.Text.JSON import Ideas.Utils.Prelude (distinct) import qualified Ideas.Service.Diagnose as Diagnose import qualified Ideas.Service.Submit as Submit import qualified Ideas.Service.Types as Tp type JSONBuilder = [(Maybe Key, JSON)] listJSONBuilder :: [JSONBuilder] -> JSONBuilder listJSONBuilder xs = {- case mapM isSingleton xs of Just ys -> ys Nothing -> -} [(Nothing, Array (map builderToJSON xs))] isSingleton :: [a] -> Maybe a isSingleton [x] = Just x isSingleton _ = Nothing builderToJSON :: JSONBuilder -> JSON builderToJSON [(Nothing, x)] = x builderToJSON xs = case mapM fst xs of Just ks -> Object (zip ks (map snd xs)) Nothing -> Array (map f xs) where f (Nothing, a) = a f (Just k, a) = Object [(k, a)] tagJSONBuilder :: String -> JSONBuilder -> JSONBuilder tagJSONBuilder s = tagJSON (map toLower s) . builderToJSON tagJSON :: String -> JSON -> JSONBuilder tagJSON s a = [(Just s, a)] ------------------------------------------------------------- -- jsonEncoder :: TypedValue (Type a) -> EncoderX a JSONBuilder jsonEncoder tv@(val ::: tp) = case tp of Iso p t -> jsonEncoder (to p val ::: t) t1 :|: t2 -> case val of Left x -> jsonEncoder (x ::: t1) Right y -> jsonEncoder (y ::: t2) Pair t1 t2 -> (++) <$> jsonEncoder (fst val ::: t1) <*> jsonEncoder (snd val ::: t2) Tp.List t -> listJSONBuilder <$> sequence [ jsonEncoder (x ::: t) | x <- val ] Tp.Tag s t | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis tv | otherwise -> tagJSONBuilder (map toLower s) <$> jsonEncoder (val ::: t) Tp.Unit -> pure [] Const ctp -> jsonEncodeConst (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp jsonEncodeConst :: TypedValue (Const a) -> EncoderX a JSONBuilder jsonEncodeConst (val ::: tp) = case tp of Rule -> encodeRule val Location -> encodeLocation val Environment -> encodeEnvironment val Context -> encodeContext val State -> encodeState val SomeExercise -> case val of Some ex -> pure (exerciseInfo ex) Text -> pure [(Nothing, toJSON (show val))] Tp.String -> pure [(Nothing, toJSON val)] Tp.Int -> pure [(Nothing, toJSON val)] Tp.Bool -> pure [(Nothing, toJSON val)] _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" {- encoderFor $ \(val ::: tp) -> case tp of Rule -> encodeRule // val Location -> encodeLocation // val Environment -> encodeEnvironment // val Context -> encodeContext // val State -> encodeState // val _ -> pure [(Nothing, toJSON (show tp))] {- SomeExercise -> case val of Some ex -> pure (exerciseInfo ex) Term -> pure (termToJSON val) Text -> pure (toJSON (show val)) Int -> pure (toJSON val) Bool -> pure (toJSON val) Tp.String -> pure (toJSON val) _ -> fail $ "Type " ++ show tp ++ " not supported in JSON" -} -} encodeRule :: Rule (Context a) -> EncoderX a JSONBuilder encodeRule r = pure (tagJSON "rule" (toJSON (showId r))) encodeEnvironment :: Environment -> EncoderX a JSONBuilder encodeEnvironment env = let f a = (showId a, String (showValue a)) in pure $ tagJSON "environment" $ Object [ f a | a <- bindings env ] {- {-encodeStateEnvironment :: JSONEncoder a (Context a) encodeStateEnvironment = makeEncoder $ \ctx -> let loc = fromLocation (location ctx) env = (if null loc then id else insertRef (makeRef "location") loc) $ environment ctx in Object [ (showId a, String $ showValue a) | a <- bindings env ] -} -} encodeContext :: Context a -> EncoderX a JSONBuilder encodeContext ctx = let encValue = case fromContext ctx of Just a -> encodeTerm a Nothing -> pure $ tagJSON "term" Null -- todo: merge with encodeTerm encEnv = encodeEnvironment (environment ctx) encLoc = encodeLocation (location ctx) in (\xs ys zs -> tagJSONBuilder "context" $ xs ++ ys ++ zs) <$> encValue <*> encEnv <*> encLoc encodeTerm :: a -> EncoderX a JSONBuilder encodeTerm a = (tagJSON "term" . f) <$> getExercise where f ex = case hasJSONView ex of Just jv -> build jv a Nothing -> String (prettyPrinter ex a) -- True ex = tagJSON "term" . fromMaybe Null . liftA2 build (hasJSONView ex) . return -- f False ex = tagJSON "term" . String . prettyPrinter ex encodeLocation :: Location -> EncoderX a JSONBuilder encodeLocation loc = pure (tagJSON "location" (toJSON (fromLocation loc))) encodeState :: State a -> EncoderX a JSONBuilder encodeState st = let ctx = stateContext st get f = maybe Null String (f st) make ppCtx = [ (Just "exerciseid", String $ showId (exercise st)) , (Just "prefix", if withoutPrefix st then Null else String (show (statePrefix st)) ) ] ++ ppCtx ++ [ (Just "userid", get stateUser) , (Just "sessionid", get stateSession) , (Just "taskid", get stateStartTerm) ] in (tagJSONBuilder "state" . make) <$> (encodeContext ctx) encodeDiagnosis :: Diagnose.Diagnosis a -> EncoderX a JSONBuilder encodeDiagnosis diagnosis = case diagnosis of Diagnose.Correct b st -> (\xs ys -> (Just "diagnosetype", toJSON "correct") : xs ++ ys) <$> encodeReady b <*> encodeState st Diagnose.Similar b st mr -> (\xs ys zs -> (Just "diagnosetype", toJSON "similar") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeMaybeRule mr Diagnose.NotEquivalent s -> return [(Just "diagnosetype", toJSON "notequiv"), (Just "message", toJSON s)] Diagnose.Expected b st r -> (\xs ys zs -> (Just "diagnosetype", toJSON "expected") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeRule r Diagnose.Buggy env r -> (\xs ys -> (Just "diagnosetype", toJSON "buggy") : xs ++ ys) <$> encodeEnvironment env <*> encodeRule r Diagnose.Detour b st env r -> (\xs ys zs vs -> (Just "diagnosetype", toJSON "detour") : xs ++ ys ++ zs ++ vs) <$> encodeReady b <*> encodeState st <*> encodeEnvironment env <*> encodeRule r Diagnose.WrongRule b st mr -> (\xs ys zs -> (Just "diagnosetype", toJSON "wrongrule") : xs ++ ys ++ zs) <$> encodeReady b <*> encodeState st <*> encodeMaybeRule mr Diagnose.SyntaxError msg -> pure [(Just "diagnosetype", toJSON "syntaxerror"), (Just "message", toJSON msg)] where encodeReady b = return [(Just "ready", toJSON b)] encodeRule r = return [(Just "rule", toJSON (showId r))] encodeMaybeRule mr = return [(Just "rule", maybe Null (toJSON . showId) mr)] -- make "correct" [fromReady b, fromState st] {- Diagnose.SyntaxError s -> pure $ Object [("syntaxerror", String s)] Diagnose.NotEquivalent s -> if null s then pure (Object [("notequiv", Null)]) else make "notequiv" [fromReason s] Diagnose.Buggy env r -> make "buggy" [fromEnv env, fromRule r] Diagnose.Similar b st -> make "similar" [fromReady b, fromState st] Diagnose.WrongRule b st mr -> make "wrongrule" [fromReady b, fromState st, fromMaybeRule mr] Diagnose.Expected b st r -> make "expected" [fromReady b, fromState st, fromRule r] Diagnose.Detour b st env r -> make "detour" [fromReady b, fromState st, fromEnv env, fromRule r] Diagnose.Correct b st -> make "correct" [fromReady b, fromState st] Diagnose.Unknown b st -> make "unknown" [fromReady b, fromState st] where make s = fmap (\xs -> Object $ ("diagnosis", toJSON s) : xs) . sequence fromEnv env = fmap (\x -> ("env", x)) $ jsonEncoder // (env ::: tEnvironment) fromRule r = pure ("rule", (toJSON (showId r))) fromMaybeRule mr = pure ("mayberule", (maybe Null (toJSON . showId) mr)) fromReady b = pure ("ready", toJSON b) fromState st = fmap (\x -> ("state", x)) $ jsonEncoder // (st ::: tState) fromReason s = pure ("reason", (Object [("reason", toJSON s)])) -} {- {- Tp.Tag s t | s == "Result" -> encodeTyped encodeResult Submit.tResult | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis | s == "Derivation" -> (encodeDerivation, tDerivation (tPair tRule tEnvironment) tContext) <?> encodeTyped encodeDerivationText (tDerivation tString tContext) | s == "elem" -> jsonEncoder // (val ::: t) | otherwise -> (\b -> Object [(s, b)]) <$> jsonEncoder // (val ::: t) Tp.Unit -> pure Null Const ctp -> jsonEncodeConst // (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp -} {- jsonEncoder = encoderFor $ \tv@(val ::: tp) -> case tp of _ | length (tupleList tv) > 1 -> jsonTuple <$> sequence [ jsonEncoder // x | x <- tupleList tv ] Iso p t -> jsonEncoder // (to p val ::: t) t1 :|: t2 -> case val of Left x -> jsonEncoder // (x ::: t1) Right y -> jsonEncoder // (y ::: t2) Pair t1 t2 -> let f x y = jsonTuple [x, y] in liftA2 f (jsonEncoder // (fst val ::: t1)) (jsonEncoder // (snd val ::: t2)) List (Const Rule) -> pure $ Array $ map ruleShortInfo val Tp.Tag s t | s == "Result" -> encodeTyped encodeResult Submit.tResult | s == "Diagnosis" -> encodeTyped encodeDiagnosis Diagnose.tDiagnosis | s == "Derivation" -> (encodeDerivation, tDerivation (tPair tRule tEnvironment) tContext) <?> encodeTyped encodeDerivationText (tDerivation tString tContext) | s == "elem" -> jsonEncoder // (val ::: t) | otherwise -> (\b -> Object [(s, b)]) <$> jsonEncoder // (val ::: t) Tp.Unit -> pure Null Tp.List t -> Array <$> sequence [ jsonEncoder // (x ::: t) | x <- val ] Const ctp -> jsonEncodeConst // (val ::: ctp) _ -> fail $ "Cannot encode type: " ++ show tp where tupleList :: TypedValue (TypeRep f) -> [TypedValue (TypeRep f)] tupleList (x ::: Tp.Iso p t) = tupleList (to p x ::: t) tupleList (p ::: Tp.Pair t1 t2) = tupleList (fst p ::: t1) ++ tupleList (snd p ::: t2) tupleList (x ::: Tag s t) | s == "Message" = tupleList (x ::: t) tupleList (ev ::: (t1 :|: t2)) = either (\x -> tupleList (x ::: t1)) (\x -> tupleList (x ::: t2)) ev tupleList tv = [tv] -------------------------- -- legacy representation encodeEnvironment :: JSONEncoder a Environment encodeEnvironment = makeEncoder $ \env -> let f a = Object [(showId a, String (showValue a))] in Object [("environment", Array [ f a | a <- bindings env ])] encodeDerivation :: JSONEncoder a (Derivation (Rule (Context a), Environment) (Context a)) encodeDerivation = encoderFor $ \d -> let xs = [ (s, a) | (_, s, a) <- triples d ] in jsonEncoder // (xs ::: tList (tPair (tPair tRule tEnvironment) tContext)) encodeDerivationText :: JSONEncoder a (Derivation String (Context a)) encodeDerivationText = encoderFor $ \d -> let xs = [ (s, a) | (_, s, a) <- triples d ] in jsonEncoder // (xs ::: tList (tPair tString tContext)) encodeResult :: JSONEncoder a (Submit.Result a) encodeResult = encoderFor $ \result -> Object <$> case result of Submit.Buggy rs -> pure [ ("result", String "Buggy") , ("rules", Array $ map (String . showId) rs) ] Submit.NotEquivalent s -> pure $ ("result", String "NotEquivalent") : [ ("reason", String s) | not (null s)] Submit.Ok rs st -> let f x = [ ("result", String "Ok") , ("rules", Array $ map (String . showId) rs) , ("state", x) ] in f <$> jsonEncoder // (st ::: tState) Submit.Detour rs st -> let f x = [ ("result", String "Detour") , ("rules", Array $ map (String . showId) rs) , ("state", x) ] in f <$> jsonEncoder // (st ::: tState) Submit.Unknown st -> let f x = [ ("result", String "Unknown") , ("state", x) ] in f <$> jsonEncoder // (st ::: tState) encodeDiagnosis :: JSONEncoder a (Diagnose.Diagnosis a) encodeDiagnosis = encoderFor $ \diagnosis -> case diagnosis of Diagnose.SyntaxError s -> pure $ Object [("syntaxerror", String s)] Diagnose.NotEquivalent s -> if null s then pure (Object [("notequiv", Null)]) else make "notequiv" [fromReason s] Diagnose.Buggy env r -> make "buggy" [fromEnv env, fromRule r] Diagnose.Similar b st -> make "similar" [fromReady b, fromState st] Diagnose.WrongRule b st mr -> make "wrongrule" [fromReady b, fromState st, fromMaybeRule mr] Diagnose.Expected b st r -> make "expected" [fromReady b, fromState st, fromRule r] Diagnose.Detour b st env r -> make "detour" [fromReady b, fromState st, fromEnv env, fromRule r] Diagnose.Correct b st -> make "correct" [fromReady b, fromState st] Diagnose.Unknown b st -> make "unknown" [fromReady b, fromState st] where make s = fmap (\xs -> Object $ ("diagnosis", toJSON s) : xs) . sequence fromEnv env = fmap (\x -> ("env", x)) $ jsonEncoder // (env ::: tEnvironment) fromRule r = pure ("rule", (toJSON (showId r))) fromMaybeRule mr = pure ("mayberule", (maybe Null (toJSON . showId) mr)) fromReady b = pure ("ready", toJSON b) fromState st = fmap (\x -> ("state", x)) $ jsonEncoder // (st ::: tState) fromReason s = pure ("reason", (Object [("reason", toJSON s)])) {- encodeTree :: Tree JSON -> JSON encodeTree (Node r ts) = case r of Array [x, t] -> Object [ ("rootLabel", x) , ("type", t) , ("subForest", Array $ map encodeTree ts) ] _ -> error "ModeJSON: malformed tree!" -} jsonTuple :: [JSON] -> JSON jsonTuple xs = case catMaybes <$> mapM f xs of Just ys | distinct (map fst ys) -> Object ys _ -> Array xs where f (Object [p]) = Just (Just p) f Null = Just Nothing f _ = Nothing ruleShortInfo :: Rule a -> JSON ruleShortInfo r = Object [ ("name", toJSON (showId r)) , ("buggy", toJSON (isBuggy r)) , ("arguments", toJSON (length (getRefs r))) , ("rewriterule", toJSON (isRewriteRule r)) ] -} -} exerciseInfo :: Exercise a -> JSONBuilder exerciseInfo ex = tagJSON "exercise" $ Object [ ("exerciseid", toJSON (showId ex)) , ("description", toJSON (description ex)) , ("status", toJSON (show (status ex))) ]
ideas-edu/ideas
src/Ideas/Encoding/NewEncoderJSON.hs
apache-2.0
16,205
0
19
4,580
2,343
1,196
1,147
128
11
module TestSuite1 ( tests ) where import Distribution.TestSuite import Kind.Assumption tests :: IO [Test] tests = return [ Test test1 ] where test1 = TestInstance { run = return $ Finished $ if kgammaIsEmpty kgammaEmpty then Pass else Fail "kgammaEmpty is not empty" , name = "Kind.Assumption.isEmpty" , tags = [] , options = [] , setOption = \_ _ -> Right test1 }
lpeterse/koka
src/TestSuite1.hs
apache-2.0
517
0
11
216
119
68
51
14
2
module Actions.LoginScreen.RegistrationConfirmation.Url where url :: String url = "/registrationConfirmation"
DataStewardshipPortal/ds-wizard
DSServer/app/Actions/LoginScreen/RegistrationConfirmation/Url.hs
apache-2.0
112
0
4
11
18
12
6
3
1
{-# LANGUAGE MultiParamTypeClasses #-} module SoftwareRenderer where import Point import Circle import Rectangle import Renderer import Shape import Data.Matrix import Data.Colour import Data.Colour.Names import Data.Colour.SRGB data SoftwareBuffer = SoftwareBuffer { w,h :: Integer, frame :: Point -> Colour Double} swBufferMatrix :: SoftwareBuffer -> Matrix (Colour Double) swBufferMatrix (SoftwareBuffer w h f)= matrix (fromInteger w) (fromInteger h) matrixGen where matrixGen :: (Int,Int) -> Colour Double matrixGen (x,y) = f (pointCreate (toInteger x) (toInteger y)) instance RenderObject SoftwareBuffer Rectangle where render (SoftwareBuffer w h frame) trans rect = (SoftwareBuffer w h newRect) where newRect :: Point -> Colour Double newRect pos | contains rect ((getMiddle rect) + (trans $ relativPos rect pos)) = over (getColour rect) (frame pos) | otherwise = frame pos instance RenderObject SoftwareBuffer Circle where render (SoftwareBuffer w h frame) trans circle = (SoftwareBuffer w h newCircle) where newCircle :: Point -> Colour Double newCircle pos | contains circle ((getMiddle circle) + (trans $ relativPos circle pos)) = over (getColour circle) (frame pos) | otherwise = frame pos instance Renderer SoftwareBuffer where emptyFrame w h = (SoftwareBuffer w h a) where a :: Point -> Colour Double a p = white
marcelhollerbach/hrem
src/SoftwareRenderer.hs
apache-2.0
1,446
0
16
312
492
252
240
32
1
-- Copyright 2010 Google Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Source where import DevUtils import Tutorial import Control.Monad (when) import Control.Monad.IO.Class import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Snap.Types import Text.Html hiding ((</>)) import qualified Text.Html as Html handler :: Snap () handler = do fileparam <- getParam (C.pack "file") showPreview <- (maybe False (not . C.null)) `fmap` getParam (C.pack "preview") case maybe Nothing (legalPath . C.unpack) fileparam of Nothing -> errorBadRequest Just file -> do meth <- rqMethod `fmap` getRequest when (meth == POST) $ handleSave file html <- liftIO $ mkSrcPage file showPreview htmlResponse html handleSave :: FilePath -> Snap() handleSave file = do contents <- getParam (C.pack "contents") case contents of Nothing -> errorBadRequest Just c -> liftIO $ B.writeFile file $ clean c where clean = T.encodeUtf8 . T.filter (/= '\r') . T.decodeUtf8 mkSrcPage :: FilePath -> Bool -> IO Html mkSrcPage path showPreview = do si <- getSrcInfo path contents <- if srcExists si then readFile (srcPath si) else return $ emptyModule (srcPath si) return $ srcPage si contents showPreview srcPage :: SrcInfo -> String -> Bool -> Html srcPage si contents showPreview = devpage ("Source of " ++ srcPath si) content (modules si) scriptSrcs where content = thediv ! [identifier "source-page"] << [ h1 << srcPath si , p << small << srcFullPath si , rocker , preview showPreview si , editor contents ] rocker = thediv ! [identifier "rocker", theclass "button-set"] << [ thediv ! [identifier "rocker-edit-image"] << noHtml , thediv ! [identifier "rocker-run-image", displayHidden] << noHtml , anchor ! [identifier "rocker-edit", href "#"] << "Edit" , anchor ! [identifier "rocker-run", href "#"] << "Run" ] editor :: String -> Html editor contents = thediv ! [identifier "editor", displayHidden] << [ errors , form ! [Html.method "POST"] << [editorBox, btns, hidden] ] where btns = thediv ! [theclass "button-set"] << [ input ! [thetype "button", value "Cancel", theclass "btn-cancel"] , input ! [thetype "submit", value "Save", theclass "btn-save"] ] editorBox = thediv ! [identifier "editor-box"] << textarea ! [theclass "src", name "contents", identifier "txt-src", strAttr "readonly" "readonly" ] << contents hidden = input ! [thetype "hidden", name "preview", value "1"] preview :: Bool -> SrcInfo -> Html preview showPreview = maybe noHtml build . previewPath where build path = thediv ! [ identifier "preview" , theclass "panel with-preview" , displayHidden ] << [ h1 << "Rendering Preview" , tag "iframe" ! [ theclass "panel-content" ] << noHtml , p ! [ identifier "preview-url", displayHidden ] << path , showMarker ] showMarker = if showPreview then thediv ! [ identifier "preview-show", displayHidden ] << noHtml else noHtml errors :: Html errors = thediv ! [ identifier "errors" , theclass "panel with-errors" , displayHidden] << [ h1 << "Compilation Errors" , pre ! [ theclass "panel-content", displayHidden ] << noHtml ] modules :: SrcInfo -> [Html] modules si = catMaybes [ Just $ modFStat si , Just $ modActions si , modTutorial si , Just modSearch] modFStat :: SrcInfo -> Html modFStat si = (h2 << "File Info") +++ if srcExists si then [if srcWritable si then noHtml else p << bold << "read only", p << show (srcModTime si)] else [p << bold << "new file"] modActions :: SrcInfo -> Html modActions si = (h2 << "Actions") +++ ulist << map (li ! [theclass "op"]) (catMaybes [ previewLink si --, Just $ italics << "Revert" , downloadLink si , fileLink si , Just (anchor ! [ identifier "recompile", theclass "op-recompile", href "#" ] << "Force Recompile") ]) modTutorial :: SrcInfo -> Maybe Html modTutorial si = previewPath si >>= tutorialModule modSearch :: Html modSearch = (h2 << "Research") +++ [ form ! [action "http://holumbus.fh-wedel.de/hayoo/hayoo.html" , target "barley-reseach"] << [ input ! [thetype "text", name "query", theclass "research-query"] , input ! [thetype "submit", value "Hayoo"] ] , form ! [action "http://haskell.org/hoogle", target "barley-reseach"] << [ input ! [thetype "text", name "q", theclass "research-query"] , input ! [thetype "submit", value "Hoogle"] ] ] emptyModule :: FilePath -> String emptyModule filename = "module " ++ modName ++ " where\n\ \\n\ \import Text.Html\n\ \\n\ \page = body << [\n\ \ h1 << \"Hi!\",\n\ \ paragraph << \"testing\"\n\ \ ]\n" where modName = filename -- TODO should replace slashes with dots scriptSrcs :: [String] scriptSrcs = [ "/static/jquery.js" , "/static/codemirror.js" , "/static/mode/haskell.js" , "Source.js" ] displayHidden :: HtmlAttr displayHidden = thestyle "display: none;"
mzero/barley
seed/Source.hs
apache-2.0
6,332
0
15
1,871
1,617
858
759
131
3
-- (C) 2013 Pepijn Kokke & Wout Elsinghorst -- Adapted by Jurriaan Hage {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} module FunFlow.Parsing where import FunFlow.Ast import Prelude hiding ( abs, sum ) import Data.Char (isSpace) import Text.ParserCombinators.UU import Text.ParserCombinators.UU.Utils import Text.ParserCombinators.UU.Idioms (iI,Ii (..)) import Text.ParserCombinators.UU.BasicInstances (Parser,pSym) -- * Top-Level Parsers parseExpr :: String -> Expr parseExpr = runParser "stdin" pExpr -- * Parsing the FUN language pExpr :: Parser Expr pExpr = (pFn <|> pFun <|> pITE <|> pLet <|> pPair <|> pPCase <|> pCons <|> pNil <|> pLCase <|> pDType <|> pDTCase) <<|> pBin where -- literal expressions pLit = Int <$> pInteger <|> Bool True <$ pSymbol "true" <|> Bool False <$ pSymbol "false" -- atomic expressions pAtom = pLit <<|> Var <$> pIdent <<|> pDType <<|> pParens pExpr -- simple expressions pFn, pFun, pLet, pITE, pPair, pPCase, pCons, pNil, pLCase, pDType, pDTCase :: Parser Expr pFn = iI (Fn 0) "fn" pIdent "=>" pExpr Ii -- Default Pi to 0 pFun = iI (Fun 0) "fun" pIdent pIdent "=>" pExpr Ii -- Dito pLet = iI Let "let" pIdent "=" pExpr "in" pExpr Ii pITE = iI ITE "if" pExpr "then" pExpr "else" pExpr Ii pPair = iI (Pair 0) "Pair" "(" pExpr "," pExpr ")" Ii pPCase = iI PCase "pcase" pExpr "of" "Pair" "(" pIdent "," pIdent ")" "=>" pExpr Ii pCons = iI (Cons 0) "Cons" "(" pExpr "," pExpr ")" Ii pNil = (Nil 0) <$ pSymbol "Nil" pLCase = iI LCase "lcase" pExpr "of" "Cons" "(" pIdent "," pIdent ")" "=>" pExpr "or" pExpr Ii pDType = iI (DType 0) "C" "(" (pListSep (pSymbol ",") pExpr) ")" Ii pDTCase = iI DTCase "case" pExpr "of" "C" "(" (pListSep (pSymbol ",") pIdent) ")" "=>" pExpr "or" pExpr Ii -- chained expressions pApp = pChainl_ng (App <$ pSpaces) pAtom pBin = pChainl_ng (bin <$> pOper) pApp pIdent,pConst,pOper :: Parser Name pIdent = lexeme $ (:) <$> pLower <*> pMany (pLetter <|> pDigit <|> pUnderscore) pConst = lexeme $ (:) <$> pUpper <*> pMany (pLetter <|> pDigit <|> pUnderscore) pOper = lexeme $ pSome $ pAnySym "*+/-" pUnderscore :: Parser Char pUnderscore = pSym '_' -- * Recognising more list structures with separators pFoldr2Sep :: IsParser p => (a -> b -> b, b) -> p a1 -> p a -> p b pFoldr2Sep alg@(op,e) sep p = must_be_non_empties "pFoldr2Sep" sep p pfm where pfm = op <$> p <*> pFoldr1 alg (sep *> p) pList2Sep :: IsParser p => p a1 -> p a -> p [a] pList2Sep s p = must_be_non_empties "pListSep" s p (pFoldr2Sep list_alg s p)
aochagavia/CompilerConstruction
funflow/src/FunFlow/Parsing.hs
apache-2.0
2,595
0
16
545
892
481
411
46
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QPolygon.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:31 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Core.QPolygon ( QqqPolygon(..), QqPolygon(..) ,QqqPolygon_nf(..), QqPolygon_nf(..) ,qpoint, qqpoint ,QqputPoints(..) ,QqsetPoint(..), qqsetPoint ,qPolygon_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core class QqqPolygon x1 where qqPolygon :: x1 -> IO (QPolygon ()) class QqPolygon x1 where qPolygon :: x1 -> IO (QPolygon ()) instance QqPolygon (()) where qPolygon () = withQPolygonResult $ qtc_QPolygon foreign import ccall "qtc_QPolygon" qtc_QPolygon :: IO (Ptr (TQPolygon ())) instance QqPolygon ((QPolygon t1)) where qPolygon (x1) = withQPolygonResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon1 cobj_x1 foreign import ccall "qtc_QPolygon1" qtc_QPolygon1 :: Ptr (TQPolygon t1) -> IO (Ptr (TQPolygon ())) instance QqqPolygon ((QRect t1)) where qqPolygon (x1) = withQPolygonResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon2 cobj_x1 foreign import ccall "qtc_QPolygon2" qtc_QPolygon2 :: Ptr (TQRect t1) -> IO (Ptr (TQPolygon ())) instance QqPolygon ((Rect)) where qPolygon (x1) = withQPolygonResult $ withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QPolygon3 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QPolygon3" qtc_QPolygon3 :: CInt -> CInt -> CInt -> CInt -> IO (Ptr (TQPolygon ())) instance QqPolygon ((Int)) where qPolygon (x1) = withQPolygonResult $ qtc_QPolygon4 (toCInt x1) foreign import ccall "qtc_QPolygon4" qtc_QPolygon4 :: CInt -> IO (Ptr (TQPolygon ())) instance QqqPolygon ((QRect t1, Bool)) where qqPolygon (x1, x2) = withQPolygonResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon5 cobj_x1 (toCBool x2) foreign import ccall "qtc_QPolygon5" qtc_QPolygon5 :: Ptr (TQRect t1) -> CBool -> IO (Ptr (TQPolygon ())) instance QqPolygon ((Rect, Bool)) where qPolygon (x1, x2) = withQPolygonResult $ withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QPolygon6 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCBool x2) foreign import ccall "qtc_QPolygon6" qtc_QPolygon6 :: CInt -> CInt -> CInt -> CInt -> CBool -> IO (Ptr (TQPolygon ())) class QqqPolygon_nf x1 where qqPolygon_nf :: x1 -> IO (QPolygon ()) class QqPolygon_nf x1 where qPolygon_nf :: x1 -> IO (QPolygon ()) instance QqPolygon_nf (()) where qPolygon_nf () = withObjectRefResult $ qtc_QPolygon instance QqPolygon_nf ((QPolygon t1)) where qPolygon_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon1 cobj_x1 instance QqqPolygon_nf ((QRect t1)) where qqPolygon_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon2 cobj_x1 instance QqPolygon_nf ((Rect)) where qPolygon_nf (x1) = withObjectRefResult $ withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QPolygon3 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QqPolygon_nf ((Int)) where qPolygon_nf (x1) = withObjectRefResult $ qtc_QPolygon4 (toCInt x1) instance QqqPolygon_nf ((QRect t1, Bool)) where qqPolygon_nf (x1, x2) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon5 cobj_x1 (toCBool x2) instance QqPolygon_nf ((Rect, Bool)) where qPolygon_nf (x1, x2) = withObjectRefResult $ withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QPolygon6 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCBool x2) instance QqqboundingRect (QPolygon a) (()) (IO (QRect ())) where qqboundingRect x0 () = withQRectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_boundingRect cobj_x0 foreign import ccall "qtc_QPolygon_boundingRect" qtc_QPolygon_boundingRect :: Ptr (TQPolygon a) -> IO (Ptr (TQRect ())) instance QqboundingRect (QPolygon a) (()) (IO (Rect)) where qboundingRect x0 () = withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_boundingRect_qth cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h foreign import ccall "qtc_QPolygon_boundingRect_qth" qtc_QPolygon_boundingRect_qth :: Ptr (TQPolygon a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO () instance QqcontainsPoint (QPolygon a) ((Point, FillRule)) where qcontainsPoint x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QPolygon_containsPoint_qth cobj_x0 cpoint_x1_x cpoint_x1_y (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QPolygon_containsPoint_qth" qtc_QPolygon_containsPoint_qth :: Ptr (TQPolygon a) -> CInt -> CInt -> CLong -> IO CBool instance QqqcontainsPoint (QPolygon a) ((QPoint t1, FillRule)) where qqcontainsPoint x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon_containsPoint cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QPolygon_containsPoint" qtc_QPolygon_containsPoint :: Ptr (TQPolygon a) -> Ptr (TQPoint t1) -> CLong -> IO CBool instance Qqintersected (QPolygon a) ((QPolygon t1)) (IO (QPolygon ())) where qintersected x0 (x1) = withQPolygonResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon_intersected cobj_x0 cobj_x1 foreign import ccall "qtc_QPolygon_intersected" qtc_QPolygon_intersected :: Ptr (TQPolygon a) -> Ptr (TQPolygon t1) -> IO (Ptr (TQPolygon ())) qpoint :: QPolygon a -> ((Int)) -> IO (Point) qpoint x0 (x1) = withPointResult $ \cpoint_ret_x cpoint_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_point_qth cobj_x0 (toCInt x1) cpoint_ret_x cpoint_ret_y foreign import ccall "qtc_QPolygon_point_qth" qtc_QPolygon_point_qth :: Ptr (TQPolygon a) -> CInt -> Ptr CInt -> Ptr CInt -> IO () qqpoint :: QPolygon a -> ((Int)) -> IO (QPoint ()) qqpoint x0 (x1) = withQPointResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_point cobj_x0 (toCInt x1) foreign import ccall "qtc_QPolygon_point" qtc_QPolygon_point :: Ptr (TQPolygon a) -> CInt -> IO (Ptr (TQPoint ())) class QqputPoints x1 where qputPoints :: QPolygon a -> x1 -> IO () instance QqputPoints ((Int, Int, QPolygon t3)) where qputPoints x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QPolygon_putPoints cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 foreign import ccall "qtc_QPolygon_putPoints" qtc_QPolygon_putPoints :: Ptr (TQPolygon a) -> CInt -> CInt -> Ptr (TQPolygon t3) -> IO () instance QqputPoints ((Int, Int, QPolygon t3, Int)) where qputPoints x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QPolygon_putPoints1 cobj_x0 (toCInt x1) (toCInt x2) cobj_x3 (toCInt x4) foreign import ccall "qtc_QPolygon_putPoints1" qtc_QPolygon_putPoints1 :: Ptr (TQPolygon a) -> CInt -> CInt -> Ptr (TQPolygon t3) -> CInt -> IO () class QqsetPoint x1 where qsetPoint :: QPolygon a -> x1 -> IO () instance QqsetPoint ((Int, Int, Int)) where qsetPoint x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_setPoint1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) foreign import ccall "qtc_QPolygon_setPoint1" qtc_QPolygon_setPoint1 :: Ptr (TQPolygon a) -> CInt -> CInt -> CInt -> IO () instance QqsetPoint ((Int, Point)) where qsetPoint x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x2 $ \cpoint_x2_x cpoint_x2_y -> qtc_QPolygon_setPoint_qth cobj_x0 (toCInt x1) cpoint_x2_x cpoint_x2_y foreign import ccall "qtc_QPolygon_setPoint_qth" qtc_QPolygon_setPoint_qth :: Ptr (TQPolygon a) -> CInt -> CInt -> CInt -> IO () qqsetPoint :: QPolygon a -> ((Int, QPoint t2)) -> IO () qqsetPoint x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QPolygon_setPoint cobj_x0 (toCInt x1) cobj_x2 foreign import ccall "qtc_QPolygon_setPoint" qtc_QPolygon_setPoint :: Ptr (TQPolygon a) -> CInt -> Ptr (TQPoint t2) -> IO () instance Qqsubtracted (QPolygon a) ((QPolygon t1)) (IO (QPolygon ())) where qsubtracted x0 (x1) = withQPolygonResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon_subtracted cobj_x0 cobj_x1 foreign import ccall "qtc_QPolygon_subtracted" qtc_QPolygon_subtracted :: Ptr (TQPolygon a) -> Ptr (TQPolygon t1) -> IO (Ptr (TQPolygon ())) instance Qqtranslate (QPolygon a) ((Int, Int)) (IO ()) where qtranslate x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_translate1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QPolygon_translate1" qtc_QPolygon_translate1 :: Ptr (TQPolygon a) -> CInt -> CInt -> IO () instance Qqtranslate (QPolygon a) ((Point)) (IO ()) where qtranslate x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QPolygon_translate_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QPolygon_translate_qth" qtc_QPolygon_translate_qth :: Ptr (TQPolygon a) -> CInt -> CInt -> IO () instance Qqqtranslate (QPolygon a) ((QPoint t1)) where qqtranslate x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon_translate cobj_x0 cobj_x1 foreign import ccall "qtc_QPolygon_translate" qtc_QPolygon_translate :: Ptr (TQPolygon a) -> Ptr (TQPoint t1) -> IO () instance Qqunited (QPolygon a) ((QPolygon t1)) (IO (QPolygon ())) where qunited x0 (x1) = withQPolygonResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QPolygon_united cobj_x0 cobj_x1 foreign import ccall "qtc_QPolygon_united" qtc_QPolygon_united :: Ptr (TQPolygon a) -> Ptr (TQPolygon t1) -> IO (Ptr (TQPolygon ())) qPolygon_delete :: QPolygon a -> IO () qPolygon_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QPolygon_delete cobj_x0 foreign import ccall "qtc_QPolygon_delete" qtc_QPolygon_delete :: Ptr (TQPolygon a) -> IO ()
uduki/hsQt
Qtc/Core/QPolygon.hs
bsd-2-clause
10,379
0
16
1,797
3,535
1,818
1,717
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} module Tests.Properties.Mul (tests) where import Control.Applicative ((<$>), pure) import Control.Exception as E (SomeException, catch, evaluate) import Data.Int (Int32, Int64) import Data.Text.Internal (mul, mul32, mul64) import System.IO.Unsafe (unsafePerformIO) import Test.Tasty (TestTree) import Test.Tasty.QuickCheck (testProperty) import Test.QuickCheck hiding ((.&.)) mulRef :: (Integral a, Bounded a) => a -> a -> Maybe a mulRef a b | ab < bot || ab > top = Nothing | otherwise = Just (fromIntegral ab) where ab = fromIntegral a * fromIntegral b top = fromIntegral (maxBound `asTypeOf` a) :: Integer bot = fromIntegral (minBound `asTypeOf` a) :: Integer eval :: (a -> b -> c) -> a -> b -> Maybe c eval f a b = unsafePerformIO $ (Just <$> evaluate (f a b)) `E.catch` (\(_::SomeException) -> pure Nothing) t_mul32 :: Int32 -> Int32 -> Property t_mul32 a b = mulRef a b === eval mul32 a b t_mul64 :: Int64 -> Int64 -> Property t_mul64 a b = mulRef a b === eval mul64 a b t_mul :: Int -> Int -> Property t_mul a b = mulRef a b === eval mul a b tests :: [TestTree] tests = [ testProperty "t_mul" t_mul , testProperty "t_mul32" t_mul32 , testProperty "t_mul64" t_mul64 ]
bgamari/text
tests/Tests/Properties/Mul.hs
bsd-2-clause
1,261
0
11
254
500
273
227
31
1
{-# LANGUAGE OverloadedStrings #-} module SimpleParams where import Data.List.Split import Data.String.Utils (endswith, replace) import Safe import Data.Char parseEmbedded :: String -> String parseEmbedded str = case splitOn "#" str of [k, v] -> if endswith "@" v then "{\"key\":\"" ++ k ++ "\",\"value\":\"" ++ replace "@" "" v ++ "\",\"last\":true}" else "{\"key\":\"" ++ k ++ "\",\"value\":\"" ++ v ++ "\"}" _ -> "" processPart :: String -> String processPart str | isDigit symb = str | symb `elem` specialCharacters = str | '#' `elem` str = parseEmbedded str | otherwise = "\"" ++ str ++ "\"" where symb = headDef ' ' str simpleParamsToJson :: String -> String simpleParamsToJson sparams = "{" ++ concatMap processPart (splitOnSpecialCharacters sparams) ++ "}" splitOnSpecialCharacters :: String -> [String] splitOnSpecialCharacters = split $ dropBlanks $ oneOf specialCharacters specialCharacters :: String specialCharacters = ",:[]{} "
dbushenko/trurl
src/SimpleParams.hs
bsd-3-clause
1,056
0
12
253
291
153
138
27
3
module Network.Raptr.StorageSpec where import Control.Exception (bracket) import Control.Monad.Trans (liftIO) import Data.Binary import Data.ByteString.Lazy (fromStrict, toStrict) import Network.Raptr.Raptr hiding (run) import Network.Raptr.TestUtils import System.IO.Storage import System.Random import Test.Hspec import Test.QuickCheck import Test.QuickCheck.Monadic newtype Payload = P Int deriving (Eq, Show) instance Binary Payload where put (P i) = put i get = P <$> get instance Arbitrary Payload where arbitrary = P <$> arbitrary data SAction = AddEntry Payload | Truncate Int | GetEntry Int | LastEntry | Observe (Maybe Payload) deriving (Eq,Show) payloadFromEntry = fmap (decode . fromStrict . eValue) indexAt i = foldr (const succIndex) index0 [1 .. i] runActions :: FileLog -> [ SAction ] -> IO [ Maybe Payload ] runActions log [] = return [] runActions log (Observe p:as) = (p:) <$> runActions log as runActions log (Truncate i:as) = truncateLogAtIndex log idx >> runActions log as where idx = indexAt i runActions log (AddEntry s:as) = insertEntry log e >> runActions log as where e = Entry index0 term0 (toStrict $ encode s) runActions log (GetEntry i:as) = decodeEntry >>= \ e -> (e:) <$> runActions log as where idx = indexAt i decodeEntry = do e <- getEntry log idx return $ payloadFromEntry e runActions log (LastEntry:as) = decodeLastEntry >>= \ e -> (e:) <$> runActions log as where decodeLastEntry = do e <- getLastEntry log return $ payloadFromEntry e actions :: Int -- ^ length of underlying structure -> Gen [ SAction ] actions n = oneof [ return [] , (:) <$> (AddEntry <$> arbitrary) <*> actions (n+1) , do i <- choose (1,n) (GetEntry i:) <$> actions n , (LastEntry:) <$> actions n , if n == 0 then return [] else do i <- choose (0, n) (Truncate i:) <$> actions i ] delta :: [SAction] -> Int delta q = delta' q 0 where delta' [] n = n delta' (AddEntry _:qs) n = delta' qs (n+1) delta' (Truncate i:qs) n = delta' qs i delta' (_:qs) n = delta' qs n observe :: [SAction] -> [SAction] -> [SAction] -> PropertyM IO [Maybe Payload] observe pref actions suff = run $ bracket (randomRIO (1,100000000 :: Int) >>= \ i-> openLog ("test-qc-" ++ show i ++ ".log") ) (removeFileSafely . logName) (flip runActions (pref ++ actions ++ suff)) -- | Observational equivalence of sequence of actions within arbitrary context (==~) :: [ SAction ] -> [ SAction ] -> Property a ==~ b = monadicIO $ do pref <- pick $ actions 0 suff <- pick $ actions (delta $ pref ++ a) oc <- observe pref a suff oc' <- observe pref b suff liftIO $ putStrLn $ "observing " ++ show oc ++ " for " ++ show a liftIO$ putStrLn $ "observing " ++ show oc' ++ " for " ++ show b assert $ oc == oc' -- | Observational equivalence of sequence of actions with arbitrary prefix (^==) :: [ SAction ] -> [ SAction ] -> Property a ^== b = monadicIO $ do pref <- pick $ actions 0 oc <- observe pref a [] oc' <- observe pref b [] liftIO $ putStrLn $ "observing " ++ show oc ++ " for " ++ show a liftIO$ putStrLn $ "observing " ++ show oc' ++ " for " ++ show b assert $ oc == oc' prop_last_entry :: Payload -> Property prop_last_entry n = [ AddEntry n, LastEntry ] ^== [ Truncate 0, AddEntry n, LastEntry ] prop_last_entry_get_first_after_truncate :: Payload -> Property prop_last_entry_get_first_after_truncate n = [ Truncate 0, AddEntry n, GetEntry 1 ] ^== [ AddEntry n, LastEntry ] prop_get_0_is_empty :: Payload -> Property prop_get_0_is_empty n = [ GetEntry 0 ] ==~ [ Observe Nothing ] storageSpec :: Spec storageSpec = do it "last entry always retrieves previously added entry" $ property prop_last_entry it "last entry equals get first entry after truncate" $ property prop_last_entry_get_first_after_truncate it "entry 0 is always empty" $ property prop_get_0_is_empty
capital-match/raptr
test/Network/Raptr/StorageSpec.hs
bsd-3-clause
4,535
0
14
1,444
1,487
759
728
97
4
import Distribution.PackageDescription import Distribution.PackageDescription.Parse import Distribution.Verbosity import Distribution.System import Distribution.Simple import Distribution.Simple.Utils import Distribution.Simple.Setup import Distribution.Simple.Command import Distribution.Simple.Program import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PreProcess hiding (ppC2hs) import Control.Exception import Control.Monad import System.Exit import System.FilePath import System.Directory import System.Environment import System.IO.Error hiding (catch) import Prelude hiding (catch) -- Replicate the invocation of the postConf script, so that we can insert the -- arguments of --extra-include-dirs and --extra-lib-dirs as paths in CPPFLAGS -- and LDFLAGS into the environment -- main :: IO () main = defaultMainWithHooks customHooks where preprocessors = hookedPreProcessors autoconfUserHooks customHooks = autoconfUserHooks { preConf = preConfHook, postConf = postConfHook, hookedPreProcessors = ("chs",ppC2hs) : filter (\x -> fst x /= "chs") preprocessors } preConfHook :: Args -> ConfigFlags -> IO HookedBuildInfo preConfHook args flags = do let verbosity = fromFlag (configVerbosity flags) confExists <- doesFileExist "configure" unless confExists $ do code <- rawSystemExitCode verbosity "autoconf" [] case code of ExitSuccess -> return () ExitFailure c -> die $ "autoconf exited with code " ++ show c preConf autoconfUserHooks args flags postConfHook :: Args -> ConfigFlags -> PackageDescription -> LocalBuildInfo -> IO () postConfHook args flags pkg_descr lbi = let verbosity = fromFlag (configVerbosity flags) in do noExtraFlags args confExists <- doesFileExist "configure" if confExists then runConfigureScript verbosity False flags lbi else die "configure script not found." pbi <- getHookedBuildInfo verbosity let pkg_descr' = updatePackageDescription pbi pkg_descr postConf simpleUserHooks args flags pkg_descr' lbi runConfigureScript :: Verbosity -> Bool -> ConfigFlags -> LocalBuildInfo -> IO () runConfigureScript verbosity backwardsCompatHack flags lbi = do env <- getEnvironment (ccProg, ccFlags) <- configureCCompiler verbosity (withPrograms lbi) let env' = foldr appendToEnvironment env [("CC", ccProg) ,("CFLAGS", unwords ccFlags) ,("CPPFLAGS", unwords $ map ("-I"++) (configExtraIncludeDirs flags)) ,("LDFLAGS", unwords $ map ("-L"++) (configExtraLibDirs flags)) ] handleNoWindowsSH $ rawSystemExitWithEnv verbosity "sh" args env' where args = "configure" : configureArgs backwardsCompatHack flags appendToEnvironment (key, val) [] = [(key, val)] appendToEnvironment (key, val) (kv@(k, v) : rest) | key == k = (key, v ++ " " ++ val) : rest | otherwise = kv : appendToEnvironment (key, val) rest handleNoWindowsSH action | buildOS /= Windows = action | otherwise = action `catch` \ioe -> if isDoesNotExistError ioe then die notFoundMsg else throwIO ioe notFoundMsg = "The package has a './configure' script. This requires a " ++ "Unix compatibility toolchain such as MinGW+MSYS or Cygwin." getHookedBuildInfo :: Verbosity -> IO HookedBuildInfo getHookedBuildInfo verbosity = do maybe_infoFile <- defaultHookedPackageDesc case maybe_infoFile of Nothing -> return emptyHookedBuildInfo Just infoFile -> do info verbosity $ "Reading parameters from " ++ infoFile readHookedBuildInfo verbosity infoFile -- Replicate the default C2HS preprocessor hook here, and inject a value for -- extra-c2hs-options, if it was present in the buildinfo file -- -- Everything below copied from Distribution.Simple.PreProcess -- ppC2hs :: BuildInfo -> LocalBuildInfo -> PreProcessor ppC2hs bi lbi = PreProcessor { platformIndependent = False, runPreProcessor = \(inBaseDir, inRelativeFile) (outBaseDir, outRelativeFile) verbosity -> rawSystemProgramConf verbosity c2hsProgram (withPrograms lbi) . filter (not . null) $ maybe [] words (lookup "x-extra-c2hs-options" (customFieldsBI bi)) ++ ["--include=" ++ outBaseDir] ++ ["--cppopts=" ++ opt | opt <- getCppOptions bi lbi] ++ ["--output-dir=" ++ outBaseDir, "--output=" ++ outRelativeFile, inBaseDir </> inRelativeFile] } getCppOptions :: BuildInfo -> LocalBuildInfo -> [String] getCppOptions bi lbi = ["-I" ++ dir | dir <- includeDirs bi] ++ [opt | opt@('-':c:_) <- ccOptions bi, c `elem` "DIU"]
bmsherman/magma-gpu
Setup.hs
bsd-3-clause
5,030
0
16
1,307
1,180
616
564
98
3
module Game where import Commands (FieldItem(..), MoveDirection(..)) import Data.Array (Array, listArray, bounds, (!), assocs) import Data.List (find) import Data.Maybe (fromJust) import Data.Text (Text, empty) data Game = Game { gameSettings :: GameSettings , gameState :: GameState } deriving (Show) data GameSettings = GameSettings { settingsTimeBank :: Int , settingsTimePerMove :: Int , settingsPlayerNames :: [Text] , settingsYourBot :: Text , settingsYourBotId :: Int , settingsFieldWidth :: Int , settingsFieldHeight :: Int } deriving (Show) type Point = (Int, Int) type Field = Array Point FieldItem data GameState = GameState { stateRound :: Int , stateField :: Field } deriving (Show) emptyGame :: Game emptyGame = Game emptySettings emptyState where emptySettings = GameSettings 0 0 [] empty 0 0 0 emptyState = GameState 0 emptyField emptyField = listArray ((0, 0), (0, 0)) [] getNeighbours :: Field -> (Int, Int) -> [(MoveDirection, (Int, Int))] getNeighbours g (y, x) = let possibleNeighbours = [ (MoveUp, (y - 1, x)) , (MoveLeft, (y, x - 1)) , (MoveDown, (y + 1, x)) , (MoveRight, (y, x + 1)) ] in filter (isValidPosition . snd) possibleNeighbours where isValidPosition p@(y', x') = let (_, (maxY, maxX)) = bounds g w = maxX + 1 h = maxY + 1 in (x' >= 0) && (x' < w) && (y' >= 0) && (y' < h) && isAccessiblePosition g p isAccessiblePosition :: Field -> (Int, Int) -> Bool isAccessiblePosition f = not . checkField f (\fi -> fi == Wall || isPlayer fi) checkField :: Array (Int, Int) a -> (a -> Bool) -> (Int, Int) -> Bool checkField field check pos = check $ field ! pos isPlayer :: FieldItem -> Bool isPlayer (Player _) = True isPlayer _ = False getPlayerPosition :: Int -> Field -> Point getPlayerPosition playerId f = fst $ fromJust $ find ((== (Player playerId)) . snd) $ assocs f
asvyazin/starapple-haskell-starter
app/Game.hs
bsd-3-clause
2,054
0
14
564
766
440
326
63
1
{-# LANGUAGE TypeFamilies, FlexibleContexts, FlexibleInstances #-} module QueryArrow.DB.NoConnection where import QueryArrow.DB.DB -- interface class INoConnectionDatabase2 db where type NoConnectionQueryType db type NoConnectionRowType db noConnectionDBStmtExec :: db -> NoConnectionQueryType db -> DBResultStream (NoConnectionRowType db) -> DBResultStream (NoConnectionRowType db) -- instance for IDatabase newtype NoConnectionDatabase db = NoConnectionDatabase db instance (IDatabase0 db) => (IDatabase0 (NoConnectionDatabase db)) where type DBFormulaType (NoConnectionDatabase db) = DBFormulaType db getName (NoConnectionDatabase db) = getName db getPreds (NoConnectionDatabase db) = getPreds db supported (NoConnectionDatabase db) = supported db instance (IDatabase1 db) => (IDatabase1 (NoConnectionDatabase db)) where type DBQueryType (NoConnectionDatabase db) = DBQueryType db translateQuery (NoConnectionDatabase db) = translateQuery db instance (INoConnectionDatabase2 db) => IDatabase2 (NoConnectionDatabase db) where data ConnectionType (NoConnectionDatabase db) = NoConnectionDBConnection db dbOpen (NoConnectionDatabase db) = return (NoConnectionDBConnection db) instance (IDatabase0 db, IDatabase1 db, INoConnectionDatabase2 db, DBQueryType db ~ NoConnectionQueryType db) => IDatabase (NoConnectionDatabase db) where -- instance for IDBConnection instance IDBConnection0 (ConnectionType (NoConnectionDatabase db)) where dbClose _ = return () dbBegin _ = return () dbCommit _ = return () dbPrepare _ = return () dbRollback _ = return () instance (INoConnectionDatabase2 db) => IDBConnection (ConnectionType (NoConnectionDatabase db)) where type QueryType (ConnectionType (NoConnectionDatabase db)) = NoConnectionQueryType db type StatementType (ConnectionType (NoConnectionDatabase db)) = NoConnectionDBStatement db prepareQuery (NoConnectionDBConnection db) qu = return (NoConnectionDBStatement db qu) -- instance for IDBStatement data NoConnectionDBStatement db = NoConnectionDBStatement db (NoConnectionQueryType db) instance (INoConnectionDatabase2 db) => IDBStatement (NoConnectionDBStatement db) where type RowType (NoConnectionDBStatement db) = NoConnectionRowType db dbStmtClose _ = return () dbStmtExec (NoConnectionDBStatement db qu ) = noConnectionDBStmtExec db qu
xu-hao/QueryArrow
QueryArrow-common/src/QueryArrow/DB/NoConnection.hs
bsd-3-clause
2,447
6
12
408
304
244
60
35
0
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} -- | -- -- This module contains exports a single function, 'substituteNames', -- for performing name substitution in an Futhark expression. module Futhark.Transform.Substitute (Substitutions, Substitute(..), Substitutable) where import Control.Monad.Identity import qualified Data.HashMap.Lazy as HM import qualified Data.HashSet as HS import Futhark.Representation.AST.Syntax import Futhark.Representation.AST.Traversals -- | The substitutions to be made are given by a mapping from names to -- names. type Substitutions = HM.HashMap VName VName -- | A type that is an instance of this class supports substitution of -- any names contained within. class Substitute a where -- | @substituteNames m e@ replaces the variable names in @e@ with -- new names, based on the mapping in @m@. It is assumed that all -- names in @e@ are unique, i.e. there is no shadowing. Aliasing -- information is also updated, although the resulting information -- may be erroneous if any if the substitute names in @m@ were -- already in use in @e@. substituteNames :: HM.HashMap VName VName -> a -> a instance Substitute a => Substitute [a] where substituteNames substs = map $ substituteNames substs instance (Substitute a, Substitute b) => Substitute (a,b) where substituteNames substs (x,y) = (substituteNames substs x, substituteNames substs y) instance (Substitute a, Substitute b, Substitute c) => Substitute (a,b,c) where substituteNames substs (x,y,z) = (substituteNames substs x, substituteNames substs y, substituteNames substs z) instance Substitute a => Substitute (Maybe a) where substituteNames substs = fmap $ substituteNames substs instance Substitute Bool where substituteNames = flip const instance Substitute VName where substituteNames substs k = HM.lookupDefault k k substs instance Substitute SubExp where substituteNames substs (Var v) = Var $ substituteNames substs v substituteNames _ (Constant v) = Constant v instance Substitutable lore => Substitute (Exp lore) where substituteNames substs = mapExp $ replace substs instance Substitute attr => Substitute (PatElemT attr) where substituteNames substs (PatElem ident bindage attr) = PatElem (substituteNames substs ident) (substituteNames substs bindage) (substituteNames substs attr) instance Substitute Bindage where substituteNames _ BindVar = BindVar substituteNames substs (BindInPlace cs src is) = BindInPlace (map (substituteNames substs) cs) (substituteNames substs src) (map (substituteNames substs) is) instance Substitute attr => Substitute (ParamT attr) where substituteNames substs (Param name attr) = Param (substituteNames substs name) (substituteNames substs attr) instance Substitute attr => Substitute (PatternT attr) where substituteNames substs (Pattern context values) = Pattern (substituteNames substs context) (substituteNames substs values) instance Substitutable lore => Substitute (Binding lore) where substituteNames substs (Let pat annot e) = Let (substituteNames substs pat) (substituteNames substs annot) (substituteNames substs e) instance Substitutable lore => Substitute (Body lore) where substituteNames substs (Body attr bnds res) = Body (substituteNames substs attr) (substituteNames substs bnds) (substituteNames substs res) replace :: (Substitutable lore) => HM.HashMap VName VName -> Mapper lore lore Identity replace substs = Mapper { mapOnVName = return . substituteNames substs , mapOnSubExp = return . substituteNames substs , mapOnBody = return . substituteNames substs , mapOnCertificates = return . map (substituteNames substs) , mapOnRetType = return . substituteNames substs , mapOnFParam = return . substituteNames substs , mapOnOp = return . substituteNames substs } instance Substitute Rank where substituteNames _ = id instance Substitute () where substituteNames _ = id instance Substitute Shape where substituteNames substs (Shape es) = Shape $ map (substituteNames substs) es instance Substitute ExtShape where substituteNames substs (ExtShape es) = ExtShape $ map (substituteNames substs) es instance Substitute ExtDimSize where substituteNames substs (Free se) = Free $ substituteNames substs se substituteNames _ (Ext x) = Ext x instance Substitute Names where substituteNames = HS.map . substituteNames instance Substitute shape => Substitute (TypeBase shape u) where substituteNames _ (Prim et) = Prim et substituteNames substs (Array et sz u) = Array et (substituteNames substs sz) u substituteNames substs (Mem sz space) = Mem (substituteNames substs sz) space instance Substitutable lore => Substitute (Lambda lore) where substituteNames substs (Lambda params body rettype) = Lambda (substituteNames substs params) (substituteNames substs body) (map (substituteNames substs) rettype) instance Substitutable lore => Substitute (ExtLambda lore) where substituteNames substs (ExtLambda params body rettype) = ExtLambda (substituteNames substs params) (substituteNames substs body) (map (substituteNames substs) rettype) instance Substitute Ident where substituteNames substs v = v { identName = substituteNames substs $ identName v , identType = substituteNames substs $ identType v } instance Substitute ExtRetType where substituteNames substs (ExtRetType ts) = ExtRetType $ map (substituteNames substs) ts instance Substitute d => Substitute (DimChange d) where substituteNames substs = fmap $ substituteNames substs -- | Lores in which all annotations support name -- substitution. type Substitutable lore = (Annotations lore, Substitute (ExpAttr lore), Substitute (BodyAttr lore), Substitute (LetAttr lore), Substitute (FParamAttr lore), Substitute (LParamAttr lore), Substitute (RetType lore), Substitute (Op lore))
CulpaBS/wbBach
src/Futhark/Transform/Substitute.hs
bsd-3-clause
6,404
0
10
1,411
1,690
862
828
131
1
{-# LANGUAGE OverloadedStrings, FlexibleContexts #-} module SampleWorld where import Control.Lens import Control.Monad.State as State import qualified Data.Aeson as A import qualified Data.ByteString.Lazy.Char8 as B import qualified Data.Map as M import qualified Data.Text as T import qualified Data.IntMap as I import TaskPals addComponent :: ObjId -> Component -> World -> World addComponent objId component = case component of CompWork w -> work %~ I.insert objId w CompTasks t -> tasks %~ I.insert objId t CompPhysics p -> physics %~ I.insert objId p CompMeta m -> meta %~ I.insert objId m addObj :: Obj -> World -> World addObj obj world = let objId = world^.nextObj in nextObj %~ succ $ foldr (addComponent $ objId) world (obj objId) addObjs :: [Obj] -> World -> World addObjs objs world = foldr addObj world objs door :: Obj door objId = [ CompPhysics $ PhysicsComponent (OnMap (0,40)) (Rectangle 10 3) 0 True , CompTasks $ I.fromList [ (1, Task "Open" Open Labor 0 2 0 [EnableTask (objId, 2), ResetThisTask, DisableThisTask, SetBlocking False] True) , (2, Task "Close" Close Labor 0 2 0 [EnableTask (objId, 1), DisableThisTask, SetBlocking True] False) , (3, Task "Break" Break Labor 2 5 0 [] True) ] , CompMeta $ MetaComponent "Door" [] Nothing ] james :: Obj james objId = [ CompPhysics $ PhysicsComponent (OnMap (0,0)) (Circle 3) 3 True , CompTasks $ I.fromList [ (1, Task "Kill" Break Combat 0 10 0 [RemoveThisObj] True) , (2, Task "Heal" Fix Medical 0 1 0 [ResetThisTask, RemoveWorkFrom (objId, 1) 1] True) ] -- , CompWork $ WorkComponent NeverAct (Just $ WorkOn (2,1)) Nothing [(Skill Labor 1 1)] , CompWork $ WorkComponent NeverAct (Just $ GoTo (ToMap (2,2))) Nothing [(Skill Labor 1 1)] , CompMeta $ MetaComponent "James" ["pal"] (Just "James") ] blankWorld :: World blankWorld = World 1 I.empty I.empty I.empty I.empty world :: World world = addObjs [door, james] blankWorld
ojw/taskpals
src/SampleWorld.hs
bsd-3-clause
2,109
0
13
527
731
396
335
39
4
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -fno-warn-orphans #-} import System.Lifted import System.Directory.Lifted import qualified System.Directory as D import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Control.Applicative import qualified Data.Text as T import qualified Data.Text.IO as T import GHC.IO.Exception type EitherString = EitherT String deriveSystemLiftedErrors "DisallowIOE [HardwareFault]" ''MaybeT deriveSystemLiftedErrors "AllIOE" ''EitherString deriveSystemDirectory ''MaybeT deriveSystemDirectory ''EitherString main :: IO () main = do m <- runMaybeT $ createDirectory "abc" r <- runEitherT $ bimapEitherT T.pack id $ do createDirectory "cde" createDirectory "cdd" print m case r of Left s -> T.putStrLn s Right _ -> putStrLn "OK" j <- runEitherT $ ioFilterT (DisallowIOE [HardwareFault]) $ do D.createDirectory "ajj" D.createDirectory "aji" case j of Left s -> Prelude.putStrLn s Right _ -> putStrLn "OK!" print j x <- runMaybeT $ joinMaybeMT (findFile ["."] "LICENSE") <|> getHomeDirectory print x putStrLn "end"
jcristovao/system-lifted
example/main.hs
bsd-3-clause
1,474
0
13
278
342
169
173
45
3
{-# OPTIONS_GHC -fno-warn-tabs #-} import Common import MT19937 import Control.Concurrent import Control.Monad import Data.Time.Clock.POSIX import Data.Word import System.Random hiding (next) wait :: Int -> IO () wait n = do putStr "Waiting" replicateM_ n $ do threadDelay 1000000 putStr "." putStr "\n" crack :: Word32 -> IO Word32 crack out = do time <- fmap truncate getPOSIXTime return $ head $ filter ((out ==) . fst . next . seed) [time - 999..time] main = do putStrLn "=== Challange22 ===" wait =<< getStdRandom (randomR (40, 400)) s <- fmap truncate getPOSIXTime let rng = seed s wait =<< getStdRandom (randomR (40, 400)) cs <- crack (fst $ next rng) if cs == s then putStrLn "Success!" else putStrLn "Failure!"
andrewcchen/matasano-cryptopals-solutions
set3/Challange22.hs
bsd-3-clause
741
0
13
140
293
143
150
27
2
{-# LANGUAGE PatternGuards, ViewPatterns #-} {-# LANGUAGE RecordWildCards #-} {- map f [] = [] map f (x:xs) = f x : map f xs foldr f z [] = z foldr f z (x:xs) = f x (foldr f z xs) foldl f z [] = z foldl f z (x:xs) = foldl f (f z x) xs -} {- <TEST> f (x:xs) = negate x + f xs ; f [] = 0 -- f xs = foldr ((+) . negate) 0 xs f (x:xs) = x + 1 : f xs ; f [] = [] -- f xs = map (+ 1) xs f z (x:xs) = f (z*x) xs ; f z [] = z -- f z xs = foldl (*) z xs f a (x:xs) b = x + a + b : f a xs b ; f a [] b = [] -- f a xs b = map (\ x -> x + a + b) xs f [] a = return a ; f (x:xs) a = a + x >>= \fax -> f xs fax -- f xs a = foldM (+) a xs f (x:xs) a = a + x >>= \fax -> f xs fax ; f [] a = pure a -- f xs a = foldM (+) a xs foos [] x = x; foos (y:ys) x = foo y $ foos ys x -- foos ys x = foldr foo x ys f [] y = y; f (x:xs) y = f xs $ g x y -- f xs y = foldl (flip g) y xs f [] y = y; f (x : xs) y = let z = g x y in f xs z -- f xs y = foldl (flip g) y xs f [] y = y; f (x:xs) y = f xs (f xs z) fun [] = []; fun (x:xs) = f x xs ++ fun xs </TEST> -} module Hint.ListRec(listRecHint) where import Hint.Type (DeclHint, Severity(Suggestion, Warning), idea, toSSA) import Data.Generics.Uniplate.DataOnly import Data.List.Extra import Data.Maybe import Data.Either.Extra import Control.Monad import Refact.Types hiding (RType(Match)) import GHC.Types.SrcLoc import GHC.Hs.Extension import GHC.Hs.Pat import GHC.Builtin.Types import GHC.Hs.Type import GHC.Types.Name.Reader import GHC.Hs.Binds import GHC.Hs.Expr import GHC.Hs.Decls import GHC.Types.Basic import GHC.Parser.Annotation import Language.Haskell.Syntax.Extension import GHC.Util import Language.Haskell.GhclibParserEx.GHC.Hs.Pat import Language.Haskell.GhclibParserEx.GHC.Hs.Expr import Language.Haskell.GhclibParserEx.GHC.Hs.ExtendInstances import Language.Haskell.GhclibParserEx.GHC.Utils.Outputable import Language.Haskell.GhclibParserEx.GHC.Types.Name.Reader listRecHint :: DeclHint listRecHint _ _ = concatMap f . universe where f o = maybeToList $ do let x = o (x, addCase) <- findCase x (use,severity,x) <- matchListRec x let y = addCase x guard $ recursiveStr `notElem` varss y -- Maybe we can do better here maintaining source -- formatting? pure $ idea severity ("Use " ++ use) (reLoc o) (reLoc y) [Replace Decl (toSSA o) [] (unsafePrettyPrint y)] recursiveStr :: String recursiveStr = "_recursive_" recursive = strToVar recursiveStr data ListCase = ListCase [String] -- recursion parameters (LHsExpr GhcPs) -- nil case (String, String, LHsExpr GhcPs) -- cons case -- For cons-case delete any recursive calls with 'xs' in them. Any -- recursive calls are marked "_recursive_". data BList = BNil | BCons String String deriving (Eq, Ord, Show) data Branch = Branch String -- function name [String] -- parameters Int -- list position BList (LHsExpr GhcPs) -- list type/body --------------------------------------------------------------------- -- MATCH THE RECURSION matchListRec :: ListCase -> Maybe (String, Severity, LHsExpr GhcPs) matchListRec o@(ListCase vs nil (x, xs, cons)) -- Suggest 'map'? | [] <- vs, varToStr nil == "[]", (L _ (OpApp _ lhs c rhs)) <- cons, varToStr c == ":" , astEq (fromParen rhs) recursive, xs `notElem` vars lhs = Just $ (,,) "map" Hint.Type.Warning $ appsBracket [ strToVar "map", niceLambda [x] lhs, strToVar xs] -- Suggest 'foldr'? | [] <- vs, App2 op lhs rhs <- view cons , xs `notElem` (vars op ++ vars lhs) -- the meaning of xs changes, see #793 , astEq (fromParen rhs) recursive = Just $ (,,) "foldr" Suggestion $ appsBracket [ strToVar "foldr", niceLambda [x] $ appsBracket [op,lhs], nil, strToVar xs] -- Suggest 'foldl'? | [v] <- vs, view nil == Var_ v, (L _ (HsApp _ r lhs)) <- cons , astEq (fromParen r) recursive , xs `notElem` vars lhs = Just $ (,,) "foldl" Suggestion $ appsBracket [ strToVar "foldl", niceLambda [v,x] lhs, strToVar v, strToVar xs] -- Suggest 'foldM'? | [v] <- vs, (L _ (HsApp _ ret res)) <- nil, isReturn ret, varToStr res == "()" || view res == Var_ v , [L _ (BindStmt _ (view -> PVar_ b1) e), L _ (BodyStmt _ (fromParen -> (L _ (HsApp _ r (view -> Var_ b2)))) _ _)] <- asDo cons , b1 == b2, astEq r recursive, xs `notElem` vars e , name <- "foldM" ++ ['_' | varToStr res == "()"] = Just $ (,,) name Suggestion $ appsBracket [strToVar name, niceLambda [v,x] e, strToVar v, strToVar xs] -- Nope, I got nothing ¯\_(ツ)_/¯. | otherwise = Nothing -- Very limited attempt to convert >>= to do, only useful for -- 'foldM' / 'foldM_'. asDo :: LHsExpr GhcPs -> [LStmt GhcPs (LHsExpr GhcPs)] asDo (view -> App2 bind lhs (L _ (HsLam _ MG { mg_origin=FromSource , mg_alts=L _ [ L _ Match { m_ctxt=LambdaExpr , m_pats=[v@(L _ VarPat{})] , m_grhss=GRHSs _ [L _ (GRHS _ [] rhs)] (EmptyLocalBinds _)}]})) ) = [ noLocA $ BindStmt EpAnnNotUsed v lhs , noLocA $ BodyStmt noExtField rhs noSyntaxExpr noSyntaxExpr ] asDo (L _ (HsDo _ (DoExpr _) (L _ stmts))) = stmts asDo x = [noLocA $ BodyStmt noExtField x noSyntaxExpr noSyntaxExpr] --------------------------------------------------------------------- -- FIND THE CASE ANALYSIS findCase :: LHsDecl GhcPs -> Maybe (ListCase, LHsExpr GhcPs -> LHsDecl GhcPs) findCase x = do -- Match a function binding with two alternatives. (L _ (ValD _ FunBind {fun_matches= MG{mg_origin=FromSource, mg_alts= (L _ [ x1@(L _ Match{..}) -- Match fields. , x2]), ..} -- Match group fields. , ..} -- Fun. bind fields. )) <- pure x Branch name1 ps1 p1 c1 b1 <- findBranch x1 Branch name2 ps2 p2 c2 b2 <- findBranch x2 guard (name1 == name2 && ps1 == ps2 && p1 == p2) [(BNil, b1), (BCons x xs, b2)] <- pure $ sortOn fst [(c1, b1), (c2, b2)] b2 <- transformAppsM (delCons name1 p1 xs) b2 (ps, b2) <- pure $ eliminateArgs ps1 b2 let ps12 = let (a, b) = splitAt p1 ps1 in map strToPat (a ++ xs : b) -- Function arguments. emptyLocalBinds = EmptyLocalBinds noExtField :: HsLocalBindsLR GhcPs GhcPs -- Empty where clause. gRHS e = noLoc $ GRHS EpAnnNotUsed [] e :: LGRHS GhcPs (LHsExpr GhcPs) -- Guarded rhs. gRHSSs e = GRHSs emptyComments [gRHS e] emptyLocalBinds -- Guarded rhs set. match e = Match{m_ext=EpAnnNotUsed,m_pats=ps12, m_grhss=gRHSSs e, ..} -- Match. matchGroup e = MG{mg_alts=noLocA [noLocA $ match e], mg_origin=Generated, ..} -- Match group. funBind e = FunBind {fun_matches=matchGroup e, ..} :: HsBindLR GhcPs GhcPs -- Fun bind. pure (ListCase ps b1 (x, xs, b2), noLocA . ValD noExtField . funBind) delCons :: String -> Int -> String -> LHsExpr GhcPs -> Maybe (LHsExpr GhcPs) delCons func pos var (fromApps -> (view -> Var_ x) : xs) | func == x = do (pre, (view -> Var_ v) : post) <- pure $ splitAt pos xs guard $ v == var pure $ apps $ recursive : pre ++ post delCons _ _ _ x = pure x eliminateArgs :: [String] -> LHsExpr GhcPs -> ([String], LHsExpr GhcPs) eliminateArgs ps cons = (remove ps, transform f cons) where args = [zs | z : zs <- map fromApps $ universeApps cons, astEq z recursive] elim = [all (\xs -> length xs > i && view (xs !! i) == Var_ p) args | (i, p) <- zipFrom 0 ps] ++ repeat False remove = concat . zipWith (\b x -> [x | not b]) elim f (fromApps -> x : xs) | astEq x recursive = apps $ x : remove xs f x = x --------------------------------------------------------------------- -- FIND A BRANCH findBranch :: LMatch GhcPs (LHsExpr GhcPs) -> Maybe Branch findBranch (L _ x) = do Match { m_ctxt = FunRhs {mc_fun=(L _ name)} , m_pats = ps , m_grhss = GRHSs {grhssGRHSs=[L l (GRHS _ [] body)] , grhssLocalBinds=EmptyLocalBinds _ } } <- pure x (a, b, c) <- findPat ps pure $ Branch (occNameStr name) a b c $ simplifyExp body findPat :: [LPat GhcPs] -> Maybe ([String], Int, BList) findPat ps = do ps <- mapM readPat ps [i] <- pure $ findIndices isRight ps let (left, [right]) = partitionEithers ps pure (left, i, right) readPat :: LPat GhcPs -> Maybe (Either String BList) readPat (view -> PVar_ x) = Just $ Left x readPat (L _ (ParPat _ (L _ (ConPat _ (L _ n) (InfixCon (view -> PVar_ x) (view -> PVar_ xs)))))) | n == consDataCon_RDR = Just $ Right $ BCons x xs readPat (L _ (ConPat _ (L _ n) (PrefixCon [] []))) | n == nameRdrName nilDataConName = Just $ Right BNil readPat _ = Nothing
ndmitchell/hlint
src/Hint/ListRec.hs
bsd-3-clause
8,869
0
27
2,330
2,996
1,570
1,426
151
2
module Logo.Builtins.Turtle (turtleBuiltins) where import Prelude hiding (tan) import qualified Data.Map as M import Control.Monad.Trans (lift) import Diagrams.TwoD.Path.Turtle import Diagrams.TwoD.Types (p2) import Data.Colour (Colour) import Data.Colour.Names import Logo.Types updateTurtle :: TurtleIO a -> LogoEvaluator a updateTurtle = lift fd, bk, rt, lt, home, setxy, seth, pu, pd, setpensize, setpencolor :: [LogoToken] -> LogoEvaluator LogoToken turtleBuiltins :: M.Map String LogoFunctionDef turtleBuiltins = M.fromList [ ("fd", LogoFunctionDef 1 fd) , ("bk", LogoFunctionDef 1 bk) , ("rt", LogoFunctionDef 1 rt) , ("lt", LogoFunctionDef 1 lt) , ("home", LogoFunctionDef 0 home) , ("setxy", LogoFunctionDef 2 setxy) , ("seth", LogoFunctionDef 1 seth) , ("pu", LogoFunctionDef 0 pu) , ("pd", LogoFunctionDef 0 pd) , ("setpensize", LogoFunctionDef 1 setpensize) , ("setpencolor", LogoFunctionDef 1 setpencolor) ] fd (NumLiteral d : []) = do updateTurtle (forward d) return $ StrLiteral "" fd args = error $ "Invalid arguments to fd" ++ show args bk (NumLiteral d : []) = do updateTurtle (backward d) return $ StrLiteral "" bk _ = error "Invalid arguments to fd" rt (NumLiteral a : []) = do updateTurtle (right a) return $ StrLiteral "" rt _ = error "Invalid arguments to rt" lt (NumLiteral a : []) = do updateTurtle (left a) return $ StrLiteral "" lt _ = error "Invalid arguments to lt" home [] = do updateTurtle (setPos (p2 (0,0))) return $ StrLiteral "" home _ = error "Invalid arguments to home" setxy [NumLiteral x, NumLiteral y] = do updateTurtle (setPos (p2 (x,y))) return $ StrLiteral "" setxy _ = error "Invalid arguments to setxy" seth [NumLiteral n] = do updateTurtle (setHeading n) return $ StrLiteral "" seth _ = error "Invalid arguments to seth" pu [] = do updateTurtle penUp return $ StrLiteral "" pu _ = error "Invalid arguments to pu" pd [] = do updateTurtle penDown return $ StrLiteral "" pd _ = error "Invalid arguments to pd" setpensize [NumLiteral d] = do updateTurtle (setPenWidth d) return $ StrLiteral "" setpensize _ = error "Invalid arguments to setpensize" setpencolor [NumLiteral d] = do updateTurtle (setPenColor (numToColor . round $ d)) return $ StrLiteral "" where numToColor :: Int -> Colour Double numToColor 0 = black numToColor 1 = blue numToColor 2 = green numToColor 3 = cyan numToColor 4 = red numToColor 5 = magenta numToColor 6 = yellow numToColor 7 = white numToColor 8 = brown numToColor 9 = tan numToColor 10 = forestgreen numToColor 11 = aqua numToColor 12 = salmon numToColor 13 = purple numToColor 14 = orange numToColor 15 = grey numToColor _ = error "Color values greater than 15 are not supported" setpencolor _ = error "Invalid arguments to setpencolor"
deepakjois/hs-logo
src/Logo/Builtins/Turtle.hs
bsd-3-clause
2,933
0
12
657
1,029
523
506
87
17
module Win32File {- ( AccessMode, ShareMode, CreateMode, FileAttributeOrFlag , CreateFile, CloseHandle, DeleteFile, CopyFile , MoveFileFlag, MoveFile, MoveFileEx, ) -} where import Win32Types import StdDIS ---------------------------------------------------------------- -- Enumeration types ---------------------------------------------------------------- type AccessMode = UINT gENERIC_NONE :: AccessMode gENERIC_NONE = unsafePerformIO( prim_Win32File_cpp_gENERIC_NONE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_gENERIC_NONE :: IO (Word32) gENERIC_READ :: AccessMode gENERIC_READ = unsafePerformIO( prim_Win32File_cpp_gENERIC_READ >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_gENERIC_READ :: IO (Word32) gENERIC_WRITE :: AccessMode gENERIC_WRITE = unsafePerformIO( prim_Win32File_cpp_gENERIC_WRITE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_gENERIC_WRITE :: IO (Word32) gENERIC_EXECUTE :: AccessMode gENERIC_EXECUTE = unsafePerformIO( prim_Win32File_cpp_gENERIC_EXECUTE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_gENERIC_EXECUTE :: IO (Word32) gENERIC_ALL :: AccessMode gENERIC_ALL = unsafePerformIO( prim_Win32File_cpp_gENERIC_ALL >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_gENERIC_ALL :: IO (Word32) dELETE :: AccessMode dELETE = unsafePerformIO( prim_Win32File_cpp_dELETE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dELETE :: IO (Word32) rEAD_CONTROL :: AccessMode rEAD_CONTROL = unsafePerformIO( prim_Win32File_cpp_rEAD_CONTROL >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_rEAD_CONTROL :: IO (Word32) wRITE_DAC :: AccessMode wRITE_DAC = unsafePerformIO( prim_Win32File_cpp_wRITE_DAC >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_wRITE_DAC :: IO (Word32) wRITE_OWNER :: AccessMode wRITE_OWNER = unsafePerformIO( prim_Win32File_cpp_wRITE_OWNER >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_wRITE_OWNER :: IO (Word32) sYNCHRONIZE :: AccessMode sYNCHRONIZE = unsafePerformIO( prim_Win32File_cpp_sYNCHRONIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sYNCHRONIZE :: IO (Word32) sTANDARD_RIGHTS_REQUIRED :: AccessMode sTANDARD_RIGHTS_REQUIRED = unsafePerformIO( prim_Win32File_cpp_sTANDARD_RIGHTS_REQUIRED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sTANDARD_RIGHTS_REQUIRED :: IO (Word32) sTANDARD_RIGHTS_READ :: AccessMode sTANDARD_RIGHTS_READ = unsafePerformIO( prim_Win32File_cpp_sTANDARD_RIGHTS_READ >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sTANDARD_RIGHTS_READ :: IO (Word32) sTANDARD_RIGHTS_WRITE :: AccessMode sTANDARD_RIGHTS_WRITE = unsafePerformIO( prim_Win32File_cpp_sTANDARD_RIGHTS_WRITE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sTANDARD_RIGHTS_WRITE :: IO (Word32) sTANDARD_RIGHTS_EXECUTE :: AccessMode sTANDARD_RIGHTS_EXECUTE = unsafePerformIO( prim_Win32File_cpp_sTANDARD_RIGHTS_EXECUTE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sTANDARD_RIGHTS_EXECUTE :: IO (Word32) sTANDARD_RIGHTS_ALL :: AccessMode sTANDARD_RIGHTS_ALL = unsafePerformIO( prim_Win32File_cpp_sTANDARD_RIGHTS_ALL >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sTANDARD_RIGHTS_ALL :: IO (Word32) sPECIFIC_RIGHTS_ALL :: AccessMode sPECIFIC_RIGHTS_ALL = unsafePerformIO( prim_Win32File_cpp_sPECIFIC_RIGHTS_ALL >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sPECIFIC_RIGHTS_ALL :: IO (Word32) aCCESS_SYSTEM_SECURITY :: AccessMode aCCESS_SYSTEM_SECURITY = unsafePerformIO( prim_Win32File_cpp_aCCESS_SYSTEM_SECURITY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_aCCESS_SYSTEM_SECURITY :: IO (Word32) mAXIMUM_ALLOWED :: AccessMode mAXIMUM_ALLOWED = unsafePerformIO( prim_Win32File_cpp_mAXIMUM_ALLOWED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_mAXIMUM_ALLOWED :: IO (Word32) ---------------------------------------------------------------- type ShareMode = UINT fILE_SHARE_NONE :: ShareMode fILE_SHARE_NONE = unsafePerformIO( prim_Win32File_cpp_fILE_SHARE_NONE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_SHARE_NONE :: IO (Word32) fILE_SHARE_READ :: ShareMode fILE_SHARE_READ = unsafePerformIO( prim_Win32File_cpp_fILE_SHARE_READ >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_SHARE_READ :: IO (Word32) fILE_SHARE_WRITE :: ShareMode fILE_SHARE_WRITE = unsafePerformIO( prim_Win32File_cpp_fILE_SHARE_WRITE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_SHARE_WRITE :: IO (Word32) ---------------------------------------------------------------- type CreateMode = UINT cREATE_NEW :: CreateMode cREATE_NEW = unsafePerformIO( prim_Win32File_cpp_cREATE_NEW >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_cREATE_NEW :: IO (Word32) cREATE_ALWAYS :: CreateMode cREATE_ALWAYS = unsafePerformIO( prim_Win32File_cpp_cREATE_ALWAYS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_cREATE_ALWAYS :: IO (Word32) oPEN_EXISTING :: CreateMode oPEN_EXISTING = unsafePerformIO( prim_Win32File_cpp_oPEN_EXISTING >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_oPEN_EXISTING :: IO (Word32) oPEN_ALWAYS :: CreateMode oPEN_ALWAYS = unsafePerformIO( prim_Win32File_cpp_oPEN_ALWAYS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_oPEN_ALWAYS :: IO (Word32) tRUNCATE_EXISTING :: CreateMode tRUNCATE_EXISTING = unsafePerformIO( prim_Win32File_cpp_tRUNCATE_EXISTING >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_tRUNCATE_EXISTING :: IO (Word32) ---------------------------------------------------------------- type FileAttributeOrFlag = UINT fILE_ATTRIBUTE_READONLY :: FileAttributeOrFlag fILE_ATTRIBUTE_READONLY = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_READONLY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_READONLY :: IO (Word32) fILE_ATTRIBUTE_HIDDEN :: FileAttributeOrFlag fILE_ATTRIBUTE_HIDDEN = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_HIDDEN >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_HIDDEN :: IO (Word32) fILE_ATTRIBUTE_SYSTEM :: FileAttributeOrFlag fILE_ATTRIBUTE_SYSTEM = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_SYSTEM >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_SYSTEM :: IO (Word32) fILE_ATTRIBUTE_DIRECTORY :: FileAttributeOrFlag fILE_ATTRIBUTE_DIRECTORY = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_DIRECTORY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_DIRECTORY :: IO (Word32) fILE_ATTRIBUTE_ARCHIVE :: FileAttributeOrFlag fILE_ATTRIBUTE_ARCHIVE = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_ARCHIVE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_ARCHIVE :: IO (Word32) fILE_ATTRIBUTE_NORMAL :: FileAttributeOrFlag fILE_ATTRIBUTE_NORMAL = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_NORMAL >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_NORMAL :: IO (Word32) fILE_ATTRIBUTE_TEMPORARY :: FileAttributeOrFlag fILE_ATTRIBUTE_TEMPORARY = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_TEMPORARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_TEMPORARY :: IO (Word32) fILE_ATTRIBUTE_COMPRESSED :: FileAttributeOrFlag fILE_ATTRIBUTE_COMPRESSED = unsafePerformIO( prim_Win32File_cpp_fILE_ATTRIBUTE_COMPRESSED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_ATTRIBUTE_COMPRESSED :: IO (Word32) fILE_FLAG_WRITE_THROUGH :: FileAttributeOrFlag fILE_FLAG_WRITE_THROUGH = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_WRITE_THROUGH >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_WRITE_THROUGH :: IO (Word32) fILE_FLAG_OVERLAPPED :: FileAttributeOrFlag fILE_FLAG_OVERLAPPED = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_OVERLAPPED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_OVERLAPPED :: IO (Word32) fILE_FLAG_NO_BUFFERING :: FileAttributeOrFlag fILE_FLAG_NO_BUFFERING = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_NO_BUFFERING >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_NO_BUFFERING :: IO (Word32) fILE_FLAG_RANDOM_ACCESS :: FileAttributeOrFlag fILE_FLAG_RANDOM_ACCESS = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_RANDOM_ACCESS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_RANDOM_ACCESS :: IO (Word32) fILE_FLAG_SEQUENTIAL_SCAN :: FileAttributeOrFlag fILE_FLAG_SEQUENTIAL_SCAN = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_SEQUENTIAL_SCAN >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_SEQUENTIAL_SCAN :: IO (Word32) fILE_FLAG_DELETE_ON_CLOSE :: FileAttributeOrFlag fILE_FLAG_DELETE_ON_CLOSE = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_DELETE_ON_CLOSE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_DELETE_ON_CLOSE :: IO (Word32) fILE_FLAG_BACKUP_SEMANTICS :: FileAttributeOrFlag fILE_FLAG_BACKUP_SEMANTICS = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_BACKUP_SEMANTICS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_BACKUP_SEMANTICS :: IO (Word32) fILE_FLAG_POSIX_SEMANTICS :: FileAttributeOrFlag fILE_FLAG_POSIX_SEMANTICS = unsafePerformIO( prim_Win32File_cpp_fILE_FLAG_POSIX_SEMANTICS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_FLAG_POSIX_SEMANTICS :: IO (Word32) sECURITY_ANONYMOUS :: FileAttributeOrFlag sECURITY_ANONYMOUS = unsafePerformIO( prim_Win32File_cpp_sECURITY_ANONYMOUS >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_ANONYMOUS :: IO (Word32) sECURITY_IDENTIFICATION :: FileAttributeOrFlag sECURITY_IDENTIFICATION = unsafePerformIO( prim_Win32File_cpp_sECURITY_IDENTIFICATION >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_IDENTIFICATION :: IO (Word32) sECURITY_IMPERSONATION :: FileAttributeOrFlag sECURITY_IMPERSONATION = unsafePerformIO( prim_Win32File_cpp_sECURITY_IMPERSONATION >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_IMPERSONATION :: IO (Word32) sECURITY_DELEGATION :: FileAttributeOrFlag sECURITY_DELEGATION = unsafePerformIO( prim_Win32File_cpp_sECURITY_DELEGATION >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_DELEGATION :: IO (Word32) sECURITY_CONTEXT_TRACKING :: FileAttributeOrFlag sECURITY_CONTEXT_TRACKING = unsafePerformIO( prim_Win32File_cpp_sECURITY_CONTEXT_TRACKING >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_CONTEXT_TRACKING :: IO (Word32) sECURITY_EFFECTIVE_ONLY :: FileAttributeOrFlag sECURITY_EFFECTIVE_ONLY = unsafePerformIO( prim_Win32File_cpp_sECURITY_EFFECTIVE_ONLY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_EFFECTIVE_ONLY :: IO (Word32) sECURITY_SQOS_PRESENT :: FileAttributeOrFlag sECURITY_SQOS_PRESENT = unsafePerformIO( prim_Win32File_cpp_sECURITY_SQOS_PRESENT >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sECURITY_SQOS_PRESENT :: IO (Word32) ---------------------------------------------------------------- type MoveFileFlag = DWORD mOVEFILE_REPLACE_EXISTING :: MoveFileFlag mOVEFILE_REPLACE_EXISTING = unsafePerformIO( prim_Win32File_cpp_mOVEFILE_REPLACE_EXISTING >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_mOVEFILE_REPLACE_EXISTING :: IO (Word32) mOVEFILE_COPY_ALLOWED :: MoveFileFlag mOVEFILE_COPY_ALLOWED = unsafePerformIO( prim_Win32File_cpp_mOVEFILE_COPY_ALLOWED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_mOVEFILE_COPY_ALLOWED :: IO (Word32) mOVEFILE_DELAY_UNTIL_REBOOT :: MoveFileFlag mOVEFILE_DELAY_UNTIL_REBOOT = unsafePerformIO( prim_Win32File_cpp_mOVEFILE_DELAY_UNTIL_REBOOT >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_mOVEFILE_DELAY_UNTIL_REBOOT :: IO (Word32) ---------------------------------------------------------------- type FilePtrDirection = DWORD fILE_BEGIN :: FilePtrDirection fILE_BEGIN = unsafePerformIO( prim_Win32File_cpp_fILE_BEGIN >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_BEGIN :: IO (Word32) fILE_CURRENT :: FilePtrDirection fILE_CURRENT = unsafePerformIO( prim_Win32File_cpp_fILE_CURRENT >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_CURRENT :: IO (Word32) fILE_END :: FilePtrDirection fILE_END = unsafePerformIO( prim_Win32File_cpp_fILE_END >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_END :: IO (Word32) ---------------------------------------------------------------- type DriveType = UINT dRIVE_UNKNOWN :: DriveType dRIVE_UNKNOWN = unsafePerformIO( prim_Win32File_cpp_dRIVE_UNKNOWN >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_UNKNOWN :: IO (Word32) dRIVE_NO_ROOT_DIR :: DriveType dRIVE_NO_ROOT_DIR = unsafePerformIO( prim_Win32File_cpp_dRIVE_NO_ROOT_DIR >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_NO_ROOT_DIR :: IO (Word32) dRIVE_REMOVABLE :: DriveType dRIVE_REMOVABLE = unsafePerformIO( prim_Win32File_cpp_dRIVE_REMOVABLE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_REMOVABLE :: IO (Word32) dRIVE_FIXED :: DriveType dRIVE_FIXED = unsafePerformIO( prim_Win32File_cpp_dRIVE_FIXED >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_FIXED :: IO (Word32) dRIVE_REMOTE :: DriveType dRIVE_REMOTE = unsafePerformIO( prim_Win32File_cpp_dRIVE_REMOTE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_REMOTE :: IO (Word32) dRIVE_CDROM :: DriveType dRIVE_CDROM = unsafePerformIO( prim_Win32File_cpp_dRIVE_CDROM >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_CDROM :: IO (Word32) dRIVE_RAMDISK :: DriveType dRIVE_RAMDISK = unsafePerformIO( prim_Win32File_cpp_dRIVE_RAMDISK >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dRIVE_RAMDISK :: IO (Word32) ---------------------------------------------------------------- type DefineDosDeviceFlags = DWORD dDD_RAW_TARGET_PATH :: DefineDosDeviceFlags dDD_RAW_TARGET_PATH = unsafePerformIO( prim_Win32File_cpp_dDD_RAW_TARGET_PATH >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dDD_RAW_TARGET_PATH :: IO (Word32) dDD_REMOVE_DEFINITION :: DefineDosDeviceFlags dDD_REMOVE_DEFINITION = unsafePerformIO( prim_Win32File_cpp_dDD_REMOVE_DEFINITION >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dDD_REMOVE_DEFINITION :: IO (Word32) dDD_EXACT_MATCH_ON_REMOVE :: DefineDosDeviceFlags dDD_EXACT_MATCH_ON_REMOVE = unsafePerformIO( prim_Win32File_cpp_dDD_EXACT_MATCH_ON_REMOVE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_dDD_EXACT_MATCH_ON_REMOVE :: IO (Word32) ---------------------------------------------------------------- type BinaryType = DWORD sCS_32BIT_BINARY :: BinaryType sCS_32BIT_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_32BIT_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_32BIT_BINARY :: IO (Word32) sCS_DOS_BINARY :: BinaryType sCS_DOS_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_DOS_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_DOS_BINARY :: IO (Word32) sCS_WOW_BINARY :: BinaryType sCS_WOW_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_WOW_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_WOW_BINARY :: IO (Word32) sCS_PIF_BINARY :: BinaryType sCS_PIF_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_PIF_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_PIF_BINARY :: IO (Word32) sCS_POSIX_BINARY :: BinaryType sCS_POSIX_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_POSIX_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_POSIX_BINARY :: IO (Word32) sCS_OS216_BINARY :: BinaryType sCS_OS216_BINARY = unsafePerformIO( prim_Win32File_cpp_sCS_OS216_BINARY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_sCS_OS216_BINARY :: IO (Word32) ---------------------------------------------------------------- type FileNotificationFlag = DWORD fILE_NOTIFY_CHANGE_FILE_NAME :: FileNotificationFlag fILE_NOTIFY_CHANGE_FILE_NAME = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_FILE_NAME >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_FILE_NAME :: IO (Word32) fILE_NOTIFY_CHANGE_DIR_NAME :: FileNotificationFlag fILE_NOTIFY_CHANGE_DIR_NAME = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_DIR_NAME >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_DIR_NAME :: IO (Word32) fILE_NOTIFY_CHANGE_ATTRIBUTES :: FileNotificationFlag fILE_NOTIFY_CHANGE_ATTRIBUTES = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_ATTRIBUTES >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_ATTRIBUTES :: IO (Word32) fILE_NOTIFY_CHANGE_SIZE :: FileNotificationFlag fILE_NOTIFY_CHANGE_SIZE = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_SIZE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_SIZE :: IO (Word32) fILE_NOTIFY_CHANGE_LAST_WRITE :: FileNotificationFlag fILE_NOTIFY_CHANGE_LAST_WRITE = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_LAST_WRITE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_LAST_WRITE :: IO (Word32) fILE_NOTIFY_CHANGE_SECURITY :: FileNotificationFlag fILE_NOTIFY_CHANGE_SECURITY = unsafePerformIO( prim_Win32File_cpp_fILE_NOTIFY_CHANGE_SECURITY >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_NOTIFY_CHANGE_SECURITY :: IO (Word32) ---------------------------------------------------------------- type FileType = DWORD fILE_TYPE_UNKNOWN :: FileType fILE_TYPE_UNKNOWN = unsafePerformIO( prim_Win32File_cpp_fILE_TYPE_UNKNOWN >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_TYPE_UNKNOWN :: IO (Word32) fILE_TYPE_DISK :: FileType fILE_TYPE_DISK = unsafePerformIO( prim_Win32File_cpp_fILE_TYPE_DISK >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_TYPE_DISK :: IO (Word32) fILE_TYPE_CHAR :: FileType fILE_TYPE_CHAR = unsafePerformIO( prim_Win32File_cpp_fILE_TYPE_CHAR >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_TYPE_CHAR :: IO (Word32) fILE_TYPE_PIPE :: FileType fILE_TYPE_PIPE = unsafePerformIO( prim_Win32File_cpp_fILE_TYPE_PIPE >>= \ (res1) -> (return (res1))) primitive prim_Win32File_cpp_fILE_TYPE_PIPE :: IO (Word32) ---------------------------------------------------------------- type LPSECURITY_ATTRIBUTES = Addr type MbLPSECURITY_ATTRIBUTES = Maybe LPSECURITY_ATTRIBUTES ---------------------------------------------------------------- -- File operations ---------------------------------------------------------------- deleteFile :: String -> IO () deleteFile gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_deleteFile arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_deleteFile :: Addr -> IO (Int,Addr) copyFile :: String -> String -> Bool -> IO () copyFile gc_arg1 gc_arg2 gc_arg3 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> (marshall_bool_ gc_arg3) >>= \ (arg3) -> prim_Win32File_cpp_copyFile arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_copyFile :: Addr -> Addr -> Int -> IO (Int,Addr) moveFile :: String -> String -> IO () moveFile gc_arg1 gc_arg2 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> prim_Win32File_cpp_moveFile arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_moveFile :: Addr -> Addr -> IO (Int,Addr) moveFileEx :: String -> String -> MoveFileFlag -> IO () moveFileEx gc_arg1 gc_arg2 arg3 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> prim_Win32File_cpp_moveFileEx arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_moveFileEx :: Addr -> Addr -> Word32 -> IO (Int,Addr) setCurrentDirectory :: String -> IO () setCurrentDirectory gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_setCurrentDirectory arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_setCurrentDirectory :: Addr -> IO (Int,Addr) createDirectory :: String -> MbLPSECURITY_ATTRIBUTES -> IO () createDirectory gc_arg1 arg2 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (case arg2 of { Nothing -> (return (nullAddr)); (Just arg2) -> (return ((arg2))) }) >>= \ (arg2) -> prim_Win32File_cpp_createDirectory arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_createDirectory :: Addr -> Addr -> IO (Int,Addr) createDirectoryEx :: String -> String -> MbLPSECURITY_ATTRIBUTES -> IO () createDirectoryEx gc_arg1 gc_arg2 arg3 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> (case arg3 of { Nothing -> (return (nullAddr)); (Just arg3) -> (return ((arg3))) }) >>= \ (arg3) -> prim_Win32File_cpp_createDirectoryEx arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_createDirectoryEx :: Addr -> Addr -> Addr -> IO (Int,Addr) removeDirectory :: String -> IO () removeDirectory gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_removeDirectory arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_removeDirectory :: Addr -> IO (Int,Addr) getBinaryType :: String -> IO BinaryType getBinaryType gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_getBinaryType arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_getBinaryType :: Addr -> IO (Word32,Int,Addr) ---------------------------------------------------------------- -- HANDLE operations ---------------------------------------------------------------- createFile :: String -> AccessMode -> ShareMode -> MbLPSECURITY_ATTRIBUTES -> CreateMode -> FileAttributeOrFlag -> MbHANDLE -> IO HANDLE createFile gc_arg1 arg2 arg3 arg4 arg5 arg6 arg7 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (case arg4 of { Nothing -> (return (nullAddr)); (Just arg4) -> (return ((arg4))) }) >>= \ (arg4) -> (case arg7 of { Nothing -> (return (nullHANDLE)); (Just arg7) -> (return ((arg7))) }) >>= \ (arg7) -> prim_Win32File_cpp_createFile arg1 arg2 arg3 arg4 arg5 arg6 arg7 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_createFile :: Addr -> Word32 -> Word32 -> Addr -> Word32 -> Word32 -> Addr -> IO (Addr,Int,Addr) closeHandle :: HANDLE -> IO () closeHandle arg1 = prim_Win32File_cpp_closeHandle arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_closeHandle :: Addr -> IO (Int,Addr) getFileType :: HANDLE -> IO FileType getFileType arg1 = prim_Win32File_cpp_getFileType arg1 >>= \ (res1) -> (return (res1)) primitive prim_Win32File_cpp_getFileType :: Addr -> IO (Word32) --Apparently no error code flushFileBuffers :: HANDLE -> IO () flushFileBuffers arg1 = prim_Win32File_cpp_flushFileBuffers arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_flushFileBuffers :: Addr -> IO (Int,Addr) setEndOfFile :: HANDLE -> IO () setEndOfFile arg1 = prim_Win32File_cpp_setEndOfFile arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_setEndOfFile :: Addr -> IO (Int,Addr) setFileAttributes :: String -> FileAttributeOrFlag -> IO () setFileAttributes gc_arg1 arg2 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_setFileAttributes arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_setFileAttributes :: Addr -> Word32 -> IO (Int,Addr) getFileAttributes :: String -> IO FileAttributeOrFlag getFileAttributes gc_arg1 = (marshall_string_ gc_arg1) >>= \ (arg1) -> prim_Win32File_cpp_getFileAttributes arg1 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_getFileAttributes :: Addr -> IO (Word32,Int,Addr) ---------------------------------------------------------------- -- Read/write files ---------------------------------------------------------------- -- No support for this yet --type OVERLAPPED = -- (DWORD, -- Offset -- DWORD, -- OffsetHigh -- HANDLE) -- hEvent type LPOVERLAPPED = Addr type MbLPOVERLAPPED = Maybe LPOVERLAPPED --Sigh - I give up & prefix win32_ to the next two to avoid -- senseless Prelude name clashes. --sof. win32_ReadFile :: HANDLE -> Addr -> DWORD -> MbLPOVERLAPPED -> IO DWORD win32_ReadFile arg1 arg2 arg3 arg4 = (case arg4 of { Nothing -> (return (nullAddr)); (Just arg4) -> (return ((arg4))) }) >>= \ (arg4) -> prim_Win32File_cpp_win32_ReadFile arg1 arg2 arg3 arg4 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_win32_ReadFile :: Addr -> Addr -> Word32 -> Addr -> IO (Word32,Int,Addr) win32_WriteFile :: HANDLE -> Addr -> DWORD -> MbLPOVERLAPPED -> IO DWORD win32_WriteFile arg1 arg2 arg3 arg4 = (case arg4 of { Nothing -> (return (nullAddr)); (Just arg4) -> (return ((arg4))) }) >>= \ (arg4) -> prim_Win32File_cpp_win32_WriteFile arg1 arg2 arg3 arg4 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_win32_WriteFile :: Addr -> Addr -> Word32 -> Addr -> IO (Word32,Int,Addr) -- missing Seek functioinality; GSL ??? -- Dont have Word64; ADR -- %fun SetFilePointer :: HANDLE -> Word64 -> FilePtrDirection -> IO Word64 ---------------------------------------------------------------- -- File Notifications -- -- Use these to initialise, "increment" and close a HANDLE you can wait -- on. ---------------------------------------------------------------- findFirstChangeNotification :: String -> Bool -> FileNotificationFlag -> IO HANDLE findFirstChangeNotification gc_arg1 gc_arg2 arg3 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_bool_ gc_arg2) >>= \ (arg2) -> prim_Win32File_cpp_findFirstChangeNotification arg1 arg2 arg3 >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_findFirstChangeNotification :: Addr -> Int -> Word32 -> IO (Addr,Int,Addr) findNextChangeNotification :: HANDLE -> IO () findNextChangeNotification arg1 = prim_Win32File_cpp_findNextChangeNotification arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_findNextChangeNotification :: Addr -> IO (Int,Addr) findCloseChangeNotification :: HANDLE -> IO () findCloseChangeNotification arg1 = prim_Win32File_cpp_findCloseChangeNotification arg1 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_findCloseChangeNotification :: Addr -> IO (Int,Addr) ---------------------------------------------------------------- -- DOS Device flags ---------------------------------------------------------------- defineDosDevice :: DefineDosDeviceFlags -> String -> String -> IO () defineDosDevice arg1 gc_arg1 gc_arg2 = (marshall_string_ gc_arg1) >>= \ (arg2) -> (marshall_string_ gc_arg2) >>= \ (arg3) -> prim_Win32File_cpp_defineDosDevice arg1 arg2 arg3 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_defineDosDevice :: Word32 -> Addr -> Addr -> IO (Int,Addr) ---------------------------------------------------------------- -- These functions are very unusual in the Win32 API: -- They dont return error codes areFileApisANSI :: IO Bool areFileApisANSI = prim_Win32File_cpp_areFileApisANSI >>= \ (res1) -> (unmarshall_bool_ res1) >>= \ gc_res1 -> (return (gc_res1)) primitive prim_Win32File_cpp_areFileApisANSI :: IO (Int) setFileApisToOEM :: IO () setFileApisToOEM = prim_Win32File_cpp_setFileApisToOEM primitive prim_Win32File_cpp_setFileApisToOEM :: IO () setFileApisToANSI :: IO () setFileApisToANSI = prim_Win32File_cpp_setFileApisToANSI primitive prim_Win32File_cpp_setFileApisToANSI :: IO () setHandleCount :: UINT -> IO UINT setHandleCount arg1 = prim_Win32File_cpp_setHandleCount arg1 >>= \ (res1) -> (return (res1)) primitive prim_Win32File_cpp_setHandleCount :: Word32 -> IO (Word32) ---------------------------------------------------------------- getLogicalDrives :: IO DWORD getLogicalDrives = prim_Win32File_cpp_getLogicalDrives >>= \ (res1,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (res1)) primitive prim_Win32File_cpp_getLogicalDrives :: IO (Word32,Int,Addr) -- %fun GetDriveType :: MbString -> IO DriveType getDiskFreeSpace :: MbString -> IO (DWORD,DWORD,DWORD,DWORD) getDiskFreeSpace gc_arg1 = (case gc_arg1 of { Nothing -> (return (nullAddr)); (Just gc_arg1) -> (marshall_string_ gc_arg1) >>= \ (s) -> (return ((s))) }) >>= \ (s) -> prim_Win32File_cpp_getDiskFreeSpace s >>= \ (res1,res2,res3,res4,gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return ((res1,res2,res3,res4))) primitive prim_Win32File_cpp_getDiskFreeSpace :: Addr -> IO (Word32,Word32,Word32,Word32,Int,Addr) setVolumeLabel :: String -> String -> IO () setVolumeLabel gc_arg1 gc_arg2 = (marshall_string_ gc_arg1) >>= \ (arg1) -> (marshall_string_ gc_arg2) >>= \ (arg2) -> prim_Win32File_cpp_setVolumeLabel arg1 arg2 >>= \ (gc_failed,gc_failstring) -> if ( gc_failed /= (0::Int)) then unmarshall_string_ gc_failstring >>= ioError . userError else (return (())) primitive prim_Win32File_cpp_setVolumeLabel :: Addr -> Addr -> IO (Int,Addr) ---------------------------------------------------------------- -- End ---------------------------------------------------------------- needPrims_hugs 2
OS2World/DEV-UTIL-HUGS
libraries/win32/Win32File.hs
bsd-3-clause
32,747
307
18
4,441
8,308
4,541
3,767
-1
-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. {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.TimeGrain.SV.Rules ( rules ) where import Data.Text (Text) import Prelude import Data.String import Duckling.Dimensions.Types import qualified Duckling.TimeGrain.Types as TG import Duckling.Types grains :: [(Text, String, TG.Grain)] grains = [ ("second (grain)", "sek(und(er(na)?)?)?", TG.Second) , ("minute (grain)", "min(ut(er(na)?)?)?", TG.Minute) , ("hour (grain)", "t(imm(e(n)?|ar(na)?)?)?", TG.Hour) , ("day (grain)", "dag(en|ar(na)?)?", TG.Day) , ("week (grain)", "veck(or(na)?|a(n)?)?", TG.Week) , ("month (grain)", "m\x00e5nad(er(na)?)?", TG.Month) , ("quarter (grain)", "kvart(al)(et)?", TG.Quarter) , ("year (grain)", "\x00e5r(en)?", TG.Year) ] rules :: [Rule] rules = map go grains where go (name, regexPattern, grain) = Rule { name = name , pattern = [regex regexPattern] , prod = \_ -> Just $ Token TimeGrain grain }
rfranek/duckling
Duckling/TimeGrain/SV/Rules.hs
bsd-3-clause
1,317
0
11
277
272
173
99
25
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} module Data.API.Subledger.Error ( SubledgerError(..) , SubledgerErrorType(..) , SubledgerErrorHTTPCode(..) , mkErrorHTTP , setErrorHTTP ) where import Control.Exception import Data.Aeson import Data.Default import Data.Text (Text) import Data.Typeable (Typeable) -- | Error Codes for HTTP Responses data SubledgerErrorHTTPCode = BadRequest -- ^ 400 | UnAuthorized -- ^ 401 | RequestFailed -- ^ 402 | NotFound -- ^ 404 | VersionConflict -- ^ 409 | SubledgerServerError Int -- ^ (>=500) | UnknownHTTPCode Int -- ^ All other codes deriving (Eq, Show, Typeable) mkErrorHTTP :: Int -> SubledgerErrorHTTPCode mkErrorHTTP statusCode = case statusCode of 400 -> BadRequest 401 -> UnAuthorized 402 -> RequestFailed 404 -> NotFound 409 -> VersionConflict code | code >= 500 -> SubledgerServerError code code -> UnknownHTTPCode code -- | set the `errorHTTP` field of the `SubledgerError` based on the -- HTTP response code. setErrorHTTP :: Int -- ^ HTTP Status code -> SubledgerError -- ^ `SubledgerError` -> SubledgerError setErrorHTTP statusCode subledgerError = subledgerError { errorHTTP = Just $ mkErrorHTTP statusCode } -- | Subledger error types data SubledgerErrorType = ConnectionFailure | ParseFailure | APIError | UnknownErrorType | UnlabeledErrorType deriving (Bounded, Enum, Eq, Show, Typeable) -- | Subledger error data SubledgerError = SubledgerError { errorType :: SubledgerErrorType , errorMsg :: Text , errorHTTP :: Maybe SubledgerErrorHTTPCode } deriving (Eq, Show, Typeable) instance Default SubledgerError where def = SubledgerError UnlabeledErrorType mempty Nothing instance Exception SubledgerError instance FromJSON SubledgerError where parseJSON = withObject "SubledgerError" $ \o -> SubledgerError APIError <$> o .: "exception" <*> fmap (fmap mkErrorHTTP) (o .:? "status")
whittle/subledger
subledger-core/src/Data/API/Subledger/Error.hs
bsd-3-clause
2,332
0
11
727
421
239
182
54
7
{-# LANGUAGE FlexibleInstances, FlexibleContexts, TypeFamilies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.FingerTree -- Copyright : (c) Ross Paterson, Ralf Hinze, Paweł Nowak 2014 -- License : BSD-style -- Maintainer : pawel834@gmail.com -- Stability : provisional -- Portability : non-portable (TypeFamilies) -- -- A version of Data.FingerTree from package fingertree modified to use -- associated types instead of functional dependencies and MPTCs. -- -- A general sequence representation with arbitrary annotations, for -- use as a base for implementations of various collection types, as -- described in section 4 of -- -- * Ralf Hinze and Ross Paterson, -- \"Finger trees: a simple general-purpose data structure\", -- /Journal of Functional Programming/ 16:2 (2006) pp 197-217. -- <http://www.soi.city.ac.uk/~ross/papers/FingerTree.html> -- -- For a directly usable sequence type, see @Data.Sequence@, which is -- a specialization of this structure. -- -- An amortized running time is given for each operation, with /n/ -- referring to the length of the sequence. These bounds hold even in -- a persistent (shared) setting. -- -- /Note/: Many of these operations have the same names as similar -- operations on lists in the "Prelude". The ambiguity may be resolved -- using either qualification or the @hiding@ clause. -- ----------------------------------------------------------------------------- module Data.FingerTree ( FingerTree , Measured(..) -- * Construction , empty, singleton , (<|), (|>), (><) , fromList -- * Deconstruction , null , ViewL(..), ViewR(..), viewl, viewr , split, takeUntil, dropUntil -- * Transformation , reverse , fmap', fmapWithPos, unsafeFmap , traverse', traverseWithPos, unsafeTraverse ) where import Prelude hiding (null, reverse) import Control.Applicative (Applicative(pure, (<*>)), (<$>)) import Data.Foldable (Foldable(foldMap), toList) import Data.Monoid infixr 5 >< infixr 5 <|, :< infixl 5 |>, :> -- | View of the left end of a sequence. data ViewL s a = EmptyL -- ^ empty sequence | a :< s a -- ^ leftmost element and the rest of the sequence deriving (Eq, Ord, Show, Read) -- | View of the right end of a sequence. data ViewR s a = EmptyR -- ^ empty sequence | s a :> a -- ^ the sequence minus the rightmost element, -- and the rightmost element deriving (Eq, Ord, Show, Read) instance Functor s => Functor (ViewL s) where fmap _ EmptyL = EmptyL fmap f (x :< xs) = f x :< fmap f xs instance Functor s => Functor (ViewR s) where fmap _ EmptyR = EmptyR fmap f (xs :> x) = fmap f xs :> f x -- | 'empty' and '><'. instance Measured a => Monoid (FingerTree a) where mempty = empty mappend = (><) -- Explicit Digit type (Exercise 1) data Digit a = One a | Two a a | Three a a a | Four a a a a deriving Show instance Foldable Digit where foldMap f (One a) = f a foldMap f (Two a b) = f a <> f b foldMap f (Three a b c) = f a <> f b <> f c foldMap f (Four a b c d) = f a <> f b <> f c <> f d ------------------- -- 4.1 Measurements ------------------- -- | Things that can be measured. class Monoid (Measure a) => Measured a where type Measure a :: * measure :: a -> Measure a instance Measured a => Measured (Digit a) where type Measure (Digit a) = Measure a measure = foldMap measure --------------------------- -- 4.2 Caching measurements --------------------------- data Node a = Node2 !(Measure a) a a | Node3 !(Measure a) a a a instance Foldable Node where foldMap f (Node2 _ a b) = f a <> f b foldMap f (Node3 _ a b c) = f a <> f b <> f c node2 :: Measured a => a -> a -> Node a node2 a b = Node2 (measure a <> measure b) a b node3 :: Measured a => a -> a -> a -> Node a node3 a b c = Node3 (measure a <> measure b <> measure c) a b c instance Measured a => Measured (Node a) where type Measure (Node a) = Measure a measure (Node2 v _ _) = v measure (Node3 v _ _ _) = v nodeToDigit :: Node a -> Digit a nodeToDigit (Node2 _ a b) = Two a b nodeToDigit (Node3 _ a b c) = Three a b c -- | A representation of a sequence of values of type @a@, allowing -- access to the ends in constant time, and append and split in time -- logarithmic in the size of the smaller piece. -- -- The collection is also parameterized by a measure type @v@, which -- is used to specify a position in the sequence for the 'split' operation. -- The types of the operations enforce the constraint @'Measured' v a@, -- which also implies that the type @v@ is determined by @a@. -- -- A variety of abstract data types can be implemented by using different -- element types and measurements. data FingerTree a = Empty | Single a | Deep !(Measure a) !(Digit a) (FingerTree (Node a)) !(Digit a) deep :: Measured a=> Digit a -> FingerTree (Node a) -> Digit a -> FingerTree a deep pr m sf = Deep ((measure pr `mappendVal` m) <> measure sf) pr m sf -- | /O(1)/. The cached measure of a tree. instance Measured a => Measured (FingerTree a) where type Measure (FingerTree a) = Measure a measure Empty = mempty measure (Single x) = measure x measure (Deep v _ _ _) = v instance Foldable FingerTree where foldMap _ Empty = mempty foldMap f (Single x) = f x foldMap f (Deep _ pr m sf) = foldMap f pr <> foldMap (foldMap f) m <> foldMap f sf instance Eq a => Eq (FingerTree a) where xs == ys = toList xs == toList ys instance Ord a => Ord (FingerTree a) where compare xs ys = compare (toList xs) (toList ys) instance Show a => Show (FingerTree a) where showsPrec p xs = showParen (p > 10) $ showString "fromList " . shows (toList xs) -- | Like 'fmap', but with a more constrained type. fmap' :: (Measured a, Measured b) => (a -> b) -> FingerTree a -> FingerTree b fmap' = mapTree mapTree :: (Measured a, Measured b) => (a -> b) -> FingerTree a -> FingerTree b mapTree _ Empty = Empty mapTree f (Single x) = Single (f x) mapTree f (Deep _ pr m sf) = deep (mapDigit f pr) (mapTree (mapNode f) m) (mapDigit f sf) mapNode :: (Measured a, Measured b) => (a -> b) -> Node a -> Node b mapNode f (Node2 _ a b) = node2 (f a) (f b) mapNode f (Node3 _ a b c) = node3 (f a) (f b) (f c) mapDigit :: (a -> b) -> Digit a -> Digit b mapDigit f (One a) = One (f a) mapDigit f (Two a b) = Two (f a) (f b) mapDigit f (Three a b c) = Three (f a) (f b) (f c) mapDigit f (Four a b c d) = Four (f a) (f b) (f c) (f d) -- | Map all elements of the tree with a function that also takes the -- measure of the prefix of the tree to the left of the element. fmapWithPos :: (Measured a, Measured b) => (Measure a -> a -> b) -> FingerTree a -> FingerTree b fmapWithPos f = mapWPTree f mempty mapWPTree :: (Measured a, Measured b) => (Measure a -> a -> b) -> Measure a -> FingerTree a -> FingerTree b mapWPTree _ _ Empty = Empty mapWPTree f v (Single x) = Single (f v x) mapWPTree f v (Deep _ pr m sf) = deep (mapWPDigit f v pr) (mapWPTree (mapWPNode f) vpr m) (mapWPDigit f vm sf) where vpr = v <> measure pr vm = vpr `mappendVal` m mapWPNode :: (Measured a, Measured b) => (Measure a -> a -> b) -> Measure a -> Node a -> Node b mapWPNode f v (Node2 _ a b) = node2 (f v a) (f va b) where va = v <> measure a mapWPNode f v (Node3 _ a b c) = node3 (f v a) (f va b) (f vab c) where va = v <> measure a vab = va <> measure b mapWPDigit :: Measured a => (Measure a -> a -> b) -> Measure a -> Digit a -> Digit b mapWPDigit f v (One a) = One (f v a) mapWPDigit f v (Two a b) = Two (f v a) (f va b) where va = v <> measure a mapWPDigit f v (Three a b c) = Three (f v a) (f va b) (f vab c) where va = v <> measure a vab = va <> measure b mapWPDigit f v (Four a b c d) = Four (f v a) (f va b) (f vab c) (f vabc d) where va = v <> measure a vab = va <> measure b vabc = vab <> measure c -- | Like 'fmap', but safe only if the function preserves the measure. unsafeFmap :: Measure a ~ Measure b => (a -> b) -> FingerTree a -> FingerTree b unsafeFmap _ Empty = Empty unsafeFmap f (Single x) = Single (f x) unsafeFmap f (Deep v pr m sf) = Deep v (mapDigit f pr) (unsafeFmap (unsafeFmapNode f) m) (mapDigit f sf) unsafeFmapNode :: Measure a ~ Measure b => (a -> b) -> Node a -> Node b unsafeFmapNode f (Node2 v a b) = Node2 v (f a) (f b) unsafeFmapNode f (Node3 v a b c) = Node3 v (f a) (f b) (f c) -- | Like 'traverse', but with a more constrained type. traverse' :: (Measured a, Measured b, Applicative f) => (a -> f b) -> FingerTree a -> f (FingerTree b) traverse' = traverseTree traverseTree :: (Measured b, Applicative f) => (a -> f b) -> FingerTree a -> f (FingerTree b) traverseTree _ Empty = pure Empty traverseTree f (Single x) = Single <$> f x traverseTree f (Deep _ pr m sf) = deep <$> traverseDigit f pr <*> traverseTree (traverseNode f) m <*> traverseDigit f sf traverseNode :: (Measured b, Applicative f) => (a -> f b) -> Node a -> f (Node b) traverseNode f (Node2 _ a b) = node2 <$> f a <*> f b traverseNode f (Node3 _ a b c) = node3 <$> f a <*> f b <*> f c traverseDigit :: (Applicative f) => (a -> f b) -> Digit a -> f (Digit b) traverseDigit f (One a) = One <$> f a traverseDigit f (Two a b) = Two <$> f a <*> f b traverseDigit f (Three a b c) = Three <$> f a <*> f b <*> f c traverseDigit f (Four a b c d) = Four <$> f a <*> f b <*> f c <*> f d -- | Traverse the tree with a function that also takes the -- measure of the prefix of the tree to the left of the element. traverseWithPos :: (Measured a, Measured b, Applicative f) => (Measure a -> a -> f b) -> FingerTree a -> f (FingerTree b) traverseWithPos f = traverseWPTree f mempty traverseWPTree :: (Measured a, Measured b, Applicative f) => (Measure a -> a -> f b) -> Measure a -> FingerTree a -> f (FingerTree b) traverseWPTree _ _ Empty = pure Empty traverseWPTree f v (Single x) = Single <$> f v x traverseWPTree f v (Deep _ pr m sf) = deep <$> traverseWPDigit f v pr <*> traverseWPTree (traverseWPNode f) vpr m <*> traverseWPDigit f vm sf where vpr = v <> measure pr vm = vpr `mappendVal` m traverseWPNode :: (Measured a, Measured b, Applicative f) => (Measure a -> a -> f b) -> Measure a -> Node a -> f (Node b) traverseWPNode f v (Node2 _ a b) = node2 <$> f v a <*> f va b where va = v <> measure a traverseWPNode f v (Node3 _ a b c) = node3 <$> f v a <*> f va b <*> f vab c where va = v <> measure a vab = va <> measure b traverseWPDigit :: (Measured a, Applicative f) => (Measure a -> a -> f b) -> Measure a -> Digit a -> f (Digit b) traverseWPDigit f v (One a) = One <$> f v a traverseWPDigit f v (Two a b) = Two <$> f v a <*> f va b where va = v <> measure a traverseWPDigit f v (Three a b c) = Three <$> f v a <*> f va b <*> f vab c where va = v <> measure a vab = va <> measure b traverseWPDigit f v (Four a b c d) = Four <$> f v a <*> f va b <*> f vab c <*> f vabc d where va = v <> measure a vab = va <> measure b vabc = vab <> measure c -- | Like 'traverse', but safe only if the function preserves the measure. unsafeTraverse :: (Measure a ~ Measure b, Applicative f) => (a -> f b) -> FingerTree a -> f (FingerTree b) unsafeTraverse _ Empty = pure Empty unsafeTraverse f (Single x) = Single <$> f x unsafeTraverse f (Deep v pr m sf) = Deep v <$> traverseDigit f pr <*> unsafeTraverse (unsafeTraverseNode f) m <*> traverseDigit f sf unsafeTraverseNode :: (Measure a ~ Measure b, Applicative f) => (a -> f b) -> Node a -> f (Node b) unsafeTraverseNode f (Node2 v a b) = Node2 v <$> f a <*> f b unsafeTraverseNode f (Node3 v a b c) = Node3 v <$> f a <*> f b <*> f c ----------------------------------------------------- -- 4.3 Construction, deconstruction and concatenation ----------------------------------------------------- -- | /O(1)/. The empty sequence. empty :: Measured a => FingerTree a empty = Empty -- | /O(1)/. A singleton sequence. singleton :: Measured a => a -> FingerTree a singleton = Single -- | /O(n)/. Create a sequence from a finite list of elements. fromList :: Measured a => [a] -> FingerTree a fromList = foldr (<|) Empty -- | /O(1)/. Add an element to the left end of a sequence. -- Mnemonic: a triangle with the single element at the pointy end. (<|) :: Measured a => a -> FingerTree a -> FingerTree a a <| Empty = Single a a <| Single b = deep (One a) Empty (One b) a <| Deep v (Four b c d e) m sf = m `seq` Deep (measure a <> v) (Two a b) (node3 c d e <| m) sf a <| Deep v pr m sf = Deep (measure a <> v) (consDigit a pr) m sf consDigit :: a -> Digit a -> Digit a consDigit a (One b) = Two a b consDigit a (Two b c) = Three a b c consDigit a (Three b c d) = Four a b c d consDigit _ (Four _ _ _ _) = illegal_argument "consDigit" -- | /O(1)/. Add an element to the right end of a sequence. -- Mnemonic: a triangle with the single element at the pointy end. (|>) :: Measured a => FingerTree a -> a -> FingerTree a Empty |> a = Single a Single a |> b = deep (One a) Empty (One b) Deep v pr m (Four a b c d) |> e = m `seq` Deep (v <> measure e) pr (m |> node3 a b c) (Two d e) Deep v pr m sf |> x = Deep (v <> measure x) pr m (snocDigit sf x) snocDigit :: Digit a -> a -> Digit a snocDigit (One a) b = Two a b snocDigit (Two a b) c = Three a b c snocDigit (Three a b c) d = Four a b c d snocDigit (Four _ _ _ _) _ = illegal_argument "snocDigit" -- | /O(1)/. Is this the empty sequence? null :: Measured a => FingerTree a -> Bool null Empty = True null _ = False -- | /O(1)/. Analyse the left end of a sequence. viewl :: Measured a => FingerTree a -> ViewL FingerTree a viewl Empty = EmptyL viewl (Single x) = x :< Empty viewl (Deep _ (One x) m sf) = x :< rotL m sf viewl (Deep _ pr m sf) = lheadDigit pr :< deep (ltailDigit pr) m sf rotL :: Measured a => FingerTree (Node a) -> Digit a -> FingerTree a rotL m sf = case viewl m of EmptyL -> digitToTree sf a :< m' -> Deep (measure m <> measure sf) (nodeToDigit a) m' sf lheadDigit :: Digit a -> a lheadDigit (One a) = a lheadDigit (Two a _) = a lheadDigit (Three a _ _) = a lheadDigit (Four a _ _ _) = a ltailDigit :: Digit a -> Digit a ltailDigit (One _) = illegal_argument "ltailDigit" ltailDigit (Two _ b) = One b ltailDigit (Three _ b c) = Two b c ltailDigit (Four _ b c d) = Three b c d -- | /O(1)/. Analyse the right end of a sequence. viewr :: Measured a => FingerTree a -> ViewR FingerTree a viewr Empty = EmptyR viewr (Single x) = Empty :> x viewr (Deep _ pr m (One x)) = rotR pr m :> x viewr (Deep _ pr m sf) = deep pr m (rtailDigit sf) :> rheadDigit sf rotR :: Measured a => Digit a -> FingerTree (Node a) -> FingerTree a rotR pr m = case viewr m of EmptyR -> digitToTree pr m' :> a -> Deep (measure pr `mappendVal` m) pr m' (nodeToDigit a) rheadDigit :: Digit a -> a rheadDigit (One a) = a rheadDigit (Two _ b) = b rheadDigit (Three _ _ c) = c rheadDigit (Four _ _ _ d) = d rtailDigit :: Digit a -> Digit a rtailDigit (One _) = illegal_argument "rtailDigit" rtailDigit (Two a _) = One a rtailDigit (Three a b _) = Two a b rtailDigit (Four a b c _) = Three a b c digitToTree :: Measured a => Digit a -> FingerTree a digitToTree (One a) = Single a digitToTree (Two a b) = deep (One a) Empty (One b) digitToTree (Three a b c) = deep (Two a b) Empty (One c) digitToTree (Four a b c d) = deep (Two a b) Empty (Two c d) ---------------- -- Concatenation ---------------- -- | /O(log(min(n1,n2)))/. Concatenate two sequences. (><) :: Measured a => FingerTree a -> FingerTree a -> FingerTree a (><) = appendTree0 appendTree0 :: Measured a => FingerTree a -> FingerTree a -> FingerTree a appendTree0 Empty xs = xs appendTree0 xs Empty = xs appendTree0 (Single x) xs = x <| xs appendTree0 xs (Single x) = xs |> x appendTree0 (Deep _ pr1 m1 sf1) (Deep _ pr2 m2 sf2) = deep pr1 (addDigits0 m1 sf1 pr2 m2) sf2 addDigits0 :: Measured a => FingerTree (Node a) -> Digit a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a) addDigits0 m1 (One a) (One b) m2 = appendTree1 m1 (node2 a b) m2 addDigits0 m1 (One a) (Two b c) m2 = appendTree1 m1 (node3 a b c) m2 addDigits0 m1 (One a) (Three b c d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits0 m1 (One a) (Four b c d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits0 m1 (Two a b) (One c) m2 = appendTree1 m1 (node3 a b c) m2 addDigits0 m1 (Two a b) (Two c d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits0 m1 (Two a b) (Three c d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits0 m1 (Two a b) (Four c d e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits0 m1 (Three a b c) (One d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits0 m1 (Three a b c) (Two d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits0 m1 (Three a b c) (Three d e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits0 m1 (Three a b c) (Four d e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits0 m1 (Four a b c d) (One e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits0 m1 (Four a b c d) (Two e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits0 m1 (Four a b c d) (Three e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits0 m1 (Four a b c d) (Four e f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 appendTree1 :: Measured a => FingerTree a -> a -> FingerTree a -> FingerTree a appendTree1 Empty a xs = a <| xs appendTree1 xs a Empty = xs |> a appendTree1 (Single x) a xs = x <| a <| xs appendTree1 xs a (Single x) = xs |> a |> x appendTree1 (Deep _ pr1 m1 sf1) a (Deep _ pr2 m2 sf2) = deep pr1 (addDigits1 m1 sf1 a pr2 m2) sf2 addDigits1 :: Measured a => FingerTree (Node a) -> Digit a -> a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a) addDigits1 m1 (One a) b (One c) m2 = appendTree1 m1 (node3 a b c) m2 addDigits1 m1 (One a) b (Two c d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits1 m1 (One a) b (Three c d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits1 m1 (One a) b (Four c d e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits1 m1 (Two a b) c (One d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits1 m1 (Two a b) c (Two d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits1 m1 (Two a b) c (Three d e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits1 m1 (Two a b) c (Four d e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits1 m1 (Three a b c) d (One e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits1 m1 (Three a b c) d (Two e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits1 m1 (Three a b c) d (Three e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits1 m1 (Three a b c) d (Four e f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits1 m1 (Four a b c d) e (One f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits1 m1 (Four a b c d) e (Two f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits1 m1 (Four a b c d) e (Three f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits1 m1 (Four a b c d) e (Four f g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 appendTree2 :: Measured a => FingerTree a -> a -> a -> FingerTree a -> FingerTree a appendTree2 Empty a b xs = a <| b <| xs appendTree2 xs a b Empty = xs |> a |> b appendTree2 (Single x) a b xs = x <| a <| b <| xs appendTree2 xs a b (Single x) = xs |> a |> b |> x appendTree2 (Deep _ pr1 m1 sf1) a b (Deep _ pr2 m2 sf2) = deep pr1 (addDigits2 m1 sf1 a b pr2 m2) sf2 addDigits2 :: Measured a => FingerTree (Node a) -> Digit a -> a -> a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a) addDigits2 m1 (One a) b c (One d) m2 = appendTree2 m1 (node2 a b) (node2 c d) m2 addDigits2 m1 (One a) b c (Two d e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits2 m1 (One a) b c (Three d e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits2 m1 (One a) b c (Four d e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits2 m1 (Two a b) c d (One e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits2 m1 (Two a b) c d (Two e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits2 m1 (Two a b) c d (Three e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits2 m1 (Two a b) c d (Four e f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits2 m1 (Three a b c) d e (One f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits2 m1 (Three a b c) d e (Two f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits2 m1 (Three a b c) d e (Three f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits2 m1 (Three a b c) d e (Four f g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits2 m1 (Four a b c d) e f (One g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits2 m1 (Four a b c d) e f (Two g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits2 m1 (Four a b c d) e f (Three g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits2 m1 (Four a b c d) e f (Four g h i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 appendTree3 :: Measured a => FingerTree a -> a -> a -> a -> FingerTree a -> FingerTree a appendTree3 Empty a b c xs = a <| b <| c <| xs appendTree3 xs a b c Empty = xs |> a |> b |> c appendTree3 (Single x) a b c xs = x <| a <| b <| c <| xs appendTree3 xs a b c (Single x) = xs |> a |> b |> c |> x appendTree3 (Deep _ pr1 m1 sf1) a b c (Deep _ pr2 m2 sf2) = deep pr1 (addDigits3 m1 sf1 a b c pr2 m2) sf2 addDigits3 :: Measured a => FingerTree (Node a) -> Digit a -> a -> a -> a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a) addDigits3 m1 (One a) b c d (One e) m2 = appendTree2 m1 (node3 a b c) (node2 d e) m2 addDigits3 m1 (One a) b c d (Two e f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits3 m1 (One a) b c d (Three e f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits3 m1 (One a) b c d (Four e f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits3 m1 (Two a b) c d e (One f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits3 m1 (Two a b) c d e (Two f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits3 m1 (Two a b) c d e (Three f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits3 m1 (Two a b) c d e (Four f g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits3 m1 (Three a b c) d e f (One g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits3 m1 (Three a b c) d e f (Two g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits3 m1 (Three a b c) d e f (Three g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits3 m1 (Three a b c) d e f (Four g h i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 addDigits3 m1 (Four a b c d) e f g (One h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits3 m1 (Four a b c d) e f g (Two h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits3 m1 (Four a b c d) e f g (Three h i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 addDigits3 m1 (Four a b c d) e f g (Four h i j k) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2 appendTree4 :: Measured a => FingerTree a -> a -> a -> a -> a -> FingerTree a -> FingerTree a appendTree4 Empty a b c d xs = a <| b <| c <| d <| xs appendTree4 xs a b c d Empty = xs |> a |> b |> c |> d appendTree4 (Single x) a b c d xs = x <| a <| b <| c <| d <| xs appendTree4 xs a b c d (Single x) = xs |> a |> b |> c |> d |> x appendTree4 (Deep _ pr1 m1 sf1) a b c d (Deep _ pr2 m2 sf2) = deep pr1 (addDigits4 m1 sf1 a b c d pr2 m2) sf2 addDigits4 :: Measured a => FingerTree (Node a) -> Digit a -> a -> a -> a -> a -> Digit a -> FingerTree (Node a) -> FingerTree (Node a) addDigits4 m1 (One a) b c d e (One f) m2 = appendTree2 m1 (node3 a b c) (node3 d e f) m2 addDigits4 m1 (One a) b c d e (Two f g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits4 m1 (One a) b c d e (Three f g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits4 m1 (One a) b c d e (Four f g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits4 m1 (Two a b) c d e f (One g) m2 = appendTree3 m1 (node3 a b c) (node2 d e) (node2 f g) m2 addDigits4 m1 (Two a b) c d e f (Two g h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits4 m1 (Two a b) c d e f (Three g h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits4 m1 (Two a b) c d e f (Four g h i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 addDigits4 m1 (Three a b c) d e f g (One h) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node2 g h) m2 addDigits4 m1 (Three a b c) d e f g (Two h i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits4 m1 (Three a b c) d e f g (Three h i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 addDigits4 m1 (Three a b c) d e f g (Four h i j k) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2 addDigits4 m1 (Four a b c d) e f g h (One i) m2 = appendTree3 m1 (node3 a b c) (node3 d e f) (node3 g h i) m2 addDigits4 m1 (Four a b c d) e f g h (Two i j) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node2 g h) (node2 i j) m2 addDigits4 m1 (Four a b c d) e f g h (Three i j k) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node2 j k) m2 addDigits4 m1 (Four a b c d) e f g h (Four i j k l) m2 = appendTree4 m1 (node3 a b c) (node3 d e f) (node3 g h i) (node3 j k l) m2 ---------------- -- 4.4 Splitting ---------------- -- | /O(log(min(i,n-i)))/. Split a sequence at a point where the predicate -- on the accumulated measure changes from 'False' to 'True'. -- -- For predictable results, one should ensure that there is only one such -- point, i.e. that the predicate is /monotonic/. split :: Measured a => (Measure a -> Bool) -> FingerTree a -> (FingerTree a, FingerTree a) split _ Empty = (Empty, Empty) split p xs | p (measure xs) = (l, x <| r) | otherwise = (xs, Empty) where Split l x r = splitTree p mempty xs -- | /O(log(min(i,n-i)))/. -- Given a monotonic predicate @p@, @'takeUntil' p t@ is the largest -- prefix of @t@ whose measure does not satisfy @p@. -- -- * @'takeUntil' p t = 'fst' ('split' p t)@ takeUntil :: Measured a => (Measure a -> Bool) -> FingerTree a -> FingerTree a takeUntil p = fst . split p -- | /O(log(min(i,n-i)))/. -- Given a monotonic predicate @p@, @'dropUntil' p t@ is the rest of @t@ -- after removing the largest prefix whose measure does not satisfy @p@. -- -- * @'dropUntil' p t = 'snd' ('split' p t)@ dropUntil :: Measured a => (Measure a -> Bool) -> FingerTree a -> FingerTree a dropUntil p = snd . split p data Split t a = Split t a t splitTree :: Measured a => (Measure a -> Bool) -> Measure a -> FingerTree a -> Split (FingerTree a) a splitTree _ _ Empty = illegal_argument "splitTree" splitTree _ _ (Single x) = Split Empty x Empty splitTree p i (Deep _ pr m sf) | p vpr = let Split l x r = splitDigit p i pr in Split (maybe Empty digitToTree l) x (deepL r m sf) | p vm = let Split ml xs mr = splitTree p vpr m Split l x r = splitNode p (vpr `mappendVal` ml) xs in Split (deepR pr ml l) x (deepL r mr sf) | otherwise = let Split l x r = splitDigit p vm sf in Split (deepR pr m l) x (maybe Empty digitToTree r) where vpr = i <> measure pr vm = vpr `mappendVal` m -- Avoid relying on right identity (cf Exercise 7) mappendVal :: Measured a => Measure a -> FingerTree a -> Measure a mappendVal v Empty = v mappendVal v t = v <> measure t deepL :: Measured a => Maybe (Digit a) -> FingerTree (Node a) -> Digit a -> FingerTree a deepL Nothing m sf = rotL m sf deepL (Just pr) m sf = deep pr m sf deepR :: Measured a => Digit a -> FingerTree (Node a) -> Maybe (Digit a) -> FingerTree a deepR pr m Nothing = rotR pr m deepR pr m (Just sf) = deep pr m sf splitNode :: Measured a => (Measure a -> Bool) -> Measure a -> Node a -> Split (Maybe (Digit a)) a splitNode p i (Node2 _ a b) | p va = Split Nothing a (Just (One b)) | otherwise = Split (Just (One a)) b Nothing where va = i <> measure a splitNode p i (Node3 _ a b c) | p va = Split Nothing a (Just (Two b c)) | p vab = Split (Just (One a)) b (Just (One c)) | otherwise = Split (Just (Two a b)) c Nothing where va = i <> measure a vab = va <> measure b splitDigit :: Measured a => (Measure a -> Bool) -> Measure a -> Digit a -> Split (Maybe (Digit a)) a splitDigit _ i (One a) = i `seq` Split Nothing a Nothing splitDigit p i (Two a b) | p va = Split Nothing a (Just (One b)) | otherwise = Split (Just (One a)) b Nothing where va = i <> measure a splitDigit p i (Three a b c) | p va = Split Nothing a (Just (Two b c)) | p vab = Split (Just (One a)) b (Just (One c)) | otherwise = Split (Just (Two a b)) c Nothing where va = i <> measure a vab = va <> measure b splitDigit p i (Four a b c d) | p va = Split Nothing a (Just (Three b c d)) | p vab = Split (Just (One a)) b (Just (Two c d)) | p vabc = Split (Just (Two a b)) c (Just (One d)) | otherwise = Split (Just (Three a b c)) d Nothing where va = i <> measure a vab = va <> measure b vabc = vab <> measure c ------------------ -- Transformations ------------------ -- | /O(n)/. The reverse of a sequence. reverse :: Measured a => FingerTree a -> FingerTree a reverse = reverseTree id reverseTree :: Measured b => (a -> b) -> FingerTree a -> FingerTree b reverseTree _ Empty = Empty reverseTree f (Single x) = Single (f x) reverseTree f (Deep _ pr m sf) = deep (reverseDigit f sf) (reverseTree (reverseNode f) m) (reverseDigit f pr) reverseNode :: Measured b => (a -> b) -> Node a -> Node b reverseNode f (Node2 _ a b) = node2 (f b) (f a) reverseNode f (Node3 _ a b c) = node3 (f c) (f b) (f a) reverseDigit :: (a -> b) -> Digit a -> Digit b reverseDigit f (One a) = One (f a) reverseDigit f (Two a b) = Two (f b) (f a) reverseDigit f (Three a b c) = Three (f c) (f b) (f a) reverseDigit f (Four a b c d) = Four (f d) (f c) (f b) (f a) illegal_argument :: String -> a illegal_argument name = error $ "Logic error: " ++ name ++ " called with illegal argument" {- $example Particular abstract data types may be implemented by defining element types with suitable 'Measured' instances. (from section 4.5 of the paper) Simple sequences can be implemented using a 'Sum' monoid as a measure: > newtype Elem a = Elem { getElem :: a } > > instance Measured (Elem a) where > type Measure (Elem a) = Sum Int > measure (Elem _) = Sum 1 > > newtype Seq a = Seq (FingerTree (Elem a)) Then the measure of a subsequence is simply its length. This representation supports log-time extraction of subsequences: > take :: Int -> Seq a -> Seq a > take k (Seq xs) = Seq (takeUntil (> Sum k) xs) > > drop :: Int -> Seq a -> Seq a > drop k (Seq xs) = Seq (dropUntil (> Sum k) xs) The module @Data.Sequence@ is an optimized instantiation of this type. -}
pawel-n/fingertree-tf
Data/FingerTree.hs
bsd-3-clause
32,775
0
16
8,838
15,731
7,754
7,977
611
2
{- This is the Main module for the HaCoTeB project. It is separated from the HaCoTeB module to allow for later reuse and to differentiate between the tool and its usage. -} {-# LANGUAGE RecordWildCards #-} module Main where import System.Console.CmdArgs import HaCoTeB main = do Options {..} <- cmdArgs options -- as defined in HaCoTeB.Options convert file
mihaimaruseac/HaCoTeB
src/Main.hs
bsd-3-clause
367
0
9
68
43
24
19
7
1
{-# LANGUAGE GADTs, StandaloneDeriving, KindSignatures #-} import System.Environment import System.Directory import System.FilePath.Find import System.FilePath.Posix as FilePath import qualified Graphics.Exif as Ex data Field data Exif :: * -> * where Manufacturer :: Exif String Model :: Exif String Orientation :: Exif String IsoSpeed :: Exif Int Field :: (Show t) => Exif t -> t -> Exif Field deriving instance Show (Exif a) type ExifProperties = [Exif Field] type FileName = String type FileExtension = String type FileDirectory = String data SimpleFile where SimpleFileC :: FileName -> FileDirectory -> FileExtension -> SimpleFile deriving Show data File :: * where -- don't seem to need a gadt/phantom ImageFile :: SimpleFile -> ExifProperties -> File DefaultFile :: SimpleFile -> File deriving Show {-- type Files = [File] import :: Directory -> Files import d = some pipe filter... query :: Files -> Query -> Files query fs q = fold fs q --} search pat dir = find always (fileName ~~? pat) dir fromExif :: (String, String) -> ExifProperties -> ExifProperties fromExif ("Manufacturer", v) l = Field Manufacturer v : l fromExif ("Model", v) l = Field Model v : l fromExif ("Orientation", v) l = Field Orientation v : l fromExif ("IsoSpeed", v) l = Field Manufacturer v : l -- FIXME fromExif (_, v) l = l mkSimpleFile f = SimpleFileC name path ext where (path, name) = FilePath.splitFileName f ext = FilePath.takeExtension f mkFile ".jpg" f = do exif <- Ex.fromFile f exiftags <- Ex.allTags exif let fields = foldr fromExif [] exiftags let sf = mkSimpleFile f return $ ImageFile sf fields mkFile ext f = do let (path, name) = FilePath.splitFileName f return $ DefaultFile $ mkSimpleFile f printFileMeta f = do defaultf <- mkFile (FilePath.takeExtension f) f putStrLn (show defaultf) main = do [pat] <- getArgs dir <- getCurrentDirectory files <- search pat dir mapM_ printFileMeta files -- test test = withArgs ["*"] main
gregor-samsa/hs.test
iyd1.hs
bsd-3-clause
2,102
0
11
493
631
329
302
-1
-1
import ZuriHac.Plays.XSink main :: IO () main = run
bitonic/zurihac-plays
app/xsink.hs
bsd-3-clause
53
0
6
10
22
12
10
3
1
module Reactive.Bacon.Core where import Control.Monad import Prelude hiding (map, filter) class Observable s where (==>) :: s a -> (a -> IO()) -> IO () (>>=!) :: IO (s a) -> (a -> IO()) -> IO () (>>=!) action f = action >>= \observable -> (observable ==> f) infixl 1 >>=! data EventStream a = EventStream { subscribe :: (EventSink a -> IO Disposable) } type EventSink a = (Event a -> IO (HandleResult)) data Event a = Next a | End data HandleResult = More | NoMore type Disposable = IO () class EventSource s where toEventStream :: s a -> EventStream a instance EventSource EventStream where toEventStream = id instance Observable EventStream where (==>) src f = void $ subscribe (toEventStream src) $ toObserver f instance Functor Event where fmap f (Next a) = Next (f a) fmap _ End = End instance Show a => Show (Event a) where show (Next x) = show x show End = "<END>" instance Eq a => Eq (Event a) where (==) End End = True (==) (Next x) (Next y) = (x==y) (==) _ _ = False obs :: EventSource s => s a -> EventStream a obs = toEventStream neverE :: EventStream a neverE = EventStream $ \_ -> return $ (return ()) toObserver :: (a -> IO()) -> EventSink a toObserver next = sink where sink (Next x) = next x >> return More sink End = return NoMore toEventObserver :: (Event a -> IO()) -> EventSink a toEventObserver next = sink where sink event = next event >> return More -- | Reactive property. Differences from EventStream: -- - addListener function must always deliver the latest known value to the new listener -- -- So a Property is roughly an EventStream that stores its latest value so -- that it is always available for new listeners. Doesn't mean it has to be -- up to date if it has been without listeners for a while. data Property a = Property { addPropertyListener :: PropertySink a -> IO Disposable } class PropertySource s where toProperty :: s a -> Property a instance PropertySource Property where toProperty = id data PropertyEvent a = Initial a | Update a | EndUpdate type PropertySink a = PropertyEvent a -> IO HandleResult
raimohanska/reactive-bacon
src/Reactive/Bacon/Core.hs
bsd-3-clause
2,133
0
12
464
759
397
362
47
2
module Valkyrie.Valkyrie where import Valkyrie.Types import Control.Applicative import Control.Monad import Control.Monad.Trans instance Monad m => Functor (ValkyrieM m) where fmap = liftM instance Monad m => Applicative (ValkyrieM m) where pure = return (<*>) = ap instance Monad m => Monad (ValkyrieM m) where return x = ValkyrieM $ \v -> return (x, v) (>>=) (ValkyrieM x) f = ValkyrieM $ \v -> x v >>= \(x', v') -> (runValkyrieM (f x')) v' instance MonadTrans ValkyrieM where lift mx = ValkyrieM $ \v -> mx >>= \x -> return (x, v) instance (MonadIO m) => MonadIO (ValkyrieM m) where liftIO mx = ValkyrieM $ \v -> liftIO mx >>= \x -> return (x, v) get :: Monad m => ValkyrieM m Valkyrie get = ValkyrieM $ \v -> return (v, v) put :: Monad m => Valkyrie -> ValkyrieM m () put v = ValkyrieM $ \_ -> return ((), v) modify :: Monad m => (Valkyrie -> m Valkyrie) -> ValkyrieM m () modify f = do valk <- get valk' <- lift $ f valk put valk'
Feeniks/valkyrie
src/Valkyrie/Valkyrie.hs
bsd-3-clause
998
0
14
241
456
237
219
26
1
import Test.Cabal.Prelude main = cabalTest $ cabal' "new-run" ["foo"] >>= assertOutputContains "Hello World"
themoritz/cabal
cabal-testsuite/PackageTests/NewBuild/CmdRun/Datafiles/cabal.test.hs
bsd-3-clause
114
0
8
18
31
16
15
3
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} module ECC.Code.LDPC.GPU.CUDA.TwoArrays where import ECC.Code.LDPC.Utils import ECC.Types import ECC.Puncture import Data.Char (isDigit) import qualified Data.Matrix as M import Data.Bit import Data.Bits import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Storable as S import qualified Data.Matrix.QuasiCyclic as Q import Debug.Trace import qualified ECC.Code.LDPC.Fast.Encoder as E import Data.Monoid -- import Foreign.CUDA hiding (launchKernel) import Foreign.CUDA.Runtime.Marshal as RM hiding (AllocFlag (..)) import Foreign.CUDA.Driver.Marshal (registerArray, AllocFlag (..)) import Foreign.CUDA.Types -- import qualified Foreign.CUDA.Driver as CUDA import Foreign.CUDA.Driver.Context.Base import Foreign.CUDA.Driver.Exec import qualified Foreign.CUDA.Driver.Device as CUDA import qualified Foreign.CUDA.Driver.Stream as Stream import Foreign.CUDA.Driver.Module import Foreign.Storable (sizeOf) import Foreign.ForeignPtr import qualified Foreign.Marshal as F import Data.IORef import GHC.Int import Control.DeepSeq import Data.Foldable (fold) import Control.Monad --(liftM2) import GHC.Conc import GHC.Float type IntT = Int32 type FloatTy = Float --Double float_t_width :: Int float_t_width = sizeOf (undefined :: FloatTy) data CudaAllocations = CudaAllocations { cm :: Module } code :: Code code = mkLDPC_CodeIO "two-arrays" 1 E.encoder decoder initialize finalize pokeListArrayAsync :: S.Storable a => S.Vector a -> DevicePtr a -> Maybe Stream -> IO () pokeListArrayAsync !xs !dptr !stream = do let len = S.length xs (fptr, _) = S.unsafeToForeignPtr0 xs withForeignPtr fptr (\p -> pokeArrayAsync len (HostPtr p) dptr stream) swapRefs :: IORef a -> IORef a -> IORef a -> IO () swapRefs tempRef xRef yRef = do x <- readIORef xRef y <- readIORef yRef atomicWriteIORef tempRef x atomicWriteIORef xRef y temp <- readIORef tempRef atomicWriteIORef yRef temp convertToFloatT :: [Double] -> [FloatTy] convertToFloatT = map realToFrac maxBlockSize :: IntT maxBlockSize = 1024 decoder :: CudaAllocations -> Q.QuasiCyclic Integer -> IO (Rate -> Int -> U.Vector Double -> IO (Maybe (U.Vector Bool))) decoder CudaAllocations{..} arr@(Q.QuasiCyclic sz _) = do (mLet0, offsets, rowCount, colCount) <- init'd let rowsPerBlock | rowCount <= maxBlockSize = rowCount | otherwise = rowCount `div` 2 colsPerBlock | colCount <= maxBlockSize = colCount | otherwise = colCount `div` 4 rowBlockSize | rowCount <= maxBlockSize = rowCount `div` 2 | otherwise = rowCount `div` 4 colBlockSize = colCount `div` 22 productColsPerBlock = colBlockSize `div` 2 makeNonzeroMatFun <- getFun cm "makeNonzeroMat" tanhTransformFun <- getFun cm "tanhTransform" setToOneFun <- getFun cm "setToOne" insertOnesFun <- getFun cm "insertOnes" selfProductFun <- getFun cm "selfProduct" atanhTransformFun <- getFun cm "atanhTransform" updateLamFun <- getFun cm "updateLamT" parityRowResultsFun <- getFun cm "parityRowResults" checkParityFun <- getFun cm "checkParity" memset mLet0 (fromIntegral (rowCount * colCount * fromIntegral float_t_width)) 0 mLetRef <- newIORef mLet0 newMLet0 <- mallocArray (fromIntegral $ rowCount * colCount) :: IO (DevicePtr FloatTy) newMLetRef <- newIORef newMLet0 tempRef <- newIORef =<< (mallocArray 1 :: IO (DevicePtr FloatTy)) -- rowResults <- mallocArray (fromIntegral rowCount) :: IO (DevicePtr Int32) partials <- mallocArray (fromIntegral rowCount) :: IO (DevicePtr FloatTy) print (rowCount, colCount) print (colCount*rowCount) mLetT <- mallocArray (fromIntegral $ rowCount * colCount) :: IO (DevicePtr FloatTy) let orig_lam_len = fromIntegral colCount*sz :: Int orig_lam_dev <- mallocArray orig_lam_len :: IO (DevicePtr FloatTy) lam_dev <- mallocArray orig_lam_len :: IO (DevicePtr FloatTy) pop_dev <- newListArray [0] :: IO (DevicePtr Int32) done_dev <- newListArray [0] :: IO (DevicePtr Int32) stream1 <- Stream.create [] stream2 <- Stream.create [] mletStream <- Stream.create [] -- putStr "atanh compute occupancy: " -- -- (fromIntegral (colCount `div` colBlockSize), fromIntegral (rowCount `div` rowBlockSize), 1) -- -- (fromIntegral colBlockSize,fromIntegral rowBlockSize,1) -- print (colBlockSize * rowBlockSize) return $ \rate maxIterations orig_lam -> do let orig_lam_stor = S.map double2Float $ U.convert orig_lam :: S.Vector FloatTy orig_lam_list = U.toList orig_lam -- pokeListArray orig_lam_list orig_lam_dev -- pokeListArray orig_lam_list lam_dev pokeListArrayAsync orig_lam_stor orig_lam_dev (Just stream1) pokeListArrayAsync orig_lam_stor lam_dev (Just stream2) pokeListArray [0] pop_dev lamResultRef <- newIORef lam_dev mLet' <- readIORef mLetRef memset mLet' (fromIntegral $ rowCount * colCount * fromIntegral float_t_width) 0 let go !iters | iters >= maxIterations = writeIORef lamResultRef orig_lam_dev | otherwise = do mLet <- readIORef mLetRef newMLet <- readIORef newMLetRef -- Check parity every 5th iteration parity <- if True --iters < 3 || iters `rem` 5 == 0 || iters == maxIterations - 1 then do launchKernel parityRowResultsFun (1, fromIntegral rowCount, 1) (fromIntegral colCount, 1, 1) 0 Nothing [VArg done_dev ,VArg lam_dev ,IArg rowCount ,IArg colCount ,IArg (fromIntegral sz) ,VArg offsets ] [done] <- peekListArray 1 done_dev return (done > 0) else return True writeIORef lamResultRef lam_dev when parity $ do -- Update matrix let nr = 4 launchKernel selfProductFun (fromIntegral rowCount `div` nr, 1, 1) (nr, fromIntegral colCount, 1) (fromIntegral colCount * nr * float_t_width) Nothing [VArg lam_dev ,VArg mLet ,VArg newMLet ,VArg mLetT ,IArg rowCount ,IArg colCount ,IArg (fromIntegral sz) ,VArg offsets ] copyArray orig_lam_len orig_lam_dev lam_dev swapRefs tempRef mLetRef newMLetRef -- Update guess launchKernel updateLamFun -- (fromIntegral sz, 1, 1) -- (fromIntegral colCount, 1, 1) (fromIntegral (colCount `div` colBlockSize), fromIntegral (rowCount `div` rowBlockSize), 1) (fromIntegral colBlockSize, fromIntegral rowBlockSize, 1) -- (fromIntegral sz, 1, 1) -- (fromIntegral colCount, 1, 1) 0 Nothing [VArg lam_dev ,VArg mLetT ,IArg rowCount ,IArg colCount ,IArg (fromIntegral sz) ,VArg offsets ] go (iters+1) Stream.block stream1 Stream.block stream2 go 0 lamPtr <- readIORef lamResultRef result <- peekListArray orig_lam_len lamPtr let r = Just $! U.map hard $! S.convert $! U.fromList result -- free orig_lam_dev -- free lam_dev -- free pop_dev -- enqueueFree orig_lam_dev -- enqueueFree lam_dev -- enqueueFree pop_dev return $! r where init'd = initMatrixlet arr initialize :: IO CudaAllocations initialize = do dummy <- RM.mallocArray 1 :: IO (DevicePtr Int) -- Sets up CUDA context cm <- loadFile "cudabits/two_arrays.ptx" RM.free dummy return (CudaAllocations {..}) finalize :: CudaAllocations -> IO () finalize CudaAllocations {..} = do return () initMatrixlet :: Q.QuasiCyclic Integer -> IO (DevicePtr FloatTy, DevicePtr IntT, IntT, IntT) initMatrixlet (Q.QuasiCyclic sz qm) = do mLetPtr <- mallocArray (mLetRowCount * mLetColCount) offsetsPtr <- newListArray offsets return (mLetPtr, offsetsPtr, fromIntegral mLetRowCount, fromIntegral mLetColCount) where mLetRowCount = M.nrows qm*sz mLetColCount = M.ncols qm pop :: [Integer] -> Integer pop = getSum . foldMap (\n -> if n == 0 then 0 else 1) -- The number must be a power of two, because there is only one bit set. g :: Integer -> IntT g x | x `testBit` 0 = 0 | x == 0 = error "got to zero; should never happen" | otherwise = 1 + g (x `shiftR` 1) offsets :: [IntT] offsets = foldMap (\n -> case n of 0 -> [-1] _ -> [g n]) $ qm
ku-fpg/ecc-ldpc
src/ECC/Code/LDPC/GPU/CUDA/TwoArrays.hs
bsd-3-clause
9,684
91
17
3,172
2,267
1,213
1,054
204
3
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] - [@ISO639-2@] - [@ISO639-3@] kap [@Native name@] бежкьалас миц [@English name@] Bezhta -} module Text.Numeral.Language.KAP.TestData (cardinals) where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" Prelude ( Num ) import "numerals" Text.Numeral.Grammar.Reified ( defaultInflection ) import "this" Text.Numeral.Test ( TestData ) -------------------------------------------------------------------------------- -- Test data -------------------------------------------------------------------------------- {- Sources: http://www.languagesandnumbers.com/how-to-count-in-bezhta/en/kap/ -} cardinals ∷ (Num i) ⇒ TestData i cardinals = [ ( "default" , defaultInflection , [ (0, "nol") , (1, "hõs") , (2, "q’ona") , (3, "łana") , (4, "ṏq’önä") , (5, "łina") , (6, "iłna") , (7, "aƛna") , (8, "beƛna") , (9, "äč’ena") , (10, "ac’ona") , (11, "ac’ona hõs") , (12, "ac’ona q’ona") , (13, "ac’ona łana") , (14, "ac’ona ṏq’önä") , (15, "ac’ona łina") , (16, "ac’ona iłna") , (17, "ac’ona aƛna") , (18, "ac’ona beƛna") , (19, "ac’ona äč’ena") , (20, "qona") , (21, "qona hõs") , (22, "qona q’ona") , (23, "qona łana") , (24, "qona ṏq’önä") , (25, "qona łina") , (26, "qona iłna") , (27, "qona aƛna") , (28, "qona beƛna") , (29, "qona äč’ena") , (30, "łanayig") , (31, "łanayig hõs") , (32, "łanayig q’ona") , (33, "łanayig łana") , (34, "łanayig ṏq’önä") , (35, "łanayig łina") , (36, "łanayig iłna") , (37, "łanayig aƛna") , (38, "łanayig beƛna") , (39, "łanayig äč’ena") , (40, "ṏq’önäyig") , (41, "ṏq’önäyig hõs") , (42, "ṏq’önäyig q’ona") , (43, "ṏq’önäyig łana") , (44, "ṏq’önäyig ṏq’önä") , (45, "ṏq’önäyig łina") , (46, "ṏq’önäyig iłna") , (47, "ṏq’önäyig aƛna") , (48, "ṏq’önäyig beƛna") , (49, "ṏq’önäyig äč’ena") , (50, "łinayig") , (51, "łinayig hõs") , (52, "łinayig q’ona") , (53, "łinayig łana") , (54, "łinayig ṏq’önä") , (55, "łinayig łina") , (56, "łinayig iłna") , (57, "łinayig aƛna") , (58, "łinayig beƛna") , (59, "łinayig äč’ena") , (60, "iłnayig") , (61, "iłnayig hõs") , (62, "iłnayig q’ona") , (63, "iłnayig łana") , (64, "iłnayig ṏq’önä") , (65, "iłnayig łina") , (66, "iłnayig iłna") , (67, "iłnayig aƛna") , (68, "iłnayig beƛna") , (69, "iłnayig äč’ena") , (70, "aƛnayig") , (71, "aƛnayig hõs") , (72, "aƛnayig q’ona") , (73, "aƛnayig łana") , (74, "aƛnayig ṏq’önä") , (75, "aƛnayig łina") , (76, "aƛnayig iłna") , (77, "aƛnayig aƛna") , (78, "aƛnayig beƛna") , (79, "aƛnayig äč’ena") , (80, "beƛnayig") , (81, "beƛnayig hõs") , (82, "beƛnayig q’ona") , (83, "beƛnayig łana") , (84, "beƛnayig ṏq’önä") , (85, "beƛnayig łina") , (86, "beƛnayig iłna") , (87, "beƛnayig aƛna") , (88, "beƛnayig beƛna") , (89, "beƛnayig äč’ena") , (90, "äč’enayig") , (91, "äč’enayig hõs") , (92, "äč’enayig q’ona") , (93, "äč’enayig łana") , (94, "äč’enayig ṏq’önä") , (95, "äč’enayig łina") , (96, "äč’enayig iłna") , (97, "äč’enayig aƛna") , (98, "äč’enayig beƛna") , (99, "äč’enayig äč’ena") , (100, "hõsč’it’") , (101, "hõsč’it’ hõs") , (102, "hõsč’it’ q’ona") , (103, "hõsč’it’ łana") , (104, "hõsč’it’ ṏq’önä") , (105, "hõsč’it’ łina") , (106, "hõsč’it’ iłna") , (107, "hõsč’it’ aƛna") , (108, "hõsč’it’ beƛna") , (109, "hõsč’it’ äč’ena") , (110, "hõsč’it’ ac’ona") , (123, "hõsč’it’ qona łana") , (200, "q’onač’it’") , (300, "łanač’it’") , (321, "łanač’it’ qona hõs") , (400, "ṏq’önäč’it’") , (500, "łinač’it’") , (600, "iłnač’it’") , (700, "aƛnač’it’") , (800, "beƛnač’it’") , (900, "äč’enač’it’") , (909, "äč’enač’it’ äč’ena") , (990, "äč’enač’it’ äč’enayig") , (999, "äč’enač’it’ äč’enayig äč’ena") , (1000, "hazay") ] ) ]
telser/numerals
src-test/Text/Numeral/Language/KAP/TestData.hs
bsd-3-clause
5,198
0
8
1,373
1,219
815
404
137
1
{-# 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 Name 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 -- 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 'defaultWarnErrLogger' 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 'defaultWarnErrLogger'. -- 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. setSession $ 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. -- It will also keep ic_int_print and ic_monad if their names are from -- external packages. discardIC :: HscEnv -> HscEnv discardIC hsc_env = hsc_env { hsc_IC = new_ic { ic_int_print = keep_external_name ic_int_print , ic_monad = keep_external_name ic_monad } } where dflags = ic_dflags old_ic old_ic = hsc_IC hsc_env new_ic = emptyInteractiveContext dflags keep_external_name ic_name | nameIsFromExternalPackage this_pkg old_name = old_name | otherwise = ic_name new_ic where this_pkg = thisPackage dflags old_name = ic_name old_ic 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 name_exe = do #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' <- fmap (<.> "exe") name #else name' <- name #endif mainModuleSrcPath' <- mainModuleSrcPath -- #9930: don't clobber input files (unless they ask for it) if name' == mainModuleSrcPath' then throwGhcException . UsageError $ "default output name would overwrite the input file; " ++ "must specify -o explicitly" else Just name' 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, IsBoot) -- | 'Bool' indicating if a module is a boot module or not. We need to treat -- boot modules specially when building compilation graphs, since they break -- cycles. Regular source files and signature files are treated equivalently. data IsBoot = IsBoot | NotBoot deriving (Ord, Eq, Show, Read) -- | Tests if an 'HscSource' is a boot file, primarily for constructing -- elements of 'BuildModule'. hscSourceToIsBoot :: HscSource -> IsBoot hscSourceToIsBoot HsBootFile = IsBoot hscSourceToIsBoot _ = NotBoot mkBuildModule :: ModSummary -> BuildModule mkBuildModule ms = (ms_mod ms, if isBootSummary ms then IsBoot else NotBoot) -- | 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 NotBoot) ++ zip home_src_imps (repeat IsBoot) -- 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 maybeGetIfaceDate :: DynFlags -> ModLocation -> IO (Maybe UTCTime) maybeGetIfaceDate dflags location | writeInterfaceOnlyMode dflags -- Minor optimization: it should be harmless to check the hi file location -- always, but it's better to avoid hitting the filesystem if possible. = modificationTimeIfExists (ml_hi_file location) | otherwise = return Nothing -- | 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 mb_if_date = ms_iface_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 -- See Note [Recompilation checking when typechecking only] | writeInterfaceOnlyMode dflags, Just if_date <- mb_if_date, if_date >= hs_date -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "skipping tc'd mod:" <+> ppr this_mod_name) compile_it Nothing SourceUnmodified _otherwise -> do liftIO $ debugTraceMsg (hsc_dflags hsc_env) 5 (text "compiling mod:" <+> ppr this_mod_name) compile_it Nothing SourceModified -- Note [Recompilation checking when typechecking only] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- If we are compiling with -fno-code -fwrite-interface, there won't -- be any object code that we can compare against, nor should there -- be: we're *just* generating interface files. In this case, we -- want to check if the interface file is new, in lieu of the object -- file. See also Trac #9243. -- 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, hscSourceToIsBoot 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), hscSourceToIsBoot (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 -- IsBoot; else NotBoot -- The nodes of the graph are keyed by (mod, is boot?) pairs -- NB: hsig files show up as *normal* nodes (not boot!), since they don't -- participate in cycles (for now) type NodeKey = (ModuleName, IsBoot) type NodeMap a = Map.Map NodeKey a msKey :: ModSummary -> NodeKey msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod, hscSourceToIsBoot 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 calcDeps rootSummariesOk) root_map return summs where -- When we're compiling a signature file, we have an implicit -- dependency on what-ever the signature's implementation is. -- (But not when we're type checking!) calcDeps summ | HsigFile <- ms_hsc_src summ , Just m <- getSigOf (hsc_dflags hsc_env) (moduleName (ms_mod summ)) , modulePackageKey m == thisPackage (hsc_dflags hsc_env) = (noLoc (moduleName m), NotBoot) : msDeps summ | otherwise = msDeps summ 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 NotBoot (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,IsBoot)] -- 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 (calcDeps s ++ ss) (Map.insert key [Right s] done) where key = (unLoc wanted_mod, is_boot) 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, IsBoot)] msDeps s = concat [ [(m,IsBoot), (m,NotBoot)] | m <- ms_home_srcimps s ] ++ [ (m,NotBoot) | m <- ms_home_imps s ] home_imps :: [Located (ImportDecl RdrName)] -> [Located ModuleName] home_imps imps = [ ideclName i | L _ i <- imps, isLocal (fmap snd $ 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 dflags = hsc_dflags hsc_env 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 NotBoot else return Nothing hi_timestamp <- maybeGetIfaceDate dflags location return old_summary{ ms_obj_date = obj_timestamp , ms_iface_date = hi_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 let hsc_src = if isHaskellSigFilename file then HsigFile else HsSrcFile (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 hi_timestamp <- maybeGetIfaceDate dflags location return (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_iface_date = hi_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 -> IsBoot -- IsBoot <=> 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, is_boot) 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 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 hi_timestamp <- maybeGetIfaceDate dflags location return (Just (Right old_summary{ ms_obj_date = obj_timestamp , ms_iface_date = hi_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' | IsBoot <- 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 -- NB: Despite the fact that is_boot is a top-level parameter, we -- don't actually know coming into this function what the HscSource -- of the module in question is. This is because we may be processing -- this module because another module in the graph imported it: in this -- case, we know if it's a boot or not because of the {-# SOURCE #-} -- annotation, but we don't know if it's a signature or a regular -- module until we actually look it up on the filesystem. let hsc_src = case is_boot of IsBoot -> HsBootFile _ | isHaskellSigFilename src_fn -> HsigFile | otherwise -> HsSrcFile 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 hi_timestamp <- maybeGetIfaceDate dflags location 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_iface_date = hi_timestamp, ms_obj_date = obj_timestamp }))) getObjTimestamp :: ModLocation -> IsBoot -> IO (Maybe UTCTime) getObjTimestamp location is_boot = if is_boot == IsBoot 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, IsBoot) | m <- ms_home_srcimps ms ] ++ [ (unLoc m, NotBoot) | 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)))
urbanslug/ghc
compiler/main/GhcMake.hs
bsd-3-clause
87,718
25
37
27,814
14,542
7,438
7,104
-1
-1
module ETA.CodeGen.Expr where import ETA.Core.CoreSyn import ETA.Types.Type import ETA.Types.TyCon import ETA.BasicTypes.Id import ETA.Prelude.PrimOp import ETA.StgSyn.StgSyn import ETA.BasicTypes.DataCon import ETA.Utils.Panic import ETA.Util import ETA.Debug import ETA.CodeGen.Utils import ETA.CodeGen.Monad import ETA.CodeGen.Name import ETA.CodeGen.Layout import ETA.CodeGen.Types import ETA.CodeGen.Closure import ETA.CodeGen.Env import ETA.CodeGen.Rts import ETA.CodeGen.Constr import ETA.CodeGen.Prim import ETA.CodeGen.ArgRep import {-# SOURCE #-} ETA.CodeGen.Bind (cgBind) import Codec.JVM import Data.Monoid((<>)) import Data.Foldable(fold) import Data.Maybe(mapMaybe) import Control.Monad(when, forM_, unless) cgExpr :: StgExpr -> CodeGen () cgExpr (StgApp fun args) = traceCg (str "StgApp" <+> ppr fun <+> ppr args) >> cgIdApp fun args cgExpr (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _) = cgIdApp a [] cgExpr (StgOpApp op args ty) = traceCg (str "StgOpApp" <+> ppr args <+> ppr ty) >> cgOpApp op args ty cgExpr (StgConApp con args) = traceCg (str "StgConApp" <+> ppr con <+> ppr args) >> cgConApp con args -- TODO: Deal with ticks cgExpr (StgTick t e) = traceCg (str "StgTick" <+> ppr t) >> cgExpr e cgExpr (StgLit lit) = emitReturn [mkLocDirect False $ cgLit lit] cgExpr (StgLet binds expr) = do cgBind binds cgExpr expr cgExpr (StgLetNoEscape _ _ binds expr) = cgLneBinds binds expr cgExpr (StgCase expr _ _ binder _ altType alts) = traceCg (str "StgCase" <+> ppr expr <+> ppr binder <+> ppr altType) >> cgCase expr binder altType alts cgExpr _ = unimplemented "cgExpr" cgLneBinds :: StgBinding -> StgExpr -> CodeGen () cgLneBinds (StgNonRec binder rhs) expr = do -- TODO: Optimize this to calculate the smallest type that can hold the target label <- newLabel targetLoc <- newTemp False jint (info, genBindCode) <- cgLetNoEscapeRhsBody binder rhs label 1 targetLoc n' <- peekNextLocal bindCode <- genBindCode n' addBinding info exprCode <- forkLneBody $ cgExpr expr let (bindLabel, argLocs) = expectJust "cgLneBinds:StgNonRec" . maybeLetNoEscape $ info emit $ fold (map storeDefault argLocs) <> letNoEscapeCodeBlocks label targetLoc [(bindLabel, bindCode)] exprCode cgLneBinds (StgRec pairs) expr = do label <- newLabel targetLoc <- newTemp False jint let lneInfos = snd $ foldr (\(a,b) (n,xs) -> (n - 1, (a,b,label,n,targetLoc):xs)) (length pairs, []) pairs result <- sequence $ map (\(a,b,c,d,e) -> cgLetNoEscapeRhsBody a b c d e) lneInfos n' <- peekNextLocal let (infos, genBindCodes) = unzip result (labels, argLocss) = unzip $ map (expectJust "cgLneBinds:StgRec" . maybeLetNoEscape) infos addBindings infos bindCodes <- sequence $ ($ n') <$> genBindCodes exprCode <- forkLneBody $ cgExpr expr emit $ fold (fold (map (map storeDefault) argLocss)) <> letNoEscapeCodeBlocks label targetLoc (zip labels bindCodes) exprCode cgLetNoEscapeRhsBody :: Id -> StgRhs -> Label -> Int -> CgLoc -> CodeGen (CgIdInfo, Int -> CodeGen Code) cgLetNoEscapeRhsBody binder (StgRhsClosure _ _ _ _ _ args body) jumpLabel target targetLoc = cgLetNoEscapeClosure binder (nonVoidIds args) body jumpLabel target targetLoc cgLetNoEscapeRhsBody binder (StgRhsCon _ con args) jumpLabel target targetLoc = cgLetNoEscapeClosure binder [] (StgConApp con args) jumpLabel target targetLoc cgLetNoEscapeClosure :: Id -> [NonVoid Id] -> StgExpr -> Label -> Int -> CgLoc -> CodeGen (CgIdInfo, Int -> CodeGen Code) cgLetNoEscapeClosure binder args body label target targetLoc = do argLocs <- mapM newIdLoc args let code n' = forkLneBody $ do bindArgs $ zip args argLocs setNextLocal n' cgExpr body return (lneIdInfo binder label target targetLoc argLocs, code) letNoEscapeCodeBlocks :: Label -> CgLoc -> [(Int, Code)] -> Code -> Code letNoEscapeCodeBlocks label targetLoc labelledCode body = storeDefault targetLoc <> startLabel label <> intSwitch (loadLoc targetLoc) labelledCode (Just body) maybeLetNoEscape :: CgIdInfo -> Maybe (Int, [CgLoc]) maybeLetNoEscape CgIdInfo { cgLocation = LocLne _label target _targetLoc argLocs } = Just (target, argLocs) maybeLetNoEscape _ = Nothing cgIdApp :: Id -> [StgArg] -> CodeGen () cgIdApp funId [] | isVoidTy (idType funId) = emitReturn [] cgIdApp funId args = do dflags <- getDynFlags funInfo <- getCgIdInfo funId selfLoopInfo <- getSelfLoop let cgFunId = cgId funInfo funName = idName cgFunId lfInfo = cgLambdaForm funInfo funLoc = cgLocation funInfo nArgs = length args vArgs = length $ filter (isVoidTy . stgArgType) args case getCallMethod dflags funName cgFunId lfInfo nArgs vArgs funLoc selfLoopInfo of ReturnIt -> traceCg (str "cgIdApp: ReturnIt") >> emitReturn [funLoc] EnterIt -> traceCg (str "cgIdApp: EnterIt") >> emitEnter funLoc SlowCall -> do traceCg (str "cgIdApp: SlowCall") argFtCodes <- getRepFtCodes args withContinuation $ slowCall dflags funLoc argFtCodes DirectEntry entryCode arity -> do traceCg (str "cgIdApp: DirectEntry") argFtCodes <- getRepFtCodes args withContinuation $ directCall False entryCode arity argFtCodes JumpToIt label cgLocs mLne -> do traceCg (str "cgIdApp: JumpToIt") codes <- getNonVoidArgCodes args emit $ multiAssign cgLocs codes <> maybe mempty (\(target, targetLoc) -> storeLoc targetLoc (iconst (locFt targetLoc) $ fromIntegral target)) mLne <> goto label emitEnter :: CgLoc -> CodeGen () emitEnter thunk = do sequel <- getSequel case sequel of Return -> emit $ enterMethod thunk <> greturn closureType AssignTo cgLocs -> do emit $ evaluateMethod thunk <> mkReturnEntry cgLocs cgConApp :: DataCon -> [StgArg] -> CodeGen () cgConApp con args | isUnboxedTupleCon con = do repCodes <- getNonVoidArgRepCodes args emitReturn $ map mkRepLocDirect repCodes | otherwise = do (idInfo, genInitCode) <- buildDynCon (dataConWorkId con) con args [] (initCode, _recIndexes, _dataFt) <- genInitCode emit initCode emitReturn [cgLocation idInfo] cgCase :: StgExpr -> Id -> AltType -> [StgAlt] -> CodeGen () cgCase (StgOpApp (StgPrimOp op) args _) binder (AlgAlt tyCon) alts | isEnumerationTyCon tyCon = do dflags <- getDynFlags tagExpr <- doEnumPrimop op args let closureCode = snd $ tagToClosure dflags tyCon tagExpr loadCode <- if not $ isDeadBinder binder then do bindLoc <- newIdLoc (NonVoid binder) bindArg (NonVoid binder) bindLoc emitAssign bindLoc closureCode return $ loadLoc bindLoc else return closureCode (maybeDefault, branches) <- cgAlgAltRhss (NonVoid binder) alts emit $ intSwitch (getTagMethod loadCode) branches maybeDefault where doEnumPrimop :: PrimOp -> [StgArg] -> CodeGen Code doEnumPrimop TagToEnumOp [arg] = getArgLoadCode (NonVoid arg) doEnumPrimop primop args = do codes <- cgPrimOp primop args return $ head codes cgCase (StgApp v []) _ (PrimAlt _) alts | isVoidRep (idPrimRep v) , [(DEFAULT, _, _, rhs)] <- alts = cgExpr rhs cgCase (StgApp v []) binder altType@(PrimAlt _) alts | isUnLiftedType (idType v) || repsCompatible = do unless repsCompatible $ panic "cgCase: reps do not match, perhaps a dodgy unsafeCoerce?" vInfo <- getCgIdInfo v binderLoc <- newIdLoc nvBinder emitAssign binderLoc (idInfoLoadCode vInfo) bindArgs [(nvBinder, binderLoc)] cgAlts nvBinder altType alts where repsCompatible = vRep == idPrimRep binder -- TODO: Allow integer conversions? nvBinder = NonVoid binder vRep = idPrimRep v cgCase scrut@(StgApp v []) _ (PrimAlt _) _ = do cgLoc <- newIdLoc (NonVoid v) withSequel (AssignTo [cgLoc]) $ cgExpr scrut panic "cgCase: bad unsafeCoerce!" -- TODO: Generate infinite loop here? cgCase (StgOpApp (StgPrimOp SeqOp) [StgVarArg a, _] _) binder altType alts = cgCase (StgApp a []) binder altType alts cgCase scrut binder altType alts = do altLocs <- mapM newIdLoc retBinders -- Take into account uses for unboxed tuples -- Case-of-case expressions need special care -- Since there can be multiple bindings to return -- binder. when (isCaseOfCase scrut) $ do emit $ fold (map storeDefault altLocs) withSequel (AssignTo altLocs) $ cgExpr scrut bindArgs $ zip retBinders altLocs cgAlts (NonVoid binder) altType alts where retBinders = chooseReturnBinders binder altType alts isCaseOfCase = go go (StgLet _ e) = go e go (StgTick _ e) = go e go (StgCase _ _ _ _ _ _ _) = True go _ = False chooseReturnBinders :: Id -> AltType -> [StgAlt] -> [NonVoid Id] chooseReturnBinders binder (PrimAlt _) _ = nonVoidIds [binder] chooseReturnBinders _ (UbxTupAlt _) [(_, ids, _, _)] = nonVoidIds ids chooseReturnBinders binder (AlgAlt _) _ = nonVoidIds [binder] chooseReturnBinders binder PolyAlt _ = nonVoidIds [binder] chooseReturnBinders _ _ _ = panic "chooseReturnBinders" cgAlts :: NonVoid Id -> AltType -> [StgAlt] -> CodeGen () cgAlts _ PolyAlt [(_, _, _, rhs)] = cgExpr rhs cgAlts _ (UbxTupAlt _) [(_, _, _, rhs)] = cgExpr rhs cgAlts binder (PrimAlt _) alts = do taggedBranches <- cgAltRhss binder alts binderLoc <- if null (nonVoidIds [unsafeStripNV binder]) then return $ mkLocDirect False (jint, mempty) else getCgLoc binder let (DEFAULT, deflt) = head taggedBranches taggedBranches' = [(lit, code) | (LitAlt lit, code) <- taggedBranches] emit $ litSwitch (locFt binderLoc) (loadLoc binderLoc) taggedBranches' deflt cgAlts binder (AlgAlt _) alts = do (maybeDefault, branches) <- cgAlgAltRhss binder alts binderLoc <- getCgLoc binder emit $ intSwitch (getTagMethod $ loadLoc binderLoc) branches maybeDefault cgAlts _ _ _ = panic "cgAlts" cgAltRhss :: NonVoid Id -> [StgAlt] -> CodeGen [(AltCon, Code)] cgAltRhss binder alts = forkAlts $ map cgAlt alts where cgAlt :: StgAlt -> (AltCon, CodeGen ()) cgAlt (con, binders, uses, rhs) = ( con , bindConArgs con binder binders uses >> cgExpr rhs ) bindConArgs :: AltCon -> NonVoid Id -> [Id] -> [Bool] -> CodeGen () bindConArgs (DataAlt con) binder args uses | not (null args), or uses = do dflags <- getDynFlags let conClass = dataConClass dflags con dataFt = obj conClass base <- getCgLoc binder emit $ loadLoc base <> gconv conType dataFt -- TODO: Take into account uses as well forM_ indexedFields $ \(i, (ft, (arg, use))) -> when use $ do let nvArg = NonVoid arg cgLoc <- newIdLoc nvArg emitAssign cgLoc $ dup dataFt <> getfield (mkFieldRef conClass (constrField i) ft) bindArg nvArg cgLoc -- TODO: Remove this pop in a clever way emit $ pop dataFt where indexedFields = indexList . mapMaybe (\(mb, args) -> case mb of Just m -> Just (m, args) Nothing -> Nothing) $ zip maybeFields (zip args uses) maybeFields = map repFieldType_maybe $ dataConRepArgTys con bindConArgs _ _ _ _ = return () cgAlgAltRhss :: NonVoid Id -> [StgAlt] -> CodeGen (Maybe Code, [(Int, Code)]) cgAlgAltRhss binder alts = do taggedBranches <- cgAltRhss binder alts let (maybeDefault, branches) = case taggedBranches of ((DEFAULT, rhs) : _) -> (Just rhs, allBranches) {- INVARIANT: length alts > 0 We select the *last* alternative since that will typically have a higher tag and will require more bytecode to perform the check if it's a simple case with 2 alternatives (the most frequent case). -} _ -> (Just $ snd remainingBranch, remainingBranches) (remainingBranches, remainingBranch) = (init allBranches, last allBranches) allBranches = [ (getDataConTag con, code) | (DataAlt con, code) <- taggedBranches ] return (maybeDefault, branches)
pparkkin/eta
compiler/ETA/CodeGen/Expr.hs
bsd-3-clause
12,571
0
22
3,163
4,182
2,062
2,120
273
6
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} -- {-# OPTIONS_GHC -cpp -DPiForallInstalled #-} -------------------------------------------------------------------- -- | -- Copyright : (c) Andreas Reuleaux 2015 -- License : BSD2 -- Maintainer: Andreas Reuleaux <rx@a-rx.info> -- Stability : experimental -- Portability: non-portable -- -- This module tests Pire's parser: sigma types -------------------------------------------------------------------- module ParserTests.SigmaTypes where import Test.Tasty import Test.Tasty.HUnit import Pire.Syntax import Pire.NoPos import Pire.Parser.ParseUtils import Pire.Parser.PiParseUtils import Pire.Parser.Expr import Pire.Forget import Pire.Untie import Bound #ifdef PiForallInstalled import qualified PiForall.Parser as P #endif -- sigma types, cf. beginning of test/Hw1.pi -- new as of May 2015 -- test w/ -- main' "sigma" parsingSigmaTypesU = testGroup "parsing sigma types - unit tests" $ tail [ undefined , let s = "{ x : A | B }" in testGroup ("sigma type '"++s++"'") $ tail [ undefined -- as a sigma type , testCase ("parsing sigmaTy '"++s++"'") $ (nopos $ parse sigmaTy s) @?= (Sigma "x" (V "A") (Scope (V (F (V "B"))))) -- and as an expr as well, course , testCase ("parsing expr '"++s++"'") $ (nopos $ parse expr s) @?= (Sigma "x" (V "A") (Scope (V (F (V "B"))))) , testCase ("parse & forget sigmaTy_ '"++s++"'") $ (forget $ parseP sigmaTy_ s) @?= (parseP sigmaTy s) ] #ifdef PiForallInstalled ++ tail [ undefined , testCase ("parse & untie expr '"++s++"'") $ (untie $ parse expr s) @?= (piParse P.expr s) ] #endif , let s = "\\ y . { x : A | B }" in testGroup ("bind op for sigma type: \""++s++"\"") $ tail [ undefined -- TODO seems silly, rethink , testCase ("parsing expr '"++s++"'") $ (parse expr s) @?= (parse expr s) , testCase ("parsing expr_ '"++s++"'") $ (parse expr_ s) @?= (parse expr_ s) -- , testCase ("parse & forget expr '"++s++"'") -- $ (parse expr s) @?= (parse expr s) ] , let s = "more stuff to come here... - more complicated: w/ whitespace etc" in testGroup ("sigma type '"++s++"'") $ tail [ undefined ] -- indent! ]
reuleaux/pire
tests/ParserTests/SigmaTypes.hs
bsd-3-clause
2,500
0
24
734
563
308
255
34
1
module Spec where import Test.Hspec import Challenge ( ranges ) main :: IO () main = hspec $ do describe "Challenge.ranges" $ do it "will return an empty list when no ranges exist" $ do ranges [] `shouldBe` ([] :: [String]) it "will return a single range" $ do ranges [1, 2] `shouldBe` ["1->2"] it "will return multiple ranges" $ do ranges [1, 2, 3, 4, 5, 8, 9, 10] `shouldBe` ["1->5", "8->10"] it "will return multiple ranges ignoring numbers that are not part of a range" $ do ranges [1, 2, 3, 5, 8, 9, 10, 12] `shouldBe` ["1->3", "8->10"]
mindm/2017Challenges
challenge_6/haskell/halogenandtoast/src/Spec.hs
mit
589
0
16
148
216
119
97
14
1
module Pos.Infra.Discovery ( module Pos.Infra.Discovery.Model.Class , module Pos.Infra.Discovery.Model.Neighbours ) where import Pos.Infra.Discovery.Model.Class import Pos.Infra.Discovery.Model.Neighbours
input-output-hk/pos-haskell-prototype
infra/src/Pos/Infra/Discovery.hs
mit
247
0
5
56
43
32
11
5
0
{-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Math.NumberTheory.PrimitiveRootsBench ( benchSuite ) where import Gauge.Main import Data.Constraint import Data.Maybe import Math.NumberTheory.Moduli.Multiplicative import Math.NumberTheory.Moduli.Singleton import Math.NumberTheory.Primes primRootWrap :: Integer -> Word -> Integer -> Bool primRootWrap p k g = case fromJust $ cyclicGroupFromFactors [(p', k)] of Some cg -> case proofFromCyclicGroup cg of Sub Dict -> isJust $ isPrimitiveRoot cg (fromInteger g) where p' = fromJust $ isPrime p primRootWrap2 :: Integer -> Word -> Integer -> Bool primRootWrap2 p k g = case fromJust $ cyclicGroupFromFactors [(two, 1), (p', k)] of Some cg -> case proofFromCyclicGroup cg of Sub Dict -> isJust $ isPrimitiveRoot cg (fromInteger g) where two = fromJust $ isPrime 2 p' = fromJust $ isPrime p cyclicWrap :: Integer -> Maybe (Some (CyclicGroup Integer)) cyclicWrap = cyclicGroupFromModulo benchSuite :: Benchmark benchSuite = bgroup "PrimRoot" [ bgroup "groupFromModulo" [ bench "3^20000" $ nf cyclicWrap (3^20000) -- prime to large power , bench "10000000000000061" $ nf cyclicWrap (10^16 + 61) -- large prime , bench "2*3^20000" $ nf cyclicWrap (2*3^20000) -- twice prime to large power , bench "10000000000000046" $ nf cyclicWrap (10^16 + 46) -- twice large prime , bench "224403121196654400" $ nf cyclicWrap 224403121196654400 -- highly composite ] , bgroup "check prim roots" [ bench "3^20000" $ nf (primRootWrap 3 20000) 2 -- prime to large power , bench "10000000000000061" $ nf (primRootWrap (10^16 + 61) 1) 3 -- large prime , bench "10000000000000061^2" $ nf (primRootWrap (10^16 + 61) 2) 3 -- large prime squared , bench "2*3^20000" $ nf (primRootWrap2 3 20000) 5 -- twice prime to large power , bench "10000000000000046" $ nf (primRootWrap2 (5*10^15 + 23) 1) 5 -- twice large prime ] ]
cartazio/arithmoi
benchmark/Math/NumberTheory/PrimitiveRootsBench.hs
mit
2,106
0
16
520
613
320
293
37
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="tr-TR"> <title>Tak-ve-Hackle | ZAP Uzantısı</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>İçindekiler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>İçerik</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_tr_TR/helpset_tr_TR.hs
apache-2.0
983
80
68
159
431
217
214
-1
-1
{-# LANGUAGE Unsafe #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Monad.ST.Imp -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (requires universal quantification for runST) -- -- This library provides support for /strict/ state threads, as -- described in the PLDI \'94 paper by John Launchbury and Simon Peyton -- Jones /Lazy Functional State Threads/. -- ----------------------------------------------------------------------------- module Control.Monad.ST.Imp ( -- * The 'ST' Monad ST, -- abstract, instance of Functor, Monad, Typeable. runST, fixST, -- * Converting 'ST' to 'IO' RealWorld, -- abstract stToIO, -- * Unsafe operations unsafeInterleaveST, unsafeDupableInterleaveST, unsafeIOToST, unsafeSTToIO ) where import GHC.ST ( ST, runST, fixST, unsafeInterleaveST , unsafeDupableInterleaveST ) import GHC.Base ( RealWorld ) import GHC.IO ( stToIO, unsafeIOToST, unsafeSTToIO )
rahulmutt/ghcvm
libraries/base/Control/Monad/ST/Imp.hs
bsd-3-clause
1,339
0
5
344
107
77
30
16
0
module PPrint where import Text.PrettyPrint type Var a = Int type Exp a = Int -> Doc lit :: (Show a) => a -> Exp a lit x i = text (show x) var :: Var a -> Exp a var x i = text ("x" ++ show x) dirac :: Exp a -> Exp b dirac p i = text "dirac" <> parens (p i) bern :: Exp a -> Exp b bern p i = text "bern" <> parens (p i) uniform :: Exp a -> Exp b -> Exp c uniform lo hi i = text "uniform" <> parens (lo i <> comma <> hi i) normal :: Exp a -> Exp b -> Exp c normal mu sd i = text "normal" <> parens (mu i <> comma <> sd i) categorical :: Exp a -> Exp b categorical p i = text "categorical" <> parens (p i) bind :: Exp a -> (Exp a -> Exp b) -> Exp b bind m cont i = text "let" <+> var i i <+> text "<-" <+> m i <+> text "in" $$ cont (var i) (i+1) conditioned :: Exp a -> Exp b conditioned f i = text "observe" <> parens (f i) unconditioned :: Exp a -> Exp b unconditioned f = f lam :: (Exp a -> Exp a) -> Exp (a -> b) lam body i = parens ( text "lambda" <+> var i i <+> text "->" <+> body (var i) (i+1)) app :: Exp (a -> b) -> Exp a -> Exp b app f x i = parens (f i <+> x i) fix :: (Exp a -> Exp a) -> Exp a fix g i = parens ( text "fix" <+> var i i <+> text "->" <+> g (var i) (i+1)) ifThenElse :: Exp a -> Exp b -> Exp c -> Exp d ifThenElse cond t f i = parens ( text "if" <+> cond i <+> text "then" <+> t i <+> text "else" <+> f i) test :: Exp a test = unconditioned (uniform (lit False) (lit True)) `bind` \c -> conditioned (ifThenElse c (normal (lit 1) (lit 1)) (uniform (lit 0) (lit 3))) `bind` \_ -> unconditioned (dirac c) -- main :: IO () -- main = print $ test 0
bitemyapp/hakaru
Historical/PPrint.hs
bsd-3-clause
2,013
0
14
831
950
457
493
58
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Hooks.DebugKeyEvents -- Copyright : (c) 2011 Brandon S Allbery <allbery.b@gmail.com> -- License : BSD -- -- Maintainer : Brandon S Allbery <allbery.b@gmail.com> -- Stability : unstable -- Portability : unportable -- -- A debugging module to track key events, useful when you can't tell whether -- xmonad is processing some or all key events. ----------------------------------------------------------------------------- module XMonad.Hooks.DebugKeyEvents (-- * Usage -- $usage debugKeyEvents ) where import XMonad.Core import XMonad.Operations (cleanMask) import Graphics.X11.Xlib import Graphics.X11.Xlib.Extras import Control.Monad.State (gets) import Data.Bits import Data.List (intercalate) import Data.Monoid import Numeric (showHex) import System.IO (hPutStrLn ,stderr) -- $usage -- Add this to your handleEventHook to print received key events to the -- log (the console if you use @startx@/@xinit@, otherwise usually -- @~/.xsession-errors@). -- -- > , handleEventHook = debugKeyEvents -- -- If you already have a handleEventHook then you should append it: -- -- > , handleEventHook = ... <+> debugKeyEvents -- -- Logged key events look like: -- -- @keycode 53 sym 120 (0x78, "x") mask 0x0 () clean 0x0 ()@ -- -- The @mask@ and @clean@ indicate the modifiers pressed along with -- the key; @mask@ is raw, and @clean@ is what @xmonad@ sees after -- sanitizing it (removing @numberLockMask@, etc.) -- -- For more detailed instructions on editing the logHook see: -- -- "XMonad.Doc.Extending#The_log_hook_and_external_status_bars" -- | Print key events to stderr for debugging debugKeyEvents :: Event -> X All debugKeyEvents (KeyEvent {ev_event_type = t, ev_state = m, ev_keycode = code}) | t == keyPress = withDisplay $ \dpy -> do sym <- io $ keycodeToKeysym dpy code 0 msk <- cleanMask m nl <- gets numberlockMask io $ hPutStrLn stderr $ intercalate " " ["keycode" ,show code ,"sym" ,show sym ," (" ,hex sym ," \"" ,keysymToString sym ,"\") mask" ,hex m ,"(" ++ vmask nl m ++ ")" ,"clean" ,hex msk ,"(" ++ vmask nl msk ++ ")" ] return (All True) debugKeyEvents _ = return (All True) -- | Convenient showHex variant hex :: (Integral n, Show n) => n -> String hex v = "0x" ++ showHex v "" -- | Convert a modifier mask into a useful string vmask :: KeyMask -> KeyMask -> String vmask numLockMask msk = intercalate " " $ reverse $ fst $ foldr vmask' ([],msk) masks where masks = map (\m -> (m,show m)) [0..toEnum (bitSize msk - 1)] ++ [(numLockMask,"num" ) ,( lockMask,"lock" ) ,(controlMask,"ctrl" ) ,( shiftMask,"shift") ,( mod5Mask,"mod5" ) ,( mod4Mask,"mod4" ) ,( mod3Mask,"mod3" ) ,( mod2Mask,"mod2" ) ,( mod1Mask,"mod1" ) ] vmask' _ a@( _,0) = a vmask' (m,s) (ss,v) | v .&. m == m = (s:ss,v .&. complement m) vmask' _ r = r
kmels/xmonad-launcher
XMonad/Hooks/DebugKeyEvents.hs
bsd-3-clause
4,265
0
15
1,874
675
388
287
56
3
-- | -- Copyright : (c) 2010-2012 Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Benedikt Schmidt <beschmi@gmail.com> -- -- Computing and checking the variants of a term. module Term.Narrowing.Variants ( computeVariantsCheck , module Term.Narrowing.Variants.Compute , module Term.Narrowing.Variants.Check ) where import Term.Narrowing.Variants.Compute import Term.Narrowing.Variants.Check import Term.Unification import Control.Monad.Reader -- | @variantsListCheck ts@ computes all variants of @ts@ considered as a single term -- without a bound or symmetry substitution. Before returning the result, it checks -- if the set of variants is complete and minimal. If that is not the case, it -- fails with an error computeVariantsCheck :: LNTerm -> WithMaude [LNSubstVFresh] computeVariantsCheck t = reader checkWithMaude where checkWithMaude hnd | not $ run $ checkComplete t vars = error $ "computeVariantsCheck: variant computation for "++ show t ++" failed. Computed set not complete." | not $ run $ checkMinimal t vars = error $ "computeVariantsCheck: variant computation for "++ show t ++" failed. Computed set not minimal." | otherwise = vars where vars = run $ computeVariants t run = (`runReader` hnd)
rsasse/tamarin-prover
lib/term/src/Term/Narrowing/Variants.hs
gpl-3.0
1,326
0
11
273
205
117
88
20
1
{-# LANGUAGE DataKinds, PolyKinds, TypeFamilies, GADTs, ConstraintKinds #-} module T12919 where import Data.Kind data N = Z data V :: N -> Type where VZ :: V Z type family VC (n :: N) :: Type where VC Z = Type type family VF (xs :: V n) (f :: VC n) :: Type where VF VZ f = f data Dict c where Dict :: c => Dict c prop :: xs ~ VZ => Dict (VF xs f ~ f) prop = Dict
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T12919.hs
bsd-3-clause
379
0
9
101
151
87
64
14
1
main :: IO () main = putStrLn "T15261b"
sdiehl/ghc
testsuite/tests/rts/T15261/T15261b.hs
bsd-3-clause
40
0
6
8
19
9
10
2
1
module UnitTests.Distribution.Client.Tar ( tests ) where import Distribution.Client.Tar ( filterEntries , filterEntriesM ) import Codec.Archive.Tar ( Entries(..) , foldEntries ) import Codec.Archive.Tar.Entry ( EntryContent(..) , simpleEntry , Entry(..) , toTarPath ) import Test.Tasty import Test.Tasty.HUnit import qualified Data.ByteString.Lazy as BS import qualified Data.ByteString.Lazy.Char8 as BS.Char8 import Control.Monad.Writer.Lazy (runWriterT, tell) tests :: [TestTree] tests = [ testCase "filterEntries" filterTest , testCase "filterEntriesM" filterMTest ] filterTest :: Assertion filterTest = do let e1 = getFileEntry "file1" "x" e2 = getFileEntry "file2" "y" p = (\e -> let (NormalFile dta _) = entryContent e str = BS.Char8.unpack dta in str /= "y") assertEqual "Unexpected result for filter" "xz" $ entriesToString $ filterEntries p $ Next e1 $ Next e2 Done assertEqual "Unexpected result for filter" "z" $ entriesToString $ filterEntries p $ Done assertEqual "Unexpected result for filter" "xf" $ entriesToString $ filterEntries p $ Next e1 $ Next e2 $ Fail "f" filterMTest :: Assertion filterMTest = do let e1 = getFileEntry "file1" "x" e2 = getFileEntry "file2" "y" p = (\e -> let (NormalFile dta _) = entryContent e str = BS.Char8.unpack dta in tell "t" >> return (str /= "y")) (r, w) <- runWriterT $ filterEntriesM p $ Next e1 $ Next e2 Done assertEqual "Unexpected result for filterM" "xz" $ entriesToString r assertEqual "Unexpected result for filterM w" "tt" w (r1, w1) <- runWriterT $ filterEntriesM p $ Done assertEqual "Unexpected result for filterM" "z" $ entriesToString r1 assertEqual "Unexpected result for filterM w" "" w1 (r2, w2) <- runWriterT $ filterEntriesM p $ Next e1 $ Next e2 $ Fail "f" assertEqual "Unexpected result for filterM" "xf" $ entriesToString r2 assertEqual "Unexpected result for filterM w" "tt" w2 getFileEntry :: FilePath -> [Char] -> Entry getFileEntry pth dta = simpleEntry tp $ NormalFile dta' $ BS.length dta' where tp = case toTarPath False pth of Right tp' -> tp' Left e -> error e dta' = BS.Char8.pack dta entriesToString :: Entries String -> String entriesToString = foldEntries (\e acc -> let (NormalFile dta _) = entryContent e str = BS.Char8.unpack dta in str ++ acc) "z" id
mydaum/cabal
cabal-install/tests/UnitTests/Distribution/Client/Tar.hs
bsd-3-clause
2,760
0
17
867
772
392
380
59
2
<?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="pt-BR"> <title>Início rápido | Extensão ZAP</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Conteúdo</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Índice</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Localizar</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoritos</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/diff/src/main/javahelp/org/zaproxy/zap/extension/diff/resources/help_pt_BR/helpset_pt_BR.hs
apache-2.0
982
78
66
159
422
213
209
-1
-1
import ObjLink library_name = "libfoo_script_T2615.so" -- this is really a linker script main = do initObjLinker result <- loadDLL library_name case result of Nothing -> putStrLn (library_name ++ " loaded successfully") Just x -> putStrLn ("error: " ++ x)
urbanslug/ghc
testsuite/tests/rts/T2615.hs
bsd-3-clause
273
0
12
56
70
34
36
8
2
module ShouldFail where
ezyang/ghc
testsuite/tests/plugins/T11244.hs
bsd-3-clause
24
0
2
3
4
3
1
1
0
module T9776 where
urbanslug/ghc
testsuite/tests/driver/T9776.hs
bsd-3-clause
19
0
2
3
4
3
1
1
0
{-# LANGUAGE TemplateHaskell #-} module Cenary.Codegen.CodegenState where import Cenary.Codegen.Address import Cenary.Codegen.Env import Cenary.Codegen.FuncRegistry import qualified Cenary.Codegen.MappingOrder as MO import Cenary.EvmAPI.Program import Control.Lens data CodegenState = CodegenState { _env :: !(Env Address) , _heapSpaceBegin :: Integer -- Dis boi should stay lazy or bad things happen , _sp :: !Integer -- Stack pointer , _framePtrs :: ![Integer] , _maxStackSize :: Integer , _stackStorageEnd :: !Integer , _pc :: !Integer , _funcRegistry :: !FuncRegistry , _program :: Program , _funcOffset :: !Integer , _mappingOrder :: MO.MappingOrder } makeLenses ''CodegenState
yigitozkavci/ivy
src/Cenary/Codegen/CodegenState.hs
mit
830
0
11
234
149
92
57
35
0
{-# LANGUAGE DeriveGeneric, CPP #-} module Data.KdMap.Dynamic ( -- * Usage -- $usage -- * Reference -- ** Types PointAsListFn , SquaredDistanceFn , KdMap -- ** Dynamic /k/-d map construction , empty , singleton , emptyWithDist , singletonWithDist -- ** Insertion , insert , insertPair , batchInsert -- ** Query , nearest , inRadius , kNearest , inRange , assocs , keys , elems , null , size -- ** Folds , foldrWithKey -- ** Utilities , defaultSqrDist -- ** Internal (for testing) , subtreeSizes ) where import Prelude hiding (null) #if MIN_VERSION_base(4,8,0) #else import Control.Applicative hiding (empty) import Data.Foldable import Data.Traversable #endif import Data.Bits import Data.Function import qualified Data.List as L import Control.DeepSeq import Control.DeepSeq.Generics (genericRnf) import GHC.Generics import qualified Data.KdMap.Static as KDM import Data.KdMap.Static (PointAsListFn, SquaredDistanceFn, defaultSqrDist) -- $usage -- -- The 'KdMap' is a variant of -- @Data.KdTree.Dynamic.@'Data.KdTree.Dynamic.KdTree' where each point -- in the tree is associated with some data. It is the dynamic variant -- of @Data.KdMap.Static.@'Data.KdMap.Static.KdMap'. -- -- Here's an example of interleaving point-value insertions and point -- queries using 'KdMap', where points are 3D points and values are -- 'String's: -- -- @ -- >>> let dkdm = 'singleton' point3dAsList ((Point3D 0.0 0.0 0.0), \"First\") -- -- >>> let dkdm' = 'insert' dkdm ((Point3D 1.0 1.0 1.0), \"Second\") -- -- >>> 'nearest' dkdm' (Point3D 0.4 0.4 0.4) -- (Point3D {x = 0.0, y = 0.0, z = 0.0}, \"First\") -- -- >>> let dkdm'' = 'insert' dkdm' ((Point3D 0.5 0.5 0.5), \"Third\") -- -- >>> 'nearest' dkdm'' (Point3D 0.4 0.4 0.4) -- (Point3D {x = 0.5, y = 0.5, z = 0.5}, \"Third\") -- @ -- | A dynamic /k/-d tree structure that stores points of type @p@ -- with axis values of type @a@. Additionally, each point is -- associated with a value of type @v@. data KdMap a p v = KdMap { _trees :: [KDM.KdMap a p v] , _pointAsList :: PointAsListFn a p , _distSqr :: SquaredDistanceFn a p , _numNodes :: Int } deriving Generic instance (NFData a, NFData p, NFData v) => NFData (KdMap a p v) where rnf = genericRnf instance (Show a, Show p, Show v) => Show (KdMap a p v) where show kdm = "KdMap " ++ show (_trees kdm) instance Functor (KdMap a p) where fmap f dkdMap = dkdMap { _trees = map (fmap f) $ _trees dkdMap } -- | Performs a foldr over each point-value pair in the 'KdMap'. foldrWithKey :: ((p, v) -> b -> b) -> b -> KdMap a p v -> b foldrWithKey f z dkdMap = L.foldr (flip $ KDM.foldrWithKey f) z $ _trees dkdMap instance Foldable (KdMap a p) where foldr f = foldrWithKey (f . snd) instance Traversable (KdMap a p) where traverse f (KdMap t p d n) = KdMap <$> traverse (traverse f) t <*> pure p <*> pure d <*> pure n -- | Generates an empty 'KdMap' with a user-specified distance function. emptyWithDist :: PointAsListFn a p -> SquaredDistanceFn a p -> KdMap a p v emptyWithDist p2l d2 = KdMap [] p2l d2 0 -- | Returns whether the 'KdMap' is empty. null :: KdMap a p v -> Bool null (KdMap [] _ _ _) = True null _ = False -- | Generates a 'KdMap' with a single point-value pair using a -- user-specified distance function. singletonWithDist :: Real a => PointAsListFn a p -> SquaredDistanceFn a p -> (p, v) -> KdMap a p v singletonWithDist p2l d2 (k, v) = KdMap [KDM.buildWithDist p2l d2 [(k, v)]] p2l d2 1 -- | Generates an empty 'KdMap' with the default distance function. empty :: Real a => PointAsListFn a p -> KdMap a p v empty p2l = emptyWithDist p2l $ defaultSqrDist p2l -- | Generates a 'KdMap' with a single point-value pair using the -- default distance function. singleton :: Real a => PointAsListFn a p -> (p, v) -> KdMap a p v singleton p2l = singletonWithDist p2l $ defaultSqrDist p2l -- | Adds a given point-value pair to a 'KdMap'. -- -- Average time complexity per insert for /n/ inserts: /O(log^2(n))/. insert :: Real a => KdMap a p v -> p -> v -> KdMap a p v insert (KdMap trees p2l d2 n) k v = let bitList = map ((1 .&.) . (n `shiftR`)) [0..] (onesPairs, theRestPairs) = span ((== 1) . fst) $ zip bitList trees ((_, ones), (_, theRest)) = (unzip onesPairs, unzip theRestPairs) newTree = KDM.buildWithDist p2l d2 $ (k, v) : L.concatMap KDM.assocs ones in KdMap (newTree : theRest) p2l d2 $ n + 1 -- | Same as 'insert', but takes point and value as a pair. insertPair :: Real a => KdMap a p v -> (p, v) -> KdMap a p v insertPair t = uncurry (insert t) -- | Given a 'KdMap' and a query point, returns the point-value pair in -- the 'KdMap' with the point nearest to the query. -- -- Average time complexity: /O(log^2(n))/. nearest :: Real a => KdMap a p v -> p -> (p, v) nearest (KdMap ts _ d2 _) query = let nearests = map (`KDM.nearest` query) ts --in if Data.List.null nearests in if L.null nearests then error "Called nearest on empty KdMap." else L.minimumBy (compare `on` (d2 query . fst)) nearests -- | Given a 'KdMap', a query point, and a number @k@, returns the -- @k@ point-value pairs with the nearest points to the query. -- -- Neighbors are returned in order of increasing distance from query -- point. -- -- Average time complexity: /log(k) * log^2(n)/ for /k/ nearest -- neighbors on a structure with /n/ data points. -- -- Worst case time complexity: /n * log(k)/ for /k/ nearest neighbors -- on a structure with /n/ data points. kNearest :: Real a => KdMap a p v -> Int -> p -> [(p, v)] kNearest (KdMap trees _ d2 _) k query = let neighborSets = map (\t -> KDM.kNearest t k query) trees in take k $ L.foldr merge [] neighborSets where merge [] ys = ys merge xs [] = xs merge xs@(x:xt) ys@(y:yt) | distX <= distY = x : merge xt ys | otherwise = y : merge xs yt where distX = d2 query $ fst x distY = d2 query $ fst y -- | Given a 'KdMap', a query point, and a radius, returns all -- point-value pairs in the 'KdTree' with points within the given -- radius of the query point. -- -- Points are not returned in any particular order. -- -- Worst case time complexity: /O(n)/ for /n/ data points. inRadius :: Real a => KdMap a p v -> a -> p -> [(p, v)] inRadius (KdMap trees _ _ _) radius query = L.concatMap (\t -> KDM.inRadius t radius query) trees -- | Finds all point-value pairs in a 'KdMap' with points within a -- given range, where the range is specified as a set of lower and -- upper bounds. -- -- Points are not returned in any particular order. -- -- Worst case time complexity: /O(n)/ for n data points and a range -- that spans all the points. inRange :: Real a => KdMap a p v -> p -- ^ lower bounds of range -> p -- ^ upper bounds of range -> [(p, v)] -- ^ point-value pairs within given -- range inRange (KdMap trees _ _ _) lowers uppers = L.concatMap (\t -> KDM.inRange t lowers uppers) trees -- | Returns the number of elements in the 'KdMap'. -- -- Time complexity: /O(1)/ size :: KdMap a p v -> Int size (KdMap _ _ _ n) = n -- | Returns a list of all the point-value pairs in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. assocs :: KdMap a p v -> [(p, v)] assocs (KdMap trees _ _ _) = L.concatMap KDM.assocs trees -- | Returns all points in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. keys :: KdMap a p v -> [p] keys = map fst . assocs -- | Returns all values in the 'KdMap'. -- -- Time complexity: /O(n)/ for /n/ data points. elems :: KdMap a p v -> [v] elems = map snd . assocs -- | Inserts a list of point-value pairs into the 'KdMap'. -- -- TODO: This will be made far more efficient than simply repeatedly -- inserting. batchInsert :: Real a => KdMap a p v -> [(p, v)] -> KdMap a p v batchInsert = L.foldl' insertPair -- | Returns size of each internal /k/-d tree that makes up the -- dynamic structure. For internal testing use. subtreeSizes :: KdMap a p v -> [Int] subtreeSizes (KdMap trees _ _ _) = map KDM.size trees
giogadi/kdt
lib-src/Data/KdMap/Dynamic.hs
mit
8,486
0
13
2,165
2,022
1,102
920
117
3
module Proteome.Path where import qualified Data.Text as Text import Path ( Abs, Dir, File, Path, Rel, parseAbsDir, parseAbsFile, parseRelDir, parseRelFile, toFilePath, (</>), ) import Path.IO (doesFileExist) parsePathMaybe :: (FilePath -> Either a (Path b t)) -> Text -> Maybe (Path b t) parsePathMaybe parser = rightToMaybe . parser . toString parseAbsDirMaybe :: Text -> Maybe (Path Abs Dir) parseAbsDirMaybe = parsePathMaybe parseAbsDir parseAbsFileMaybe :: Text -> Maybe (Path Abs File) parseAbsFileMaybe = parsePathMaybe parseAbsFile parseRelDirMaybe :: Text -> Maybe (Path Rel Dir) parseRelDirMaybe = parsePathMaybe parseRelDir parseRelFileMaybe :: Text -> Maybe (Path Rel File) parseRelFileMaybe = parsePathMaybe parseRelFile absoluteParseDir :: Path Abs Dir -> Text -> Maybe (Path Abs Dir) absoluteParseDir cwd spec = tryAbsolute <|> tryRelative where specS = toString spec tryAbsolute = rightToMaybe (parseAbsDir specS) tryRelative = makeAbsolute <$> rightToMaybe (parseRelDir specS) makeAbsolute path = cwd </> path absoluteParse :: Path Abs Dir -> Text -> Maybe (Path Abs File) absoluteParse cwd spec = tryAbsolute <|> tryRelative where specS = toString spec tryAbsolute = rightToMaybe (parseAbsFile specS) tryRelative = makeAbsolute <$> rightToMaybe (parseRelFile specS) makeAbsolute path = cwd </> path existingFile :: MonadIO m => Path Abs Dir -> Text -> m (Maybe (Path Abs File)) existingFile cwd spec = join <$> traverse check (absoluteParse cwd spec) where check path = do exists <- doesFileExist path return $ if exists then Just path else Nothing pathText :: Path b t -> Text pathText = toText . toFilePath dropSlash :: Path b t -> Text dropSlash = Text.dropWhileEnd ('/' ==) . pathText
tek/proteome
packages/proteome/lib/Proteome/Path.hs
mit
1,906
0
12
452
593
306
287
85
2
module Parser (LispVal(..) ,ParseError ,parseLispVal ) where import Control.Applicative ((*>), (<*)) import Control.Monad import Text.ParserCombinators.Parsec hiding (spaces) import System.Environment import Data.Char (isDigit) import Data.Maybe (fromJust, fromMaybe) import Numeric (readHex, readOct, readFloat) import Internal symbol :: Parser Char symbol = oneOf "!#$%&|*+-/:<=>?@^_~" spaces :: Parser () spaces = skipMany1 space {- Exercise 3 -} escapingTable = [('"', '"') ,('\'', '\'') ,('n', '\n') ,('t', '\t') ,('r', '\r') ,('\\', '\\') ] charNameTable = [("space", ' ') ,("newline", '\n') ,("tab", '\t') ] parseString :: Parser LispVal -- parseString = liftM String (char '"' *> many (noneOf "\"") <* char '"') {- Exercise 2 -} parseString = liftM String (char '"' *> many foo <* char '"') where foo = try bar <|> char '\\' <|> noneOf "\"" bar = do char '\\' x <- oneOf (map fst escapingTable) return $ fromJust $ lookup x escapingTable nameToChar :: String -> Char nameToChar xs = fromMaybe (error $ "No character names '" ++ xs ++ "' found!") (lookup xs charNameTable) parseIdentifier :: Parser LispVal parseIdentifier = do first <- symbol <|> letter rest <- many (symbol <|> alphaNum <|> char '\\') -- '\\' is for char syntax let (x:xs) = rest return $ if first == '#' then case x of 't' -> Bool True 'f' -> Bool False 'o' -> (Number . fst . head . readOct) xs -- Exercise 4 'h' -> (Number . fst . head . readHex) xs -- Exercise 4 '\\'-> Character $ if length xs == 1 -- Exercise 5 then head xs else nameToChar xs _ -> error "invalid syntax" else Identifier (first : rest) parseSign :: Parser Char parseSign = option '+' (char '-' <|> char '+') signify :: (Num a) => Char -> a -> a signify '-' a = -a signify '+' a = a signify _ _ = error "invalid sign" parseIntegerNumber :: Parser LispVal parseIntegerNumber = do i <- parseInteger optional $ char 'L' return $ Number i parseInteger :: Parser Integer parseInteger = do sign <- parseSign int <- parseUnsignedInteger return $ signify sign int parseUnsignedInteger :: Parser Integer parseUnsignedInteger = liftM read $ many1 digit {- Exercise 6 -} parseFloatNumber :: Parser LispVal parseFloatNumber = do f <- parseFloat optional $ char 'F' return $ Float f parseFloat :: Parser Double parseFloat = do sign <- parseSign num <- parseUnsignedFloat return $ signify sign num parseUnsignedFloat :: Parser Double parseUnsignedFloat = try parseExponential <|> parseDecimal parseDecimal :: Parser Double parseDecimal = do ipart <- parseNumStr char '.' fpart <- parseNumStr return $ fst $ head $ readFloat (ipart ++ "." ++ fpart) where parseNumStr = many1 digit parseExponential :: Parser Double parseExponential = do bpart <- try parseDecimal <|> liftM fromIntegral parseInteger oneOf "eE" epart <- liftM fromIntegral parseInteger return (bpart * 10 ** epart) {- Exercise 7 -} parseRationalNumber :: Parser LispVal parseRationalNumber = do den <- parseInteger char '/' num <- parseInteger let x = gcd den num d = den `div` x n = num `div` x d' = if n < 0 then -d else d n' = if n < 0 then -n else n return $ if n == 1 then Number d' else Rational d' n' {- Exercise 7 -} parseComplexNumber :: Parser LispVal parseComplexNumber = do real <- try parseFloat <|> (liftM fromIntegral $ try parseInteger) signi<- char '+' <|> char '-' imag <- option 1 (try parseUnsignedFloat <|> liftM fromIntegral parseUnsignedInteger) char 'i' return $ Complex real (signify signi imag) {- Modified implementation of this function -} parseNumber :: Parser LispVal parseNumber = try parseComplexNumber <|> try parseFloatNumber <|> try parseRationalNumber <|> try parseIntegerNumber {- Exercise 1.1/1.2 -} {- parseNumber :: Parser LispVal parseNumber = many1 digit >>= return . Number . read parseNumber = do s <- many1 digit return $ Number $ read s -} parseExpr :: Parser LispVal parseExpr = parseString <|> try parseNumber <|> try parseIdentifier <|> try parseQuoted <|> char '(' *> (try parseList <|> parseDottedList) <* char ')' parseList :: Parser LispVal parseList = liftM List $ sepBy parseExpr spaces parseDottedList :: Parser LispVal parseDottedList = do head <- endBy parseExpr spaces tail <- char '.' >> spaces >> parseExpr return $ DottedList head tail parseQuoted :: Parser LispVal parseQuoted = do char '\'' x <- parseExpr return $ List [Identifier "quote", x] testParse :: String -> IO () testParse input = putStrLn $ case parse (parseExpr <* eof) "lisp" input of Left err -> "No match: " ++ show err Right _ -> "Found value." parseLispVal :: String -> Either ParseError LispVal parseLispVal = parse (parseExpr <* eof) "input" main :: IO () main = getArgs >>= testParse . head
shouya/thinking-dumps
wys48h/code/Parser.hs
mit
5,660
0
16
1,811
1,611
810
801
140
8
{-# LANGUAGE DeriveGeneric, OverloadedStrings #-} {-| Anscombe's quartet Four datasets with nearly identical statistical properties Wikipedia article: <https://en.wikipedia.org/wiki/Anscombe%27s_quartet> -} module Numeric.Datasets.Anscombe where anscombe :: [[(Double,Double)]] anscombe = [anscombe1, anscombe2, anscombe3, anscombe4] anscombe1, anscombe2, anscombe3, anscombe4 :: [(Double, Double)] anscombe1 = [ (10,8.04), (8,6.95), (13,7.58), (9,8.81), (11,8.33), (14,9.96), (6,7.24), (4,4.26), (12,10.84), (7,4.82), (5,5.68) ] anscombe2 = [ (10,9.14), (8,8.14), (13,8.74), (9,8.77), (11,9.26), (14,8.1), (6,6.13), (4,3.1), (12,9.13), (7,7.26), (5,4.74) ] anscombe3 = [ (10,7.46), (8,6.77), (13,12.74), (9,7.11), (11,7.81), (14,8.84), (6,6.08), (4,5.39), (12,8.15), (7,6.42), (5,5.73) ] anscombe4 = [ (8,6.58), (8,5.76), (8,7.71), (8,8.84), (8,8.47), (8,7.04), (8,5.25), (19,12.5), (8,5.56), (8,7.91), (8,6.89) ]
glutamate/datasets
datasets/src/Numeric/Datasets/Anscombe.hs
mit
1,018
0
7
201
479
320
159
53
1
----------------------------------------------------------------------------- -- -- Module : Tikz.DSL -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- {-# LANGUAGE ExistentialQuantification, TypeSynonymInstances, FlexibleInstances #-} module Tikz.DSL ( Repr , Elem(..) , ElemType(..) , TypeOfElem(..) , Attr(..) , Expr(..) , ExprType(..) , TypeOfExpr(..) , Cmd(..) , Env(..) , EmptyLine(..) , CommentLines(..) , RawExpr(..) , picture , PictureDefs(..) , PictureAttrs(..) , PictureStyles(..) , Style(..) , Def(..) , Node(..) , Path(..) , PathType(..) ) where import qualified Data.List as List import Prelude hiding (concat, unwords, lines) import Data.ByteString.Char8 (ByteString, pack, concat, intercalate, unwords, append) import qualified Data.ByteString.Char8 as BS ----------------------------------------------------------------------------- type Repr = ByteString type Indent = Int ----------------------------------------------------------------------------- data ElemType = TAttr | TExpr data ExprType = TCmd | TEnv type family TypeOfElem e :: ElemType type family TypeOfExpr e :: ExprType class Elem a where -- elemType :: a -> ElemType elemMultiline :: a -> Bool elemRepr :: Indent -> a -> ByteString data Attr = forall e . (Elem e, TypeOfElem e ~ TAttr) => Attr e data Expr = forall e . (Elem e, TypeOfElem e ~ TExpr) => Expr e data Cmd = forall e . (Elem e, TypeOfElem e ~ TExpr, TypeOfExpr e ~ TCmd) => Cmd e data Env = Env { envName :: String , envAttrs :: [Attr] , envBody :: [Expr] } data EmptyLine = EmptyLine data CommentLines = CommentLines [String] data RawExpr = RawExpr String instance Elem Attr where -- elemType _ = TAttr elemMultiline (Attr a) = elemMultiline a elemRepr i (Attr a) = elemRepr i a instance Elem Expr where -- elemType _ = TExpr elemMultiline (Expr e) = elemMultiline e elemRepr i (Expr e) = elemRepr i e instance Elem Cmd where -- elemType _ = TExpr elemMultiline (Cmd c) = elemMultiline c elemRepr i (Cmd c) = elemRepr i c instance Elem Env where -- elemType _ = TExpr elemMultiline _ = True elemRepr i e = concat [ indent i , latexKey "begin" , key , optArgs $ envAttrs e , newline , lines . map (elemRepr (nextIndent i)) $ envBody e , newline , indent i , latexKey "end" , key ] where key = surroundBracketsCurly . pack $ envName e instance Elem EmptyLine where -- elemType _ = TExpr elemMultiline _ = True elemRepr _ _ = newline instance Elem CommentLines where -- elemType _ = TExpr elemMultiline _ = True elemRepr i (CommentLines ls) = pack $ pre ++ List.intercalate pre ls ++ "\n" where pre = indent' i ++ "% " instance Elem RawExpr where elemMultiline (RawExpr s) = '\n' `elem` s elemRepr _ (RawExpr s) = pack s type instance TypeOfElem Attr = TAttr type instance TypeOfElem Expr = TExpr type instance TypeOfElem Cmd = TExpr type instance TypeOfElem Env = TExpr type instance TypeOfElem EmptyLine = TExpr type instance TypeOfElem CommentLines = TExpr type instance TypeOfElem RawExpr = TExpr ----------------------------------------------------------------------------- newtype PictureDefs = PictureDefs [Def] newtype PictureAttrs = PictureAttrs [Attr] newtype PictureStyles = PictureStyles [Style] ----------------------------------------------------------------------------- indent = pack . indent' indent' = flip replicate ' ' nextIndent = (+) 4 newline = pack "\n" lines = intercalate (pack "\n") latexKey k = pack $ "\\" ++ k surround pre suf x = concat [pack pre, x, pack suf] surround' pre suf x = concat $ map pack [pre, x, suf] surroundBracketsCurly = surround "{" "}" surroundBracketsSquare = surround "[" "]" surroundBracketsRound = surround "(" ")" surroundBracketsCurly' = surround' "{" "}" surroundBracketsSquare' = surround' "[" "]" surroundBracketsRound' = surround' "(" ")" surroundSpace s = surround s' s' where s' = replicate s ' ' optArgs [] = BS.empty optArgs as = surroundBracketsSquare . intercalate (pack ",") $ map (elemRepr 0) as ----------------------------------------------------------------------------- type instance TypeOfElem String = TAttr instance Elem String where elemMultiline _ = False elemRepr _ = pack ----------------------------------------------------------------------------- picture (PictureAttrs attrs) (PictureStyles styles) (PictureDefs defs) body = Env "tikzpicture" attrs ( map Expr styles ++ Expr EmptyLine : map Expr defs ++ Expr EmptyLine : body) ----------------------------------------------------------------------------- data Style = Style String [Attr] instance Elem Style where elemMultiline _ = False elemRepr i (Style name vals) = concat [ indent i , latexKey "tikzstyle" , surroundBracketsCurly' name , pack " = " , optArgs vals , pack ";" ] type instance TypeOfElem Style = TExpr ----------------------------------------------------------------------------- data Def = Def String String instance Elem Def where elemMultiline _ = False elemRepr i (Def name val) = concat [ indent i , latexKey "def" , latexKey name , surroundBracketsCurly' val ] type instance TypeOfElem Def = TExpr ----------------------------------------------------------------------------- data Node = Node String [Attr] (Maybe String) [Expr] instance Elem Node where elemMultiline (Node _ _ _ []) = False elemMultiline _ = True elemRepr i (Node name attrs at body) = concat [ indent i , latexKey "node" , optArgs attrs , surroundBracketsRound' name , at' , body' `append` pack ";" ] where at' = case at of Just a -> concat [ pack " at " , surroundBracketsRound' a ] _ -> BS.empty body' = case body of [] -> pack "{}" [x] | not $ elemMultiline x -> surroundBracketsCurly . surroundSpace 1 $ elemRepr 0 x _ -> concat [ pack "{" , newline , lines $ map (elemRepr (nextIndent i)) body , newline , indent i , pack "}" ] type instance TypeOfElem Node = TExpr ----------------------------------------------------------------------------- data PathType = Edge data Path = Path PathType String String instance Elem Path where elemMultiline _ = False elemRepr i (Path Edge from to) = concat [ indent i , latexKey "path " , surroundBracketsRound' from , pack " edge " , surroundBracketsRound' to , pack ";" ] type instance TypeOfElem Path = TExpr -----------------------------------------------------------------------------
fehu/hneuro
src/Tikz/DSL.hs
mit
8,830
0
18
3,529
1,948
1,064
884
-1
-1
module Hate.Math.OpenGL where import Data.Vect.Float import qualified Graphics.Rendering.OpenGL as GL toOpenGLVertex :: Vec4 -> GL.Vertex4 Float toOpenGLVertex (Vec4 x y z w) = GL.Vertex4 x y z w
bananu7/Hate
src/Hate/Math/OpenGL.hs
mit
203
0
7
35
67
38
29
5
1
import qualified Data.ByteString.Lazy.Char8 as L closing = readPrice . (!!4) . L.split ',' readPrice :: L.ByteString -> Maybe Int readPrice str = case L.readInt str of Nothing -> Nothing Just (dollars, rest) -> case L.readInt (L.tail rest) of Nothing -> Nothing Just (cent, more) -> Just (dollars * 100 + cent) highestClose = maximum . (Nothing :) . map closing . L.lines highestCloseFrom path = do content <- L.readFile path print (highestClose content)
zhangjiji/real-world-haskell
ch8/highestClose.hs
mit
495
0
14
113
195
100
95
14
3
{-# LANGUAGE Safe #-} {-# LANGUAGE OverloadedStrings #-} -- | A pretty-printer for a small subset of LLVM module LlvmPrinter where import Data.String ( fromString , IsString ) import Data.List ( intercalate ) import Data.Monoid ( (<>) , mempty , mconcat , Monoid ) import LlvmData -- | A typeclass for transforming any type to any monoidal string type class ToLlvm a where toLlvm :: (Eq s, Monoid s, IsString s) => a -> s instance ToLlvm ToplevelEntity where toLlvm (Function ret nm args as blk) = "\ndefine " <> fromString ret <+> "@" <> fromString nm <> "(" <> fromString (intercalate ", " (map parameter args)) <> ")" <+> fromString (unwords as) <+> "{\n" <> mconcat (map (bbLine . toLlvm) blk) <> "}" toLlvm (Target nm val) = "target " <> fromString nm <> " = \"" <> fromString val <> "\"" -- | Print a basic block line bbLine :: (Monoid s, IsString s) => s -> s bbLine s = s <> "\n" instance ToLlvm Statement where toLlvm (Assignment s e) = " %" <> fromString s <> " = " <> toLlvm e toLlvm (Return s e) = " ret " <> fromString s <+> toLlvm e toLlvm (Label s) = "\n" <> fromString s <> ":" toLlvm (Branch s) = " br" <+> label s toLlvm (BranchCond b t f) = " br i1" <+> toLlvm b <> "," <+> label t <> "," <+> label f toLlvm (Flush) = mempty instance ToLlvm Expr where toLlvm (ExprConstant lit) = toLlvm lit toLlvm (ExprVar nm) = identifier nm toLlvm (ExprAdd ty e1 e2) = "add " <> fromString ty <+> toLlvm e1 <> ", " <> toLlvm e2 toLlvm (ExprPhi ty es) = "phi " <> fromString ty <+> mintercalate ", " (map phiField es) instance ToLlvm Literal where toLlvm (LitString s) = fromString (show s) toLlvm (LitInteger x) = fromString (show x) toLlvm (LitBool True) = "true" toLlvm (LitBool False) = "false" -- | Print a function parameter parameter :: (Eq s, Monoid s, IsString s) => Parameter -> s parameter (Parameter ty s) = fromString ty <+> identifier s -- | Print a label label :: (Eq s, Monoid s, IsString s) => String -> s label s = "label" <+> identifier s -- | Print an identifier identifier :: (Eq s, Monoid s, IsString s) => String -> s identifier s = "%" <> fromString s -- | Same as intercalate from Data.List, but works for any monoid mintercalate :: (Monoid s, IsString s) => s -> [s] -> s mintercalate _ [] = mempty mintercalate sep xs = foldr1 (\x y -> x <> sep <> y) xs -- | Prints a phi field phiField :: (Eq s, Monoid s, IsString s) => (Expr, String) -> s phiField (e, s) = "[" <+> toLlvm e <> "," <+> identifier s <+> "]" -- | Concat with a space between, unless one is empty (<+>) :: (Eq s, Monoid s, IsString s) => s -> s -> s a <+> b | a == mempty = b | b == mempty = a | otherwise = a <> " " <> b
garious/hopt
LlvmPrinter.hs
mit
2,992
0
16
902
1,061
538
523
58
1
module MLUtil.Folding ( columnHead , foldColumn ) where import MLUtil.Imports columnHead :: Matrix -> Int -> R columnHead m c = m `atIndex` (0, c) foldColumn :: (R -> b -> b) -> b -> Matrix -> Int -> b foldColumn f acc m c = foldr (\r acc' -> f (m `atIndex` (r, c)) acc') acc [0..rows m - 1]
rcook/mlutil
mlutil/src/MLUtil/Folding.hs
mit
317
0
11
86
149
83
66
8
1
{-# LANGUAGE TupleSections #-} module Main where import Data.Bool (bool) import Data.Either (fromRight) import Data.List (unfoldr) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Read as T import Data.Vector (Vector) import qualified Data.Vector as V rd :: Text -> Int rd = fromRight 0 . (fmap fst . T.signed T.decimal) rdProg :: Text -> Vector Int rdProg = V.fromList . fmap rd . T.split (== ',') step :: (Int, Vector Int) -> Maybe (Vector Int, (Int, Vector Int)) step (i, xs) | o == 99 = Nothing | o == 1 || o == 2 = Just (xs', (i + 4, xs')) | otherwise = error "unknown opcode" where o = xs V.! i a = xs V.! (i + 1) b = xs V.! (i + 2) c = xs V.! (i + 3) x = xs V.! a y = xs V.! b z = bool (x * y) (x + y) (o == 1) xs' = xs V.// [(c, z)] start :: Int -> Int -> Vector Int -> Vector Int start noun verb = (V.// [(1, noun), (2, verb)]) run :: Vector Int -> Int run = V.head . last . unfoldr step . (0, ) part1 :: Vector Int -> Int part1 = run . start 12 2 part2 :: Vector Int -> Int part2 xs = head [ 100 * noun + verb | noun <- [0 .. 99] , verb <- [0 .. 99] , 19690720 == run (start noun verb xs) ] main :: IO () main = do xs <- rdProg <$> T.readFile "input" print $ part1 xs print $ part2 xs
genos/online_problems
advent_of_code_2019/day02/src/Main.hs
mit
1,342
0
11
356
678
368
310
46
1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} -- | This module provides the ability to create reapers: dedicated cleanup -- threads. These threads will automatically spawn and die based on the -- presence of a workload to process on. module Control.Reaper ( -- * Settings ReaperSettings , defaultReaperSettings -- * Accessors , reaperAction , reaperDelay , reaperCons , reaperNull , reaperEmpty -- * Type , Reaper(..) -- * Creation , mkReaper -- * Helper , mkListAction ) where import Control.AutoUpdate.Util (atomicModifyIORef') import Control.Concurrent (forkIO, threadDelay, killThread, ThreadId) import Control.Exception (mask_) import Data.IORef (IORef, newIORef, readIORef, writeIORef) -- | Settings for creating a reaper. This type has two parameters: -- @workload@ gives the entire workload, whereas @item@ gives an -- individual piece of the queue. A common approach is to have @workload@ -- be a list of @item@s. This is encouraged by 'defaultReaperSettings' and -- 'mkListAction'. -- -- Since 0.1.1 data ReaperSettings workload item = ReaperSettings { reaperAction :: workload -> IO (workload -> workload) -- ^ The action to perform on a workload. The result of this is a -- \"workload modifying\" function. In the common case of using lists, -- the result should be a difference list that prepends the remaining -- workload to the temporary workload. For help with setting up such -- an action, see 'mkListAction'. -- -- Default: do nothing with the workload, and then prepend it to the -- temporary workload. This is incredibly useless; you should -- definitely override this default. -- -- Since 0.1.1 , reaperDelay :: {-# UNPACK #-} !Int -- ^ Number of microseconds to delay between calls of 'reaperAction'. -- -- Default: 30 seconds. -- -- Since 0.1.1 , reaperCons :: item -> workload -> workload -- ^ Add an item onto a workload. -- -- Default: list consing. -- -- Since 0.1.1 , reaperNull :: workload -> Bool -- ^ Check if a workload is empty, in which case the worker thread -- will shut down. -- -- Default: 'null'. -- -- Since 0.1.1 , reaperEmpty :: workload -- ^ An empty workload. -- -- Default: empty list. -- -- Since 0.1.1 } -- | Default @ReaperSettings@ value, biased towards having a list of work -- items. -- -- Since 0.1.1 defaultReaperSettings :: ReaperSettings [item] item defaultReaperSettings = ReaperSettings { reaperAction = \wl -> return (wl ++) , reaperDelay = 30000000 , reaperCons = (:) , reaperNull = null , reaperEmpty = [] } -- | A data structure to hold reaper APIs. data Reaper workload item = Reaper { -- | Adding an item to the workload reaperAdd :: item -> IO () -- | Reading workload. , reaperRead :: IO workload -- | Stopping the reaper thread if exists. -- The current workload is returned. , reaperStop :: IO workload -- | Killing the reaper thread immediately if exists. , reaperKill :: IO () } -- | State of reaper. data State workload = NoReaper -- ^ No reaper thread | Workload workload -- ^ The current jobs -- | Create a reaper addition function. This funciton can be used to add -- new items to the workload. Spawning of reaper threads will be handled -- for you automatically. -- -- Since 0.1.1 mkReaper :: ReaperSettings workload item -> IO (Reaper workload item) mkReaper settings@ReaperSettings{..} = do stateRef <- newIORef NoReaper tidRef <- newIORef Nothing return Reaper { reaperAdd = add settings stateRef tidRef , reaperRead = readRef stateRef , reaperStop = stop stateRef , reaperKill = kill tidRef } where readRef stateRef = do mx <- readIORef stateRef case mx of NoReaper -> return reaperEmpty Workload wl -> return wl stop stateRef = atomicModifyIORef' stateRef $ \mx -> case mx of NoReaper -> (NoReaper, reaperEmpty) Workload x -> (Workload reaperEmpty, x) kill tidRef = do mtid <- readIORef tidRef case mtid of Nothing -> return () Just tid -> killThread tid add :: ReaperSettings workload item -> IORef (State workload) -> IORef (Maybe ThreadId) -> item -> IO () add settings@ReaperSettings{..} stateRef tidRef item = mask_ $ do next <- atomicModifyIORef' stateRef cons next where cons NoReaper = let !wl = reaperCons item reaperEmpty in (Workload wl, spawn settings stateRef tidRef) cons (Workload wl) = let wl' = reaperCons item wl in (Workload wl', return ()) spawn :: ReaperSettings workload item -> IORef (State workload) -> IORef (Maybe ThreadId) -> IO () spawn settings stateRef tidRef = do tid <- forkIO $ reaper settings stateRef tidRef writeIORef tidRef $ Just tid reaper :: ReaperSettings workload item -> IORef (State workload) -> IORef (Maybe ThreadId) -> IO () reaper settings@ReaperSettings{..} stateRef tidRef = do threadDelay reaperDelay -- Getting the current jobs. Push an empty job to the reference. wl <- atomicModifyIORef' stateRef swapWithEmpty -- Do the jobs. A function to merge the left jobs and -- new jobs is returned. !merge <- reaperAction wl -- Merging the left jobs and new jobs. -- If there is no jobs, this thread finishes. next <- atomicModifyIORef' stateRef (check merge) next where swapWithEmpty NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (1)" swapWithEmpty (Workload wl) = (Workload reaperEmpty, wl) check _ NoReaper = error "Control.Reaper.reaper: unexpected NoReaper (2)" check merge (Workload wl) -- If there is no job, reaper is terminated. | reaperNull wl' = (NoReaper, writeIORef tidRef Nothing) -- If there are jobs, carry them out. | otherwise = (Workload wl', reaper settings stateRef tidRef) where wl' = merge wl -- | A helper function for creating 'reaperAction' functions. You would -- provide this function with a function to process a single work item and -- return either a new work item, or @Nothing@ if the work item is -- expired. -- -- Since 0.1.1 mkListAction :: (item -> IO (Maybe item')) -> [item] -> IO ([item'] -> [item']) mkListAction f = go id where go !front [] = return front go !front (x:xs) = do my <- f x let front' = case my of Nothing -> front Just y -> front . (y:) go front' xs
erikd/wai
auto-update/Control/Reaper.hs
mit
6,832
0
16
1,868
1,296
697
599
106
4
import Data.Char cap :: String -> String cap = map toUpper rev :: String -> String rev = reverse tupled :: String -> (String, String) tupled = (,) <$> cap <*> rev tupled' :: String -> (String, String) tupled' = do c <- cap r <- rev return (c,r) tupled'' :: String -> (String, String) tupled'' = cap >>= \c -> rev >>= \r -> return (c,r)
JustinUnger/haskell-book
ch22/ex.hs
mit
393
0
10
124
161
89
72
16
1
-- Power function. Primitive Recursion. module Power where import Test.QuickCheck power :: Integer -> Integer -> Integer power basis exponent | exponent < 0 = error "Power.hs: Negative exponent." | otherwise = power' basis exponent where power' :: Integer -> Integer -> Integer power' _ 0 = 1 -- power' _ 1 = 2 -- There would be an attempt to match this in every recursion step. -- Under what condition(s) could this mathching be an advantage? -- Under what condition(s) could this matching be a disadvantage? -- (Keywords: recursion pattern, parallelism, complex data structures ...) power' basis exponent | even exponent = power' (square basis) (halve exponent) | otherwise = basis * power' (square basis) (halve exponent) square :: Integer -> Integer square basis = basis * basis halve :: Integer -> Integer halve exponent = exponent `div` 2 {- GHCi> power 2 0 power 2 1 power 2 2 power 2 3 -} -- 1 -- 2 -- 4 -- 8 prop_power :: Integer -> (Positive Integer) -> Bool prop_power b (Positive e) = power b e == b ^ e -- GHCi> quickCheck prop_power
pascal-knodel/haskell-craft
Examples/· Recursion/· Primitive Recursion/Calculations/Power.hs
mit
1,160
0
11
300
253
131
122
18
2
module Scorer.Emit where import Scorer.Config import Scorer.Einsendung import Scorer.Aufgabe import Scorer.Util hiding ( size ) --import Prelude hiding (unwords, map, head, null, all, filter, foldr1) import Control.Types hiding ( size ) import qualified Control.Vorlesung as V import qualified Control.Aufgabe as A import qualified Control.Student as S import qualified Control.Schule as U import Autolib.FiniteMap hiding ( collect ) import Autolib.Set import Autolib.Util.Sort import Autolib.ToDoc import Autolib.Output ( Output ) import qualified Autolib.Output as O import qualified Data.Text as T import Control.Monad ( guard , liftM, when, forM ) import System.IO ( hFlush, stdout ) import Data.Char -- | druckt Auswertung für alle Aufgaben einer Vorlesung emit :: Bool -- ^ obfuscate Matrikelnummers? -> U.Schule -> V.Vorlesung -> DataFM -> IO ( Maybe Output ) emit deco u vor fm0 = do studs <- V.steilnehmer $ V.vnr vor let ssnrs = mkSet $ map S.snr studs smnrs = mkSet $ map S.mnr studs registered (Left mnr) = internal mnr `elementOf` smnrs registered (Right snr) =internal snr `elementOf` ssnrs let fm = mapFM ( \ key val -> do e <- val return ( e { visible = registered $ matrikel e } ) ) fm0 if ( 0 < sizeFM fm ) then do let header = O.Doc $ vcat [ text $ unwords [ toString $ U.name u ] , text $ unwords [ "Auswertung für Lehrveranstaltung" , toString $ V.name vor, ":" ] ] out <- forM ( fmToList fm ) $ single deco (V.unr vor) to <- totalize deco (V.unr vor) fm return $ Just $ O.lead header $ foldr1 O.Above [ O.Itemize out, to, inform ] else return Nothing inform :: Output inform = O.Doc $ text $ unwords [ "Dabei gibt es pro Score" , show scorePoints, "Punkte" , "für die Plätze [1 ..", show scoreItems, "]" ] realize :: [ Einsendung ] -> [ Einsendung ] realize es = take scoreItems -- genau 10 stück $ filter visible $ es -- | FIXME: this is badly broken -- und zwar für Matrikelnummern, die keine Zahlen sind isadmin :: ToString r => Obfuscated r -> Bool isadmin m = let cs = toString $ internal m in if all isDigit cs then 1023 > ( read cs :: Int ) else False -- | druckt Auswertung einer Aufgabe single :: Bool -> UNr -> ( ANr, [ Einsendung ] ) -> IO Output single deco u arg @( anr, es ) = do [ auf ] <- A.get_this anr let header = O.Text $ T.pack $ unwords [ "Aufgabe" , toString $ A.name auf , unwords $ if null es then [] else [ "( beste bekannte Lösung", show (size $ head es), ")" ] ] let realized = realize es decorated <- if False -- deco then mapM (liftM show . decorate u) realized else return $ map show realized let scored = O.Itemize $ map (O.Text . T.pack) decorated let try = O.Named_Link "Aufgabe ausprobieren (ohne Wertung)" $ "/cgi-bin/Trial.cgi?problem=" ++ Control.Types.toString ( A.anr auf ) return $ O.lead (O.lead header try ) scored decorate :: UNr -> Einsendung -> IO SE decorate u e = case matrikel e of Left mnr -> do studs <- S.get_unr_mnr ( u , internal mnr ) case studs of [] -> return $ SE ( read "SNr 0" ) e (s:_) -> return $ SE ( S.snr s ) e Right snr -> return $ SE ( internal snr ) e totalize :: Bool -> UNr -> DataFM -> IO Output totalize deco u fm = do infos <- collect deco u fm return $ O.lead (O.Text $ T.pack "Top Ten") $ O.Doc $ vcat $ do (i,(p,ps)) <- infos return $ text $ unwords [ stretch 10 $ show p , ":" , stretch 10 $ case i of Left m -> toString m Right s -> toString s , ":" , pshow ps ] pshow ps = unwords $ [ stretch 4 $ show (Prelude.length ps) , "Platzierungen" , ":" , cshow ps ] cshow ps = fshow $ addListToFM_C (+) emptyFM $ Prelude.zip ps $ repeat (1 :: Integer) fshow pfm = unwords $ do p <- [1..10] return $ stretch 3 $ case lookupFM pfm p of Just k -> show k _ -> [] -- | gesamtliste der highscore collect :: Bool -> UNr -> DataFM -> IO [ ( Either (Obfuscated MNr) (Obfuscated SNr) , (Int , [Int] ) ) ] -- ^ ( Matrikel, Punkt, Plätze ) collect deco u fm = do let nice (e,p) = if False -- deco then do SE s _ <- decorate u e return ( error "Scorer.Emit.collect") -- ( show s , p ) else return ( matrikel e , p ) infos <- mapM nice $ do (auf,es) <- fmToList fm (e,p,k) <- zip3 (realize es) scorePoints [1..] return (e,(p,[k])) return $ Prelude.take scoreItems $ sortBy ( \ (_,(p,_)) -> negate p ) -- größten zuerst $ fmToList $ addListToFM_C ( \ (x,xs) (y,ys) -> (x+y,xs++ys) ) emptyFM $ infos {- collect :: DataFM -> [ ( MNr, Int ) ] -- ^ ( Matrikel, Punkt ) collect fm = take scoreItems $ sortBy ( \ (m, p) -> negate p ) -- größten zuerst $ fmToList $ addListToFM_C (+) emptyFM $ do ( auf, es ) <- fmToList fm ( e, p ) <- zip ( realize es ) scorePoints return ( matrikel e, p ) -}
marcellussiegburg/autotool
db/src/Scorer/Emit.hs
gpl-2.0
5,434
128
22
1,759
1,736
939
797
123
3
{-# LANGUAGE FlexibleInstances, UndecidableInstances, TypeSynonymInstances #-} {-# LANGUAGE LambdaCase #-} module Data.Binary.StringRef ( ListOfStringable(..) , StringReferencingBinary(..) , IntLen(..) , ls_encode , ls_decode ) where import Data.Binary import Data.Binary.Put import Data.Binary.Get import Control.Monad import Control.Applicative ((<$>)) import Data.List import Data.ByteString.Lazy (ByteString) import qualified Data.MyText as T import Data.MyText (Text, decodeUtf8, encodeUtf8) import Debug.Trace class StringReferencingBinary a => ListOfStringable a where listOfStrings :: a -> [Text] -- | An extended version of Binary that passes the list of strings of the -- previous sample class StringReferencingBinary a where ls_put :: [Text] -> a -> Put ls_get :: [Text] -> Get a ------------------------------------------------------------------------ -- Instances for the first few tuples instance (StringReferencingBinary a, StringReferencingBinary b) => StringReferencingBinary (a,b) where ls_put strs (a,b) = ls_put strs a >> ls_put strs b ls_get strs = liftM2 (,) (ls_get strs) (ls_get strs) instance (StringReferencingBinary a, StringReferencingBinary b, StringReferencingBinary c) => StringReferencingBinary (a,b,c) where ls_put strs (a,b,c) = ls_put strs a >> ls_put strs b >> ls_put strs c ls_get strs = liftM3 (,,) (ls_get strs) (ls_get strs) (ls_get strs) instance (StringReferencingBinary a, StringReferencingBinary b, StringReferencingBinary c, StringReferencingBinary d) => StringReferencingBinary (a,b,c,d) where ls_put strs (a,b,c,d) = ls_put strs a >> ls_put strs b >> ls_put strs c >> ls_put strs d ls_get strs = liftM4 (,,,) (ls_get strs) (ls_get strs) (ls_get strs) (ls_get strs) instance (StringReferencingBinary a, StringReferencingBinary b, StringReferencingBinary c, StringReferencingBinary d, StringReferencingBinary e) => StringReferencingBinary (a,b,c,d,e) where ls_put strs (a,b,c,d,e) = ls_put strs a >> ls_put strs b >> ls_put strs c >> ls_put strs d >> ls_put strs e ls_get strs = liftM5 (,,,,) (ls_get strs) (ls_get strs) (ls_get strs) (ls_get strs) (ls_get strs) newtype CompactNum a = CompactNum { fromCompactNum :: a } instance (Integral a, Num a, Binary a) => StringReferencingBinary (CompactNum a) where ls_put _ (CompactNum i) | 0 <= i && i < 255 = putWord8 (fromIntegral i) | otherwise = putWord8 255 >> put i ls_get _ = fmap CompactNum $ getWord8 >>= \case i | 0 <= i && i < 255 -> return (fromIntegral i) | otherwise -> get instance StringReferencingBinary a => StringReferencingBinary [a] where ls_put strs l = ls_put strs (CompactNum (length l)) >> mapM_ (ls_put strs) l ls_get strs = ls_getMany strs . fromCompactNum =<< ls_get strs instance StringReferencingBinary Text where ls_put strs s = case elemIndex s strs of Just i | 0 <= i && i < 255 -> putWord8 (fromIntegral (succ i)) _ -> putWord8 0 >> ls_put strs (T.unpack s) ls_get strs = getWord8 >>= \case 0 -> T.pack <$> ls_get strs i -> return $! strs !! fromIntegral (pred i) -- | 'ls_get strsMany n' ls_get strs 'n' elements in order, without blowing the stack. ls_getMany :: StringReferencingBinary a => [Text] -> Int -> Get [a] ls_getMany strs n = go [] n where go xs 0 = return $! reverse xs go xs i = do x <- ls_get strs -- we must seq x to avoid stack overflows due to laziness in -- (>>=) x `seq` go (x:xs) (i-1) {-# INLINE ls_getMany #-} -- compat newtype for deserialization of v2-v4 CaptureData newtype IntLen a = IntLen { fromIntLen :: a } -- compat instance for deserialization of v1 CaptureData instance Binary a => Binary (IntLen a) where put = put . fromIntLen get = IntLen <$> get -- compat instance for deserialization of v2-v4 CaptureData instance StringReferencingBinary a => StringReferencingBinary (IntLen [a]) where ls_put strs (IntLen l) = ls_put strs (length l) >> mapM_ (ls_put strs) l ls_get strs = fmap IntLen $ ls_getMany strs =<< ls_get strs -- compat instance for deserialization of v2-v4 CaptureData instance StringReferencingBinary (IntLen Text) where ls_put strs (IntLen s) = case elemIndex s strs of Just i | 0 <= i && i < 255 -> putWord8 (fromIntegral (succ i)) _ -> putWord8 0 >> ls_put strs (IntLen (T.unpack s)) ls_get strs = fmap IntLen $ getWord8 >>= \case 0 -> T.pack . fromIntLen <$> ls_get strs i -> return $! strs !! fromIntegral (pred i) {- instance Binary a => StringReferencingBinary a where ls_put _ = put ls_get _ = get -} instance StringReferencingBinary Char where { ls_put _ = put; ls_get _ = get } instance StringReferencingBinary Int where { ls_put _ = put; ls_get _ = get } instance StringReferencingBinary Integer where { ls_put _ = put; ls_get _ = get } instance StringReferencingBinary Bool where { ls_put _ = put; ls_get _ = get } ls_encode :: StringReferencingBinary a => [Text] -> a -> ByteString ls_encode strs = runPut . ls_put strs {-# INLINE ls_encode #-} -- | Decode a value from a lazy ByteString, reconstructing the original structure. -- ls_decode :: StringReferencingBinary a => [Text] -> ByteString -> a ls_decode strs = runGet (ls_get strs)
nomeata/darcs-mirror-arbtt
src/Data/Binary/StringRef.hs
gpl-2.0
5,618
0
15
1,384
1,759
913
846
84
2
module Coloring ( livenessAnalysis, livenessGraph, graphColoring, registerAllocate, dotAllocationGraph, ) where import Data.Maybe import Data.List import Data.Function import Data.Ord import Data.Graph.Inductive.Graph import Data.Graph.Inductive.PatriciaTree import Data.Graph.Inductive.Dot import System.Process import Control.Monad.State import Debug.Trace import Language import qualified X86 as X86 type Lifetime = (Int, Int) meet :: Lifetime -> Lifetime -> Bool meet (p,q) (s,t) = if p <= s then s <= q else p <= t livenessAnalysis :: Int -> [A ()] -> [(Cell, Lifetime)] livenessAnalysis _ [] = [] livenessAnalysis n (x:xs) = birth n x xs ++ livenessAnalysis (n+1) xs where birth n (AMov (Cell i) _) rest = death n (n+1) i rest birth n _ _ = [] death m n i (AAdd _ (Cell j):_) | i == j = [(i,(m,n))] death m n i (AAdd _ _:rest) = death m (n+1) i rest death m n i (ASub _ (Cell j):_) | i == j = [(i,(m,n))] death m n i (ASub _ _:rest) = death m (n+1) i rest death m n i (AMul (Cell j):_) | i == j = [(i,(m,n))] death m n i (AMul _:rest) = death m (n+1) i rest death m n i (AMov (Cell j) _:_) | i == j = [(i,(m,n))] death m n i (AMov _ _:rest) = death m (n+1) i rest death m n i [] = [(i,(m,n))] livenessGraph :: [(Node, Lifetime)] -> Gr Lifetime () livenessGraph analysis = mkGraph nodes edges where nodes = analysis edges = concatMap overlaps nodes overlaps (i,life) = map (\(j, _) -> (i, j, ())) . filter (meet life . snd) . filter (\(j,_) -> j /= i) $ analysis coloring graph = execState (mapM colorVertex heuristic) [] where -- sort the vertices of the graph in order of most edges first heuristic = sortBy (flip (comparing (deg graph))) . nodes $ graph colorVertex i = do let ne = neighbors graph i colors <- get let neColors = catMaybes . map (flip lookup colors) $ ne let myColor = head $ [1..] \\ neColors put ((i,myColor):colors) graphColoring graph = gmap color graph where color (l, i, _, r) = (l, i, fromJust . lookup i $ colors, r) colors = coloring graph registerAllocate asm = map r asm where colors = graphColoring . livenessGraph . livenessAnalysis 0 $ asm priority = map (snd . head) . sortBy (flip (comparing length)) . groupBy ((==)`on`snd) . labNodes $ colors allocation = zip priority ([X86.R X86.EBX, X86.R X86.ECX, X86.R X86.ESI, X86.R X86.EDI] ++ map ((X86.DV) . ("ev"++) . show) [0..]) r (AAdd x y) = X86.Add (i x) (i y) r (ASub x y) = X86.Sub (i x) (i y) r (AMul x) = X86.Mul (i x) r (AMov x y) = X86.Mov (i x) (i y) i (Register ()) = X86.R X86.EAX i (Deref ()) = X86.DR X86.EAX i (Cell c) = let y = lookup c . labNodes $ colors in let x = lookup (fromJust y) $ allocation in fromJust x i (Num n) = X86.I n dotAllocationGraph asm = do let dot = showDot . fglToDot . graphColoring . livenessGraph . livenessAnalysis 0 $ asm writeFile "file.dot" dot system("dot -Tpng -ofile.png file.dot")
orchid-hybrid/bee
Bee/Coloring.hs
gpl-3.0
3,119
2
18
826
1,581
824
757
72
10
import Tree (isLeaf, fringe)
evolutics/haskell-formatter
testsuite/resources/source/orders_parts/root_import_entities/Input.hs
gpl-3.0
29
0
5
4
12
7
5
1
0
module ScopalVerbs (rules) where import AbsAST rules = [ "(ComplVV manage_to $1) -> $1" , "(UseCl $3 PPos (PredVP $2 (ComplVV forget_to $1) ^ (UseCl $3 PPos (PredVP $2 $1))" , "(UseCl $3 PPos (PredVP $2 (ComplVV forget_to $1) -> (UseCl $3 PNeg (PredVP $2 $1))" , "(UseCl $3 PPos (PredVP $2 (ComplVV refused_to $1) | (UseCl $3 PPos (PredVP $2 $1))" , "(UseCl $3 PPos (PredVP $2 (ComplVV refused_to $1) -> (UseCl $3 PNeg (PredVP $2 $1))" ]
cunger/mule
src/rules/ScopalVerbs.hs
gpl-3.0
496
0
5
137
32
21
11
8
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Repair -- 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) -- -- Recreates the required App Engine features for the specified App Engine -- application, for example a Cloud Storage bucket or App Engine service -- account. Use this method if you receive an error message about a missing -- feature, for example, Error retrieving the App Engine service account. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ Google App Engine Admin API Reference> for @appengine.apps.repair@. module Network.Google.Resource.AppEngine.Apps.Repair ( -- * REST Resource AppsRepairResource -- * Creating a Request , appsRepair , AppsRepair -- * Request Lenses , arXgafv , arUploadProtocol , arPp , arAccessToken , arUploadType , arPayload , arBearerToken , arAppsId , arCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.repair@ method which the -- 'AppsRepair' request conforms to. type AppsRepairResource = "v1" :> "apps" :> CaptureMode "appsId" "repair" Text :> QueryParam "$.xgafv" Text :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RepairApplicationRequest :> Post '[JSON] Operation -- | Recreates the required App Engine features for the specified App Engine -- application, for example a Cloud Storage bucket or App Engine service -- account. Use this method if you receive an error message about a missing -- feature, for example, Error retrieving the App Engine service account. -- -- /See:/ 'appsRepair' smart constructor. data AppsRepair = AppsRepair' { _arXgafv :: !(Maybe Text) , _arUploadProtocol :: !(Maybe Text) , _arPp :: !Bool , _arAccessToken :: !(Maybe Text) , _arUploadType :: !(Maybe Text) , _arPayload :: !RepairApplicationRequest , _arBearerToken :: !(Maybe Text) , _arAppsId :: !Text , _arCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'AppsRepair' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'arXgafv' -- -- * 'arUploadProtocol' -- -- * 'arPp' -- -- * 'arAccessToken' -- -- * 'arUploadType' -- -- * 'arPayload' -- -- * 'arBearerToken' -- -- * 'arAppsId' -- -- * 'arCallback' appsRepair :: RepairApplicationRequest -- ^ 'arPayload' -> Text -- ^ 'arAppsId' -> AppsRepair appsRepair pArPayload_ pArAppsId_ = AppsRepair' { _arXgafv = Nothing , _arUploadProtocol = Nothing , _arPp = True , _arAccessToken = Nothing , _arUploadType = Nothing , _arPayload = pArPayload_ , _arBearerToken = Nothing , _arAppsId = pArAppsId_ , _arCallback = Nothing } -- | V1 error format. arXgafv :: Lens' AppsRepair (Maybe Text) arXgafv = lens _arXgafv (\ s a -> s{_arXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). arUploadProtocol :: Lens' AppsRepair (Maybe Text) arUploadProtocol = lens _arUploadProtocol (\ s a -> s{_arUploadProtocol = a}) -- | Pretty-print response. arPp :: Lens' AppsRepair Bool arPp = lens _arPp (\ s a -> s{_arPp = a}) -- | OAuth access token. arAccessToken :: Lens' AppsRepair (Maybe Text) arAccessToken = lens _arAccessToken (\ s a -> s{_arAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). arUploadType :: Lens' AppsRepair (Maybe Text) arUploadType = lens _arUploadType (\ s a -> s{_arUploadType = a}) -- | Multipart request metadata. arPayload :: Lens' AppsRepair RepairApplicationRequest arPayload = lens _arPayload (\ s a -> s{_arPayload = a}) -- | OAuth bearer token. arBearerToken :: Lens' AppsRepair (Maybe Text) arBearerToken = lens _arBearerToken (\ s a -> s{_arBearerToken = a}) -- | Part of \`name\`. Name of the application to repair. Example: -- apps\/myapp arAppsId :: Lens' AppsRepair Text arAppsId = lens _arAppsId (\ s a -> s{_arAppsId = a}) -- | JSONP arCallback :: Lens' AppsRepair (Maybe Text) arCallback = lens _arCallback (\ s a -> s{_arCallback = a}) instance GoogleRequest AppsRepair where type Rs AppsRepair = Operation type Scopes AppsRepair = '["https://www.googleapis.com/auth/cloud-platform"] requestClient AppsRepair'{..} = go _arAppsId _arXgafv _arUploadProtocol (Just _arPp) _arAccessToken _arUploadType _arBearerToken _arCallback (Just AltJSON) _arPayload appEngineService where go = buildClient (Proxy :: Proxy AppsRepairResource) mempty
rueshyna/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Repair.hs
mpl-2.0
5,882
0
19
1,503
941
548
393
130
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AdSenseHost.Accounts.List -- 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) -- -- List hosted accounts associated with this AdSense account by ad client -- id. -- -- /See:/ <https://developers.google.com/adsense/host/ AdSense Host API Reference> for @adsensehost.accounts.list@. module Network.Google.Resource.AdSenseHost.Accounts.List ( -- * REST Resource AccountsListResource -- * Creating a Request , accountsList , AccountsList -- * Request Lenses , alFilterAdClientId ) where import Network.Google.AdSenseHost.Types import Network.Google.Prelude -- | A resource alias for @adsensehost.accounts.list@ method which the -- 'AccountsList' request conforms to. type AccountsListResource = "adsensehost" :> "v4.1" :> "accounts" :> QueryParams "filterAdClientId" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Accounts -- | List hosted accounts associated with this AdSense account by ad client -- id. -- -- /See:/ 'accountsList' smart constructor. newtype AccountsList = AccountsList' { _alFilterAdClientId :: [Text] } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AccountsList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'alFilterAdClientId' accountsList :: [Text] -- ^ 'alFilterAdClientId' -> AccountsList accountsList pAlFilterAdClientId_ = AccountsList' {_alFilterAdClientId = _Coerce # pAlFilterAdClientId_} -- | Ad clients to list accounts for. alFilterAdClientId :: Lens' AccountsList [Text] alFilterAdClientId = lens _alFilterAdClientId (\ s a -> s{_alFilterAdClientId = a}) . _Coerce instance GoogleRequest AccountsList where type Rs AccountsList = Accounts type Scopes AccountsList = '["https://www.googleapis.com/auth/adsensehost"] requestClient AccountsList'{..} = go _alFilterAdClientId (Just AltJSON) adSenseHostService where go = buildClient (Proxy :: Proxy AccountsListResource) mempty
brendanhay/gogol
gogol-adsense-host/gen/Network/Google/Resource/AdSenseHost/Accounts/List.hs
mpl-2.0
2,848
0
12
613
318
196
122
50
1
import CanvasHs import CanvasHs.Data import Widgets data State = State Int initState = State 3 -- | call widgetHandler with your personal state main = widgetHandler handler initState -- | Be wary, you get CombinedState here containing your state handler state StartEvent = (state, shape $ Container 900 600 [checkboxShape]) where (widgetState, checkboxShape) = newRadioButton 3 "myRadioButton" ["optie 1", "optie 2", "optie 3", "optie 4"] {- data WidgetState = WidgetState { widgets :: [Widget], hasFocus :: Widget } data Widget = DropDown { dropDownId :: String, options :: [String], selected :: Int, collapsed :: Bool, offset :: Int } | NoWidget initState = WidgetState [] NoWidget main = installEventHandler handler initState handler :: WidgetState -> Event -> (WidgetState, Output) handler st StartEvent = (st, shape $ drawDropDown ndd) where widgs = widgets st ndd = newDropDown "abcde" (map (\x -> "Optie: " ++ (show x)) [1..10]) newWidgs = (ndd):widgs drawDropDown :: Widget -> Shape drawDropDown DropDown{dropDownId = dropDownId, options = options, selected = selected, collapsed = collapsed, offset = offset} = Container 256 totalSize ([ -- | De omtrek Fill (255, 255, 255, 1.0) $ Stroke (64, 64, 64, 1.0) 1 $ Rect (0, 0) 256 32, -- | Het tekstvak Translate 8 8 $ Container 216 16 [Text (0,0) (options !! selected) defaults{size=16}], -- | het pijltje van de dropdown Translate 224 0 $ Event defaults{eventId=dropDownId, mouseClick = True} $ Container 32 32 [Stroke (128, 128, 128, 1.0) 1 $ Fill (64, 64, 64, 1.0) $ Polygon [(8, 10), (16, 16), (24, 10), (16, 22)]], -- | De container waar straks de andere opties instaan Translate 0 32 $ Fill (255, 255, 255, 1.0) $ Stroke (64, 64, 64, 1.0) 1 $ Rect (0, 0) 256 dropDownSize ] ++ (if (not collapsed) then [ -- | De andere opties, als de dropdown open is :P Translate 8 40 $ Container 240 192 (map (\x -> Translate 0 (32 * x) $ Text (0,0) (options !! (x + offset)) defaults{size=16} ) [0..(maxLen - 1)]) ] else [])) where len = length options maxLen = min len 6 totalSize = if collapsed then 32 else (maxLen + 1) * 32 dropDownSize = maxLen * 32 newDropDown :: String -> [String] -> Widget newDropDown newId options = DropDown ("dropdown:" ++ newId) options 0 True 0 -}
CanvasHS/Widgets
demo.hs
lgpl-2.1
2,478
1
8
636
110
59
51
8
1
-- Solutions to H99 problems -- import System.Random -- -- Exercises 1 to 28: Lists --Ex 1 myLast :: [a] -> a myLast [x] = x myLast (x:xs) = myLast xs --Ex 2 myButLast :: [a] -> a myButLast [x,_] = x myButLast (x:xs) = myButLast xs --Ex 3 elementAt :: (Integral b) => [a] -> b -> a elementAt (x:xs) 0 = x elementAt (x:xs) ix = elementAt xs (ix-1) --Ex 4 myLength :: (Integral b) => [a] -> b myLength [] = 0 myLength (x:xs) = myLength xs + 1 --Ex 5 myReverse :: [a] -> [a] myReverse [] = [] myReverse xs = foldl (\acc x -> x:acc) [] xs --Ex 6 myPalindrome :: Eq a => [a] -> Bool myPalindrome [] = True myPalindrome x = x == myReverse x --Ex 7 data NestedList a = Elem a | List [NestedList a] myFlatten :: NestedList a -> [a] myFlatten (Elem a) = [a] myFlatten (List inner) = foldl (\acc x -> acc ++ (myFlatten x)) [] inner --Ex 8 compress :: Eq a => [a] -> [a] compress [] = [] compress (x:xs) = x : (compress $ dropWhile (== x) xs) --Ex 9 pack :: Eq a => [a] -> [[a]] pack [] = [] pack list = let (left,right) = span (== head list) list in left : pack right --Ex 10 encode :: (Eq a) => [a] -> [(Int, a)] encode list = map (\x -> (length x, head x)) (pack list) --Ex 11 data RleElem c a = Single a | Multiple c a deriving Show encode' :: (Integral c, Eq a) => [a] -> [RleElem c a] encode' list = map (\x -> case length x of 1 -> Single (head x) _ -> Multiple (fromIntegral $ length x) (head x)) (pack list) --Ex 12 decode :: (Integral c) => [RleElem c a] -> [a] decode list = foldr (\x acc -> case x of Single elem -> elem:acc Multiple count elem -> (replicate (fromIntegral count) elem) ++ acc) [] list --Ex 13 encodeDirect :: (Integral c, Eq a) => [a] -> [RleElem c a] encodeElem :: Integral c => c -> a -> RleElem c a encodeElem c a = if c > 1 then (Multiple c a) else (Single a) encodeInner :: (Integral c, Eq a) => (c,a) -> [a] -> [RleElem c a] encodeInner (c,a) [] = [encodeElem c a] encodeInner (c,a) (h:t) | a == h = encodeInner (c+1, a) t | otherwise = (encodeElem c a) : encodeInner (1,h) t encodeDirect [] = [] encodeDirect (h:t) = encodeInner (1, h) t --Ex 14 dupli :: [a] -> [a] dupli [] = [] dupli (x:xs) = x:x:(dupli xs) --Ex 15 repli :: Integral c => [a] -> c -> [a] repli [] _ = [] repli (x:xs) c = (replicate (fromIntegral c) x) ++ (repli xs c) --Ex 16 dropEvery :: Integral c => [a] -> c -> [a] -- I don't really like the foldr solution --dropEvery list n = foldr (\(x,c) acc -> if c `mod` n == 0 then acc -- else x:acc) [] (zip list [1..]) dropEvery list n = map fst $ filter (\(x,c) -> c `mod` n /= 0) (zip list [1..]) --Ex 17 split :: Integral c => [a] -> c -> ([a],[a]) helper :: Integral c => [a] -> c -> [a] -> ([a],[a]) helper front n back = if n == 0 then (front, back) else helper (front ++ [head back]) (n-1) (tail back) split list c = helper [] c list --Ex 18 slice :: Int -> Int -> ([a] -> [a]) slice i k = take (k-i+1) . drop (i-1) --Ex 19 rotate :: Int -> [a] -> [a] rotate c list@(x:xs) | c == 0 = list | c < 0 = rotate (length list + c) list | c > 0 = rotate (c-1) (xs ++ [x]) --Ex 20 removeAt :: Int -> [a] -> (a, [a]) removeAt c list = (head (drop (c-1) list), (take (c-1) list) ++ (drop c list)) --Ex 21 insertAt :: Int -> a -> [a] -> [a] insertAt c e xs = f ++ e : s where f = take (c-1) xs s = drop (c-1) xs --Ex 22 range :: Int -> Int -> [Int] range a b = [x | x <- [a..b]] --Ex 23 rndSelect :: Int -> [a] -> [a] rndSelect 0 _ = [] rndSelect c xs = foldl fun [] $ take c $ randomRs (1, length xs) (mkStdGen seed) where fun acc r = (elementAt xs r) : acc seed = 42 -- exercise 23 variation with generator passing rndSelect' :: (RandomGen g) => Int -> [a] -> g -> ([a], g) rndSelect' 0 _ g = ([], g) rndSelect' n xs g = ((at i) : ys, g'') where at = elementAt xs (i, g') = randomR (1, length xs) g (ys, g'') = rndSelect' (n-1) xs g'
bananu7/H99-solutions
ex-01-28-lists.hs
unlicense
4,163
6
15
1,221
2,255
1,194
1,061
93
2
module EitherMonad where import Control.Applicative -- years ago type Founded = Int -- number of programmers type Coders = Int data SoftwareShop = Shop { founded :: Founded , programmers :: Coders } deriving (Eq, Show) data FoundedError = NegativeYears Founded | TooManyYears Founded | NegativeCoders Coders | TooManyCoders Coders | TooManyCodersForYears Founded Coders deriving (Eq, Show) validateFounded :: Int -> Either FoundedError Founded validateFounded n | n < 0 = Left $ NegativeYears n | n > 500 = Left $ TooManyYears n | otherwise = Right n -- Tho, many programmers *are* negative. validateCoders :: Int -> Either FoundedError Coders validateCoders n | n < 0 = Left $ NegativeCoders n | n > 5000 = Left $ TooManyCoders n | otherwise = Right n mkSoftware :: Int -> Int -> Either FoundedError SoftwareShop mkSoftware years coders = do founded <- validateFounded years programmers <- validateCoders coders if programmers > div founded 10 then Left $ TooManyCodersForYears founded programmers else Right $ Shop founded programmers -- Either monad data Sum a b = First a | Second b deriving (Eq, Show) instance Functor (Sum a) where fmap _ (First a) = First a fmap f (Second b) = Second (f b) instance Applicative (Sum a) where pure = Second First x <*> _ = First x Second _ <*> First x = First x Second f <*> Second x = Second (f x) instance Monad (Sum a) where return = pure First x >>= _ = First x Second x >>= f = f x
dmvianna/haskellbook
src/Ch18-EitherMonad.hs
unlicense
1,618
0
9
448
547
269
278
45
2
{-# LANGUAGE OverloadedStrings #-} module Haskoin.Crypto.SignatureSpec (spec) where import Control.Monad import Data.Bits (testBit) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Serialize as S import Data.String.Conversions (cs) import Data.Text (Text) import Haskoin.Address import Haskoin.Transaction import Haskoin.Keys import Haskoin.Crypto import Haskoin.Script import Haskoin.Constants import Haskoin.Util import Haskoin.Util.Arbitrary import Haskoin.UtilSpec (readTestFile) import Test.Hspec import Test.Hspec.QuickCheck import Test.HUnit import Test.QuickCheck spec :: Spec spec = do describe "Signature properties" $ do prop "verify signature" $ forAll arbitrarySignature $ \(m, key', sig) -> verifyHashSig m sig (derivePubKey key') prop "s component less than half order" $ forAll arbitrarySignature $ isCanonicalHalfOrder . lst3 prop "encoded signature is canonical" $ forAll arbitrarySignature $ testIsCanonical . lst3 prop "decodeStrictSig . exportSig identity" $ forAll arbitrarySignature $ (\s -> decodeStrictSig (exportSig s) == Just s) . lst3 prop "importSig . exportSig identity" $ forAll arbitrarySignature $ (\s -> importSig (exportSig s) == Just s) . lst3 prop "getSig . putSig identity" $ forAll arbitrarySignature $ (\s -> runGet getSig (runPut $ putSig s) == Right s) . lst3 describe "Signature vectors" $ checkDistSig $ \file1 file2 -> do vectors <- runIO (readTestFile file1 :: IO [(Text, Text, Text)]) vectorsDER <- runIO (readTestFile file2 :: IO [(Text, Text, Text)]) it "Passes the trezor rfc6979 test vectors" $ mapM_ (testRFC6979Vector . toVector) vectors it "Passes the rfc6979 DER test vectors" $ mapM_ (testRFC6979DERVector . toVector) vectorsDER describe "BIP143 signature vectors" $ do it "agrees with BIP143 p2wpkh example" testBip143p2wpkh it "agrees with BIP143 p2sh-p2wpkh example" testBip143p2shp2wpkh it "builds a p2wsh multisig transaction" testP2WSHMulsig it "agrees with BIP143 p2sh-p2wsh multisig example" testBip143p2shp2wpkhMulsig -- github.com/bitcoin/bitcoin/blob/master/src/script.cpp -- from function IsCanonicalSignature testIsCanonical :: Sig -> Bool testIsCanonical sig = not $ -- Non-canonical signature: too short (len < 8) || -- Non-canonical signature: too long (len > 72) || -- Non-canonical signature: wrong type (BS.index s 0 /= 0x30) || -- Non-canonical signature: wrong length marker (BS.index s 1 /= len - 2) || -- Non-canonical signature: S length misplaced (5 + rlen >= len) || -- Non-canonical signature: R+S length mismatch (rlen + slen + 6 /= len) || -- Non-canonical signature: R value type mismatch (BS.index s 2 /= 0x02) || -- Non-canonical signature: R length is zero (rlen == 0) || -- Non-canonical signature: R value negative testBit (BS.index s 4) 7 || -- Non-canonical signature: R value excessively padded ( rlen > 1 && BS.index s 4 == 0 && not (testBit (BS.index s 5) 7) ) || -- Non-canonical signature: S value type mismatch (BS.index s (fromIntegral rlen + 4) /= 0x02) || -- Non-canonical signature: S length is zero (slen == 0) || -- Non-canonical signature: S value negative testBit (BS.index s (fromIntegral rlen+6)) 7 || -- Non-canonical signature: S value excessively padded ( slen > 1 && BS.index s (fromIntegral rlen + 6) == 0 && not (testBit (BS.index s (fromIntegral rlen + 7)) 7) ) where s = exportSig sig len = fromIntegral $ BS.length s rlen = BS.index s 3 slen = BS.index s (fromIntegral rlen + 5) -- RFC6979 note: Different libraries of libsecp256k1 use different constants -- to produce a nonce. Thus, their deterministric signatures will be different. -- We still want to test against fixed signatures so we need a way to switch -- between implementations. We check the output of signMsg 1 0 data ValidImpl = ImplCore | ImplABC implSig :: Text implSig = encodeHex $ exportSig $ signMsg "0000000000000000000000000000000000000000000000000000000000000001" "0000000000000000000000000000000000000000000000000000000000000000" -- We have test vectors for these cases validImplMap :: Map Text ValidImpl validImplMap = Map.fromList [ ( "3045022100a0b37f8fba683cc68f6574cd43b39f0343a50008bf6ccea9d13231\ \d9e7e2e1e4022011edc8d307254296264aebfc3dc76cd8b668373a072fd64665\ \b50000e9fcce52" , ImplCore) , ( "304402200581361d23e645be9e3efe63a9a2ac2e8dd0c70ba3ac8554c9befe06\ \0ad0b36202207d8172f1e259395834793d81b17e986f1e6131e4734969d2f4ae\ \3a9c8bc42965" , ImplABC) ] getImpl :: Maybe ValidImpl getImpl = implSig `Map.lookup` validImplMap rfc6979files :: ValidImpl -> (FilePath, FilePath) rfc6979files ImplCore = ("rfc6979core.json", "rfc6979DERcore.json") rfc6979files ImplABC = ("rfc6979abc.json", "rfc6979DERabc.json") checkDistSig :: (FilePath -> FilePath -> Spec) -> Spec checkDistSig go = case rfc6979files <$> getImpl of Just (file1, file2) -> go file1 file2 _ -> it "Passes rfc6979 test vectors" $ void $ assertFailure "Invalid rfc6979 signature" {- Trezor RFC 6979 Test Vectors -} -- github.com/trezor/python-ecdsa/blob/master/ecdsa/test_pyecdsa.py toVector :: (Text, Text, Text) -> (SecKey, ByteString, Text) toVector (prv, m, res) = (fromJust $ (secKey <=< decodeHex) prv, cs m, res) testRFC6979Vector :: (SecKey, ByteString, Text) -> Assertion testRFC6979Vector (prv, m, res) = do assertEqual "RFC 6979 Vector" res (encodeHex $ encode $ exportCompactSig s) assertBool "Signature is valid" $ verifyHashSig h s (derivePubKey prv) assertBool "Signature is canonical" $ testIsCanonical s assertBool "Signature is normalized" $ isCanonicalHalfOrder s where h = sha256 m s = signHash prv h -- Test vectors from: -- https://crypto.stackexchange.com/questions/20838/request-for-data-to-test-deterministic-ecdsa-signature-algorithm-for-secp256k1 testRFC6979DERVector :: (SecKey, ByteString, Text) -> Assertion testRFC6979DERVector (prv, m, res) = do assertEqual "RFC 6979 DER Vector" res (encodeHex $ exportSig s) assertBool "DER Signature is valid" $ verifyHashSig h s (derivePubKey prv) assertBool "DER Signature is canonical" $ testIsCanonical s assertBool "DER Signature is normalized" $ isCanonicalHalfOrder s where h = sha256 m s = signHash prv h -- Reproduce the P2WPKH example from BIP 143 testBip143p2wpkh :: Assertion testBip143p2wpkh = case getImpl of Just ImplCore -> assertEqual "BIP143 Core p2wpkh" (Right signedTxCore) generatedSignedTx Just ImplABC -> assertEqual "BIP143 ABC p2wpkh" (Right signedTxABC) generatedSignedTx Nothing -> assertFailure "Invalid secp256k1 library" where signedTxCore = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\ \541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742f\ \a9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1\ \c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89\ \d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffff\ \ffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac\ \7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0\ \167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32\ \a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f33\ \58f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e\ \7acafcdb3566bb0ad253f62fc70f07aeee635711000000" signedTxABC = "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433\ \541db4e4ad969f000000004847304402200fbc9dad97500334e47c2dca50096a\ \2117c01952c2870102e320823d21c36229022007cb36c2b141d11c08ef81d948\ \f148332fc09fe8f6d226aaaf8ba6ae0d8a66ba01eeffffffef51e1b804cc89d1\ \82d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffff\ \ff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a\ \6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f016\ \7faa815988ac0002473044022011cb891cee521eb1fc7aef681655a881288553\ \fc024cff9cee5007bae5e6b8c602200b89d60ee2f98aa9a645dad59cd680b4b6\ \25f343efcd3e7fb70852100ef601890121025476c2e83188368da1ff3e292e7a\ \cafcdb3566bb0ad253f62fc70f07aeee635711000000" unsignedTx = "0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541d\ \b4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b\ \1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb20600000000\ \1976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d0000\ \00001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000" Just key0 = secHexKey "bbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866" pubKey0 = toPubKey key0 Just key1 = secHexKey "619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9" [op0, op1] = prevOutput <$> txIn unsignedTx sigIn0 = SigInput (PayPK pubKey0) 625000000 op0 sigHashAll Nothing WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key1 sigIn1 = SigInput (PayWitnessPKHash h) 600000000 op1 sigHashAll Nothing generatedSignedTx = signTx btc unsignedTx [sigIn0, sigIn1] [key0, key1] -- Reproduce the P2SH-P2WPKH example from BIP 143 testBip143p2shp2wpkh :: Assertion testBip143p2shp2wpkh = case getImpl of Just ImplCore -> assertEqual "BIP143 Core p2sh-p2wpkh" (Right signedTxCore) generatedSignedTx Just ImplABC -> assertEqual "BIP143 ABC p2sh-p2wpkh" (Right signedTxABC) generatedSignedTx Nothing -> assertFailure "Invalid secp256k1 library" where signedTxCore = "01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\ \ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\ \df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\ \c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\ \a7ad0402e8bd8ad6d77c88ac02473044022047ac8e878352d3ebbde1c94ce3a1\ \0d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d\ \877c1f64677e3622ad4010726870540656fe9dcb012103ad1d8e89212f0b92c7\ \4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000" signedTxABC = "01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092\ \ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009b\ \df0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bb\ \c043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fe\ \a7ad0402e8bd8ad6d77c88ac024730440220091c78fd1e21535f6ddc45515e4c\ \afca15cdf344765d72c1529fb82d3ada2d1802204a980d5e37d0b04f5e1185a0\ \f97295c383764e9a4b08d8bd1161b33c6719139a012103ad1d8e89212f0b92c7\ \4d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000" unsignedTx = "0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d\ \3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7\ \f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b\ \1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000" Just key0 = secHexKey "eb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf" op0 = prevOutput . head $ txIn unsignedTx WitnessPubKeyAddress h = pubKeyWitnessAddr $ toPubKey key0 sigIn0 = SigInput (PayWitnessPKHash h) 1000000000 op0 sigHashAll Nothing generatedSignedTx = signNestedWitnessTx btc unsignedTx [sigIn0] [key0] -- P2WSH multisig example (tested against bitcoin-core 0.19.0.1) testP2WSHMulsig :: Assertion testP2WSHMulsig = case getImpl of Just ImplCore -> assertEqual "Core p2wsh multisig" (Right signedTxCore) generatedSignedTx Just ImplABC -> assertEqual "ABC p2wsh multisig" (Right signedTxABC) generatedSignedTx Nothing -> assertFailure "Invalid secp256k1 library" where signedTxCore = "01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\ \34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\ \2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100fad4fedd2b\ \b4c439c64637eb8e9150d9020a7212808b8dc0578d5ff5b4ad65fe0220714640\ \f261b37eb3106310bf853f4b706e51436fb6b64c2ab00768814eb55b98014730\ \44022100baff4e4ceea4022b9725a2e6f6d77997a554f858165b91ac8c16c983\ \3008bee9021f5f70ebc3f8580dc0a5e96451e3697bdf1f1f5883944f0f33ab0c\ \fb272354040169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea811\ \549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f69e\ \a311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695e2\ \d8e007a7f26db96c2ee42db15dc953ae00000000" signedTxABC = "01000000000101d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f8961\ \34a448c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a35\ \2cab583b12fbcb26d1269b4a2c951a33ad88ac0400483045022100b79bf3714a\ \50f8f0e2f946034361ba4f6567b796d55910d89e98720d2e99f98c0220134879\ \518002df23e80a058475fa8b10bc4182bedfecd5f85e446a00f211ea53014830\ \45022100ce3c77480d664430a7544c1a962d1ae31151109a528a37e5bccc92ba\ \2e460ad10220317bc9a71d0c3471058d16d4c3b1ea99616208db6b9b9040fb81\ \0a7fa27f72b40169522102ba46d3bb8db74c77c6cf082db57fc0548058fcdea8\ \11549e186526e3d10caf6721038ac8aef2dd9cea5e7d66e2f6e23f177a6c21f6\ \9ea311fa0c85d81badb6b37ceb2103d96d2bfbbc040faaf93491d69e2bfe9695\ \e2d8e007a7f26db96c2ee42db15dc953ae00000000" unsignedTx = "0100000001d2e34df5d7ee565208eddd231548916b9b0e99f4f5071f896134a4\ \48c5fb07bf0100000000ffffffff01f0b9f505000000001976a9143d5a352cab\ \583b12fbcb26d1269b4a2c951a33ad88ac00000000" op0 = head $ prevOutput <$> txIn unsignedTx Just keys = traverse secHexKey [ "3030303030303030303030303030303030303030303030303030303030303031" , "3030303030303030303030303030303030303030303030303030303030303032" , "3030303030303030303030303030303030303030303030303030303030303033" ] rdm = PayMulSig (toPubKey <$> keys) 2 sigIn = SigInput (toP2WSH $ encodeOutput rdm) 100000000 op0 sigHashAll (Just rdm) generatedSignedTx = signTx btc unsignedTx [sigIn] (take 2 keys) -- Reproduce the P2SH-P2WSH multisig example from BIP 143 testBip143p2shp2wpkhMulsig :: Assertion testBip143p2shp2wpkhMulsig = case getImpl of Just ImplCore -> assertEqual "BIP143 Core p2sh-p2wsh multisig" (Right signedTxCore) generatedSignedTx Just ImplABC -> assertEqual "BIP143 Core p2sh-p2wsh multisig" (Right signedTxABC) generatedSignedTx Nothing -> assertFailure "Invalid secp256k1 library" where signedTxCore = "0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\ \6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\ \9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\ \389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\ \a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac080047304402206a\ \c44d672dac41f9b00e28f4df20c52eeb087207e8d758d76d92c6fab3b73e2b02\ \20367750dbbe19290069cba53d096f44530e4f98acaa594810388cf7409a1870\ \ce01473044022068c7946a43232757cbdf9176f009a928e1cd9a1a8c212f15c1\ \e11ac9f2925d9002205b75f937ff2f9f3c1246e547e54f62e027f64eefa26955\ \78cc6432cdabce271502473044022059ebf56d98010a932cf8ecfec54c48e613\ \9ed6adb0728c09cbe1e4fa0915302e022007cd986c8fa870ff5d2b3a89139c9f\ \e7e499259875357e20fcbb15571c76795403483045022100fbefd94bd0a488d5\ \0b79102b5dad4ab6ced30c4069f1eaa69a4b5a763414067e02203156c6a5c9cf\ \88f91265f5a942e96213afae16d83321c8b31bb342142a14d163814830450221\ \00a5263ea0553ba89221984bd7f0b13613db16e7a70c549a86de0cc0444141a4\ \07022005c360ef0ae5a5d4f9f2f87a56c1546cc8268cab08c73501d6b3be2e1e\ \1a8a08824730440220525406a1482936d5a21888260dc165497a90a15669636d\ \8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa8\ \4c7df9abe12a01a11e2b4783cf56210307b8ae49ac90a048e9b53357a2354b33\ \34e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c\ \3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b97\ \81957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a\ \21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba0\ \4d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b330\ \2ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000" signedTxABC = "0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa10\ \6c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b8\ \9af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914\ \389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976\ \a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac0800483045022100\ \b70b684ef0d17b51adf71c0dae932beca5d447dd5eec03394328436bdba836e7\ \0220208ebfd7408d21e41da11d8287655528385429d3fe300bee241f10944339\ \5b580147304402204b5f9bc06c8f0a252b9842ea44785853beb1638002cec5f2\ \489d73e5f6f5109302204f3b132b32638835d4b1a651e7d18dc93c10192db553\ \999932af6a8e3d8a153202483045022100e0ed8d3a245a138c751d74e1359aee\ \6a52476ddf33a3a9a5f0c2ad30147319650220581318187061ad0f48fc4f5c85\ \1822e554d59977005b8de4b78bf2ce2fe8399703483045022100a0a40abc581e\ \4b725775a3aa93bf0f0fd9a02ad3aa0f93483214784a47ba5387022069151c30\ \f85a7e20c8671107c5af884ee4c5a82bd06398327fa68a993f7cc64b81473044\ \022016d828460f6fab3cf89ae4b87c8f02c11c798cf739967f3b7406e7367c29\ \ae8b022079e82b822eb6c37a66efabc3f0b40a2b98c52f848d36463f6623cbdc\ \fe675812824730440220225a14ba7434858dbb5e6e0a0969ddf3b5455edaabf9\ \9f5773d1f59e7816b918022047ed1ab87840a74f7e9489f3af051e5fd26b790f\ \b308c79f4b0ed73c0422795d83cf56210307b8ae49ac90a048e9b53357a2354b\ \3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac\ \5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b\ \9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a\ \9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94b\ \a04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3\ \302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000" unsignedTx = "010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1c\ \a29787b96e0100000000ffffffff0200e9a435000000001976a914389ffce9cd\ \9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a3\ \3f950689af511e6e84c138dbbd3c3ee41588ac00000000" op0 = head $ prevOutput <$> txIn unsignedTx rawKeys = [ "730fff80e1413068a05b57d6a58261f07551163369787f349438ea38ca80fac6" , "11fa3d25a17cbc22b29c44a484ba552b5a53149d106d3d853e22fdd05a2d8bb3" , "77bf4141a87d55bdd7f3cd0bdccf6e9e642935fec45f2f30047be7b799120661" , "14af36970f5025ea3e8b5542c0f8ebe7763e674838d08808896b63c3351ffe49" , "fe9a95c19eef81dde2b95c1284ef39be497d128e2aa46916fb02d552485e0323" , "428a7aee9f0c2af0cd19af3cf1c78149951ea528726989b2e83e4778d2c3f890" ] Just keys = traverse secHexKey rawKeys rdm = PayMulSig (toPubKey <$> keys) 6 sigIn sh = SigInput (toP2WSH $ encodeOutput rdm) 987654321 op0 sh (Just rdm) sigHashesA = [sigHashAll, sigHashNone, sigHashSingle] sigHashesB = setAnyoneCanPayFlag <$> sigHashesA sigIns = sigIn <$> (sigHashesA <> sigHashesB) generatedSignedTx = foldM addSig unsignedTx $ zip sigIns keys addSig tx (sigIn', key') = signNestedWitnessTx btc tx [sigIn'] [key'] secHexKey :: Text -> Maybe SecKey secHexKey = decodeHex >=> secKey toPubKey :: SecKey -> PubKeyI toPubKey = derivePubKeyI . wrapSecKey True
haskoin/haskoin
test/Haskoin/Crypto/SignatureSpec.hs
unlicense
21,190
0
20
4,130
2,472
1,282
1,190
246
3
{-# LANGUAGE TupleSections #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE CPP #-} {-# OPTIONS_HADDOCK hide #-} module Text.HTML.Scalpel.Internal.Serial ( SerialScraper , SerialScraperT , inSerial , stepBack , stepNext , seekBack , seekNext , untilBack , untilNext ) where import Text.HTML.Scalpel.Internal.Scrape import Text.HTML.Scalpel.Internal.Select import Control.Applicative import Control.Monad import Control.Monad.Trans import Control.Monad.Except (MonadError) import Control.Monad.Cont (MonadCont) import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.Maybe import Control.Monad.Writer (MonadWriter) import Data.Bifunctor import Data.Functor.Identity import Data.List.PointedList (PointedList) import Data.Maybe import Prelude hiding (until) import qualified Control.Monad.Fail as Fail import qualified Data.List.PointedList as PointedList import qualified Data.Tree as Tree import qualified Text.StringLike as TagSoup -- | Serial scrapers operate on a zipper of tag specs that correspond to the -- root nodes / siblings in a document. -- -- Access to the zipper is always performed in a move-then-read manner. For this -- reason it is valid for the current focus of the zipper to be just off either -- end of list such that moving forward or backward would result in reading the -- first or last node. -- -- These valid focuses are expressed as Nothing values at either end of the -- zipper since they are valid positions for the focus to pass over, but not -- valid positions to read. type SpecZipper str = PointedList (Maybe (TagSpec str)) -- | A 'SerialScraper' allows for the application of 'Scraper's on a sequence of -- sibling nodes. This allows for use cases like targeting the sibling of a -- node, or extracting a sequence of sibling nodes (e.g. paragraphs (\<p\>) -- under a header (\<h2\>)). -- -- Conceptually serial scrapers operate on a sequence of tags that correspond to -- the immediate children of the currently focused node. For example, given the -- following HTML: -- -- @ -- \<article\> -- \<h1\>title\</h1\> -- \<h2\>Section 1\</h2\> -- \<p\>Paragraph 1.1\</p\> -- \<p\>Paragraph 1.2\</p\> -- \<h2\>Section 2\</h2\> -- \<p\>Paragraph 2.1\</p\> -- \<p\>Paragraph 2.2\</p\> -- \</article\> -- @ -- -- A serial scraper that visits the header and paragraph nodes can be executed -- with the following: -- -- @ -- 'chroot' "article" $ 'inSerial' $ do ... -- @ -- -- Each 'SerialScraper' primitive follows the pattern of first moving the focus -- backward or forward and then extracting content from the new focus. -- Attempting to extract content from beyond the end of the sequence causes the -- scraper to fail. -- -- To complete the above example, the article's structure and content can be -- extracted with the following code: -- -- @ -- 'chroot' "article" $ 'inSerial' $ do -- title <- 'seekNext' $ 'text' "h1" -- sections <- many $ do -- section <- 'seekNext' $ text "h2" -- ps <- 'untilNext' ('matches' "h2") (many $ 'seekNext' $ 'text' "p") -- return (section, ps) -- return (title, sections) -- @ -- -- Which will evaluate to: -- -- @ -- ("title", [ -- ("Section 1", ["Paragraph 1.1", "Paragraph 1.2"]), -- ("Section 2", ["Paragraph 2.1", "Paragraph 2.2"]), -- ]) -- @ type SerialScraper str a = SerialScraperT str Identity a -- | Run a serial scraper transforming over a monad 'm'. newtype SerialScraperT str m a = MkSerialScraper (StateT (SpecZipper str) (MaybeT m) a) deriving (Functor, Applicative, Alternative, Monad, MonadPlus, MonadFix, MonadIO, MonadCont, MonadError e, MonadReader r, MonadWriter w) #if MIN_VERSION_base(4,9,0) deriving instance Monad m => Fail.MonadFail (SerialScraperT str m) #else instance Fail.MonadFail m => Fail.MonadFail (SerialScraperT str m) where fail = lift . Fail.fail #endif instance MonadTrans (SerialScraperT str) where lift op = MkSerialScraper . lift . lift $ op instance MonadState s m => MonadState s (SerialScraperT str m) where get = MkSerialScraper (lift . lift $ get) put = MkSerialScraper . lift . lift . put -- | Executes a 'SerialScraper' in the context of a 'Scraper'. The immediate -- children of the currently focused node are visited serially. inSerial :: (TagSoup.StringLike str, Monad m) => SerialScraperT str m a -> ScraperT str m a inSerial (MkSerialScraper serialScraper) = MkScraper $ ReaderT $ scraper where scraper spec@(vec, root : _, ctx) | ctxInChroot ctx = evalStateT serialScraper (toZipper (vec, Tree.subForest root, ctx)) | otherwise = evalStateT serialScraper (toZipper spec) scraper _ = empty -- Create a zipper from the current tag spec by generating a new tag spec -- that just contains each root node in the forest. toZipper (vector, forest, context) = zipperFromList $ map ((vector, , context) . return) forest -- | Creates a SpecZipper from a list of tag specs. This requires bookending the -- zipper with Nothing values to denote valid focuses that are just off either -- end of the list. zipperFromList :: TagSoup.StringLike str => [TagSpec str] -> SpecZipper str zipperFromList = PointedList.insertLeft Nothing . foldr (PointedList.insertLeft . Just) (PointedList.singleton Nothing) stepWith :: (TagSoup.StringLike str, Monad m) => (SpecZipper str -> Maybe (SpecZipper str)) -> ScraperT str m b -> SerialScraperT str m b stepWith moveList (MkScraper (ReaderT scraper)) = MkSerialScraper . StateT $ \zipper -> do zipper' <- maybeT $ moveList zipper focus <- maybeT $ PointedList._focus zipper' value <- scraper focus return (value, zipper') -- | Move the cursor back one node and execute the given scraper on the new -- focused node. stepBack :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m a stepBack = stepWith PointedList.previous -- | Move the cursor forward one node and execute the given scraper on the new -- focused node. stepNext :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m a stepNext = stepWith PointedList.next seekWith :: (TagSoup.StringLike str, Monad m) => (SpecZipper str -> Maybe (SpecZipper str)) -> ScraperT str m b -> SerialScraperT str m b seekWith moveList (MkScraper (ReaderT scraper)) = MkSerialScraper (StateT go) where go zipper = do zipper' <- maybeT $ moveList zipper runScraper zipper' <|> go zipper' runScraper zipper = do focus <- maybeT $ PointedList._focus zipper value <- scraper focus return (value, zipper) -- | Move the cursor backward until the given scraper is successfully able to -- execute on the focused node. If the scraper is never successful then the -- serial scraper will fail. seekBack :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m a seekBack = seekWith PointedList.previous -- | Move the cursor forward until the given scraper is successfully able to -- execute on the focused node. If the scraper is never successful then the -- serial scraper will fail. seekNext :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m a seekNext = seekWith PointedList.next untilWith :: (TagSoup.StringLike str, Monad m) => (SpecZipper str -> Maybe (SpecZipper str)) -> (Maybe (TagSpec str) -> SpecZipper str -> SpecZipper str) -> ScraperT str m a -> SerialScraperT str m b -> SerialScraperT str m b untilWith moveList appendNode (MkScraper (ReaderT until)) (MkSerialScraper scraper) = MkSerialScraper $ do inner <- StateT split lift (evalStateT scraper (appendNode Nothing inner)) where split zipper = do zipper' <- maybeT $ moveList zipper spec <- maybeT $ PointedList._focus zipper' do until spec return (PointedList.singleton Nothing, zipper) <|> (first (appendNode (Just spec)) `liftM` split zipper') <|> return (PointedList.singleton Nothing, zipper) -- | Create a new serial context by moving the focus backward and collecting -- nodes until the scraper matches the focused node. The serial scraper is then -- executed on the collected nodes. untilBack :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m b -> SerialScraperT str m b untilBack = untilWith PointedList.previous PointedList.insertRight -- | Create a new serial context by moving the focus forward and collecting -- nodes until the scraper matches the focused node. The serial scraper is then -- executed on the collected nodes. -- -- The provided serial scraper is unable to see nodes outside the new restricted -- context. untilNext :: (TagSoup.StringLike str, Monad m) => ScraperT str m a -> SerialScraperT str m b -> SerialScraperT str m b untilNext = untilWith PointedList.next PointedList.insertLeft maybeT :: Monad m => Maybe a -> MaybeT m a maybeT = MaybeT . return
fimad/scalpel
scalpel-core/src/Text/HTML/Scalpel/Internal/Serial.hs
apache-2.0
9,371
0
17
1,942
1,771
963
808
123
2
<?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="id-ID"> <title>Browser View | 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>Telusuri</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>
0xkasun/security-tools
src/org/zaproxy/zap/extension/browserView/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
976
80
66
160
415
210
205
-1
-1
-- cabal-helper: Simple interface to Cabal's configuration state -- Copyright (C) 2015-2017 Daniel Gröber <cabal-helper@dxld.at> -- -- SPDX-License-Identifier: Apache-2.0 -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 {-# LANGUAGE TemplateHaskell, ScopedTypeVariables, CPP #-} {-| Module : CabalHelper.Compiletime.Data Description : Embeds source code for runtime component using TH License : Apache-2.0 -} module CabalHelper.Compiletime.Data where import Control.Monad import Control.Monad.IO.Class import Data.Digest.Pure.SHA import Data.Functor import Data.List import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.ByteString.Lazy as LBS import qualified Data.ByteString.Lazy.UTF8 as LUTF8 import Language.Haskell.TH import Language.Haskell.TH.Syntax (addDependentFile) import System.Directory import System.FilePath import System.IO.Temp import System.PosixCompat.Files import System.PosixCompat.Time import System.PosixCompat.Types import Prelude import CabalHelper.Compiletime.Compat.Environment withSystemTempDirectoryEnv :: String -> (FilePath -> IO b) -> IO b withSystemTempDirectoryEnv tpl f = do m <- liftIO $ lookupEnv "CABAL_HELPER_KEEP_SOURCEDIR" case m of Nothing -> withSystemTempDirectory tpl f Just _ -> do tmpdir <- getCanonicalTemporaryDirectory f =<< createTempDirectory tmpdir tpl createHelperSources :: FilePath -> IO () createHelperSources dir = do let chdir = dir </> "CabalHelper" liftIO $ do createDirectoryIfMissing True $ chdir </> "Runtime" createDirectoryIfMissing True $ chdir </> "Shared" let modtime :: EpochTime modtime = fromIntegral $ (read :: String -> Integer) -- See https://reproducible-builds.org/specs/source-date-epoch/ $(runIO $ do msde :: Maybe Integer <- fmap read <$> lookupEnv "SOURCE_DATE_EPOCH" (current_time :: Integer) <- round . toRational <$> epochTime return $ LitE . StringL $ show $ maybe current_time id msde) liftIO $ forM_ sourceFiles $ \(fn, src) -> do let path = chdir </> fn BS.writeFile path $ UTF8.fromString src setFileTimes path modtime modtime sourceHash :: String sourceHash = fst runtimeSources sourceFiles :: [(FilePath, String)] sourceFiles = snd runtimeSources runtimeSources :: (String, [(FilePath, FilePath)]) runtimeSources = $( let files = map (\f -> (f, ("src/CabalHelper" </> f))) $ sort $ [ ("Runtime/Main.hs") , ("Runtime/HelperMain.hs") , ("Runtime/Compat.hs") , ("Shared/Common.hs") , ("Shared/InterfaceTypes.hs") ] in do contents <- forM (map snd files) $ \lf -> do addDependentFile lf runIO (LBS.readFile lf) let hashes = map (bytestringDigest . sha256) contents let top_hash = showDigest $ sha256 $ LBS.concat hashes let exprWrapper = #if MIN_VERSION_template_haskell(2,16,0) Just #else id #endif thfiles <- forM (map fst files `zip` contents) $ \(f, xs) -> do return $ TupE [exprWrapper (LitE (StringL f)), exprWrapper (LitE (StringL (LUTF8.toString xs)))] return $ TupE [exprWrapper (LitE (StringL top_hash)), exprWrapper (ListE thfiles)] ) -- - $(LitE . StringL <$> runIO (UTF8.toString <$> BS.readFile
DanielG/cabal-helper
src/CabalHelper/Compiletime/Data.hs
apache-2.0
3,553
0
26
739
862
461
401
69
2
{-# LANGUAGE OverloadedStrings #-} module Barc.FutharkGen (genFuthark) where import Data.List import qualified Data.Text as T import Prelude import Barc.ExpInner genFuthark :: Prog -> T.Text genFuthark (Prog w h e) = T.concat [ "let board_is_okay(board: " , board_t , "): bool =\n" , futLet "vs" (futCall "map" ["i32.i8", futCall "flatten" ["board"]]) (codeBoolExp e) , "" , "let main [n] (boards: [n]" , board_t , "): [n]bool =\n" , " map board_is_okay boards\n" ] where w' = T.pack $ show w h' = T.pack $ show h board_t = T.concat [ "[", h', "][", w', "]i8"] codeBoolExp :: ExpBool -> T.Text codeBoolExp e = T.append (codeBoolExp' e) "\n" codeBoolExp' :: ExpBool -> T.Text codeBoolExp' e = case e of BoolVal b -> if b then "true" else "false" IndexBool bs i -> futIndex (codeBoolListExp bs) (codeIntExp i) BoolConv e' -> futCall "i32.bool" [codeIntExp e'] ReduceBool ident neutral list body -> futReduce "bool" ident (codeBoolExp neutral) (codeBoolListExp list) (codeBoolExp body) ReduceBoolValueFirst ident -> reduceValueFirst ident ReduceBoolValueSecond ident -> reduceValueSecond ident And e0 e1 -> futBinOp "&&" (codeBoolExp e0) (codeBoolExp e1) Or e0 e1 -> futBinOp "||" (codeBoolExp e0) (codeBoolExp e1) Not e' -> futUnOp "!" (codeBoolExp e') Eq e0 e1 -> futBinOp "==" (codeIntExp e0) (codeIntExp e1) Gt e0 e1 -> futBinOp ">" (codeIntExp e0) (codeIntExp e1) codeIntExp :: ExpInt -> T.Text codeIntExp e = T.append (codeIntExp' e) "\n" codeIntExp' :: ExpInt -> T.Text codeIntExp' e = case e of Const n -> T.pack $ show n IndexInt ns i -> futIndex (codeIntListExp ns) (codeIntExp i) CurrentIndex ident -> currentIndex ident LengthInt ns -> futLength $ codeIntListExp ns LengthBool bs -> futLength $ codeBoolListExp bs IntConv e' -> futCall "i32.bool" [codeBoolExp e'] ReduceInt ident neutral list body -> futReduce "i32" ident (codeIntExp neutral) (codeIntListExp list) (codeIntExp body) ReduceIntValueFirst ident -> reduceValueFirst ident ReduceIntValueSecond ident -> reduceValueSecond ident Add e0 e1 -> futBinOp "+" (codeIntExp e0) (codeIntExp e1) Subtract e0 e1 -> futBinOp "-" (codeIntExp e0) (codeIntExp e1) Multiply e0 e1 -> futBinOp "*" (codeIntExp e0) (codeIntExp e1) Modulo e0 e1 -> futBinOp "%" (codeIntExp e0) (codeIntExp e1) codeBoolListExp :: ExpBoolList -> T.Text codeBoolListExp e = T.append (codeBoolListExp' e) "\n" codeBoolListExp' :: ExpBoolList -> T.Text codeBoolListExp' e = case e of ListBool bs -> brackets $ commaSep $ map codeBoolExp bs MapBool ident len body -> futMap "bool" ident (codeIntExp len) (codeBoolExp body) codeIntListExp :: ExpIntList -> T.Text codeIntListExp e = T.append (codeIntListExp' e) "\n" codeIntListExp' :: ExpIntList -> T.Text codeIntListExp' e = case e of BoardValues -> "vs" ListInt ns -> brackets $ commaSep $ map codeIntExp ns MapInt ident len body -> futMap "i32" ident (codeIntExp len) (codeIntExp body) futReduce :: T.Text -> Int -> T.Text -> T.Text -> T.Text -> T.Text futReduce baseType ident neutral list body = futCall "reduce" [fun, neutral, list] where fun = T.concat [ "\\" , T.concat $ map parens args , ": " , baseType , " -> " , body ] args = [ T.concat [ reduceValueFirst ident , ": " , baseType ] , T.concat [ reduceValueSecond ident , ": " , baseType ] ] reduceValueFirst :: Int -> T.Text reduceValueFirst ident = T.concat [ "reduce_value_first_" , T.pack $ show ident ] reduceValueSecond :: Int -> T.Text reduceValueSecond ident = T.concat [ "reduce_value_second_" , T.pack $ show ident ] futMap :: T.Text -> Int -> T.Text -> T.Text -> T.Text futMap baseType ident len body = futCall "map" [fun, list] where fun = T.concat [ "\\" , parens arg , ": " , baseType , " -> " , body ] arg = T.concat [ currentIndex ident , ": i32" ] list = futCall "iota" [len] currentIndex :: Int -> T.Text currentIndex ident = T.concat [ "current_index_" , T.pack $ show ident ] futIndex :: T.Text -> T.Text -> T.Text futIndex xs i = T.concat [ parens xs , brackets i ] futCall :: T.Text -> [T.Text] -> T.Text futCall name args = name <> mconcat (map parens args) futLength :: T.Text -> T.Text futLength xs = futCall "length" [xs] futBinOp :: T.Text -> T.Text -> T.Text -> T.Text futBinOp op x y = parens $ T.concat [x, op, y] futUnOp :: T.Text -> T.Text -> T.Text futUnOp op x = parens $ T.concat [op, x] futLet :: T.Text -> T.Text -> T.Text -> T.Text futLet v e body = T.concat [ "let " , v , " = " , e , " in\n" , body ] parens :: T.Text -> T.Text parens t = T.concat [ "(" , t , ")" ] brackets :: T.Text -> T.Text brackets t = T.concat [ "[" , t , "]" ] commaSep :: [T.Text] -> T.Text commaSep = T.intercalate ", "
Athas/banko
barc/Barc/FutharkGen.hs
bsd-2-clause
5,910
0
12
2,111
1,857
940
917
137
13
module Handler.GoogleVerify where import Import getGoogleVerifyR :: Handler RepHtml getGoogleVerifyR = sendFile "text/html" "config/googled672395359cbd0e8.html"
pbrisbin/devsite
Handler/GoogleVerify.hs
bsd-2-clause
163
0
5
16
27
15
12
4
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module System.EtCetera.Internal where import Control.Category (id, (.)) import Control.Lens (Lens', over, set, view) import Data.Monoid ((<>)) import Generics.Deriving.Base (Generic) import Generics.Deriving.Monoid (GMonoid, gmempty, gmappend) import Prelude hiding (id, (.)) import Text.Boomerang.Combinators (manyl, manyr, opt, push, rCons, rList, rList1, rListSep, rNil, somel, somer) import Text.Boomerang.HStack ((:-)(..)) import Text.Boomerang.String (StringBoomerang, StringError) import System.EtCetera.Internal.Boomerangs (eol) import System.EtCetera.Internal.Prim (Prs(..), Ser(..), toPrs, toSer) -- | Configuration files usually are just sets -- of unodered options. I wasn't able to easily -- express final parser and printer constructions -- with Boomerangs only, so my strategy is following: -- -- * create separate boomerangs for every single option -- -- * create separate parser - it will hold sum off all options -- parsers, so it can parse any option definition -- -- * create separate serializer which will hold whole config -- serialization -- -- * use these options boomerangs with options lens to feed above -- parser and serializer at once -- -- * these will produce partial parser (it parses only single option) -- and final serializer, because they are not isomorphic I've decided -- to not use Boomerang to hold them type SingleOptionParser config r = Prs StringError String (config :- r) (config :- r) type Serializer config r = Ser String (config :- r) (config :- r) data Optional a = Present a | Missing deriving (Eq, Show) instance Monoid (Optional a) where mempty = Missing v@(Present a) `mappend` _ = v _ `mappend` u = u instance GMonoid (Optional a) where gmempty = mempty gmappend = mappend extendSerializerWithScalarOption :: Lens' config (Optional a) -> StringBoomerang (config :- r) (a :- config :- r) -> Serializer config r -> Serializer config r extendSerializerWithScalarOption optionLens optionBoomerang serializer = valueExtractor . optionSerializer . serializer <> serializer where optionSerializer = toSer (optionBoomerang . eol) valueExtractor = Ser (\(config :- r) -> case view optionLens config of (Present v) -> Just (id, v :- set optionLens Missing config :- r) Missing -> Nothing) extendSerializerWithVectorOption :: Lens' config [a] -> StringBoomerang (config :- r) ([a] :- config :- r) -> Serializer config r -> Serializer config r extendSerializerWithVectorOption optionLens optionBoomerang serializer = serializer . valueExtractor . optionSerializer <> serializer where optionSerializer = toSer (optionBoomerang . eol) valueExtractor = Ser (\(config :- r) -> let ov = view optionLens config in (case ov of [] -> Nothing otherwise -> Just (id, ov :- set optionLens [] config :- r))) extendSerializerWithRepeatableScalar :: Lens' config [a] -> StringBoomerang (config :- r) (a :- config :- r) -> Serializer config r -> Serializer config r extendSerializerWithRepeatableScalar optionLens optionBoomerang serializer = serializer . valueExtractor . optionSerializer <> serializer where optionSerializer = toSer (rList (optionBoomerang . eol)) valueExtractor = Ser (\(config :- r) -> Just (id, view optionLens config :- set optionLens [] config :- r)) addScalarOptionParser :: Lens' config (Optional a) -> StringBoomerang (config :- r) (a :- config :- r) -> SingleOptionParser config r -> SingleOptionParser config r addScalarOptionParser optionLens optionBoomerang optionsParser = optionsParser <> (valueSetter . toPrs optionBoomerang) where valueSetter = Prs (return (\(v :- config :- r) -> set optionLens (Present v) config :- r)) addVectorOptionParser :: Lens' config [a] -> StringBoomerang (config :- r) ([a] :- config :- r) -> SingleOptionParser config r -> SingleOptionParser config r addVectorOptionParser optionLens optionBoomerang optionsParser = optionsParser <> (valueSetter . toPrs optionBoomerang) where valueSetter = Prs (return (\(v :- config :- r) -> set optionLens v config :- r)) addRepeatableScalarParser :: Lens' config [a] -> StringBoomerang (config :- r) (a :- config :- r) -> SingleOptionParser config r -> SingleOptionParser config r addRepeatableScalarParser optionLens optionBoomerang optionsParser = (valueSetter . toPrs optionBoomerang) <> optionsParser where valueSetter = Prs (return (\(v :- config :- r) -> over optionLens (v :) config :- r)) vector :: Lens' config [a] -> StringBoomerang (config :- r) ([a] :- config :- r) -> (SingleOptionParser config r, Serializer config r) -> (SingleOptionParser config r, Serializer config r) vector optionLens optionBoomerang (p, s) = (p', s') where p' = addVectorOptionParser optionLens optionBoomerang p s' = extendSerializerWithVectorOption optionLens optionBoomerang s scalar :: Lens' config (Optional a) -> StringBoomerang (config :- r) (a :- config :- r) -> (SingleOptionParser config r, Serializer config r) -> (SingleOptionParser config r, Serializer config r) scalar optionLens optionBoomerang (p, s) = (p', s') where p' = addScalarOptionParser optionLens optionBoomerang p s' = extendSerializerWithScalarOption optionLens optionBoomerang s repeatableScalar :: Lens' config [a] -> StringBoomerang (config :- r) (a :- config :- r) -> (SingleOptionParser config r, Serializer config r) -> (SingleOptionParser config r, Serializer config r) repeatableScalar optionLens optionBoomerang (p, s) = (p', s') where p' = addRepeatableScalarParser optionLens optionBoomerang p s' = extendSerializerWithRepeatableScalar optionLens optionBoomerang s
paluh/et-cetera
src/System/EtCetera/Internal.hs
bsd-3-clause
6,589
0
21
1,775
1,718
933
785
-1
-1
module Main (main) where import System.Environment import Data.List import Data.Ord import Data.Function collatz :: Int -> [Int] -> [Int] collatz n xs | n == 1 = xs ++ [1] collatz n xs | even n = collatz (n `div` 2) $ xs ++ [n] collatz n xs | otherwise = collatz (n * 3 + 1) $ xs ++ [n] main :: IO () main = do [x] <- getArgs print $ fst $ maximumBy (comparing length `on` snd) $ fmap (\ x -> (x, collatz x []) ) [1..(read x)]
lnds/programando.org
siracusa/damowe-2.hs
bsd-3-clause
451
0
13
116
250
131
119
13
1
module ChatData where import Control.Distributed.STM.DSTM type CmdTVar = TVar (Maybe ServerCmd) data ServerCmd = Join String CmdTVar | Msg String String | Leave String deriving (Show,Read) instance Dist ServerCmd where finTVars (Join _ cmd) = finTVars cmd finTVars _ = return () regTVars env (Join _ cmd) = regTVars env cmd regTVars _ _ = return ()
proger/haskell-dstm
Chat/ChatData.hs
bsd-3-clause
382
0
8
90
138
72
66
12
0