code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
-- -- A very simple example application using System.MIDI. -- It's a basic MIDI monitor: prints all the incoming messages. -- module Main where -------------------------------------------------------------------------------- import Control.Monad import Control.Concurrent import System.MIDI import System.MIDI.Utility -------------------------------------------------------------------------------- -- the essence mythread conn = do events <- getEvents conn mapM_ print events (threadDelay 5000) mythread conn -------------------------------------------------------------------------------- -- main main = do src <- selectInputDevice "Select midi input device" Nothing conn <- openSource src Nothing putStrLn "connected" threadid <- forkIO (mythread conn) start conn ; putStrLn "started. Press 'ENTER' to exit." getLine stop conn ; putStrLn "stopped." killThread threadid close conn ; putStrLn "closed."
chpatrick/hmidi
examples/monitor.hs
Haskell
bsd-3-clause
976
-- {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} -- {-# LANGUAGE MultiParamTypeClasses #-} -- {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE RecordWildCards #-} -- {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- {-# LANGUAGE MultiWayIf #-} -- {-# LANGUAGE OverloadedStrings #-} -- {-# LANGUAGE RecordWildCards #-} -- {-# OPTIONS_GHC -Wall #-} -- {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- {-# OPTIONS_GHC -fno-warn-orphans #-} -- {-# OPTIONS_GHC -fno-warn-missing-signatures #-} -- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-} -- {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# 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 -- -- basic refactorings: renaming, -- built upon the zipper navigation in the syntax tree, {- usage renaming of simple expressions runExcept $ renameExpr "y" "YY" $ lam "y" $ V "x" * in the simpler Either monad, like so: pp $ fromRight' $ (ezipper $ Mod m) >>= navigate [Decl 1, Rhs, Binding] * or in the the Refactor monad, which has state as well pp $ fromRight' $ refactor $ (rzipper $ Mod m) >>= navigate [Decl 1, Rhs, Binding] >>= rename "a" "b" one would just navigate to the relevant piece of the syntax tree, like -- top make the tree, list pair a zipper here (for printing the top lvl) pp $ fromRight' $ refactor $ (rzipper $ Mod m) >>= top >>= rename "a" "b" ** next things TODO: see if renaming Zero to Z works - I doubt it - but make it work -} module Pire.Refactor.Refactor ( module Pire.Refactor.Refactor ) where import Pire.Syntax.Expr import Pire.Syntax.GetNm -- import Pire.Syntax.Binder import Pire.Syntax.MkVisible import Pire.Syntax.Smart import Pire.Syntax.Decl import Pire.Syntax.Modules import Pire.Syntax.Nm -- import Pire.Modules -- import Pire.Untie import Pire.Syntax.Telescope import Pire.Syntax.Constructor import Pire.Refactor.Navigation import Pire.Pretty.Common import Pire.Utils import Bound import Bound.Term #ifdef MIN_VERSION_GLASGOW_HASKELL #if MIN_VERSION_GLASGOW_HASKELL(7,10,3,0) -- ghc >= 7.10.3 -- import Control.Monad.Except #else -- older ghc versions, but MIN_VERSION_GLASGOW_HASKELL defined #endif #else -- MIN_VERSION_GLASGOW_HASKELL not even defined yet (ghc <= 7.8.x) import Control.Applicative #endif import Control.Monad.Except import Control.Lens -- import System.IO.Silently import Pire.Syntax.Pattern -- import Data.Bitraversable -- import Data.Bifunctor -- import Control.Monad.Trans.Either import Pire.Forget (forgetExp, forgetMatch) import Control.Monad.State.Strict import Debug.Trace #ifdef PiForallInstalled -- import PiForall.Environment -- import PiForall.TypeCheck #endif #ifdef DocTest -- fromRight' import Data.Either.Combinators import Pire.Syntax.Eps import Pire.NoPos import Pire.Text2String (t2s) import Pire.Parser.ParseUtils (parse, module_) import Pire.Modules (getModules_) import Pire.Refactor.LineColumnNavigation (lineColumn) import Pire.Refactor.ForgetZipper (forgetZ) import Pire.Parser.Expr (expr) #endif -- -------------------------------------------------- -- renaming exprs {-| see if a variable is a binding variable in an expression >>> "x" `isBindingVarIn` (lam "x" $ V "y") True >>> "y" `isBindingVarIn` (lam "x" $ V "y") False The next example (cf. @samples/Nat.pi@) - seems fine to me (but test coverage is maybe not exhaustive enough, think eg. of some case, where we would have to recurse into the rhs of a match: @Zero -> \\x. n@, ie. recurse into the @lambda: \\x. n@ then, etc.) let @c@ be a case expression: @ case n of Zero -> Zero Succ n' -> n' @ >>> let c = Case (V "n") [Match (PatCon "Zero" []) (Scope (DCon "Zero" [] (Annot Nothing))),Match (PatCon "Succ" [(RuntimeP, PatVar "n'")]) (Scope (V (B 0)))] (Annot Nothing) >>> "y" `isBindingVarIn` c False OK? >>> "Succ" `isBindingVarIn` c False >>> "n'" `isBindingVarIn` c True -} -- Show a at least for debugging with Debug.Trace.trace below -- isBindingVarIn :: (Eq a, Disp (Expr a a)) => a -> Expr a a -> Bool isBindingVarIn :: (Eq a, MkVisible a, Disp (Expr a a), Show a) => a -> Expr a a -> Bool _ `isBindingVarIn` (V _) = False y `isBindingVarIn` (Ws_ v _) = y `isBindingVarIn` v -- do we really need this ? y `isBindingVarIn` (BndV _ ex) = y `isBindingVarIn` ex _ `isBindingVarIn` (Nat _) = False _ `isBindingVarIn` (Nat_ {}) = False y `isBindingVarIn` (l :@ r) = y `isBindingVarIn` l || y `isBindingVarIn` r y `isBindingVarIn` (Lam y' sc) | y == y' = True | otherwise = y `isBindingVarIn` (instantiate1 (V y') sc) y `isBindingVarIn` (Lam_ _ bndr _ sc) | y == y' = True -- -- | otherwise = y `isBindingVarIn` (instantiate1 (Ws_ (V y') $ Ws "") sc) | otherwise = y `isBindingVarIn` (instantiate1 (V y') sc) where y' = name' bndr y `isBindingVarIn` (LamPAs ns sc) | y `elem` ns' = True | otherwise = y `isBindingVarIn` (instantiate (\i -> V $ ns !! i ^. _2) sc) where ns' = (^. _2) <$> ns y `isBindingVarIn` (LamPAs_ _ ns _ sc) | y `elem` ns' = True | otherwise = y `isBindingVarIn` (instantiate (\i -> V $ ns !! i ^. _2 & name') sc) where ns' = name' . (^. _2) <$> ns -- y `isBindingVarIn` (Lam' y' sc) -- | y == y' = True -- | otherwise = y `isBindingVarIn` (instantiate1 (V y') sc) y `isBindingVarIn` (Position _ ex) = y `isBindingVarIn` ex y `isBindingVarIn` (Paren ex) = y `isBindingVarIn` ex y `isBindingVarIn` (Paren_ _ ex _) = y `isBindingVarIn` ex -- TODO: rethink, if this is what we really want! y `isBindingVarIn` (Case ex matches _) | y `isBindingVarIn` ex = True -- -- | y `elem` ns' = True | y `elem` ns' = False | y `elem` ns'' = True -- -- | otherwise = False | otherwise = any (\match -> y `isThisBindingVarInMatch` match) matches where ps = [p | (Match p _) <- matches] -- scopes = [s | (Match _ s) <- matches] -- ns' eg. ["Zero", "Succ"] ns' = name' <$> ps -- ns'' eg. ["n'"] given some "Succ n'" - rethink -- ns'' = (name' <$>) $ (fst <$>) $ concat $ argPatterns <$> ps ns'' = (name' <$>) $ (snd <$>) $ concat $ argPatterns <$> ps -- instantiate the scope - cf pretty printing of Match -- maybe this helper function should be more powerful, and cover some of the case above ? -- c `isThisBindingVarInMatch` (Match p sc) = c `isBindingVarIn` instantiate (\i -> V $ (argPatterns p) !! i ^. _1 & name') sc c `isThisBindingVarInMatch` (Match p sc) = c `isBindingVarIn` instantiate (\i -> V $ (argPatterns p) !! i ^. _2 & name') sc -- is this too simple, maybe ? y `isBindingVarIn` c@(Case_ {}) = y `isBindingVarIn` (forgetExp c) -- needed, even for the Case doctest cases above -- but rethink/refine ! -- too simple ? -- y `isBindingVarIn` (TCon tm args) = False _ `isBindingVarIn` (TCon {}) = False _ `isBindingVarIn` (TCon_ {}) = False _ `isBindingVarIn` (DCon {}) = False _ `isBindingVarIn` (DCon_ {}) = False _ `isBindingVarIn` (LitBool {}) = False _ `isBindingVarIn` (LitBool_ {}) = False _ `isBindingVarIn` (TyBool {}) = False _ `isBindingVarIn` (TyBool_ {}) = False _ `isBindingVarIn` (Refl {}) = False _ `isBindingVarIn` (Refl_ {}) = False -- rethink ! y `isBindingVarIn` (Subst ex1 ex2 _) = y `isBindingVarIn` ex1 || y `isBindingVarIn` ex2 y `isBindingVarIn` (Subst_ _ ex1 _ ex2 _) = y `isBindingVarIn` ex1 || y `isBindingVarIn` ex2 y `isBindingVarIn` (Ann ex1 ex2) = y `isBindingVarIn` ex1 || y `isBindingVarIn` ex2 y `isBindingVarIn` (Ann_ ex) = y `isBindingVarIn` ex y `isBindingVarIn` (TyEq ex1 ex2) = y `isBindingVarIn` ex1 || y `isBindingVarIn` ex2 y `isBindingVarIn` (TyEq_ ex1 _ ex2) = y `isBindingVarIn` ex1 || y `isBindingVarIn` ex2 y `isBindingVarIn` (Let y' ex sc) | y == y' = True | y `isBindingVarIn` ex = True | otherwise = y `isBindingVarIn` (instantiate1 (V y') sc) -- too simple ? y `isBindingVarIn` l@(Let_ {}) = y `isBindingVarIn` (forgetExp l) y `isBindingVarIn` (PiP _ nm ex sc) | y == nm = True | y `isBindingVarIn` ex = True | otherwise = y `isBindingVarIn` (instantiate1 (V nm) sc) y `isBindingVarIn` (PiP_ _ ex _ sc) | y == nm = True | y `isBindingVarIn` ex = True | otherwise = y `isBindingVarIn` (instantiate1 (V nm) sc) where nm = name' ex -- too simple ? _ `isBindingVarIn` (InferredAnnBnd_ {}) = False -- too simple ? _ `isBindingVarIn` (WitnessedAnnBnd_ {}) = False _ `isBindingVarIn` (WitnessedAnnEx_ {}) = False y `isBindingVarIn` (Brackets_ _ ex _) = y `isBindingVarIn` ex _ `isBindingVarIn` (Type_ {}) = False _ `isBindingVarIn` (Type {}) = False y `isBindingVarIn` (Contra ex _) = y `isBindingVarIn` ex y `isBindingVarIn` (Contra_ _ ex _) = y `isBindingVarIn` ex -- _ `isBindingVarIn` ex = error $ "isBindingVarIn, missing..." ++ ppS ex _ `isBindingVarIn` ex = trace (show ex) $ error $ "isBindingVarIn, missing..." ++ ppS ex {-| helper function, hidden in a where clause in the above @isBindingVarIn@ already, but easier to test separately here -} c `isBindingVarInMatch` (Match p sc) = c `isBindingVarIn` instantiate (\i -> V $ (argPatterns p) !! i ^. _1 & name') sc c `isBindingVarInMatch` m@(Match_ {}) = c `isBindingVarInMatch` (forgetMatch m) {-| helper function to create expressions in the @Either RefactorError@ monad, for convenience in the ghci / cabal repl, could just use @Right@ instead, but would need @-XFlexibleContexts@ then -} eexpr :: t -> Either RefactorError t eexpr t = Right t {-| renaming expressions, with the simple @renameExpr'@ function (takes just an expression): >>> renameExpr' "x" "z" $ lam "y" $ V "x" Right (Lam "y" (Scope (V (F (V "z"))))) or with @renameExpr@ in the @Refactoring@ monad (cf. below): >>> (eexpr $ lam "y" $ V "x") >>= renameExpr "x" "z" Right (Lam "y" (Scope (V (F (V "z"))))) >>> continuing with the simpler @renameExpr'@: >>> renameExpr' "a" "x" $ lam "y" $ V "x" Left (NameCaptureFV "x" "\\y . x") >>> renameExpr' "x" "y" $ lam "y" $ V "x" Left (NameCaptureBindingVar "y" "\\y . x") >>> let l = lam "a" $ lam "b" $ lam "c" $ lam "y" $ V "x" >>> pp l \a . \b . \c . \y . x no effect if @y@ is bound >>> pp $ fromRight' $ renameExpr' "y" "YY" $ l \a . \b . \c . \y . x works fine if @x@ is free >>> pp $ fromRight' $ renameExpr' "x" "zzz" $ l \a . \b . \c . \y . zzz detect name capture deep down inside >>> renameExpr' "x" "b" $ l Left (NameCaptureBindingVar "b" "\\a . \\b . \\c . \\y . x") another example: >>> let l' = lam "a" $ V "foo" :@ (lam "c" $ V "a" :@ V "c") >>> pp l' \a . foo (\c . a c) >>> renameExpr' "a" "c" $ l' Left (NameCaptureBindingVar "c" "\\a . foo (\\c . a c)") further example, similar to the above, but parsed and not desugared: @LamPAs@ >>> let l = nopos $ t2s $ parse expr "\\a b . \\c . \\y . x" >>> l LamPAs [(RuntimeP,"a",Annot Nothing),(RuntimeP,"b",Annot Nothing)] (Scope (LamPAs [(RuntimeP,"c",Annot Nothing)] (Scope (LamPAs [(RuntimeP,"y",Annot Nothing)] (Scope (V (F (V (F (V (F (V "x")))))))))))) >>> renameExpr' "a" "c" $ l Left (NameCaptureBindingVar "c" "\\a b . \\c . \\y . x") -} -- Show a at least for debugging `isBindingVar` with Debug.Trace renameExpr' :: (Disp (Expr a a), Disp a, Eq a, MkVisible a, Show a) => a -> a -> Expr a a -> Either RefactorError (Expr a a) renameExpr' old new lambda@(Lam x sc) | new `elem` fv sc = Left $ NameCaptureFV (ppS new) (ppS lambda) | new `isBindingVarIn` lambda = Left $ NameCaptureBindingVar (ppS new) (ppS lambda) | otherwise, x == old = return $ Lam new sc' | otherwise, x /= old = return $ Lam x sc' where (Lam _ sc') = substituteVar old new lambda renameExpr' old new lambda@(LamPAs_ lamtok xs dot' sc) -- | new `elem` fv sc = throwError $ NameCaptureFV $ ppS newlam | new `elem` fv sc = Left $ NameCaptureFV (ppS new) (ppS lambda) | new `isBindingVarIn` lambda = Left $ NameCaptureBindingVar (ppS new) (ppS lambda) -- -- | otherwise, old `elem` [x ^. _2 & name' | x <- xs] = return $ LamPAs_ lamtok xsnew dot' sc' -- -- | otherwise, (not $ old `elem` [x ^. _2 & name' | x <- xs]) = return $ LamPAs_ lamtok xs dot' sc' -- [July 2016] getting rid of this tracing -- -- | otherwise, old `elem` [x ^. _2 & name' | x <- xs] = trace "#1" $ return $ bimap (\tt -> if tt==old then new else tt) (\tt -> if tt==old then new else tt) $ LamPAs_ lamtok xsnew dot' sc' -- -- | otherwise, (not $ old `elem` [x ^. _2 & name' | x <- xs]) = trace "#2" $ return $ bimap (\tt -> if tt==old then new else tt) (\tt -> if tt==old then new else tt) $ LamPAs_ lamtok xs dot' sc' -- -- this would benefit from a helper function (\tt -> if tt==old then new else tt) I guess | otherwise, old `elem` [x ^. _2 & name' | x <- xs] = return $ bimap (\tt -> if tt==old then new else tt) (\tt -> if tt==old then new else tt) $ LamPAs_ lamtok xsnew dot' sc' | otherwise, (not $ old `elem` [x ^. _2 & name' | x <- xs]) = return $ bimap (\tt -> if tt==old then new else tt) (\tt -> if tt==old then new else tt) $ LamPAs_ lamtok xs dot' sc' where sc' = scopepl $ substituteVar old new lambda -- using lens to short cut -- xsnew = [(eps, if name' bndr == old then bndr `replaceInBndr` new else bndr, ann) | (eps, bndr, ann) <- xs] xsnew = [over _2 (\b -> if name' b == old then b `replaceInBndr` new else b) x | x <- xs] bndr `replaceInBndr` n = fmap (\tt -> if tt==old then n else tt) bndr -- renameExpr' old new l@(Lam' x sc) -- | new `elem` fv sc = Left $ NameCaptureFV (ppS new) (ppS l) -- | new `isBindingVarIn` l = Left $ NameCaptureBindingVar (ppS new) (ppS l) -- | otherwise, x == old = return $ Lam' new sc' -- | otherwise, x /= old = return $ Lam' x sc' -- where (Lam' _ sc') = substituteVar old new l renameExpr' old new expr@(Case {}) | new `isBindingVarIn` expr = Left $ NameCaptureBindingVar (ppS new) (ppS expr) -- -- | otherwise = return $ expr' -- -- | otherwise = trace (show "# renameExpr'...(Case {}), in otherwise") $ return $ Case ex' (renameMatch old new <$> matches') annot' | otherwise = return $ Case ex' (renameMatch old new <$> matches') annot' where -- expr' = substituteVar old new expr (Case ex' matches' annot') = substituteVar old new expr renameExpr' old new expr | new `isBindingVarIn` expr = Left $ NameCaptureBindingVar (ppS new) (ppS expr) | otherwise = return $ expr' where expr' = substituteVar old new expr -- Show at least for debugging with Debug.Trace.trace below {-| we want @renameExpr@ to work in whatever monad, just requiring the @Refactoring@ interface, (so @renameZ'@/@renameZ@ can be in line with the other navigation functions) for examples of its usage cf. the simpler function @renameExpr'@ above -} -- not sure if it is a good idea (if we really need) to make renameExpr -- rely on the simpler renameExpr' function, that works just in Either ? -- anyway, it makes the doctests above simpler: -- we *can* use -- (eexpr $ V "a" :@ V "b") >>= renameExpr "a" "xx" -- but we can just as well use the simpler: -- renameExpr' "a" "xx" $ V "a" :@ V "b" renameExpr :: (Refactoring m, Disp (Expr a a), Disp a, Eq a, MkVisible a, Show a) => a -> a -> Expr a a -> m (Expr a a) renameExpr old new ex | Left l <- renameExpr' old new ex = rthrow l | Right r <- renameExpr' old new ex = rsucceed r -- -------------------------------------------------- -- renaming decls {-| rename in declarations, the @Nat@ at position 19 8 of @pitestfiles/Lec3.pi@ to @Natural@ eg., as used throughout, and in (data type) decl 18 in particular: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 19 8 >>= repr Parsing File "pitestfiles/Lec3.pi" Nat >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 19 8 >>= upToBinding2 >>= \(old, z) -> renameZ old "Natural" z >>= toDecl 18 >>= repr Parsing File "pitestfiles/Lec3.pi" data Beautiful (n : Natural) : Type where B0 of [n = 0] B3 of [n = 3] B5 of [n = 5] Bsum of (m1:Natural)(m2:Natural)(Beautiful m1)(Beautiful m2)[n = plus m1 m2] <BLANKLINE> <BLANKLINE> likewise @Zero@ occurs at position 21 3 in the context of the definition of @plus@: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= repr Parsing File "pitestfiles/Lec3.pi" Zero >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= navigate [Up, Up, Up, Up, Up] >>= repr Parsing File "pitestfiles/Lec3.pi" plus = \ x y. case x of Zero -> y Succ x' -> Succ (plus x' y) <BLANKLINE> <BLANKLINE> and we can rename @Nat@ to @Natural@ again (on the module level), and turn our attention to decl 3, where the naturals are actually defined, either in white space aware or abstract syntax (forgetZ): >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= \(old, z) -> renameZ old "Natural" z >>= toDecl 3 >>= repr Parsing File "pitestfiles/Lec3.pi" data Nat : Type where Natural Succ of (Nat) <BLANKLINE> <BLANKLINE> >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= \(old, z) -> forgetZ z >>= renameZ old "Natural" >>= toDecl 3 >>= repr Parsing File "pitestfiles/Lec3.pi" data Nat : Type where Natural Succ of (_1 : Nat) -} -- Show at least for debugging with Debug.Trace.trace below renameDecl :: (Refactoring m, Disp (Expr a a), Disp a, Eq a, MkVisible a, Show a) => a -> a -> Decl a a -> m (Decl a a) renameDecl old new (Def x expr) | x == old = do { ; expr' <- renameExpr old new expr ; return $ Def new expr' } | otherwise = do { ; expr' <- renameExpr old new expr ; return $ Def x expr' } renameDecl old new (Def_ nm eq expr) | name' nm == old = do { ; expr' <- renameExpr old new expr ; return $ Def_ (Nm1_ new ws) eq expr' } | otherwise = do { ; expr' <- renameExpr old new expr ; return $ Def_ nm eq expr' } where (Nm1_ _ ws) = nm -- recall: -- signature decls -- eg. foo : bar renameDecl old new (Sig nm ex) | nm == old = do { ; expr' <- renameExpr old new ex ; return $ Sig new expr' } | otherwise = do { ; expr' <- renameExpr old new ex ; return $ Sig nm expr' } renameDecl old new (Sig_ nm colontok ex) | name' nm == old = do { ; expr' <- renameExpr old new ex ; return $ Sig_ (Nm1_ new ws) colontok expr' } | otherwise = do { ; expr' <- renameExpr old new ex ; return $ Sig_ nm colontok expr' } where (Nm1_ _ ws) = nm {- data type decls, eg. data Nat : Type where Zero Succ of (Nat) -} -- start out w/ no renaming at all -- renameDecl _ _ d@(Data {}) = return d -- renameDecl _ _ d@(Data_ {}) = return d renameDecl old new (Data tt tele constrdefs) = -- Data <$> (pure $ if tt == old then new else tt) <*> (renameTele old new tele) <*> pure constrdefs Data <$> (pure $ if tt == old then new else tt) <*> (renameTele old new tele) <*> pure (renameConstructorDef old new <$> constrdefs) renameDecl old new (Data_ datatok nm tele colontok ex wheretoken maybo constrdefsAndMaySemiCola maybc ) = Data_ <$> pure datatok <*> (pure $ if name' nm == old then (Nm1_ new ws) else nm) <*> (renameTele old new tele) <*> pure colontok <*> pure ex <*> pure wheretoken <*> pure maybo -- need to do renaming in constructor defs as well <*> pure [(renameConstructorDef old new cd, semi) | (cd, semi) <- constrdefsAndMaySemiCola] <*> pure maybc where (Nm1_ _ ws) = nm -- TODO to be completed for the remaining constraint constructors -- -- | ConsWildInParens_ Eps (Token 'ParenOpenTy t) (Binder t) (Expr t a) (Token 'ParenCloseTy t) (Telescope t a) -- -- | ConsInBrackets_ Eps (Token 'BracketOpenTy t) (Nm t) (Token 'ColonTy t) (Expr t a) (Token 'BracketCloseTy t) (Telescope t a) -- -- -- need this as well - cf. equal_ -- -- -- should keep = as well -- -- | Constraint_ (Token 'BracketOpenTy t) (Expr t a) (Token 'EqualTy t) (Expr t a) (Token 'BracketCloseTy t) (Telescope t a) renameTele _ _ EmptyTele = pure EmptyTele renameTele old new (Cons eps tt ex tele) = Cons <$> pure eps <*> pure (if tt==old then new else tt) <*> (renameExpr old new ex) <*> (renameTele old new tele) renameTele old new (ConsInParens_ eps po nm col ex pc tele) = ConsInParens_ <$> pure eps <*> pure po <*> (pure $ if name' nm == old then (Nm1_ new ws) else nm) <*> pure col <*> (renameExpr old new ex) <*> pure pc <*> (renameTele old new tele) where (Nm1_ _ ws) = nm renameTele old new (Constraint ex1 ex2 tele) = Constraint <$> (renameExpr old new ex1) <*> (renameExpr old new ex2) <*> (renameTele old new tele) renameConstructorDef old new cd@(ConstructorDef {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd renameConstructorDef old new cd@(ConstructorDef' {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd renameConstructorDef old new cd@(ConstructorDef_ {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd renameConstructorDef old new cd@(ConstructorDef'_ {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd {-| rename in matches, looks fine to me: >>> renameMatch "Zero" "ZZ" <$> [Match (PatCon "Zero" []) (Scope (LitBool True)),Match (PatCon "Succ" [(RuntimeP, PatVar "n")]) (Scope (LitBool False))] [Match (PatCon "ZZ" []) (Scope (LitBool True)),Match (PatCon "Succ" [(RuntimeP,PatVar "n")]) (Scope (LitBool False))] and in @Lec3.pi@, at position 21 5, there is @Zero@ >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 5 >>= focus Parsing File "pitestfiles/Lec3.pi" Zero this is defined at the module level (somewhere up the syntax tree ie.: @upToBinding2@), and used in the case expression of decl 5 as well: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 5 >>= upToBinding2 >>= \(old, z) -> forgetZ z >>= toDecl 5 >>= focus Parsing File "pitestfiles/Lec3.pi" is_zero = \x . case x of Zero -> True (Succ n) -> False now renaming @Zero@ to @ZZ@ works fine: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Lec3.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 5 >>= upToBinding2 >>= \(old, z) -> forgetZ z >>= toDecl 5 >>= renameZ old "ZZ" >>= focus Parsing File "pitestfiles/Lec3.pi" is_zero = \x . case x of ZZ -> True (Succ n) -> False -} renameMatch old new cd@(Match {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd renameMatch old new cd@(Match_ {}) = bimap (\tt -> if tt==old then new else tt) (\somea -> if somea==old then new else somea) cd -- -------------------------------------------------- -- rename in the zipper -- similar to upToBinding'/upToBinding -- two function here: -- renameZ takes an old and a new name -- renameZ' just takes a new name (and gets the old name from the state) {-| @renameZ old new z@ rename an @old@ name to a @new@ new in zipper @z@. this function does not require @MonadState (RefactorState a) m@ (but two names: the @old@ one, as well as the @new@ one) some examples, starting with the deliberatly simple @Test.pi@ module: >>> tst <- (runExceptT $ getModules_ ["samples"] "Test") >>= return . last . fromRight' Parsing File "samples/Nat.pi" Parsing File "samples/Nat.pi" Parsing File "samples/Sample.pi" Parsing File "samples/Test.pi" >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= lineColumn 21 9 >>= repr a see what @a@ we are talking about (at position 21 9), navigating there step by step: >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= navigate [Decl 6] >>= repr j = \y . a (\a . x (\a . a)) <BLANKLINE> >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= navigate [Decl 6, Rhs] >>= repr \y . a (\a . x (\a . a)) <BLANKLINE> >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= navigate [Decl 6, Rhs, Rhs] >>= repr a (\a . x (\a . a)) <BLANKLINE> >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= navigate [Decl 6, Rhs, Rhs, Lhs] >>= repr a in any case, this is the @a@ bound at the top level, thus renaming changes it throughout the module (but not the deeper locally bound instances). >>> (pp . fromRight' <$>) refactor $ (rzipper $ Mod $ t2s $ tst) >>= lineColumn 21 9 >>= upToBinding >>= renameZ "a" "A" >>= focus <BLANKLINE> -- leading ws, module copied from M.pi, do not touch though: used in the doctests <BLANKLINE> module Main where <BLANKLINE> import Nat import Sample <BLANKLINE> A = \x . 2 <BLANKLINE> b = \x [ y ] z . x 2 <BLANKLINE> k = \x . frec x <BLANKLINE> <BLANKLINE> f = \x . A x g = \x . c x <BLANKLINE> hh = \ yy . A (\a . x a) <BLANKLINE> j = \y . A (\a . x (\a . a)) frec = \y . frec (\a . x (\a . a)) <BLANKLINE> cf this very example renamed with @renameZ'@ below. as of February 2016: can now rename by means of @upToBinding2@, which works with the simpler @ezipper@ like so (rename @pred@ to @predecessor@): @pred@ can be found at position 21 3, its definition at the module level: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= focus Parsing File "pitestfiles/Nat.pi" pred >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= focus Parsing File "pitestfiles/Nat.pi" pred renaming @pred@ to @predecessor@ - throughout the module ie. (the result thus too long to be shown here, but you can try this out yourself): >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= \(old, z) -> renameZ old "predecessor" z >>= repr ... but cf. its usage in decl 12 (@mult@) eg. >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= \(old, z) -> renameZ old "predecessor" z >>= toDecl 12 >>= repr Parsing File "pitestfiles/Nat.pi" mult = \ n m . case n of Zero -> Zero Succ predecessor -> plus m (mult predecessor m) <BLANKLINE> <BLANKLINE> <BLANKLINE> replace @pred@ by @predecessor@ (in both: signature + def) in the non white space aware (regular absy) case: >>> (pp . fromRight' <$>) $ module' "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= toDecl 4 >>= left >>= upToBinding2 >>= \(old, z) -> renameZ old "predecessor" z >>= repr ... likewise in the whitespace aware case (same means of navigation to @pred@ - can navigate there by lineColumn as well, of course, cf. below), ie. @pred@ -> @predecessor@, in both: sig+def: >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= toDecl 4 >>= left >>= upToBinding2 >>= \(old, z) -> renameZ old "predecessor" z >>= repr ... as above, but navigate to @pred@ with lineColumn >>> (pp . fromRight' <$>) $ module_ "pitestfiles/Nat.pi" >>= \m -> return $ (ezipper $ Mod $ t2s $ nopos m) >>= lineColumn 21 3 >>= upToBinding2 >>= \(old, z) -> renameZ old "predecessor" z >>= repr ... -} -- Show at least for debugging with Debug.Trace.trace below renameZ :: (Refactoring m, Disp (Expr a a), Disp a, Eq a, MkVisible a, Show a) => a -> a -> Zipper a -> m (Zipper a) renameZ old new (Dcl decl, bs) = do { ; decl' <- renameDecl old new decl ; rsucceed (Dcl decl', bs) } renameZ old new (Exp expr, bs) = do { ; expr' <- renameExpr old new expr ; rsucceed (Exp expr', bs) } renameZ old new z@(Aa _, _) = do { ; up z >>= \z' -> renameZ old new z' } renameZ old new (Mod (Module nm mimports mdecls mconstrs), bs) = do { ; dcls <- forM mdecls (\decl -> renameDecl old new decl) ; rsucceed (Mod (Module nm mimports dcls mconstrs), bs) } renameZ old new (Mod m@(Module_ {..}), bs) = do { -- any better / simpler - in one line maybe ? -- ; dcls <- forM ((^. decls) m) (\decl -> renameDecl old new decl) ; dcls <- forM (_decls) (\decl -> renameDecl old new decl) ; rsucceed $ (Mod $ over (decls) (\_-> dcls) m, bs) } {-| @renameZ' new z@ rename a name a zipper @z@, to a @new@ one. this function requires MonadState (RefactorState a) m idea/requirement: the name encountered has been recorded as the old name in the state, @renamaZ'@ thus only needs the @new@ name continuing with the example above (this time just using the more convenient @module_@ for parsing the @Test@ module): moving upwards with @upToBinding@ (that records the name encountered) and then using @renameZ'@ for the renameing (that just needs the new name @AAA@) >>> tst <- module_ "samples/Test" >>= return Parsing File "samples/Nat.pi" Parsing File "samples/Nat.pi" Parsing File "samples/Sample.pi" Parsing File "samples/Test.pi" >>> pp $ fromRight' $ refactor $ (rzipper $ Mod $ t2s $ tst) >>= lineColumn 21 9 >>= upToBinding >>= renameZ' "AAA" >>= repr <BLANKLINE> -- leading ws, module copied from M.pi, do not touch though: used in the doctests <BLANKLINE> module Main where <BLANKLINE> import Nat import Sample <BLANKLINE> AAA = \x . 2 <BLANKLINE> b = \x [ y ] z . x 2 <BLANKLINE> k = \x . frec x <BLANKLINE> <BLANKLINE> f = \x . AAA x g = \x . c x <BLANKLINE> hh = \ yy . AAA (\a . x a) <BLANKLINE> j = \y . AAA (\a . x (\a . a)) frec = \y . frec (\a . x (\a . a)) <BLANKLINE> TODO think about if it is possible at all now to get an "no old name found" error for renameZ, as there is now only * upToBinding, which does record the name * upToBinding2, which takes the old name as a param -} renameZ' :: (Eq a, Show a, MonadState (RefactorState a) m, MkVisible a, Disp a, Disp (Expr a a), Refactoring m) => a -> Zipper a -> m (Zipper a) renameZ' new (Dcl decl, bs) = do { ; Just old <- oldNmFound <$> get ; decl' <- renameDecl old new decl ; rsucceed (Dcl decl', bs) } renameZ' new (Exp expr, bs) = do { ; Just old <- oldNmFound <$> get ; expr' <- renameExpr old new expr ; rsucceed (Exp expr', bs) } renameZ' new z@(Aa _, _) = do { ; Just old <- oldNmFound <$> get ; up z >>= renameZ old new } renameZ' new (Mod (Module nm mimports mdecls mconstrs), bs) = do { ; Just old <- oldNmFound <$> get ; dcls <- forM mdecls (\decl -> renameDecl old new decl) ; rsucceed (Mod (Module nm mimports dcls mconstrs), bs) } -- reworked in July 2016: consider the possibility of -- "no old name found" -- but maybe not necessary, as there is only upToBinding/upToBinding2 left -- renameZ' new (Mod m@(Module_ {..}), bs) = do { -- ; Just old <- oldNmFound <$> get -- ; dcls <- forM (_decls) (\decl -> renameDecl old new decl) -- ; rsucceed $ (Mod $ over (decls) (\_-> dcls) m, bs) -- } renameZ' new (Mod m@(Module_ {..}), bs) = oldNmFound <$> get >>= \o -> maybe (rfail "renameZ' new (Mod m@(Module_ {..}), bs): no old name found") (\old -> do { ; dcls <- forM (_decls) (\decl -> renameDecl old new decl) ; rsucceed $ (Mod $ over (decls) (\_-> dcls) m, bs) }) o #ifdef PiForallInstalled -- typecheckM m -- stuff st = -- (do -- ; silence $ runExceptT $ getModules ["keepme"] "Foo.pi" -- ; return () -- ) -- typecheckM m@(Module {..}) = -- (do -- ; let m' = untie m -- ; r <- runTcMonad emptyEnv (tcModules [m']) -- ; return r -- -- ; case r of -- -- Left x -> -- -- Right y -> return y -- ) -- typecheckM_ m@(Module_ {..}) = -- (do -- ; let m' = untie m -- ; runTcMonad emptyEnv (tcModules [m']) -- ; return () -- ) #endif -- instance Rename (Zipper a) a where -- rename = renameZ' -- renameTo :: (Eq a, MonadState (RefactorState a) m, Disp a, Refactoring m) => -- a -> Zipper a -> m (Zipper a) -- renameTo new zipper@(Ex expr, bs) = -- (do -- ; st <- get -- ; case oldNmFound st of -- Nothing -> rfail $ "no old name found to rename" -- Just old -> renameZ' old new zipper >>= \renamed -> return renamed -- ) ; -- renameTo new zipper@(Mod (Module nm imports decls constrs), bs) = -- (do -- ; st <- get -- ; case oldNmFound st of -- Nothing -> rfail $ "no old name found to rename" -- Just old -> renameZ' old new zipper >>= \renamed -> return renamed -- ) -- -- rnm :: (Refactoring m, MonadWriter String m) -- -- => Module String String -> Path -> String -> m (Module String String) -- rnm mdl path new = -- (do -- ; let zipper = (Mod mdl, []) -- ; when (new `L.elem` topLevelVars mdl) -- )
reuleaux/pire
src/Pire/Refactor/Refactor.hs
Haskell
bsd-3-clause
34,059
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wall #-} module Language.Fortran.Model.Op.Meta.Core where -- import Data.Int (Int16, Int32, Int64, Int8) -- import Data.Word (Word8) -- import Control.Monad.Reader.Class (MonadReader (ask)) -- import Data.SBV -- import Data.SBV.Dynamic -- import Data.SBV.Internals (SBV (..)) -- import Language.Expression -- import Language.Expression.Pretty -- import Language.Fortran.Model.EvalPrim -- import Language.Fortran.Model.Types -- import Language.Fortran.Model.MetaOp.Repr
dorchard/camfort
src/Language/Fortran/Model/Op/Meta/Core.hs
Haskell
apache-2.0
1,113
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables, TypeOperators, GADTs, EmptyDataDecls, PatternGuards #-} module Reflex.Dynamic.TH (qDyn, unqDyn, mkDyn) where import Reflex.Dynamic import Language.Haskell.TH import qualified Language.Haskell.TH.Syntax as TH import Language.Haskell.TH.Quote import Data.Data import Control.Monad.State import qualified Language.Haskell.Exts as Hs import qualified Language.Haskell.Meta.Syntax.Translate as Hs import Data.Monoid import Data.Generics -- | Quote a Dynamic expression. Within the quoted expression, you can use '$(unqDyn [| x |])' to refer to any expression 'x' of type 'Dynamic t a'; the unquoted result will be of type 'a' qDyn :: Q Exp -> Q Exp qDyn qe = do e <- qe let f :: forall d. Data d => d -> StateT [(Name, Exp)] Q d f d = case eqT of Just (Refl :: d :~: Exp) | AppE (VarE m) eInner <- d , m == 'unqMarker -> do n <- lift $ newName "dyn" modify ((n, eInner):) return $ VarE n _ -> gmapM f d (e', exprsReversed) <- runStateT (gmapM f e) [] let exprs = reverse exprsReversed arg = foldr (\a b -> ConE 'FHCons `AppE` a `AppE` b) (ConE 'FHNil) $ map snd exprs param = foldr (\a b -> ConP 'HCons [VarP a, b]) (ConP 'HNil []) $ map fst exprs [| mapDyn $(return $ LamE [param] e') =<< distributeFHListOverDyn $(return arg) |] unqDyn :: Q Exp -> Q Exp unqDyn e = [| unqMarker $e |] -- | This type represents an occurrence of unqDyn before it has been processed by qDyn. If you see it in a type error, it probably means that unqDyn has been used outside of a qDyn context. data UnqDyn -- unqMarker must not be exported; it is used only as a way of smuggling data from unqDyn to qDyn --TODO: It would be much nicer if the TH AST was extensible to support this kind of thing without trickery unqMarker :: a -> UnqDyn unqMarker = error "An unqDyn expression was used outside of a qDyn expression" mkDyn :: QuasiQuoter mkDyn = QuasiQuoter { quoteExp = mkDynExp , quotePat = error "mkDyn: pattern splices are not supported" , quoteType = error "mkDyn: type splices are not supported" , quoteDec = error "mkDyn: declaration splices are not supported" } mkDynExp :: String -> Q Exp mkDynExp s = case Hs.parseExpWithMode (Hs.defaultParseMode { Hs.extensions = [ Hs.EnableExtension Hs.TemplateHaskell ] }) s of Hs.ParseFailed (Hs.SrcLoc _ l c) err -> fail $ "mkDyn:" <> show l <> ":" <> show c <> ": " <> err Hs.ParseOk e -> qDyn $ return $ everywhere (id `extT` reinstateUnqDyn) $ Hs.toExp $ everywhere (id `extT` antiE) e where TH.Name (TH.OccName occName) (TH.NameG _ _ (TH.ModName modName)) = 'unqMarker antiE x = case x of Hs.SpliceExp se -> Hs.App (Hs.Var $ Hs.Qual (Hs.ModuleName modName) (Hs.Ident occName)) $ case se of Hs.IdSplice v -> Hs.Var $ Hs.UnQual $ Hs.Ident v Hs.ParenSplice ps -> ps _ -> x reinstateUnqDyn (TH.Name (TH.OccName occName') (TH.NameQ (TH.ModName modName'))) | modName == modName' && occName == occName' = 'unqMarker reinstateUnqDyn x = x
k0001/reflex
src/Reflex/Dynamic/TH.hs
Haskell
bsd-3-clause
3,156
-- Command-line based Flapjax compiler. Run without any options for usage -- information. module Main where import Control.Monad import qualified Data.List as L import System.Exit import System.IO import System.Console.GetOpt import System.Environment hiding (withArgs) import System.Directory import BrownPLT.Html (renderHtml) import Text.PrettyPrint.HughesPJ import Text.ParserCombinators.Parsec(ParseError,parseFromFile) import Flapjax.HtmlEmbedding() import Flapjax.Parser(parseScript) -- for standalone mode import BrownPLT.Html.PermissiveParser (parseHtmlFromString) import Flapjax.Compiler import BrownPLT.JavaScript.Parser (parseExpression) import BrownPLT.JavaScript.Lexer import BrownPLT.JavaScript.PrettyPrint import Text.ParserCombinators.Parsec hiding (getInput) import BrownPLT.Flapjax.CompilerMessage import BrownPLT.Flapjax.Interface import Text.XHtml (showHtml,toHtml,HTML) data Option = Usage | Flapjax String | Stdin | Output String | Stdout | ExprMode | WebMode deriving (Eq,Ord) options:: [OptDescr Option] options = [ Option ['h'] ["help"] (NoArg Usage) "shows this help message" , Option ['f'] ["flapjax-path"] (ReqArg Flapjax "URL") "url of flapjax.js" , Option ['o'] ["output"] (ReqArg Output "FILE") "output path" , Option [] ["stdout"] (NoArg Stdout) "write to standard output" , Option [] ["stdin"] (NoArg Stdin) "read from standard input" , Option [] ["expression"] (NoArg ExprMode) "compile a single expression" , Option [] ["web-mode"] (NoArg WebMode) "web-compiler mode" ] checkUsage (Usage:_) = do putStrLn "Flapjax Compiler (fxc-2.0)" putStrLn (usageInfo "Usage: fxc [OPTION ...] file" options) exitSuccess checkUsage _ = return () getFlapjaxPath :: [Option] -> IO (String,[Option]) getFlapjaxPath ((Flapjax s):rest) = return (s,rest) getFlapjaxPath rest = do s <- getInstalledFlapjaxPath return ("file://" ++ s,rest) getInput :: [String] -> [Option] -> IO (Handle,String,[Option]) getInput [] (Stdin:rest) = return (stdin,"stdin",rest) getInput [path] options = do h <- openFile path ReadMode return (h,path,options) getInput [] _ = do hPutStrLn stderr "neither --stdin nor an input file was specified" exitFailure getInput (_:_) _ = do hPutStrLn stderr "multiple input files specified" exitFailure getOutput :: String -> [Option] -> IO (Handle,[Option]) getOutput _ (Stdout:rest) = return (stdout,rest) getOutput _ ((Output outputName):rest) = do h <- openFile outputName WriteMode return (h,rest) getOutput inputName options = do h <- openFile (inputName ++ ".html") WriteMode return (h,options) getWebMode :: [Option] -> IO (Bool,[Option]) getWebMode (WebMode:[]) = return (True, []) getWebMode (WebMode:_) = do hPutStrLn stderr "invalid arguments, use -h for help" exitFailure getWebMode options = return (False,options) getExprMode (ExprMode:[]) = return (True, []) getExprMode (ExprMode:_) = do hPutStrLn stderr "invalid arguments, use -h for help" exitFailure getExprMode args = return (False, args) parseExpr = do whiteSpace e <- parseExpression eof return e main = do argv <- getArgs let (permutedArgs,files,errors) = getOpt Permute options argv unless (null errors) $ do mapM_ (hPutStrLn stderr) errors exitFailure let args = L.sort permutedArgs checkUsage args (fxPath,args) <- getFlapjaxPath args (inputHandle,inputName,args) <- getInput files args (outputHandle,args) <- getOutput inputName args (isExprMode, args) <- getExprMode args (isWebMode, args) <- getWebMode args unless (null args) $ do hPutStrLn stderr "invalid arguments, use -h for help" exitFailure -- monomorphism restriction, I think let showErr :: (Show a, HTML a) => a -> String showErr = if isWebMode then showHtml.toHtml else show inputText <- hGetContents inputHandle case isExprMode of True -> case parse parseExpr "web request" inputText of Left _ -> do hPutStr outputHandle "throw \'parse error\'" exitFailure Right fxExpr -> do jsExpr <- compileExpr defaults fxExpr hPutStr outputHandle (renderExpression jsExpr) exitSuccess False -> case parseHtmlFromString inputName inputText of Left err -> do -- TODO: web mode is different hPutStrLn stderr (showErr err) exitFailure Right (html,_) -> do -- ignoring all warnings (msgs,outHtml) <- compilePage (defaults { flapjaxPath = fxPath }) html -- TODO: web mode is different mapM_ (hPutStrLn stderr . showErr) msgs hPutStrLn outputHandle (renderHtml outHtml) hClose outputHandle exitSuccess
ducis/flapjax-fixed
flapjax/trunk/compiler/src/Fxc.hs
Haskell
bsd-3-clause
4,654
{-# LANGUAGE CPP #-} -- | -- Module : Network.TLS.Backend -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- A Backend represents a unified way to do IO on different -- types without burdening our calling API with multiple -- ways to initialize a new context. -- -- Typically, a backend provides: -- * a way to read data -- * a way to write data -- * a way to close the stream -- * a way to flush the stream -- module Network.TLS.Backend ( HasBackend(..) , Backend(..) ) where import Data.ByteString (ByteString) import qualified Data.ByteString as B import System.IO (Handle, hSetBuffering, BufferMode(..), hFlush, hClose) #ifdef INCLUDE_NETWORK import Control.Monad import qualified Network.Socket as Network (Socket, sClose) import qualified Network.Socket.ByteString as Network #endif #ifdef INCLUDE_HANS import qualified Data.ByteString.Lazy as L import qualified Hans.NetworkStack as Hans #endif -- | Connection IO backend data Backend = Backend { backendFlush :: IO () -- ^ Flush the connection sending buffer, if any. , backendClose :: IO () -- ^ Close the connection. , backendSend :: ByteString -> IO () -- ^ Send a bytestring through the connection. , backendRecv :: Int -> IO ByteString -- ^ Receive specified number of bytes from the connection. } class HasBackend a where initializeBackend :: a -> IO () getBackend :: a -> Backend instance HasBackend Backend where initializeBackend _ = return () getBackend = id #ifdef INCLUDE_NETWORK instance HasBackend Network.Socket where initializeBackend _ = return () getBackend sock = Backend (return ()) (Network.sClose sock) (Network.sendAll sock) recvAll where recvAll n = B.concat `fmap` loop n where loop 0 = return [] loop left = do r <- Network.recv sock left if B.null r then return [] else liftM (r:) (loop (left - B.length r)) #endif #ifdef INCLUDE_HANS instance HasBackend Hans.Socket where initializeBackend _ = return () getBackend sock = Backend (return ()) (Hans.close sock) sendAll recvAll where sendAll x = do amt <- fromIntegral `fmap` Hans.sendBytes sock (L.fromStrict x) if (amt == 0) || (amt == B.length x) then return () else sendAll (B.drop amt x) recvAll n = loop (fromIntegral n) L.empty loop 0 acc = return (L.toStrict acc) loop left acc = do r <- Hans.recvBytes sock left if L.null r then loop 0 acc else loop (left - L.length r) (acc `L.append` r) #endif instance HasBackend Handle where initializeBackend handle = hSetBuffering handle NoBuffering getBackend handle = Backend (hFlush handle) (hClose handle) (B.hPut handle) (B.hGet handle)
beni55/hs-tls
core/Network/TLS/Backend.hs
Haskell
bsd-3-clause
3,057
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} module Yesod.WebSockets ( -- * Core API WebSocketsT , webSockets , webSocketsWith , webSocketsOptions , webSocketsOptionsWith , receiveData , receiveDataE , receiveDataMessageE , sendPing , sendPingE , sendClose , sendCloseE , sendTextData , sendTextDataE , sendBinaryData , sendBinaryDataE , sendDataMessageE -- * Conduit API , sourceWS , sinkWSText , sinkWSBinary -- * Async helpers , race , race_ , concurrently , concurrently_ -- * Re-exports from websockets , WS.defaultConnectionOptions , WS.ConnectionOptions (..) ) where import Control.Monad (forever, when) import Control.Monad.Reader (ReaderT, runReaderT, MonadReader, ask) import Conduit import qualified Network.Wai.Handler.WebSockets as WaiWS import qualified Network.WebSockets as WS import qualified Yesod.Core as Y import UnliftIO (SomeException, tryAny, MonadIO, liftIO, MonadUnliftIO, withRunInIO, race, race_, concurrently, concurrently_) -- | A transformer for a WebSockets handler. -- -- Since 0.1.0 type WebSocketsT = ReaderT WS.Connection -- | Attempt to run a WebSockets handler. This function first checks if the -- client initiated a WebSockets connection and, if so, runs the provided -- application, short-circuiting the rest of your handler. If the client did -- not request a WebSockets connection, the rest of your handler will be called -- instead. -- -- Since 0.1.0 webSockets :: (MonadUnliftIO m, Y.MonadHandler m) => WebSocketsT m () -> m () webSockets = webSocketsOptions WS.defaultConnectionOptions -- | Varient of 'webSockets' which allows you to specify -- the WS.ConnectionOptions setttings when upgrading to a websocket connection. -- -- Since 0.2.5 webSocketsOptions :: (MonadUnliftIO m, Y.MonadHandler m) => WS.ConnectionOptions -> WebSocketsT m () -> m () webSocketsOptions opts = webSocketsOptionsWith opts $ const $ return $ Just $ WS.AcceptRequest Nothing [] -- | Varient of 'webSockets' which allows you to specify the 'WS.AcceptRequest' -- setttings when upgrading to a websocket connection. -- -- Since 0.2.4 webSocketsWith :: (MonadUnliftIO m, Y.MonadHandler m) => (WS.RequestHead -> m (Maybe WS.AcceptRequest)) -- ^ A Nothing indicates that the websocket upgrade request should not happen -- and instead the rest of the handler will be called instead. This allows -- you to use 'WS.getRequestSubprotocols' and only accept the request if -- a compatible subprotocol is given. Also, the action runs before upgrading -- the request to websockets, so you can also use short-circuiting handler -- actions such as 'Y.invalidArgs'. -> WebSocketsT m () -> m () webSocketsWith = webSocketsOptionsWith WS.defaultConnectionOptions -- | Varient of 'webSockets' which allows you to specify both -- the WS.ConnectionOptions and the 'WS.AcceptRequest' -- setttings when upgrading to a websocket connection. -- -- Since 0.2.5 webSocketsOptionsWith :: (MonadUnliftIO m, Y.MonadHandler m) => WS.ConnectionOptions -- ^ Custom websockets options -> (WS.RequestHead -> m (Maybe WS.AcceptRequest)) -- ^ A Nothing indicates that the websocket upgrade request should not happen -- and instead the rest of the handler will be called instead. This allows -- you to use 'WS.getRequestSubprotocols' and only accept the request if -- a compatible subprotocol is given. Also, the action runs before upgrading -- the request to websockets, so you can also use short-circuiting handler -- actions such as 'Y.invalidArgs'. -> WebSocketsT m () -> m () webSocketsOptionsWith wsConnOpts buildAr inner = do req <- Y.waiRequest when (WaiWS.isWebSocketsReq req) $ do let rhead = WaiWS.getRequestHead req mar <- buildAr rhead case mar of Nothing -> return () Just ar -> Y.sendRawResponseNoConduit $ \src sink -> withRunInIO $ \runInIO -> WaiWS.runWebSockets wsConnOpts rhead (\pconn -> do conn <- WS.acceptRequestWith pconn ar WS.forkPingThread conn 30 runInIO $ runReaderT inner conn) src sink -- | Wrapper for capturing exceptions wrapWSE :: (MonadIO m, MonadReader WS.Connection m) => (WS.Connection -> a -> IO ()) -> a -> m (Either SomeException ()) wrapWSE ws x = do conn <- ask liftIO $ tryAny $ ws conn x wrapWS :: (MonadIO m, MonadReader WS.Connection m) => (WS.Connection -> a -> IO ()) -> a -> m () wrapWS ws x = do conn <- ask liftIO $ ws conn x -- | Receive a piece of data from the client. -- -- Since 0.1.0 receiveData :: (MonadIO m, MonadReader WS.Connection m, WS.WebSocketsData a) => m a receiveData = do conn <- ask liftIO $ WS.receiveData conn -- | Receive a piece of data from the client. -- Capture SomeException as the result or operation -- Since 0.2.2 receiveDataE :: (MonadIO m, MonadReader WS.Connection m, WS.WebSocketsData a) => m (Either SomeException a) receiveDataE = do conn <- ask liftIO $ tryAny $ WS.receiveData conn -- | Receive an application message. -- Capture SomeException as the result or operation -- Since 0.2.3 receiveDataMessageE :: (MonadIO m, MonadReader WS.Connection m) => m (Either SomeException WS.DataMessage) receiveDataMessageE = do conn <- ask liftIO $ tryAny $ WS.receiveDataMessage conn -- | Send a textual message to the client. -- -- Since 0.1.0 sendTextData :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m () sendTextData = wrapWS WS.sendTextData -- | Send a textual message to the client. -- Capture SomeException as the result or operation -- and can be used like -- `either handle_exception return =<< sendTextDataE ("Welcome" :: Text)` -- Since 0.2.2 sendTextDataE :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m (Either SomeException ()) sendTextDataE = wrapWSE WS.sendTextData -- | Send a binary message to the client. -- -- Since 0.1.0 sendBinaryData :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m () sendBinaryData = wrapWS WS.sendBinaryData -- | Send a binary message to the client. -- Capture SomeException as the result of operation -- Since 0.2.2 sendBinaryDataE :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m (Either SomeException ()) sendBinaryDataE = wrapWSE WS.sendBinaryData -- | Send a ping message to the client. -- -- Since 0.2.2 sendPing :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> WebSocketsT m () sendPing = wrapWS WS.sendPing -- | Send a ping message to the client. -- Capture SomeException as the result of operation -- Since 0.2.2 sendPingE :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m (Either SomeException ()) sendPingE = wrapWSE WS.sendPing -- | Send a DataMessage to the client. -- Capture SomeException as the result of operation -- Since 0.2.3 sendDataMessageE :: (MonadIO m, MonadReader WS.Connection m) => WS.DataMessage -> m (Either SomeException ()) sendDataMessageE x = do conn <- ask liftIO $ tryAny $ WS.sendDataMessage conn x -- | Send a close request to the client. -- -- Since 0.2.2 sendClose :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> WebSocketsT m () sendClose = wrapWS WS.sendClose -- | Send a close request to the client. -- Capture SomeException as the result of operation -- Since 0.2.2 sendCloseE :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => a -> m (Either SomeException ()) sendCloseE = wrapWSE WS.sendClose -- | A @Source@ of WebSockets data from the user. -- -- Since 0.1.0 sourceWS :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => ConduitT i a m () sourceWS = forever $ lift receiveData >>= yield -- | A @Sink@ for sending textual data to the user. -- -- Since 0.1.0 sinkWSText :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => ConduitT a o m () sinkWSText = mapM_C sendTextData -- | A @Sink@ for sending binary data to the user. -- -- Since 0.1.0 sinkWSBinary :: (MonadIO m, WS.WebSocketsData a, MonadReader WS.Connection m) => ConduitT a o m () sinkWSBinary = mapM_C sendBinaryData
psibi/yesod
yesod-websockets/Yesod/WebSockets.hs
Haskell
mit
8,878
module Layout00014 where instance Indexed (Pull sh a) where Pull ixf _ ! i = ixf i
charleso/intellij-haskforce
tests/gold/parser/Layout00014.hs
Haskell
apache-2.0
88
{-# LANGUAGE RecordWildCards, GADTs #-} module CmmLayoutStack ( cmmLayoutStack, setInfoTableStackMap ) where import StgCmmUtils ( callerSaveVolatileRegs ) -- XXX layering violation import StgCmmForeign ( saveThreadState, loadThreadState ) -- XXX layering violation import BasicTypes import Cmm import CmmInfo import BlockId import CLabel import CmmUtils import MkGraph import ForeignCall import CmmLive import CmmProcPoint import SMRep import Hoopl import UniqSupply import Maybes import UniqFM import Util import DynFlags import FastString import Outputable import qualified Data.Set as Set import Control.Monad.Fix import Data.Array as Array import Data.Bits import Data.List (nub) import Control.Monad (liftM) #include "HsVersions.h" {- Note [Stack Layout] The job of this pass is to - replace references to abstract stack Areas with fixed offsets from Sp. - replace the CmmHighStackMark constant used in the stack check with the maximum stack usage of the proc. - save any variables that are live across a call, and reload them as necessary. Before stack allocation, local variables remain live across native calls (CmmCall{ cmm_cont = Just _ }), and after stack allocation local variables are clobbered by native calls. We want to do stack allocation so that as far as possible - stack use is minimized, and - unnecessary stack saves and loads are avoided. The algorithm we use is a variant of linear-scan register allocation, where the stack is our register file. - First, we do a liveness analysis, which annotates every block with the variables live on entry to the block. - We traverse blocks in reverse postorder DFS; that is, we visit at least one predecessor of a block before the block itself. The stack layout flowing from the predecessor of the block will determine the stack layout on entry to the block. - We maintain a data structure Map Label StackMap which describes the contents of the stack and the stack pointer on entry to each block that is a successor of a block that we have visited. - For each block we visit: - Look up the StackMap for this block. - If this block is a proc point (or a call continuation, if we aren't splitting proc points), emit instructions to reload all the live variables from the stack, according to the StackMap. - Walk forwards through the instructions: - At an assignment x = Sp[loc] - Record the fact that Sp[loc] contains x, so that we won't need to save x if it ever needs to be spilled. - At an assignment x = E - If x was previously on the stack, it isn't any more - At the last node, if it is a call or a jump to a proc point - Lay out the stack frame for the call (see setupStackFrame) - emit instructions to save all the live variables - Remember the StackMaps for all the successors - emit an instruction to adjust Sp - If the last node is a branch, then the current StackMap is the StackMap for the successors. - Manifest Sp: replace references to stack areas in this block with real Sp offsets. We cannot do this until we have laid out the stack area for the successors above. In this phase we also eliminate redundant stores to the stack; see elimStackStores. - There is one important gotcha: sometimes we'll encounter a control transfer to a block that we've already processed (a join point), and in that case we might need to rearrange the stack to match what the block is expecting. (exactly the same as in linear-scan register allocation, except here we have the luxury of an infinite supply of temporary variables). - Finally, we update the magic CmmHighStackMark constant with the stack usage of the function, and eliminate the whole stack check if there was no stack use. (in fact this is done as part of the main traversal, by feeding the high-water-mark output back in as an input. I hate cyclic programming, but it's just too convenient sometimes.) There are plenty of tricky details: update frames, proc points, return addresses, foreign calls, and some ad-hoc optimisations that are convenient to do here and effective in common cases. Comments in the code below explain these. -} -- All stack locations are expressed as positive byte offsets from the -- "base", which is defined to be the address above the return address -- on the stack on entry to this CmmProc. -- -- Lower addresses have higher StackLocs. -- type StackLoc = ByteOff {- A StackMap describes the stack at any given point. At a continuation it has a particular layout, like this: | | <- base |-------------| | ret0 | <- base + 8 |-------------| . upd frame . <- base + sm_ret_off |-------------| | | . vars . . (live/dead) . | | <- base + sm_sp - sm_args |-------------| | ret1 | . ret vals . <- base + sm_sp (<--- Sp points here) |-------------| Why do we include the final return address (ret0) in our stack map? I have absolutely no idea, but it seems to be done that way consistently in the rest of the code generator, so I played along here. --SDM Note that we will be constructing an info table for the continuation (ret1), which needs to describe the stack down to, but not including, the update frame (or ret0, if there is no update frame). -} data StackMap = StackMap { sm_sp :: StackLoc -- ^ the offset of Sp relative to the base on entry -- to this block. , sm_args :: ByteOff -- ^ the number of bytes of arguments in the area for this block -- Defn: the offset of young(L) relative to the base is given by -- (sm_sp - sm_args) of the StackMap for block L. , sm_ret_off :: ByteOff -- ^ Number of words of stack that we do not describe with an info -- table, because it contains an update frame. , sm_regs :: UniqFM (LocalReg,StackLoc) -- ^ regs on the stack } instance Outputable StackMap where ppr StackMap{..} = text "Sp = " <> int sm_sp $$ text "sm_args = " <> int sm_args $$ text "sm_ret_off = " <> int sm_ret_off $$ text "sm_regs = " <> ppr (eltsUFM sm_regs) cmmLayoutStack :: DynFlags -> ProcPointSet -> ByteOff -> CmmGraph -> UniqSM (CmmGraph, BlockEnv StackMap) cmmLayoutStack dflags procpoints entry_args graph0@(CmmGraph { g_entry = entry }) = do -- pprTrace "cmmLayoutStack" (ppr entry_args) $ return () -- We need liveness info. We could do removeDeadAssignments at -- the same time, but it buys nothing over doing cmmSink later, -- and costs a lot more than just cmmLocalLiveness. -- (graph, liveness) <- removeDeadAssignments graph0 let (graph, liveness) = (graph0, cmmLocalLiveness dflags graph0) -- pprTrace "liveness" (ppr liveness) $ return () let blocks = postorderDfs graph (final_stackmaps, _final_high_sp, new_blocks) <- mfix $ \ ~(rec_stackmaps, rec_high_sp, _new_blocks) -> layout dflags procpoints liveness entry entry_args rec_stackmaps rec_high_sp blocks new_blocks' <- mapM (lowerSafeForeignCall dflags) new_blocks -- pprTrace ("Sp HWM") (ppr _final_high_sp) $ return () return (ofBlockList entry new_blocks', final_stackmaps) layout :: DynFlags -> BlockSet -- proc points -> BlockEnv CmmLocalLive -- liveness -> BlockId -- entry -> ByteOff -- stack args on entry -> BlockEnv StackMap -- [final] stack maps -> ByteOff -- [final] Sp high water mark -> [CmmBlock] -- [in] blocks -> UniqSM ( BlockEnv StackMap -- [out] stack maps , ByteOff -- [out] Sp high water mark , [CmmBlock] -- [out] new blocks ) layout dflags procpoints liveness entry entry_args final_stackmaps final_sp_high blocks = go blocks init_stackmap entry_args [] where (updfr, cont_info) = collectContInfo blocks init_stackmap = mapSingleton entry StackMap{ sm_sp = entry_args , sm_args = entry_args , sm_ret_off = updfr , sm_regs = emptyUFM } go [] acc_stackmaps acc_hwm acc_blocks = return (acc_stackmaps, acc_hwm, acc_blocks) go (b0 : bs) acc_stackmaps acc_hwm acc_blocks = do let (entry0@(CmmEntry entry_lbl), middle0, last0) = blockSplit b0 let stack0@StackMap { sm_sp = sp0 } = mapFindWithDefault (pprPanic "no stack map for" (ppr entry_lbl)) entry_lbl acc_stackmaps -- pprTrace "layout" (ppr entry_lbl <+> ppr stack0) $ return () -- (a) Update the stack map to include the effects of -- assignments in this block let stack1 = foldBlockNodesF (procMiddle acc_stackmaps) middle0 stack0 -- (b) Insert assignments to reload all the live variables if this -- block is a proc point let middle1 = if entry_lbl `setMember` procpoints then foldr blockCons middle0 (insertReloads stack0) else middle0 -- (c) Look at the last node and if we are making a call or -- jumping to a proc point, we must save the live -- variables, adjust Sp, and construct the StackMaps for -- each of the successor blocks. See handleLastNode for -- details. (middle2, sp_off, last1, fixup_blocks, out) <- handleLastNode dflags procpoints liveness cont_info acc_stackmaps stack1 middle0 last0 -- pprTrace "layout(out)" (ppr out) $ return () -- (d) Manifest Sp: run over the nodes in the block and replace -- CmmStackSlot with CmmLoad from Sp with a concrete offset. -- -- our block: -- middle1 -- the original middle nodes -- middle2 -- live variable saves from handleLastNode -- Sp = Sp + sp_off -- Sp adjustment goes here -- last1 -- the last node -- let middle_pre = blockToList $ foldl blockSnoc middle1 middle2 final_blocks = manifestSp dflags final_stackmaps stack0 sp0 final_sp_high entry0 middle_pre sp_off last1 fixup_blocks acc_stackmaps' = mapUnion acc_stackmaps out -- If this block jumps to the GC, then we do not take its -- stack usage into account for the high-water mark. -- Otherwise, if the only stack usage is in the stack-check -- failure block itself, we will do a redundant stack -- check. The stack has a buffer designed to accommodate -- the largest amount of stack needed for calling the GC. -- this_sp_hwm | isGcJump last0 = 0 | otherwise = sp0 - sp_off hwm' = maximum (acc_hwm : this_sp_hwm : map sm_sp (mapElems out)) go bs acc_stackmaps' hwm' (final_blocks ++ acc_blocks) -- ----------------------------------------------------------------------------- -- Not foolproof, but GCFun is the culprit we most want to catch isGcJump :: CmmNode O C -> Bool isGcJump (CmmCall { cml_target = CmmReg (CmmGlobal l) }) = l == GCFun || l == GCEnter1 isGcJump _something_else = False -- ----------------------------------------------------------------------------- -- This doesn't seem right somehow. We need to find out whether this -- proc will push some update frame material at some point, so that we -- can avoid using that area of the stack for spilling. The -- updfr_space field of the CmmProc *should* tell us, but it doesn't -- (I think maybe it gets filled in later when we do proc-point -- splitting). -- -- So we'll just take the max of all the cml_ret_offs. This could be -- unnecessarily pessimistic, but probably not in the code we -- generate. collectContInfo :: [CmmBlock] -> (ByteOff, BlockEnv ByteOff) collectContInfo blocks = (maximum ret_offs, mapFromList (catMaybes mb_argss)) where (mb_argss, ret_offs) = mapAndUnzip get_cont blocks get_cont :: Block CmmNode x C -> (Maybe (Label, ByteOff), ByteOff) get_cont b = case lastNode b of CmmCall { cml_cont = Just l, .. } -> (Just (l, cml_ret_args), cml_ret_off) CmmForeignCall { .. } -> (Just (succ, ret_args), ret_off) _other -> (Nothing, 0) -- ----------------------------------------------------------------------------- -- Updating the StackMap from middle nodes -- Look for loads from stack slots, and update the StackMap. This is -- purely for optimisation reasons, so that we can avoid saving a -- variable back to a different stack slot if it is already on the -- stack. -- -- This happens a lot: for example when function arguments are passed -- on the stack and need to be immediately saved across a call, we -- want to just leave them where they are on the stack. -- procMiddle :: BlockEnv StackMap -> CmmNode e x -> StackMap -> StackMap procMiddle stackmaps node sm = case node of CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot area off) _) -> sm { sm_regs = addToUFM (sm_regs sm) r (r,loc) } where loc = getStackLoc area off stackmaps CmmAssign (CmmLocal r) _other -> sm { sm_regs = delFromUFM (sm_regs sm) r } _other -> sm getStackLoc :: Area -> ByteOff -> BlockEnv StackMap -> StackLoc getStackLoc Old n _ = n getStackLoc (Young l) n stackmaps = case mapLookup l stackmaps of Nothing -> pprPanic "getStackLoc" (ppr l) Just sm -> sm_sp sm - sm_args sm + n -- ----------------------------------------------------------------------------- -- Handling stack allocation for a last node -- We take a single last node and turn it into: -- -- C1 (some statements) -- Sp = Sp + N -- C2 (some more statements) -- call f() -- the actual last node -- -- plus possibly some more blocks (we may have to add some fixup code -- between the last node and the continuation). -- -- C1: is the code for saving the variables across this last node onto -- the stack, if the continuation is a call or jumps to a proc point. -- -- C2: if the last node is a safe foreign call, we have to inject some -- extra code that goes *after* the Sp adjustment. handleLastNode :: DynFlags -> ProcPointSet -> BlockEnv CmmLocalLive -> BlockEnv ByteOff -> BlockEnv StackMap -> StackMap -> Block CmmNode O O -> CmmNode O C -> UniqSM ( [CmmNode O O] -- nodes to go *before* the Sp adjustment , ByteOff -- amount to adjust Sp , CmmNode O C -- new last node , [CmmBlock] -- new blocks , BlockEnv StackMap -- stackmaps for the continuations ) handleLastNode dflags procpoints liveness cont_info stackmaps stack0@StackMap { sm_sp = sp0 } middle last = case last of -- At each return / tail call, -- adjust Sp to point to the last argument pushed, which -- is cml_args, after popping any other junk from the stack. CmmCall{ cml_cont = Nothing, .. } -> do let sp_off = sp0 - cml_args return ([], sp_off, last, [], mapEmpty) -- At each CmmCall with a continuation: CmmCall{ cml_cont = Just cont_lbl, .. } -> return $ lastCall cont_lbl cml_args cml_ret_args cml_ret_off CmmForeignCall{ succ = cont_lbl, .. } -> do return $ lastCall cont_lbl (wORD_SIZE dflags) ret_args ret_off -- one word of args: the return address CmmBranch{..} -> handleBranches CmmCondBranch{..} -> handleBranches CmmSwitch{..} -> handleBranches where -- Calls and ForeignCalls are handled the same way: lastCall :: BlockId -> ByteOff -> ByteOff -> ByteOff -> ( [CmmNode O O] , ByteOff , CmmNode O C , [CmmBlock] , BlockEnv StackMap ) lastCall lbl cml_args cml_ret_args cml_ret_off = ( assignments , spOffsetForCall sp0 cont_stack cml_args , last , [] -- no new blocks , mapSingleton lbl cont_stack ) where (assignments, cont_stack) = prepareStack lbl cml_ret_args cml_ret_off prepareStack lbl cml_ret_args cml_ret_off | Just cont_stack <- mapLookup lbl stackmaps -- If we have already seen this continuation before, then -- we just have to make the stack look the same: = (fixupStack stack0 cont_stack, cont_stack) -- Otherwise, we have to allocate the stack frame | otherwise = (save_assignments, new_cont_stack) where (new_cont_stack, save_assignments) = setupStackFrame dflags lbl liveness cml_ret_off cml_ret_args stack0 -- For other last nodes (branches), if any of the targets is a -- proc point, we have to set up the stack to match what the proc -- point is expecting. -- handleBranches :: UniqSM ( [CmmNode O O] , ByteOff , CmmNode O C , [CmmBlock] , BlockEnv StackMap ) handleBranches -- Note [diamond proc point] | Just l <- futureContinuation middle , (nub $ filter (`setMember` procpoints) $ successors last) == [l] = do let cont_args = mapFindWithDefault 0 l cont_info (assigs, cont_stack) = prepareStack l cont_args (sm_ret_off stack0) out = mapFromList [ (l', cont_stack) | l' <- successors last ] return ( assigs , spOffsetForCall sp0 cont_stack (wORD_SIZE dflags) , last , [] , out) | otherwise = do pps <- mapM handleBranch (successors last) let lbl_map :: LabelMap Label lbl_map = mapFromList [ (l,tmp) | (l,tmp,_,_) <- pps ] fix_lbl l = mapFindWithDefault l l lbl_map return ( [] , 0 , mapSuccessors fix_lbl last , concat [ blk | (_,_,_,blk) <- pps ] , mapFromList [ (l, sm) | (l,_,sm,_) <- pps ] ) -- For each successor of this block handleBranch :: BlockId -> UniqSM (BlockId, BlockId, StackMap, [CmmBlock]) handleBranch l -- (a) if the successor already has a stackmap, we need to -- shuffle the current stack to make it look the same. -- We have to insert a new block to make this happen. | Just stack2 <- mapLookup l stackmaps = do let assigs = fixupStack stack0 stack2 (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 assigs return (l, tmp_lbl, stack2, block) -- (b) if the successor is a proc point, save everything -- on the stack. | l `setMember` procpoints = do let cont_args = mapFindWithDefault 0 l cont_info (stack2, assigs) = --pprTrace "first visit to proc point" -- (ppr l <+> ppr stack1) $ setupStackFrame dflags l liveness (sm_ret_off stack0) cont_args stack0 -- (tmp_lbl, block) <- makeFixupBlock dflags sp0 l stack2 assigs return (l, tmp_lbl, stack2, block) -- (c) otherwise, the current StackMap is the StackMap for -- the continuation. But we must remember to remove any -- variables from the StackMap that are *not* live at -- the destination, because this StackMap might be used -- by fixupStack if this is a join point. | otherwise = return (l, l, stack1, []) where live = mapFindWithDefault (panic "handleBranch") l liveness stack1 = stack0 { sm_regs = filterUFM is_live (sm_regs stack0) } is_live (r,_) = r `elemRegSet` live makeFixupBlock :: DynFlags -> ByteOff -> Label -> StackMap -> [CmmNode O O] -> UniqSM (Label, [CmmBlock]) makeFixupBlock dflags sp0 l stack assigs | null assigs && sp0 == sm_sp stack = return (l, []) | otherwise = do tmp_lbl <- liftM mkBlockId $ getUniqueM let sp_off = sp0 - sm_sp stack block = blockJoin (CmmEntry tmp_lbl) (maybeAddSpAdj dflags sp_off (blockFromList assigs)) (CmmBranch l) return (tmp_lbl, [block]) -- Sp is currently pointing to current_sp, -- we want it to point to -- (sm_sp cont_stack - sm_args cont_stack + args) -- so the difference is -- sp0 - (sm_sp cont_stack - sm_args cont_stack + args) spOffsetForCall :: ByteOff -> StackMap -> ByteOff -> ByteOff spOffsetForCall current_sp cont_stack args = current_sp - (sm_sp cont_stack - sm_args cont_stack + args) -- | create a sequence of assignments to establish the new StackMap, -- given the old StackMap. fixupStack :: StackMap -> StackMap -> [CmmNode O O] fixupStack old_stack new_stack = concatMap move new_locs where old_map = sm_regs old_stack new_locs = stackSlotRegs new_stack move (r,n) | Just (_,m) <- lookupUFM old_map r, n == m = [] | otherwise = [CmmStore (CmmStackSlot Old n) (CmmReg (CmmLocal r))] setupStackFrame :: DynFlags -> BlockId -- label of continuation -> BlockEnv CmmLocalLive -- liveness -> ByteOff -- updfr -> ByteOff -- bytes of return values on stack -> StackMap -- current StackMap -> (StackMap, [CmmNode O O]) setupStackFrame dflags lbl liveness updfr_off ret_args stack0 = (cont_stack, assignments) where -- get the set of LocalRegs live in the continuation live = mapFindWithDefault Set.empty lbl liveness -- the stack from the base to updfr_off is off-limits. -- our new stack frame contains: -- * saved live variables -- * the return address [young(C) + 8] -- * the args for the call, -- which are replaced by the return values at the return -- point. -- everything up to updfr_off is off-limits -- stack1 contains updfr_off, plus everything we need to save (stack1, assignments) = allocate dflags updfr_off live stack0 -- And the Sp at the continuation is: -- sm_sp stack1 + ret_args cont_stack = stack1{ sm_sp = sm_sp stack1 + ret_args , sm_args = ret_args , sm_ret_off = updfr_off } -- ----------------------------------------------------------------------------- -- Note [diamond proc point] -- -- This special case looks for the pattern we get from a typical -- tagged case expression: -- -- Sp[young(L1)] = L1 -- if (R1 & 7) != 0 goto L1 else goto L2 -- L2: -- call [R1] returns to L1 -- L1: live: {y} -- x = R1 -- -- If we let the generic case handle this, we get -- -- Sp[-16] = L1 -- if (R1 & 7) != 0 goto L1a else goto L2 -- L2: -- Sp[-8] = y -- Sp = Sp - 16 -- call [R1] returns to L1 -- L1a: -- Sp[-8] = y -- Sp = Sp - 16 -- goto L1 -- L1: -- x = R1 -- -- The code for saving the live vars is duplicated in each branch, and -- furthermore there is an extra jump in the fast path (assuming L1 is -- a proc point, which it probably is if there is a heap check). -- -- So to fix this we want to set up the stack frame before the -- conditional jump. How do we know when to do this, and when it is -- safe? The basic idea is, when we see the assignment -- -- Sp[young(L)] = L -- -- we know that -- * we are definitely heading for L -- * there can be no more reads from another stack area, because young(L) -- overlaps with it. -- -- We don't necessarily know that everything live at L is live now -- (some might be assigned between here and the jump to L). So we -- simplify and only do the optimisation when we see -- -- (1) a block containing an assignment of a return address L -- (2) ending in a branch where one (and only) continuation goes to L, -- and no other continuations go to proc points. -- -- then we allocate the stack frame for L at the end of the block, -- before the branch. -- -- We could generalise (2), but that would make it a bit more -- complicated to handle, and this currently catches the common case. futureContinuation :: Block CmmNode O O -> Maybe BlockId futureContinuation middle = foldBlockNodesB f middle Nothing where f :: CmmNode a b -> Maybe BlockId -> Maybe BlockId f (CmmStore (CmmStackSlot (Young l) _) (CmmLit (CmmBlock _))) _ = Just l f _ r = r -- ----------------------------------------------------------------------------- -- Saving live registers -- | Given a set of live registers and a StackMap, save all the registers -- on the stack and return the new StackMap and the assignments to do -- the saving. -- allocate :: DynFlags -> ByteOff -> LocalRegSet -> StackMap -> (StackMap, [CmmNode O O]) allocate dflags ret_off live stackmap@StackMap{ sm_sp = sp0 , sm_regs = regs0 } = -- pprTrace "allocate" (ppr live $$ ppr stackmap) $ -- we only have to save regs that are not already in a slot let to_save = filter (not . (`elemUFM` regs0)) (Set.elems live) regs1 = filterUFM (\(r,_) -> elemRegSet r live) regs0 in -- make a map of the stack let stack = reverse $ Array.elems $ accumArray (\_ x -> x) Empty (1, toWords dflags (max sp0 ret_off)) $ ret_words ++ live_words where ret_words = [ (x, Occupied) | x <- [ 1 .. toWords dflags ret_off] ] live_words = [ (toWords dflags x, Occupied) | (r,off) <- eltsUFM regs1, let w = localRegBytes dflags r, x <- [ off, off - wORD_SIZE dflags .. off - w + 1] ] in -- Pass over the stack: find slots to save all the new live variables, -- choosing the oldest slots first (hence a foldr). let save slot ([], stack, n, assigs, regs) -- no more regs to save = ([], slot:stack, plusW dflags n 1, assigs, regs) save slot (to_save, stack, n, assigs, regs) = case slot of Occupied -> (to_save, Occupied:stack, plusW dflags n 1, assigs, regs) Empty | Just (stack', r, to_save') <- select_save to_save (slot:stack) -> let assig = CmmStore (CmmStackSlot Old n') (CmmReg (CmmLocal r)) n' = plusW dflags n 1 in (to_save', stack', n', assig : assigs, (r,(r,n')):regs) | otherwise -> (to_save, slot:stack, plusW dflags n 1, assigs, regs) -- we should do better here: right now we'll fit the smallest first, -- but it would make more sense to fit the biggest first. select_save :: [LocalReg] -> [StackSlot] -> Maybe ([StackSlot], LocalReg, [LocalReg]) select_save regs stack = go regs [] where go [] _no_fit = Nothing go (r:rs) no_fit | Just rest <- dropEmpty words stack = Just (replicate words Occupied ++ rest, r, rs++no_fit) | otherwise = go rs (r:no_fit) where words = localRegWords dflags r -- fill in empty slots as much as possible (still_to_save, save_stack, n, save_assigs, save_regs) = foldr save (to_save, [], 0, [], []) stack -- push any remaining live vars on the stack (push_sp, push_assigs, push_regs) = foldr push (n, [], []) still_to_save where push r (n, assigs, regs) = (n', assig : assigs, (r,(r,n')) : regs) where n' = n + localRegBytes dflags r assig = CmmStore (CmmStackSlot Old n') (CmmReg (CmmLocal r)) trim_sp | not (null push_regs) = push_sp | otherwise = plusW dflags n (- length (takeWhile isEmpty save_stack)) final_regs = regs1 `addListToUFM` push_regs `addListToUFM` save_regs in -- XXX should be an assert if ( n /= max sp0 ret_off ) then pprPanic "allocate" (ppr n <+> ppr sp0 <+> ppr ret_off) else if (trim_sp .&. (wORD_SIZE dflags - 1)) /= 0 then pprPanic "allocate2" (ppr trim_sp <+> ppr final_regs <+> ppr push_sp) else ( stackmap { sm_regs = final_regs , sm_sp = trim_sp } , push_assigs ++ save_assigs ) -- ----------------------------------------------------------------------------- -- Manifesting Sp -- | Manifest Sp: turn all the CmmStackSlots into CmmLoads from Sp. The -- block looks like this: -- -- middle_pre -- the middle nodes -- Sp = Sp + sp_off -- Sp adjustment goes here -- last -- the last node -- -- And we have some extra blocks too (that don't contain Sp adjustments) -- -- The adjustment for middle_pre will be different from that for -- middle_post, because the Sp adjustment intervenes. -- manifestSp :: DynFlags -> BlockEnv StackMap -- StackMaps for other blocks -> StackMap -- StackMap for this block -> ByteOff -- Sp on entry to the block -> ByteOff -- SpHigh -> CmmNode C O -- first node -> [CmmNode O O] -- middle -> ByteOff -- sp_off -> CmmNode O C -- last node -> [CmmBlock] -- new blocks -> [CmmBlock] -- final blocks with Sp manifest manifestSp dflags stackmaps stack0 sp0 sp_high first middle_pre sp_off last fixup_blocks = final_block : fixup_blocks' where area_off = getAreaOff stackmaps adj_pre_sp, adj_post_sp :: CmmNode e x -> CmmNode e x adj_pre_sp = mapExpDeep (areaToSp dflags sp0 sp_high area_off) adj_post_sp = mapExpDeep (areaToSp dflags (sp0 - sp_off) sp_high area_off) final_middle = maybeAddSpAdj dflags sp_off $ blockFromList $ map adj_pre_sp $ elimStackStores stack0 stackmaps area_off $ middle_pre final_last = optStackCheck (adj_post_sp last) final_block = blockJoin first final_middle final_last fixup_blocks' = map (mapBlock3' (id, adj_post_sp, id)) fixup_blocks getAreaOff :: BlockEnv StackMap -> (Area -> StackLoc) getAreaOff _ Old = 0 getAreaOff stackmaps (Young l) = case mapLookup l stackmaps of Just sm -> sm_sp sm - sm_args sm Nothing -> pprPanic "getAreaOff" (ppr l) maybeAddSpAdj :: DynFlags -> ByteOff -> Block CmmNode O O -> Block CmmNode O O maybeAddSpAdj _ 0 block = block maybeAddSpAdj dflags sp_off block = block `blockSnoc` CmmAssign spReg (cmmOffset dflags (CmmReg spReg) sp_off) {- Sp(L) is the Sp offset on entry to block L relative to the base of the OLD area. SpArgs(L) is the size of the young area for L, i.e. the number of arguments. - in block L, each reference to [old + N] turns into [Sp + Sp(L) - N] - in block L, each reference to [young(L') + N] turns into [Sp + Sp(L) - Sp(L') + SpArgs(L') - N] - be careful with the last node of each block: Sp has already been adjusted to be Sp + Sp(L) - Sp(L') -} areaToSp :: DynFlags -> ByteOff -> ByteOff -> (Area -> StackLoc) -> CmmExpr -> CmmExpr areaToSp dflags sp_old _sp_hwm area_off (CmmStackSlot area n) = cmmOffset dflags (CmmReg spReg) (sp_old - area_off area - n) -- Replace (CmmStackSlot area n) with an offset from Sp areaToSp dflags _ sp_hwm _ (CmmLit CmmHighStackMark) = mkIntExpr dflags sp_hwm -- Replace CmmHighStackMark with the number of bytes of stack used, -- the sp_hwm. See Note [Stack usage] in StgCmmHeap areaToSp dflags _ _ _ (CmmMachOp (MO_U_Lt _) [CmmMachOp (MO_Sub _) [ CmmRegOff (CmmGlobal Sp) x_off , CmmLit (CmmInt y_lit _)], CmmReg (CmmGlobal SpLim)]) | fromIntegral x_off >= y_lit = zeroExpr dflags -- Replace a stack-overflow test that cannot fail with a no-op -- See Note [Always false stack check] areaToSp _ _ _ _ other = other -- Note [Always false stack check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- We can optimise stack checks of the form -- -- if ((Sp + x) - y < SpLim) then .. else .. -- -- where are non-negative integer byte offsets. Since we know that -- SpLim <= Sp (remember the stack grows downwards), this test must -- yield False if (x >= y), so we can rewrite the comparison to False. -- A subsequent sinking pass will later drop the dead code. -- Optimising this away depends on knowing that SpLim <= Sp, so it is -- really the job of the stack layout algorithm, hence we do it now. optStackCheck :: CmmNode O C -> CmmNode O C optStackCheck n = -- Note [null stack check] case n of CmmCondBranch (CmmLit (CmmInt 0 _)) _true false -> CmmBranch false other -> other -- ----------------------------------------------------------------------------- -- | Eliminate stores of the form -- -- Sp[area+n] = r -- -- when we know that r is already in the same slot as Sp[area+n]. We -- could do this in a later optimisation pass, but that would involve -- a separate analysis and we already have the information to hand -- here. It helps clean up some extra stack stores in common cases. -- -- Note that we may have to modify the StackMap as we walk through the -- code using procMiddle, since an assignment to a variable in the -- StackMap will invalidate its mapping there. -- elimStackStores :: StackMap -> BlockEnv StackMap -> (Area -> ByteOff) -> [CmmNode O O] -> [CmmNode O O] elimStackStores stackmap stackmaps area_off nodes = go stackmap nodes where go _stackmap [] = [] go stackmap (n:ns) = case n of CmmStore (CmmStackSlot area m) (CmmReg (CmmLocal r)) | Just (_,off) <- lookupUFM (sm_regs stackmap) r , area_off area + m == off -> -- pprTrace "eliminated a node!" (ppr r) $ go stackmap ns _otherwise -> n : go (procMiddle stackmaps n stackmap) ns -- ----------------------------------------------------------------------------- -- Update info tables to include stack liveness setInfoTableStackMap :: DynFlags -> BlockEnv StackMap -> CmmDecl -> CmmDecl setInfoTableStackMap dflags stackmaps (CmmProc top_info@TopInfo{..} l v g) = CmmProc top_info{ info_tbls = mapMapWithKey fix_info info_tbls } l v g where fix_info lbl info_tbl@CmmInfoTable{ cit_rep = StackRep _ } = info_tbl { cit_rep = StackRep (get_liveness lbl) } fix_info _ other = other get_liveness :: BlockId -> Liveness get_liveness lbl = case mapLookup lbl stackmaps of Nothing -> pprPanic "setInfoTableStackMap" (ppr lbl <+> ppr info_tbls) Just sm -> stackMapToLiveness dflags sm setInfoTableStackMap _ _ d = d stackMapToLiveness :: DynFlags -> StackMap -> Liveness stackMapToLiveness dflags StackMap{..} = reverse $ Array.elems $ accumArray (\_ x -> x) True (toWords dflags sm_ret_off + 1, toWords dflags (sm_sp - sm_args)) live_words where live_words = [ (toWords dflags off, False) | (r,off) <- eltsUFM sm_regs, isGcPtrType (localRegType r) ] -- ----------------------------------------------------------------------------- -- Lowering safe foreign calls {- Note [Lower safe foreign calls] We start with Sp[young(L1)] = L1 ,----------------------- | r1 = foo(x,y,z) returns to L1 '----------------------- L1: R1 = r1 -- copyIn, inserted by mkSafeCall ... the stack layout algorithm will arrange to save and reload everything live across the call. Our job now is to expand the call so we get Sp[young(L1)] = L1 ,----------------------- | SAVE_THREAD_STATE() | token = suspendThread(BaseReg, interruptible) | r = foo(x,y,z) | BaseReg = resumeThread(token) | LOAD_THREAD_STATE() | R1 = r -- copyOut | jump Sp[0] '----------------------- L1: r = R1 -- copyIn, inserted by mkSafeCall ... Note the copyOut, which saves the results in the places that L1 is expecting them (see Note {safe foreign call convention]). Note also that safe foreign call is replace by an unsafe one in the Cmm graph. -} lowerSafeForeignCall :: DynFlags -> CmmBlock -> UniqSM CmmBlock lowerSafeForeignCall dflags block | (entry, middle, CmmForeignCall { .. }) <- blockSplit block = do -- Both 'id' and 'new_base' are KindNonPtr because they're -- RTS-only objects and are not subject to garbage collection id <- newTemp (bWord dflags) new_base <- newTemp (cmmRegType dflags (CmmGlobal BaseReg)) let (caller_save, caller_load) = callerSaveVolatileRegs dflags load_tso <- newTemp (gcWord dflags) load_stack <- newTemp (gcWord dflags) let suspend = saveThreadState dflags <*> caller_save <*> mkMiddle (callSuspendThread dflags id intrbl) midCall = mkUnsafeCall tgt res args resume = mkMiddle (callResumeThread new_base id) <*> -- Assign the result to BaseReg: we -- might now have a different Capability! mkAssign (CmmGlobal BaseReg) (CmmReg (CmmLocal new_base)) <*> caller_load <*> loadThreadState dflags load_tso load_stack (_, regs, copyout) = copyOutOflow dflags NativeReturn Jump (Young succ) (map (CmmReg . CmmLocal) res) ret_off [] -- NB. after resumeThread returns, the top-of-stack probably contains -- the stack frame for succ, but it might not: if the current thread -- received an exception during the call, then the stack might be -- different. Hence we continue by jumping to the top stack frame, -- not by jumping to succ. jump = CmmCall { cml_target = entryCode dflags $ CmmLoad (CmmReg spReg) (bWord dflags) , cml_cont = Just succ , cml_args_regs = regs , cml_args = widthInBytes (wordWidth dflags) , cml_ret_args = ret_args , cml_ret_off = ret_off } graph' <- lgraphOfAGraph $ suspend <*> midCall <*> resume <*> copyout <*> mkLast jump case toBlockList graph' of [one] -> let (_, middle', last) = blockSplit one in return (blockJoin entry (middle `blockAppend` middle') last) _ -> panic "lowerSafeForeignCall0" -- Block doesn't end in a safe foreign call: | otherwise = return block foreignLbl :: FastString -> CmmExpr foreignLbl name = CmmLit (CmmLabel (mkForeignLabel name Nothing ForeignLabelInExternalPackage IsFunction)) newTemp :: CmmType -> UniqSM LocalReg newTemp rep = getUniqueM >>= \u -> return (LocalReg u rep) callSuspendThread :: DynFlags -> LocalReg -> Bool -> CmmNode O O callSuspendThread dflags id intrbl = CmmUnsafeForeignCall (ForeignTarget (foreignLbl (fsLit "suspendThread")) (ForeignConvention CCallConv [AddrHint, NoHint] [AddrHint] CmmMayReturn)) [id] [CmmReg (CmmGlobal BaseReg), mkIntExpr dflags (fromEnum intrbl)] callResumeThread :: LocalReg -> LocalReg -> CmmNode O O callResumeThread new_base id = CmmUnsafeForeignCall (ForeignTarget (foreignLbl (fsLit "resumeThread")) (ForeignConvention CCallConv [AddrHint] [AddrHint] CmmMayReturn)) [new_base] [CmmReg (CmmLocal id)] -- ----------------------------------------------------------------------------- plusW :: DynFlags -> ByteOff -> WordOff -> ByteOff plusW dflags b w = b + w * wORD_SIZE dflags data StackSlot = Occupied | Empty -- Occupied: a return address or part of an update frame instance Outputable StackSlot where ppr Occupied = ptext (sLit "XXX") ppr Empty = ptext (sLit "---") dropEmpty :: WordOff -> [StackSlot] -> Maybe [StackSlot] dropEmpty 0 ss = Just ss dropEmpty n (Empty : ss) = dropEmpty (n-1) ss dropEmpty _ _ = Nothing isEmpty :: StackSlot -> Bool isEmpty Empty = True isEmpty _ = False localRegBytes :: DynFlags -> LocalReg -> ByteOff localRegBytes dflags r = roundUpToWords dflags (widthInBytes (typeWidth (localRegType r))) localRegWords :: DynFlags -> LocalReg -> WordOff localRegWords dflags = toWords dflags . localRegBytes dflags toWords :: DynFlags -> ByteOff -> WordOff toWords dflags x = x `quot` wORD_SIZE dflags insertReloads :: StackMap -> [CmmNode O O] insertReloads stackmap = [ CmmAssign (CmmLocal r) (CmmLoad (CmmStackSlot Old sp) (localRegType r)) | (r,sp) <- stackSlotRegs stackmap ] stackSlotRegs :: StackMap -> [(LocalReg, StackLoc)] stackSlotRegs sm = eltsUFM (sm_regs sm)
lukexi/ghc-7.8-arm64
compiler/cmm/CmmLayoutStack.hs
Haskell
bsd-3-clause
42,050
----------------------------------------------------------------------------- -- | -- Module : Graphics.X11 -- Copyright : (c) Alastair Reid, 1999-2003 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : provisional -- Portability : portable -- -- A Haskell binding for the X11 libraries. -- ----------------------------------------------------------------------------- module Graphics.X11 ( module Graphics.X11.Xlib ) where import Graphics.X11.Xlib ---------------------------------------------------------------- -- End ----------------------------------------------------------------
mgsloan/X11
Graphics/X11.hs
Haskell
bsd-3-clause
694
<?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>Requester</title> <maps> <homeID>requester</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/requester/src/main/javahelp/help_tr_TR/helpset_tr_TR.hs
Haskell
apache-2.0
960
{-# OPTIONS_JHC -fno-prelude #-} module Jhc.Inst.Show() where import Jhc.Basics import Jhc.Class.Num import Jhc.Class.Ord import Jhc.Class.Real import Jhc.Show import Jhc.Type.C -- we convert them to Word or WordMax so the showIntAtBase specialization can occur. fromIntegral :: (Integral a, Num b) => a -> b fromIntegral x = fromInteger (toInteger x) instance Show Word where showsPrec _ x = showWord x instance Show Word8 where showsPrec _ x = showWord (fromIntegral x :: Word) instance Show Word16 where showsPrec _ x = showWord (fromIntegral x :: Word) instance Show Word32 where showsPrec _ x = showWord (fromIntegral x :: Word) instance Show Word64 where showsPrec _ x = showWordMax (fromIntegral x :: WordMax) instance Show WordPtr where showsPrec _ x = showWordMax (fromIntegral x :: WordMax) instance Show WordMax where showsPrec _ x = showWordMax x instance Show Int where showsPrec p x | p `seq` x `seq` False = undefined | x < 0 = showParen (p > 6) (showChar '-' . showWord (fromIntegral $ negate x :: Word)) | True = showWord (fromIntegral x :: Word) instance Show Integer where showsPrec p x | p `seq` x `seq` False = undefined | x < 0 = showParen (p > 6) (showChar '-' . showWordMax (fromIntegral $ negate x :: WordMax)) | True = showWordMax (fromIntegral x :: WordMax) instance Show Int8 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Show Int16 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Show Int32 where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Show Int64 where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show IntPtr where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show IntMax where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show CSize where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show CInt where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show CLong where showsPrec p x = showsPrec p (fromIntegral x :: Integer) instance Show CChar where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Show CSChar where showsPrec p x = showsPrec p (fromIntegral x :: Int) instance Show CUChar where showsPrec _ x = showWord (fromIntegral x :: Word) instance Show CUInt where showsPrec _ x = showWord (fromIntegral x :: Word) instance Show CULong where showsPrec _ x = showWordMax (fromIntegral x :: WordMax) instance Show CWchar where showsPrec _ x = showWord (fromIntegral x :: Word) -- specialized base 10 only versions of show showWord :: Word -> String -> String showWord w rest = w `seq` case quotRem w 10 of (n',d) -> n' `seq` d `seq` rest' `seq` if n' == 0 then rest' else showWord n' rest' where rest' = chr (fromIntegral d + ord '0') : rest showWordMax :: WordMax -> String -> String showWordMax w rest = w `seq` case quotRem w 10 of (n',d) -> n' `seq` d `seq` rest' `seq` if n' == 0 then rest' else showWordMax n' rest' where rest' = chr (fromIntegral d + ord '0') : rest
hvr/jhc
lib/jhc/Jhc/Inst/Show.hs
Haskell
mit
3,166
{-# LANGUAGE TemplateHaskell #-} {-# OPTIONS_GHC -Wall #-} module Bug where import Language.Haskell.TH -- Warnings should be preserved through recover main :: IO () main = putStrLn $(recover (stringE "splice failed") [| let x = "a" in let x = "b" in x |])
sdiehl/ghc
testsuite/tests/th/TH_recover_warns.hs
Haskell
bsd-3-clause
284
{-# LANGUAGE PatternGuards, DeriveFunctor #-} module IRTS.Lang where import Control.Monad.State hiding (lift) import Control.Applicative hiding (Const) import Idris.Core.TT import Idris.Core.CaseTree import Data.List import Debug.Trace data Endianness = Native | BE | LE deriving (Show, Eq) data LVar = Loc Int | Glob Name deriving (Show, Eq) -- ASSUMPTION: All variable bindings have unique names here data LExp = LV LVar | LApp Bool LExp [LExp] -- True = tail call | LLazyApp Name [LExp] -- True = tail call | LLazyExp LExp | LForce LExp -- make sure Exp is evaluted | LLet Name LExp LExp -- name just for pretty printing | LLam [Name] LExp -- lambda, lifted out before compiling | LProj LExp Int -- projection | LCon (Maybe LVar) -- Location to reallocate, if available Int Name [LExp] | LCase CaseType LExp [LAlt] | LConst Const | LForeign FDesc -- Function descriptor (usually name as string) FDesc -- Return type descriptor [(FDesc, LExp)] -- first LExp is the FFI type description | LOp PrimFn [LExp] | LNothing | LError String deriving Eq data FDesc = FCon Name | FStr String | FUnknown | FIO FDesc | FApp Name [FDesc] deriving (Show, Eq) data Export = ExportData FDesc -- Exported data descriptor (usually string) | ExportFun Name -- Idris name FDesc -- Exported function descriptor FDesc -- Return type descriptor [FDesc] -- Argument types deriving (Show, Eq) data ExportIFace = Export Name -- FFI descriptor String -- interface file [Export] deriving (Show, Eq) -- Primitive operators. Backends are not *required* to implement all -- of these, but should report an error if they are unable data PrimFn = LPlus ArithTy | LMinus ArithTy | LTimes ArithTy | LUDiv IntTy | LSDiv ArithTy | LURem IntTy | LSRem ArithTy | LAnd IntTy | LOr IntTy | LXOr IntTy | LCompl IntTy | LSHL IntTy | LLSHR IntTy | LASHR IntTy | LEq ArithTy | LLt IntTy | LLe IntTy | LGt IntTy | LGe IntTy | LSLt ArithTy | LSLe ArithTy | LSGt ArithTy | LSGe ArithTy | LSExt IntTy IntTy | LZExt IntTy IntTy | LTrunc IntTy IntTy | LStrConcat | LStrLt | LStrEq | LStrLen | LIntFloat IntTy | LFloatInt IntTy | LIntStr IntTy | LStrInt IntTy | LFloatStr | LStrFloat | LChInt IntTy | LIntCh IntTy | LBitCast ArithTy ArithTy -- Only for values of equal width | LFExp | LFLog | LFSin | LFCos | LFTan | LFASin | LFACos | LFATan | LFSqrt | LFFloor | LFCeil | LFNegate | LStrHead | LStrTail | LStrCons | LStrIndex | LStrRev | LReadStr | LWriteStr -- system info | LSystemInfo | LFork | LPar -- evaluate argument anywhere, possibly on another -- core or another machine. 'id' is a valid implementation | LExternal Name | LNoOp deriving (Show, Eq) -- Supported target languages for foreign calls data FCallType = FStatic | FObject | FConstructor deriving (Show, Eq) data FType = FArith ArithTy | FFunction | FFunctionIO | FString | FUnit | FPtr | FManagedPtr | FAny deriving (Show, Eq) -- FIXME: Why not use this for all the IRs now? data LAlt' e = LConCase Int Name [Name] e | LConstCase Const e | LDefaultCase e deriving (Show, Eq, Functor) type LAlt = LAlt' LExp data LDecl = LFun [LOpt] Name [Name] LExp -- options, name, arg names, def | LConstructor Name Int Int -- constructor name, tag, arity deriving (Show, Eq) type LDefs = Ctxt LDecl data LOpt = Inline | NoInline deriving (Show, Eq) addTags :: Int -> [(Name, LDecl)] -> (Int, [(Name, LDecl)]) addTags i ds = tag i ds [] where tag i ((n, LConstructor n' (-1) a) : as) acc = tag (i + 1) as ((n, LConstructor n' i a) : acc) tag i ((n, LConstructor n' t a) : as) acc = tag i as ((n, LConstructor n' t a) : acc) tag i (x : as) acc = tag i as (x : acc) tag i [] acc = (i, reverse acc) data LiftState = LS Name Int [(Name, LDecl)] lname (NS n x) i = NS (lname n i) x lname (UN n) i = MN i n lname x i = sMN i (show x ++ "_lam") liftAll :: [(Name, LDecl)] -> [(Name, LDecl)] liftAll xs = concatMap (\ (x, d) -> lambdaLift x d) xs lambdaLift :: Name -> LDecl -> [(Name, LDecl)] lambdaLift n (LFun opts _ args e) = let (e', (LS _ _ decls)) = runState (lift args e) (LS n 0 []) in (n, LFun opts n args e') : decls lambdaLift n x = [(n, x)] getNextName :: State LiftState Name getNextName = do LS n i ds <- get put (LS n (i + 1) ds) return (lname n i) addFn :: Name -> LDecl -> State LiftState () addFn fn d = do LS n i ds <- get put (LS n i ((fn, d) : ds)) lift :: [Name] -> LExp -> State LiftState LExp lift env (LV v) = return (LV v) -- Lifting happens before these can exist... lift env (LApp tc (LV (Glob n)) args) = do args' <- mapM (lift env) args return (LApp tc (LV (Glob n)) args') lift env (LApp tc f args) = do f' <- lift env f fn <- getNextName addFn fn (LFun [Inline] fn env f') args' <- mapM (lift env) args return (LApp tc (LV (Glob fn)) (map (LV . Glob) env ++ args')) lift env (LLazyApp n args) = do args' <- mapM (lift env) args return (LLazyApp n args') lift env (LLazyExp (LConst c)) = return (LConst c) -- lift env (LLazyExp (LApp tc (LV (Glob f)) args)) -- = lift env (LLazyApp f args) lift env (LLazyExp e) = do e' <- lift env e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [NoInline] fn usedArgs e') return (LLazyApp fn (map (LV . Glob) usedArgs)) lift env (LForce e) = do e' <- lift env e return (LForce e') lift env (LLet n v e) = do v' <- lift env v e' <- lift (env ++ [n]) e return (LLet n v' e') lift env (LLam args e) = do e' <- lift (env ++ args) e let usedArgs = nub $ usedIn env e' fn <- getNextName addFn fn (LFun [Inline] fn (usedArgs ++ args) e') return (LApp False (LV (Glob fn)) (map (LV . Glob) usedArgs)) lift env (LProj t i) = do t' <- lift env t return (LProj t' i) lift env (LCon loc i n args) = do args' <- mapM (lift env) args return (LCon loc i n args') lift env (LCase up e alts) = do alts' <- mapM liftA alts e' <- lift env e return (LCase up e' alts') where liftA (LConCase i n args e) = do e' <- lift (env ++ args) e return (LConCase i n args e') liftA (LConstCase c e) = do e' <- lift env e return (LConstCase c e') liftA (LDefaultCase e) = do e' <- lift env e return (LDefaultCase e') lift env (LConst c) = return (LConst c) lift env (LForeign t s args) = do args' <- mapM (liftF env) args return (LForeign t s args') where liftF env (t, e) = do e' <- lift env e return (t, e') lift env (LOp f args) = do args' <- mapM (lift env) args return (LOp f args') lift env (LError str) = return $ LError str lift env LNothing = return $ LNothing allocUnique :: LDefs -> (Name, LDecl) -> (Name, LDecl) allocUnique defs p@(n, LConstructor _ _ _) = p allocUnique defs (n, LFun opts fn args e) = let e' = evalState (findUp e) [] in (n, LFun opts fn args e') where -- Keep track of 'updatable' names in the state, i.e. names whose heap -- entry may be reused, along with the arity which was there findUp :: LExp -> State [(Name, Int)] LExp findUp (LApp t (LV (Glob n)) as) | Just (LConstructor _ i ar) <- lookupCtxtExact n defs, ar == length as = findUp (LCon Nothing i n as) findUp (LV (Glob n)) | Just (LConstructor _ i 0) <- lookupCtxtExact n defs = return $ LCon Nothing i n [] -- nullary cons are global, no need to update findUp (LApp t f as) = LApp t <$> findUp f <*> mapM findUp as findUp (LLazyApp n as) = LLazyApp n <$> mapM findUp as findUp (LLazyExp e) = LLazyExp <$> findUp e findUp (LForce e) = LForce <$> findUp e -- use assumption that names are unique! findUp (LLet n val sc) = LLet n <$> findUp val <*> findUp sc findUp (LLam ns sc) = LLam ns <$> findUp sc findUp (LProj e i) = LProj <$> findUp e <*> return i findUp (LCon (Just l) i n es) = LCon (Just l) i n <$> mapM findUp es findUp (LCon Nothing i n es) = do avail <- get v <- findVar [] avail (length es) LCon v i n <$> mapM findUp es findUp (LForeign t s es) = LForeign t s <$> mapM (\ (t, e) -> do e' <- findUp e return (t, e')) es findUp (LOp o es) = LOp o <$> mapM findUp es findUp (LCase Updatable e@(LV (Glob n)) as) = LCase Updatable e <$> mapM (doUpAlt n) as findUp (LCase t e as) = LCase t <$> findUp e <*> mapM findUpAlt as findUp t = return t findUpAlt (LConCase i t args rhs) = do avail <- get rhs' <- findUp rhs put avail return $ LConCase i t args rhs' findUpAlt (LConstCase i rhs) = LConstCase i <$> findUp rhs findUpAlt (LDefaultCase rhs) = LDefaultCase <$> findUp rhs doUpAlt n (LConCase i t args rhs) = do avail <- get put ((n, length args) : avail) rhs' <- findUp rhs put avail return $ LConCase i t args rhs' doUpAlt n (LConstCase i rhs) = LConstCase i <$> findUp rhs doUpAlt n (LDefaultCase rhs) = LDefaultCase <$> findUp rhs findVar _ [] i = return Nothing findVar acc ((n, l) : ns) i | l == i = do put (reverse acc ++ ns) return (Just (Glob n)) findVar acc (n : ns) i = findVar (n : acc) ns i -- Return variables in list which are used in the expression usedArg env n | n `elem` env = [n] | otherwise = [] usedIn :: [Name] -> LExp -> [Name] usedIn env (LV (Glob n)) = usedArg env n usedIn env (LApp _ e args) = usedIn env e ++ concatMap (usedIn env) args usedIn env (LLazyApp n args) = concatMap (usedIn env) args ++ usedArg env n usedIn env (LLazyExp e) = usedIn env e usedIn env (LForce e) = usedIn env e usedIn env (LLet n v e) = usedIn env v ++ usedIn (env \\ [n]) e usedIn env (LLam ns e) = usedIn (env \\ ns) e usedIn env (LCon v i n args) = let rest = concatMap (usedIn env) args in case v of Nothing -> rest Just (Glob n) -> usedArg env n ++ rest usedIn env (LProj t i) = usedIn env t usedIn env (LCase up e alts) = usedIn env e ++ concatMap (usedInA env) alts where usedInA env (LConCase i n ns e) = usedIn env e usedInA env (LConstCase c e) = usedIn env e usedInA env (LDefaultCase e) = usedIn env e usedIn env (LForeign _ _ args) = concatMap (usedIn env) (map snd args) usedIn env (LOp f args) = concatMap (usedIn env) args usedIn env _ = [] instance Show LExp where show e = show' [] "" e where show' env ind (LV (Loc i)) = env!!i show' env ind (LV (Glob n)) = show n show' env ind (LLazyApp e args) = show e ++ "|(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LApp _ e args) = show' env ind e ++ "(" ++ showSep ", " (map (show' env ind) args) ++")" show' env ind (LLazyExp e) = "lazy{ " ++ show' env ind e ++ " }" show' env ind (LForce e) = "force{ " ++ show' env ind e ++ " }" show' env ind (LLet n v e) = "let " ++ show n ++ " = " ++ show' env ind v ++ " in " ++ show' (env ++ [show n]) ind e show' env ind (LLam args e) = "\\ " ++ showSep "," (map show args) ++ " => " ++ show' (env ++ (map show args)) ind e show' env ind (LProj t i) = show t ++ "!" ++ show i show' env ind (LCon loc i n args) = atloc loc ++ show n ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" where atloc Nothing = "" atloc (Just l) = "@" ++ show (LV l) ++ ":" show' env ind (LCase up e alts) = "case" ++ update ++ show' env ind e ++ " of \n" ++ fmt alts where update = case up of Shared -> " " Updatable -> "! " fmt [] = "" fmt [alt] = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ " ") alt fmt (alt:as) = "\t" ++ ind ++ "| " ++ showAlt env (ind ++ ". ") alt ++ "\n" ++ fmt as show' env ind (LConst c) = show c show' env ind (LForeign ty n args) = concat [ "foreign{ " , show n ++ "(" , showSep ", " (map (\(ty,x) -> show' env ind x ++ " : " ++ show ty) args) , ") : " , show ty , " }" ] show' env ind (LOp f args) = show f ++ "(" ++ showSep ", " (map (show' env ind) args) ++ ")" show' env ind (LError str) = "error " ++ show str show' env ind LNothing = "____" showAlt env ind (LConCase _ n args e) = show n ++ "(" ++ showSep ", " (map show args) ++ ") => " ++ show' env ind e showAlt env ind (LConstCase c e) = show c ++ " => " ++ show' env ind e showAlt env ind (LDefaultCase e) = "_ => " ++ show' env ind e
osa1/Idris-dev
src/IRTS/Lang.hs
Haskell
bsd-3-clause
14,464
<?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="hi-IN"> <title>Getting started Guide</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
ccgreen13/zap-extensions
src/org/zaproxy/zap/extension/gettingStarted/resources/help_hi_IN/helpset_hi_IN.hs
Haskell
apache-2.0
967
-- Test we don't get a cycle for "phantom" superclasses {-# LANGUAGE ConstraintKinds, MultiParamTypeClasses, FlexibleContexts #-} module TcOK where class A cls c where meth :: cls c => c -> c class A B c => B c where
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/typecheck/should_compile/tc259.hs
Haskell
bsd-3-clause
223
{-# LANGUAGE RecordWildCards #-} module Network.HTTP.Download.VerifiedSpec where import Crypto.Hash import Control.Monad (unless) import Control.Monad.Trans.Reader import Control.Retry (limitRetries) import Data.Maybe import Network.HTTP.Client.Conduit import Network.HTTP.Download.Verified import Path import System.Directory import System.IO.Temp import Test.Hspec hiding (shouldNotBe, shouldNotReturn) -- TODO: share across test files withTempDir :: (Path Abs Dir -> IO a) -> IO a withTempDir f = withSystemTempDirectory "NHD_VerifiedSpec" $ \dirFp -> do dir <- parseAbsDir dirFp f dir -- | An example path to download the exampleReq. getExamplePath :: Path Abs Dir -> IO (Path Abs File) getExamplePath dir = do file <- parseRelFile "cabal-install-1.22.4.0.tar.gz" return (dir </> file) -- | An example DownloadRequest that uses a SHA1 exampleReq :: DownloadRequest exampleReq = fromMaybe (error "exampleReq") $ do req <- parseUrl "http://download.fpcomplete.com/stackage-cli/linux64/cabal-install-1.22.4.0.tar.gz" return DownloadRequest { drRequest = req , drHashChecks = [exampleHashCheck] , drLengthCheck = Just exampleLengthCheck , drRetryPolicy = limitRetries 1 } exampleHashCheck :: HashCheck exampleHashCheck = HashCheck { hashCheckAlgorithm = SHA1 , hashCheckHexDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec2" } exampleLengthCheck :: LengthCheck exampleLengthCheck = 302513 -- | The wrong ContentLength for exampleReq exampleWrongContentLength :: Int exampleWrongContentLength = 302512 -- | The wrong SHA1 digest for exampleReq exampleWrongDigest :: CheckHexDigest exampleWrongDigest = CheckHexDigestString "b98eea96d321cdeed83a201c192dac116e786ec3" exampleWrongContent :: String exampleWrongContent = "example wrong content" isWrongContentLength :: VerifiedDownloadException -> Bool isWrongContentLength WrongContentLength{} = True isWrongContentLength _ = False isWrongDigest :: VerifiedDownloadException -> Bool isWrongDigest WrongDigest{} = True isWrongDigest _ = False data T = T { manager :: Manager } runWith :: Manager -> ReaderT Manager m r -> m r runWith = flip runReaderT setup :: IO T setup = do manager <- newManager return T{..} teardown :: T -> IO () teardown _ = return () shouldNotBe :: (Show a, Eq a) => a -> a -> Expectation actual `shouldNotBe` expected = unless (actual /= expected) (expectationFailure msg) where msg = "Value was exactly what it shouldn't be: " ++ show expected shouldNotReturn :: (Show a, Eq a) => IO a -> a -> Expectation action `shouldNotReturn` unexpected = action >>= (`shouldNotBe` unexpected) spec :: Spec spec = beforeAll setup $ afterAll teardown $ do let exampleProgressHook _ = return () describe "verifiedDownload" $ do -- Preconditions: -- * the exampleReq server is running -- * the test runner has working internet access to it it "downloads the file correctly" $ \T{..} -> withTempDir $ \dir -> do examplePath <- getExamplePath dir let exampleFilePath = toFilePath examplePath doesFileExist exampleFilePath `shouldReturn` False let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook go `shouldReturn` True doesFileExist exampleFilePath `shouldReturn` True it "is idempotent, and doesn't redownload unnecessarily" $ \T{..} -> withTempDir $ \dir -> do examplePath <- getExamplePath dir let exampleFilePath = toFilePath examplePath doesFileExist exampleFilePath `shouldReturn` False let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook go `shouldReturn` True doesFileExist exampleFilePath `shouldReturn` True go `shouldReturn` False doesFileExist exampleFilePath `shouldReturn` True -- https://github.com/commercialhaskell/stack/issues/372 it "does redownload when the destination file is wrong" $ \T{..} -> withTempDir $ \dir -> do examplePath <- getExamplePath dir let exampleFilePath = toFilePath examplePath writeFile exampleFilePath exampleWrongContent doesFileExist exampleFilePath `shouldReturn` True readFile exampleFilePath `shouldReturn` exampleWrongContent let go = runWith manager $ verifiedDownload exampleReq examplePath exampleProgressHook go `shouldReturn` True doesFileExist exampleFilePath `shouldReturn` True readFile exampleFilePath `shouldNotReturn` exampleWrongContent it "rejects incorrect content length" $ \T{..} -> withTempDir $ \dir -> do examplePath <- getExamplePath dir let exampleFilePath = toFilePath examplePath let wrongContentLengthReq = exampleReq { drLengthCheck = Just exampleWrongContentLength } let go = runWith manager $ verifiedDownload wrongContentLengthReq examplePath exampleProgressHook go `shouldThrow` isWrongContentLength doesFileExist exampleFilePath `shouldReturn` False it "rejects incorrect digest" $ \T{..} -> withTempDir $ \dir -> do examplePath <- getExamplePath dir let exampleFilePath = toFilePath examplePath let wrongHashCheck = exampleHashCheck { hashCheckHexDigest = exampleWrongDigest } let wrongDigestReq = exampleReq { drHashChecks = [wrongHashCheck] } let go = runWith manager $ verifiedDownload wrongDigestReq examplePath exampleProgressHook go `shouldThrow` isWrongDigest doesFileExist exampleFilePath `shouldReturn` False -- https://github.com/commercialhaskell/stack/issues/240 it "can download hackage tarballs" $ \T{..} -> withTempDir $ \dir -> do dest <- fmap (dir </>) $ parseRelFile "acme-missiles-0.3.tar.gz" let destFp = toFilePath dest req <- parseUrl "http://hackage.haskell.org/package/acme-missiles-0.3/acme-missiles-0.3.tar.gz" let dReq = DownloadRequest { drRequest = req , drHashChecks = [] , drLengthCheck = Nothing , drRetryPolicy = limitRetries 1 } let go = runWith manager $ verifiedDownload dReq dest exampleProgressHook doesFileExist destFp `shouldReturn` False go `shouldReturn` True doesFileExist destFp `shouldReturn` True
akhileshs/stack
src/test/Network/HTTP/Download/VerifiedSpec.hs
Haskell
bsd-3-clause
6,282
module Main(main) where import System.Random tstRnd rng = checkRange rng (genRnd 50 rng) genRnd n rng = take n (randomRs rng (mkStdGen 2)) checkRange (lo,hi) = all pred where pred | lo <= hi = \ x -> x >= lo && x <= hi | otherwise = \ x -> x >= hi && x <= lo main :: IO () main = do print (tstRnd (1,5::Double)) print (tstRnd (1,5::Int)) print (tstRnd (10,54::Integer)) print (tstRnd ((-6),2::Int)) print (tstRnd (2,(-6)::Int))
danse/ghcjs
test/pkg/base/rand001.hs
Haskell
mit
460
module CodeModel.Core where import CodeModel.Function import CodeModel.Signature data Core = Core String [Function] instance Show Core where show (Core name funs) = "core " ++ name ++ "\n" ++ unlines (map show funs) getFunction :: Core -> String -> Maybe Function getFunction (Core _ fs) s = (\filtered -> if null filtered then Nothing else Just $ head filtered) (filter (\(Function (Signature n _) _) -> n == s) fs)
MarcusVoelker/Recolang
CodeModel/Core.hs
Haskell
mit
423
module Y2018.M05.D08.Exercise where {-- Okay, now that we have the new articles downloaded from the REST endpoint and the ArticleMetaData context from the database, let's do some triage! So, just like with the ArticleMetaData, we have to generalize the Article- TriageInformation type from the specific Package and (Dated)Article types to types that allow us to switch from Pilot(-specific) articles to WPJ, or, in the future, articles of any type, ... or so we hope. Whilst still being useful for solving this problem, too. So, without further ado: --} import Data.Aeson (Value) import Data.Map (Map) import Database.PostgreSQL.Simple -- below imports available via 1HaskellADay git repository import Store.SQL.Connection import Store.SQL.Util.Indexed -- import Y2018.M01.D30.Exercise -- template for our ArticleTriageInformation import Y2018.M04.D02.Exercise -- for Article type import Y2018.M04.D13.Exercise -- for Packet type import Y2018.M05.D04.Exercise -- for articles from the rest endpoint import Y2018.M05.D07.Exercise -- for article context from the database data Triage = NEW | UPDATED | REDUNDANT deriving (Eq, Ord, Show) instance Monoid Triage where mempty = REDUNDANT mappend = undefined -- Triage is the dual of a Semigroupoid: we only care about its unit value -- in logic analyses. data ArticleTriageInformation package block article idx = ATI { pack :: package, art :: (block, article), amd :: Maybe (IxValue (ArticleMetaData idx)) } deriving Show {-- The output from our analysis of the article context from the database (the ArticleMetadata set) and the articles downloaded from the REST endpoint (the ParsedPackage values) is the triaged article set --} type WPJATI = ArticleTriageInformation (Packet Value) Value Article Int type MapTri = Map Triage WPJATI triageArticles :: [IxValue (ArticleMetaData Int)] -> [ParsedPacket] -> MapTri triageArticles amd packets = undefined {-- So, with the above. 1. download the last week's articles from the REST endpoint 2. get the article metadata context from the database 3. triage the downloaded articles. 1. How many new articles are there? 2. How many updated articles are there? 3. How many redundant articles are there? Since the World Policy Journal doesn't publish many articles each day, and a packet has 100 articles, there 'may' be a lot of redundant articles. Do your results bear this out? --}
geophf/1HaskellADay
exercises/HAD/Y2018/M05/D08/Exercise.hs
Haskell
mit
2,432
import Test.Hspec.Attoparsec import Test.Tasty import Test.Tasty.Hspec import Data.Attoparsec.ByteString.Char8 import qualified Data.ByteString.Char8 as C8 import Data.STEP.Parsers main :: IO () main = do specs <- createSpecs let tests = testGroup "Tests" [specs] defaultMain tests createSpecs = testSpec "Parsing" $ parallel $ describe "success cases" $ do it "should parse case1" $ (C8.pack "( 1.45 , 666. ,2. ,6.022E23)") ~> parseStep `shouldParse` (Vector [1.45, 666.0, 2.0, 6.022e23]) it "should parse case2" $ (C8.pack "(1.0,2.0,3.0,4.0)") ~> parseStep `shouldParse` (Vector [1.0, 2.0, 3.0, 4.0])
Newlifer/libstep
test/test.hs
Haskell
mit
659
import Test.Tasty import Test.Tasty.QuickCheck import Coreutils import Data.List (intersperse) main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "Unit tests" [libTests] libTests :: TestTree libTests = testGroup "coreutils" [splitTests] splitTests :: TestTree splitTests = testGroup "split" [ testProperty "removes a" $ \as -> length (as :: String) > 10 ==> notElem ',' . concat . split ',' . intersperse ',' $ as , testProperty "has +1 results from element count" $ \as -> length (as :: String) > 10 ==> let commafied = intersperse ',' as count = length . filter (== ',') $ commafied len = length $ split ',' commafied in len == count + 1 ]
mrak/coreutils.hs
tests/unit/Main.hs
Haskell
mit
768
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as BC import Data.Foldable (traverse_) input :: ByteString input = "10001001100000001" bitFlip :: Char -> Char bitFlip '0' = '1' bitFlip _ = '0' dragon :: ByteString -> ByteString dragon β = β `BC.append` ('0' `BC.cons` BC.reverse (BC.map bitFlip β)) dragonTest :: Bool dragonTest = all (\(α, β) -> dragon α == β) [ ("1" , "100") , ("0" , "001") , ("11111" , "11111000000") , ("111100001010", "1111000010100101011110000") ] checkStep :: ByteString -> ByteString checkStep β = go β "" where {-# INLINABLE go #-} go :: ByteString -> ByteString -> ByteString go α ω | BC.null α = ω | otherwise = go α' ω' where γ = α `BC.index` 0 δ = α `BC.index` 1 ϵ = if γ == δ then '1' else '0' α' = BC.drop 2 α ω' = ω `BC.snoc` ϵ checkStepTest :: Bool checkStepTest = all (\(α, β) -> checkStep α == β) [("110010110100", "110101"), ("110101", "100")] shrink :: ByteString -> ByteString shrink β | odd $ BC.length β = β | otherwise = shrink $ checkStep β expand :: Int -> ByteString -> ByteString expand λ β | BC.length β >= λ = β | otherwise = expand λ $ dragon β checkSum :: Int -> ByteString -> ByteString checkSum λ = shrink . BC.take λ . expand λ main :: IO () main = do traverse_ print [dragonTest, checkStepTest] traverse_ (BC.putStrLn . (`checkSum` input)) [272, 35651584]
genos/online_problems
advent_of_code_2016/day16/hask/src/Main.hs
Haskell
mit
1,652
----------------------------------------------------------------------------- -- -- Module : Language.PureScript.CoreFn.Ann -- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors -- License : MIT -- -- Maintainer : Phil Freeman <paf31@cantab.net>, Gary Burgess <gary.burgess@gmail.com> -- Stability : experimental -- Portability : -- -- | Type alias for basic annotations -- ----------------------------------------------------------------------------- module Language.PureScript.CoreFn.Ann where import Language.PureScript.AST.SourcePos import Language.PureScript.CoreFn.Meta import Language.PureScript.Types import Language.PureScript.Comments -- | -- Type alias for basic annotations -- type Ann = (Maybe SourceSpan, [Comment], Maybe Type, Maybe Meta) -- | -- Initial annotation with no metadata -- nullAnn :: Ann nullAnn = (Nothing, [], Nothing, Nothing) -- | -- Remove the comments from an annotation -- removeComments :: Ann -> Ann removeComments (ss, _, ty, meta) = (ss, [], ty, meta)
michaelficarra/purescript
src/Language/PureScript/CoreFn/Ann.hs
Haskell
mit
1,048
import Data.List combinations :: Int -> [a] -> [[a]] combinations 0 _ = [ [] ] combinations n xs = [ y:ys | y:xs' <- tails xs , ys <- combinations (n-1) xs']
curiousily/haskell-99problems
26.hs
Haskell
mit
187
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveGeneric #-} module Codec.Xlsx.Types.Internal.CommentTable where import Data.ByteString.Lazy (ByteString) import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Lazy.Char8 as LBC8 import Data.List.Extra (nubOrd) import Data.Map (Map) import qualified Data.Map as M import Data.Text (Text) import Data.Text.Lazy (toStrict) import qualified Data.Text.Lazy.Builder as B import qualified Data.Text.Lazy.Builder.Int as B import GHC.Generics (Generic) import Safe import Text.XML import Text.XML.Cursor import Codec.Xlsx.Parser.Internal import Codec.Xlsx.Types.Comment import Codec.Xlsx.Types.Common import Codec.Xlsx.Writer.Internal newtype CommentTable = CommentTable { _commentsTable :: Map CellRef Comment } deriving (Eq, Show, Generic) fromList :: [(CellRef, Comment)] -> CommentTable fromList = CommentTable . M.fromList toList :: CommentTable -> [(CellRef, Comment)] toList = M.toList . _commentsTable lookupComment :: CellRef -> CommentTable -> Maybe Comment lookupComment ref = M.lookup ref . _commentsTable instance ToDocument CommentTable where toDocument = documentFromElement "Sheet comments generated by xlsx" . toElement "comments" instance ToElement CommentTable where toElement nm (CommentTable m) = Element { elementName = nm , elementAttributes = M.empty , elementNodes = [ NodeElement $ elementListSimple "authors" authorNodes , NodeElement . elementListSimple "commentList" $ map commentToEl (M.toList m) ] } where commentToEl (ref, Comment{..}) = Element { elementName = "comment" , elementAttributes = M.fromList [ ("ref" .= ref) , ("authorId" .= lookupAuthor _commentAuthor)] , elementNodes = [NodeElement $ toElement "text" _commentText] } lookupAuthor a = fromJustNote "author lookup" $ M.lookup a authorIds authorNames = nubOrd . map _commentAuthor $ M.elems m decimalToText :: Integer -> Text decimalToText = toStrict . B.toLazyText . B.decimal authorIds = M.fromList $ zip authorNames (map decimalToText [0..]) authorNodes = map (elementContent "author") authorNames instance FromCursor CommentTable where fromCursor cur = do let authorNames = cur $/ element (n_ "authors") &/ element (n_ "author") >=> contentOrEmpty authors = M.fromList $ zip [0..] authorNames items = cur $/ element (n_ "commentList") &/ element (n_ "comment") >=> parseComment authors return . CommentTable $ M.fromList items parseComment :: Map Int Text -> Cursor -> [(CellRef, Comment)] parseComment authors cur = do ref <- fromAttribute "ref" cur txt <- cur $/ element (n_ "text") >=> fromCursor authorId <- cur $| attribute "authorId" >=> decimal let author = fromJustNote "authorId" $ M.lookup authorId authors return (ref, Comment txt author True) -- | helper to render comment baloons vml file, -- currently uses fixed shape renderShapes :: CommentTable -> ByteString renderShapes (CommentTable m) = LB.concat [ "<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" " , "xmlns:o=\"urn:schemas-microsoft-com:office:office\" " , "xmlns:x=\"urn:schemas-microsoft-com:office:excel\">" , commentShapeType , LB.concat commentShapes , "</xml>" ] where commentShapeType = LB.concat [ "<v:shapetype id=\"baloon\" coordsize=\"21600,21600\" o:spt=\"202\" " , "path=\"m,l,21600r21600,l21600,xe\">" , "<v:stroke joinstyle=\"miter\"></v:stroke>" , "<v:path gradientshapeok=\"t\" o:connecttype=\"rect\"></v:path>" , "</v:shapetype>" ] fromRef = fromJustNote "Invalid comment ref" . fromSingleCellRef commentShapes = [ commentShape (fromRef ref) (_commentVisible cmnt) | (ref, cmnt) <- M.toList m ] commentShape (r, c) v = LB.concat [ "<v:shape type=\"#baloon\" " , "style=\"position:absolute;width:auto" -- ;width:108pt;height:59.25pt" , if v then "" else ";visibility:hidden" , "\" fillcolor=\"#ffffe1\" o:insetmode=\"auto\">" , "<v:fill color2=\"#ffffe1\"></v:fill><v:shadow color=\"black\" obscured=\"t\"></v:shadow>" , "<v:path o:connecttype=\"none\"></v:path><v:textbox style=\"mso-direction-alt:auto\">" , "<div style=\"text-align:left\"></div></v:textbox>" , "<x:ClientData ObjectType=\"Note\">" , "<x:MoveWithCells></x:MoveWithCells><x:SizeWithCells></x:SizeWithCells>" , "<x:Anchor>4, 15, 0, 7, 6, 31, 5, 1</x:Anchor><x:AutoFill>False</x:AutoFill>" , "<x:Row>" , LBC8.pack $ show (r - 1) , "</x:Row>" , "<x:Column>" , LBC8.pack $ show (c - 1) , "</x:Column>" , "</x:ClientData>" , "</v:shape>" ]
qrilka/xlsx
src/Codec/Xlsx/Types/Internal/CommentTable.hs
Haskell
mit
4,940
-- | Biegunka - configuration development library module Control.Biegunka ( -- * Interpreters control biegunka, Settings, defaultSettings, runRoot, biegunkaRoot , Templates(..), templates -- * Interpreters , Interpreter , pause, confirm, changes, run, check -- * Types , Script, Scope(..) -- * Actions layer primitives , link, register, copy, unE, substitute, raw -- * Script environment , sourceRoot -- * Modifiers , namespace , sudo, User(..), username, uid, retries, reacting, React(..), prerequisiteOf, (<~>) -- * Auxiliary , into -- * Commandline options parser autogeneration , runner_, runnerOf, Environments(..), Generic -- * Quasiquoters , multiline, sh, shell -- * Settings -- ** Mode , mode, Mode(..) -- * Little helpers , (~>) , pass ) where import GHC.Generics (Generic) import System.Directory.Layout (username, uid) import Control.Biegunka.Biegunka (biegunka) import Control.Biegunka.Settings ( Settings, defaultSettings, biegunkaRoot , Templates(..), templates , mode, Mode(..) ) import Control.Biegunka.Execute (run) import Control.Biegunka.Interpreter (Interpreter, pause, confirm, changes) import Control.Biegunka.Language (Scope(..)) import Control.Biegunka.Primitive import Control.Biegunka.Script (runRoot, sourceRoot, Script, User(..), React(..), into) import Control.Biegunka.QQ (multiline, sh, shell) import Control.Biegunka.Options (Environments(..), runnerOf, runner_) import Control.Biegunka.Check (check) infix 4 ~> -- | An alias for '(,)' for better looking pairing (~>) :: a -> b -> (a, b) (~>) = (,) -- | Do nothing. pass :: Applicative m => m () pass = pure ()
biegunka/biegunka
src/Control/Biegunka.hs
Haskell
mit
1,687
module FreePalace.Handlers.Incoming where import Control.Concurrent import Control.Exception import qualified System.Log.Logger as Log import qualified FreePalace.Domain.Chat as Chat import qualified FreePalace.Domain.GUI as GUI import qualified FreePalace.Domain.State as State import qualified FreePalace.Domain.User as User import qualified FreePalace.Media.Loader as MediaLoader import qualified FreePalace.Messages.Inbound as InboundMessages import qualified FreePalace.Messages.PalaceProtocol.InboundReader as PalaceInbound import qualified FreePalace.Net.PalaceProtocol.Connect as Connect -- TODO Time out if this takes too long, don't keep listening, tell the main thread. -- TODO Make sure exceptions are caught so as not to block the main thread waiting on the MVar initializeMessageDispatcher :: MVar State.Connected -> State.Connected -> IO () initializeMessageDispatcher conveyorOfStateBackToMainThread clientState = do Log.debugM "Incoming.Message.Await" $ "Awaiting initial handshake with state: " ++ (show clientState) header <- readHeader clientState Log.debugM "Incoming.Message.Header" (show header) message <- readMessage clientState header newState <- case message of InboundMessages.HandshakeMessage _ -> handleInboundEvent clientState message _ -> throwIO $ userError "Connection failed. No handshake." Log.debugM "Incoming.Message.Processed" $ "Message processed. New state: " ++ (show newState) putMVar conveyorOfStateBackToMainThread newState dispatchIncomingMessages newState -- TODO Handle connection loss dispatchIncomingMessages :: State.Connected -> IO () dispatchIncomingMessages clientState = do Log.debugM "Incoming.Message.Await" $ "Awaiting messages with state: " ++ (show clientState) header <- readHeader clientState Log.debugM "Incoming.Message.Header" (show header) message <- readMessage clientState header newState <- handleInboundEvent clientState message Log.debugM "Incoming.Message.Processed" $ "Message processed. New state: " ++ (show newState) dispatchIncomingMessages newState readHeader :: State.Connected -> IO InboundMessages.Header readHeader clientState = case State.protocolState clientState of State.PalaceProtocolState connection messageConverters -> PalaceInbound.readHeader connection messageConverters readMessage :: State.Connected -> InboundMessages.Header -> IO InboundMessages.InboundMessage readMessage clientState header = case State.protocolState clientState of State.PalaceProtocolState connection messageConverters -> PalaceInbound.readMessage connection messageConverters header -- TODO Right now these need to be in IO because of logging and GUI changes. Separate those out. handleInboundEvent :: State.Connected -> InboundMessages.InboundMessage -> IO State.Connected handleInboundEvent clientState (InboundMessages.HandshakeMessage handshakeData) = handleHandshake clientState handshakeData handleInboundEvent clientState (InboundMessages.LogonReplyMessage logonReply) = handleLogonReply clientState logonReply handleInboundEvent clientState (InboundMessages.ServerVersionMessage serverVersion) = handleServerVersion clientState serverVersion handleInboundEvent clientState (InboundMessages.ServerInfoMessage serverInfo) = handleServerInfo clientState serverInfo handleInboundEvent clientState (InboundMessages.UserStatusMessage userStatus) = handleUserStatus clientState userStatus handleInboundEvent clientState (InboundMessages.UserLogonMessage userLogonNotification) = handleUserLogonNotification clientState userLogonNotification handleInboundEvent clientState (InboundMessages.MediaServerMessage mediaServerInfo) = handleMediaServerInfo clientState mediaServerInfo handleInboundEvent clientState (InboundMessages.RoomDescriptionMessage roomDescription) = handleRoomDescription clientState roomDescription handleInboundEvent clientState (InboundMessages.UserListMessage userListing) = handleUserList clientState userListing handleInboundEvent clientState (InboundMessages.UserEnteredRoomMessage userEnteredRoom) = handleUserEnteredRoom clientState userEnteredRoom handleInboundEvent clientState (InboundMessages.UserExitedRoomMessage userExitedRoom) = handleUserExitedRoom clientState userExitedRoom handleInboundEvent clientState (InboundMessages.UserDisconnectedMessage userDisconnected) = handleUserDisconnected clientState userDisconnected handleInboundEvent clientState (InboundMessages.ChatMessage chat) = handleChat clientState chat handleInboundEvent clientState (InboundMessages.MovementMessage movementNotification) = handleMovement clientState movementNotification handleInboundEvent clientState (InboundMessages.NoOpMessage noOp) = handleNoOp clientState noOp handleHandshake :: State.Connected -> InboundMessages.Handshake -> IO State.Connected handleHandshake clientState handshake = do Log.debugM "Incoming.Handshake" (show handshake) let newState = handleProtocolUpdate clientState (InboundMessages.protocolInfo handshake) userRefId = InboundMessages.userRefId handshake return $ State.withUserRefId newState userRefId -- This is separate because it depends on the specific protocol handleProtocolUpdate :: State.Connected -> InboundMessages.ProtocolInfo -> State.Connected handleProtocolUpdate clientState (InboundMessages.PalaceProtocol connection endianness) = State.withProtocol clientState (State.PalaceProtocolState connection newMessageConverters) where newMessageConverters = Connect.messageConvertersFor endianness {- Re AlternateLogonReply: OpenPalace comments say: This is only sent when the server is running in "guests-are-members" mode. This is pointless... it's basically echoing back the logon packet that we sent to the server. The only reason we support this is so that certain silly servers can change our puid and ask us to reconnect "for security reasons." -} handleLogonReply :: State.Connected -> InboundMessages.LogonReply -> IO State.Connected handleLogonReply clientState logonReply = do Log.debugM "Incoming.Message.LogonReply" (show logonReply) return clientState -- TODO return puidCrc and puidCounter when we need it handleServerVersion :: State.Connected -> InboundMessages.ServerVersion -> IO State.Connected handleServerVersion clientState serverVersion = do Log.debugM "Incoming.Message.ServerVersion" $ "Server version: " ++ (show serverVersion) return clientState -- TODO Add server version to host state handleServerInfo :: State.Connected -> InboundMessages.ServerInfoNotification -> IO State.Connected handleServerInfo clientState serverInfo = do Log.debugM "Incoming.Message.ServerInfo" $ "Server info: " ++ (show serverInfo) return clientState handleUserStatus :: State.Connected -> InboundMessages.UserStatusNotification -> IO State.Connected handleUserStatus clientState userStatus = do Log.debugM "Incoming.Message.UserStatus" $ "User status -- User flags: " ++ (show userStatus) return clientState -- A user connects to this host handleUserLogonNotification :: State.Connected -> InboundMessages.UserLogonNotification -> IO State.Connected handleUserLogonNotification clientState logonNotification = do Log.debugM "Incoming.Message.UserLogonNotification" $ (show logonNotification) return clientState {- OpenPalace does: Adds the user ID to recentLogonUserIds; sets a timer to remove it in 15 seconds. This is for the Ping sound managed by the NewUserNotification. -} handleMediaServerInfo :: State.Connected -> InboundMessages.MediaServerInfo -> IO State.Connected handleMediaServerInfo clientState serverInfo = do Log.debugM "Incoming.Message.MediaServerInfo" $ show serverInfo let newState = State.withMediaServerInfo clientState serverInfo _ <- loadRoomBackgroundImage newState Log.debugM "Incoming.Message.MediaServerInfo.Processed" $ "New state: " ++ (show newState) return newState -- room name, background image, overlay images, props, hotspots, draw commands handleRoomDescription :: State.Connected -> InboundMessages.RoomDescription -> IO State.Connected handleRoomDescription clientState roomDescription = do Log.debugM "Incoming.Message.RoomDescription" $ show roomDescription let newState = State.withRoomDescription clientState roomDescription _ <- loadRoomBackgroundImage newState Log.debugM "Incoming.Message.RoomDescription.Processed" $ "New state: " ++ (show newState) return newState {- OpenPalace also does this when receiving these messages: clearStatusMessage currentRoom clearAlarms midiStop and after parsing the information: Dim room 100 Room.showAvatars = true -- scripting can hide all avatars Dispatch room change event for scripting -} -- List of users in the current room handleUserList :: State.Connected -> InboundMessages.UserListing -> IO State.Connected handleUserList clientState userList = do Log.debugM "Incoming.Message.UserList" $ show userList let newState = State.withRoomUsers clientState userList return newState {- OpenPalace - after creating each user: user.loadProps() -} handleUserEnteredRoom :: State.Connected -> InboundMessages.UserEnteredRoom -> IO State.Connected handleUserEnteredRoom clientState userNotification = do let newState = State.withRoomUsers clientState $ InboundMessages.UserListing [userNotification] gui = State.guiState clientState userWhoArrived = InboundMessages.userId userNotification message = (User.userName $ State.userIdFor newState userWhoArrived) ++ " entered the room." Log.debugM "Incoming.Message.NewUser" $ show userNotification GUI.appendMessage (GUI.logWindow gui) $ Chat.makeRoomAnnouncement message return newState {- OpenPalace does: Looks for this user in recentLogonIds (set in UserLogonNotification) - to see if the user has entered the palace within the last 15 sec. If so, remove it from the recentLogonIds and play the connection Ping: PalaceSoundPlayer.getInstance().playConnectionPing(); If someone else entered and they were selected in the user list, they are selected (for whisper) in the room too. And if one's self entered: if (needToRunSignonHandlers) { -- This flag is set to true when you first log on requestRoomList(); requestUserList(); palaceController.triggerHotspotEvents(IptEventHandler.TYPE_SIGNON); needToRunSignonHandlers = false; } palaceController.triggerHotspotEvents(IptEventHandler.TYPE_ENTER); -} handleUserExitedRoom :: State.Connected -> InboundMessages.UserExitedRoom -> IO State.Connected handleUserExitedRoom clientState exitNotification@(InboundMessages.UserExitedRoom userWhoLeft) = do let message = (User.userName $ State.userIdFor clientState userWhoLeft) ++ " left the room." gui = State.guiState clientState newState = State.withUserLeavingRoom clientState userWhoLeft Log.debugM "Incoming.Message.NewUser" $ show exitNotification GUI.appendMessage (GUI.logWindow gui) $ Chat.makeRoomAnnouncement message return newState handleUserDisconnected :: State.Connected -> InboundMessages.UserDisconnected -> IO State.Connected handleUserDisconnected clientState disconnectedNotification@(InboundMessages.UserDisconnected userWhoLeft population) = do let newState = State.withUserDisconnecting clientState userWhoLeft population Log.debugM "Incoming.Message.NewUser" $ show disconnectedNotification return newState {- OpenPalace does: If user is in the room, PalaceSoundPlayer.getInstance().playConnectionPing() If that user was the selected user for whisper (in the room or not), unset the selected user -} handleChat :: State.Connected -> InboundMessages.Chat -> IO State.Connected handleChat clientState chatData = do let gui = State.guiState clientState communication = State.communicationFromChatData clientState chatData Log.debugM "Incoming.Message.Chat" $ show communication GUI.appendMessage (GUI.logWindow gui) communication -- TODO send talk and user (and message type) to chat balloon in GUI -- TODO send talk to script event handler when there is scripting -- TODO new state with chat log and fix below let newState = clientState return newState handleMovement :: State.Connected -> InboundMessages.MovementNotification -> IO State.Connected handleMovement clientState movementData = do Log.debugM "Incoming.Message.Movement" $ show movementData let (_, newState) = State.withMovementData clientState movementData -- TODO tell the GUI to move the user (in Handler.hs) -- TODO send action to script event handler when there is scripting? return newState handleNoOp :: State.Connected -> InboundMessages.NoOp -> IO State.Connected handleNoOp clientState noOp = do Log.debugM "Incoming.Message.NoOp" $ show noOp return clientState -- TODO Do we want to reload this every time a new room description gets sent? How often does that happen? -- TODO This should happen on a separate thread. loadRoomBackgroundImage :: State.Connected -> IO State.Connected loadRoomBackgroundImage state = do let possibleMediaServer = State.mediaServer $ State.hostState state possibleImageName = State.roomBackgroundImageName . State.currentRoomState . State.hostState $ state roomCanvas = GUI.roomCanvas $ State.guiState state Log.debugM "Load.BackgroundImage" $ "Media server url: " ++ (show possibleMediaServer) Log.debugM "Load.BackgroundImage" $ "Background image: " ++ (show possibleImageName) case (possibleMediaServer, possibleImageName) of (Just mediaServerUrl, Just imageName) -> do let host = State.hostname $ State.hostState state port = State.portId $ State.hostState state Log.debugM "Load.BackgroundImage" $ "Fetching background image " ++ imageName ++ " from " ++ (show mediaServerUrl) possibleImagePath <- MediaLoader.fetchCachedBackgroundImagePath host port mediaServerUrl imageName case possibleImagePath of Just imagePath -> GUI.displayBackground roomCanvas imagePath Nothing -> return () return state (_, _) -> return state
psfblair/freepalace
src/FreePalace/Handlers/Incoming.hs
Haskell
apache-2.0
14,645
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-} module FreezePredicateParserSpec where import Bio.Motions.Types import Bio.Motions.Representation.Common import Bio.Motions.Utils.FreezePredicateParser import GHC.Exts import Data.Either import Text.Parsec import Test.Hspec import Test.Hspec.SmallCheck run :: String -> Either ParseError FreezePredicate run = parse freezePredicateParser "<test>" makeBeadSignature :: Int -> Int -> BeadSignature makeBeadSignature chain indexOnChain = BeadSignature { _beadEV = fromList [] , _beadAtomIndex = -1 , _beadChain = chain , _beadIndexOnChain = indexOnChain } prop :: String -> String -> (Int -> Int -> Bool) -> Spec prop description (run -> Right parsed) predicate = it description . property $ \(chain, index) -> parsed (makeBeadSignature chain index) == predicate chain index {-# ANN correctSpec "HLint: ignore Use ||" #-} correctSpec :: Spec correctSpec = do context "when parsing an empty file" $ prop "freezes nothing" "" $ \_ _ -> False context "when parsing a single chain" $ prop "freezes only this chain" "4" $ \chain _ -> chain == 4 context "when parsing a chain range" $ prop "freezes only those chains" "4-8" $ \chain _ -> chain `elem` [4..8] context "when parsing a bead range on a single chain" $ prop "freezes only those beads" "1:2-10" $ \chain index -> chain == 1 && index `elem` [2..10] context "when parsing a bead range on multiple chains" $ prop "freezes only those beads" "1-2:3-8" $ \chain index -> chain `elem` [1..2] && index `elem` [3..8] context "when parsing a wildcard range" $ prop "freezes only those beads" "*:2-9" $ \_ index -> index `elem` [2..9] context "when parsing a negation of a chain" $ prop "freezes everything except for this chain" "!3" $ \chain _ -> chain /= 3 context "when parsing an alternative of chains" $ prop "freezes only those chains" "1,3,9" $ \chain _ -> chain `elem` [1, 3, 9] context "when parsing a nested expression" $ prop "freezes only those chains" "!(1,7)" $ \chain _ -> chain `notElem` [1, 7] context "when parsing a complex alternative" $ prop "freezes only those chains" "1,2,3-5:4,9:6-8" $ \chain index -> or [ chain `elem` [1, 2] , chain `elem` [3..5] && index == 4 , chain == 9 && index `elem` [6..8] ] incorrectSpec :: Spec incorrectSpec = do context "when parsing a non-integer" $ it "fails" $ isLeft (run "helloworld") `shouldBe` True context "when parsing an unterminated range" $ it "fails" $ isLeft (run "1-") `shouldBe` True spec :: Spec spec = describe "the FreezePredicate parser" $ do context "when parsing correct ranges" correctSpec context "when parsing incorrect ranges" incorrectSpec
Motions/motions
test/FreezePredicateParserSpec.hs
Haskell
apache-2.0
3,060
-- "Treealize" expression terms module OperationExtension2 where import Data.Tree import DataBase import DataExtension class ToTree x where toTree :: x -> Tree String instance ToTree Lit where toTree (Lit i) = Node "Lit" [] instance (Exp x, Exp y, ToTree x, ToTree y) => ToTree (Add x y) where toTree (Add x y) = Node "Add" [toTree x, toTree y] instance (Exp x, ToTree x) => ToTree (Neg x) where toTree (Neg x) = Node "Neg" [toTree x]
egaburov/funstuff
Haskell/tytag/xproblem_src/samples/expressions/Haskell/OpenDatatype1/OperationExtension2.hs
Haskell
apache-2.0
454
------------------------------------------------------------------------------ -- Copyright 2012 Microsoft Corporation. -- -- This is free software; you can redistribute it and/or modify it under the -- terms of the Apache License, Version 2.0. A copy of the License can be -- found in the file "license.txt" at the root of this distribution. ----------------------------------------------------------------------------- {- Map constructor names to constructor info. -} ----------------------------------------------------------------------------- module Kind.Constructors( -- * Constructors Constructors, ConInfo(..) , constructorsEmpty , constructorsExtend, constructorsLookup, constructorsFind , constructorsIsEmpty , constructorsFindScheme , constructorsSet , constructorsCompose, constructorsFromList , extractConstructors -- * Pretty , ppConstructors ) where import qualified Data.List as L import qualified Common.NameMap as M import qualified Common.NameSet as S import Lib.PPrint import Common.Failure( failure ) import Common.Name import Common.Syntax ( Visibility(..)) import Kind.Pretty ( kindColon ) import Type.Type import Type.Pretty import qualified Core.Core as Core {-------------------------------------------------------------------------- Newtype map --------------------------------------------------------------------------} -- | Constructors: a map from newtype names to newtype information newtype Constructors = Constructors (M.NameMap ConInfo) constructorsEmpty :: Constructors constructorsEmpty = Constructors M.empty constructorsIsEmpty :: Constructors -> Bool constructorsIsEmpty (Constructors m) = M.null m constructorsExtend :: Name -> ConInfo -> Constructors -> Constructors constructorsExtend name conInfo (Constructors m) = Constructors (M.insert name conInfo m) constructorsFromList :: [ConInfo] -> Constructors constructorsFromList conInfos = Constructors (M.fromList [(conInfoName info, info) | info <- conInfos]) constructorsCompose :: Constructors -> Constructors -> Constructors constructorsCompose (Constructors cons1) (Constructors cons2) = Constructors (M.union cons2 cons1) -- ASSUME: left-biased union constructorsLookup :: Name -> Constructors -> Maybe ConInfo constructorsLookup name (Constructors m) = M.lookup name m constructorsFind :: Name -> Constructors -> ConInfo constructorsFind name syn = case constructorsLookup name syn of Nothing -> failure ("Kind.Constructors.constructorsFind: unknown constructor: " ++ show name) Just x -> x constructorsFindScheme :: Name -> Constructors -> Scheme constructorsFindScheme conname cons = conInfoType (constructorsFind conname cons) constructorsSet :: Constructors -> S.NameSet constructorsSet (Constructors m) = S.fromList (M.keys m) {-------------------------------------------------------------------------- Pretty printing --------------------------------------------------------------------------} instance Show Constructors where show = show . pretty instance Pretty Constructors where pretty syns = ppConstructors Type.Pretty.defaultEnv syns ppConstructors showOptions (Constructors m) = vcat [fill 8 (pretty name) <> kindColon (colors showOptions) <+> ppType showOptions (conInfoType conInfo) | (name,conInfo) <- L.sortBy (\(n1,_) (n2,_) -> compare (show n1) (show n2)) $ M.toList m] -- | Extract constructor environment from core extractConstructors :: Bool -> Core.Core -> Constructors extractConstructors publicOnly core = Constructors (M.unions (L.map (extractTypeDefGroup isVisible) (Core.coreProgTypeDefs core))) where isVisible Public = True isVisible _ = not publicOnly extractTypeDefGroup isVisible (Core.TypeDefGroup tdefs) = M.unions (L.map (extractTypeDef isVisible) tdefs) extractTypeDef :: (Visibility -> Bool) -> Core.TypeDef -> M.NameMap ConInfo extractTypeDef isVisible tdef = case tdef of Core.Data dataInfo vis conViss | isVisible vis -> let conInfos = dataInfoConstrs dataInfo in M.fromList [(conInfoName conInfo,conInfo) | (conInfo,vis) <- zip conInfos conViss, isVisible vis] _ -> M.empty
lpeterse/koka
src/Kind/Constructors.hs
Haskell
apache-2.0
4,461
{-# LANGUAGE OverloadedStrings #-} module Database.HXournal.Store.Config where import Data.Configurator as C import Data.Configurator.Types import Control.Applicative import Control.Concurrent import Control.Monad import System.Environment import System.Directory import System.FilePath data HXournalStoreConfiguration = HXournalStoreConfiguration { hxournalstore_base :: FilePath } deriving (Show) emptyConfigString :: String emptyConfigString = "# hxournal-store configuration\n# base = \"blah\"\n" loadConfigFile :: IO Config loadConfigFile = do homepath <- getEnv "HOME" let dothxournalstore = homepath </> ".hxournal-store" doesFileExist dothxournalstore >>= \b -> when (not b) $ do writeFile dothxournalstore emptyConfigString threadDelay 1000000 config <- load [Required "$(HOME)/.hxournal-store"] return config getHXournalStoreConfiguration :: Config -> IO (Maybe HXournalStoreConfiguration) getHXournalStoreConfiguration c = do mbase <- C.lookup c "base" return (HXournalStoreConfiguration <$> mbase )
wavewave/hxournal-store
lib/Database/HXournal/Store/Config.hs
Haskell
bsd-2-clause
1,079
{-# LANGUAGE PackageImports #-} import Control.Applicative hiding (many) import qualified Data.Attoparsec as P import Data.Attoparsec.Char8 -- as P8 import qualified Data.ByteString.Char8 as B hiding (map) import HEP.Parser.LHEParser import Debug.Trace import qualified Data.Iteratee as Iter import qualified Data.ListLike as LL iter_parseoneevent :: Iter.Iteratee B.ByteString IO (Maybe LHEvent) iter_parseoneevent = Iter.Iteratee step where step = undefined ------------------------------- hline = putStrLn "---------------------------------" main = do hline putStrLn "This is a test of attoparsec parser." hline putStrLn " I am reading test.lhe " bytestr <- B.readFile "test.lhe" let r = parse lheheader bytestr s = case r of Partial _ -> onlyremain (feed r B.empty) Done _ _ -> onlyremain r Fail _ _ _ -> trace "Test failed" $ onlyremain r putStrLn $ show $ B.take 100 s let r' = parse eachevent s s' = case r' of Partial _ -> onlyresult (feed r' B.empty) Done _ _ -> onlyresult r' Fail _ _ _ -> trace "Test failed" $ onlyresult r' putStrLn $ show s' onlyresult (Done _ r) = r onlyremain (Done s _) = s somestring (Fail a _ message ) = (Prelude.take 100 $ show $ B.take 100 a ) ++ " : " ++ message somestring (Done a b ) = (Prelude.take 100 $ show $ B.take 100 a ) ++ " : " ++ (Prelude.take 100 (show b))
wavewave/LHEParser
test/test.hs
Haskell
bsd-2-clause
1,490
import Data.List (nub) main = print $ length $ nub [ a^b | a <- [2 .. 100], b <- [2 .. 100] ]
foreverbell/project-euler-solutions
src/29.hs
Haskell
bsd-3-clause
95
{-# LANGUAGE TypeFamilies, CPP #-} -- | Simple interface for shell scripting-like tasks. module Control.Shell ( -- * Running Shell programs Shell, ExitReason (..) , shell, shell_, exitString -- * Error handling and control flow , (|>), capture, captureStdErr, capture2, capture3, stream, lift , try, orElse, exit , Guard (..), guard, when, unless -- * Environment handling , withEnv, withoutEnv, lookupEnv, getEnv, cmdline -- * Running external commands , MonadIO (..), Env (..) , run, sudo , unsafeLiftIO , absPath, shellEnv, getShellEnv, joinResult, runSh -- * Working with directories , cpdir, pwd, ls, mkdir, rmdir, inDirectory, isDirectory , withHomeDirectory, inHomeDirectory, withAppDirectory, inAppDirectory , forEachFile, forEachFile_, forEachDirectory, forEachDirectory_ -- * Working with files , isFile, rm, mv, cp, input, output , withFile, withBinaryFile, openFile, openBinaryFile -- * Working with temporary files and directories , FileMode (..) , withTempFile, withCustomTempFile , withTempDirectory, withCustomTempDirectory , inTempDirectory, inCustomTempDirectory -- * Working with handles , Handle, IOMode (..), BufferMode (..) , hFlush, hClose, hReady , hGetBuffering, hSetBuffering , getStdIn, getStdOut, getStdErr -- * Text I/O , hPutStr, hPutStrLn, echo, echo_, ask, stdin , hGetLine, hGetContents -- * Terminal text formatting , module Control.Shell.Color -- * ByteString I/O , hGetBytes, hPutBytes, hGetByteLine, hGetByteContents -- * Convenient re-exports , module System.FilePath , module Control.Monad ) where import qualified System.Environment as Env import System.IO.Unsafe import Control.Shell.Base hiding (getEnv, takeEnvLock, releaseEnvLock, setShellEnv) import qualified Control.Shell.Base as CSB import Control.Shell.Handle import Control.Shell.File import Control.Shell.Directory import Control.Shell.Temp import Control.Shell.Control import Control.Shell.Color import Control.Monad hiding (guard, when, unless) import System.FilePath -- | Convert an 'ExitReason' into a 'String'. Successful termination yields -- the empty string, while abnormal termination yields the termination -- error message. If the program terminaged abnormally but without an error -- message - i.e. the error message is empty string - the error message will -- be shown as @"abnormal termination"@. exitString :: ExitReason -> String exitString Success = "" exitString (Failure "") = "abnormal termination" exitString (Failure s) = s -- | Get the complete environment for the current computation. getShellEnv :: Shell Env getShellEnv = CSB.getEnv insert :: Eq k => k -> v -> [(k, v)] -> [(k, v)] insert k' v' (kv@(k, _) : kvs) | k == k' = (k', v') : kvs | otherwise = kv : insert k' v' kvs insert k v _ = [(k, v)] delete :: Eq k => k -> [(k, v)] -> [(k, v)] delete k' (kv@(k, _) : kvs) | k == k' = kvs | otherwise = kv : delete k' kvs delete _ _ = [] -- | The executable's command line arguments. cmdline :: [String] cmdline = unsafePerformIO Env.getArgs -- | Run a computation with the given environment variable set. withEnv :: String -> String -> Shell a -> Shell a withEnv k v m = do e <- CSB.getEnv inEnv (e {envEnvVars = insert k v (envEnvVars e)}) m -- | Run a computation with the given environment variable unset. withoutEnv :: String -> Shell a -> Shell a withoutEnv k m = do e <- CSB.getEnv inEnv (e {envEnvVars = delete k (envEnvVars e)}) m -- | Get the value of an environment variable. Returns Nothing if the variable -- doesn't exist. lookupEnv :: String -> Shell (Maybe String) lookupEnv k = lookup k . envEnvVars <$> CSB.getEnv -- | Get the value of an environment variable. Returns the empty string if -- the variable doesn't exist. getEnv :: String -> Shell String getEnv key = maybe "" id `fmap` lookupEnv key -- | Run a command with elevated privileges. sudo :: FilePath -> [String] -> Shell () sudo cmd as = run "sudo" (cmd:"--":as) -- | Performs a command inside a temporary directory. The directory will be -- cleaned up after the command finishes. inTempDirectory :: Shell a -> Shell a inTempDirectory = withTempDirectory . flip inDirectory -- | Performs a command inside a temporary directory. The directory will be -- cleaned up after the command finishes. inCustomTempDirectory :: FilePath -> Shell a -> Shell a inCustomTempDirectory dir m = withCustomTempDirectory dir $ flip inDirectory m -- | Get the standard input, output and error handle respectively. getStdIn, getStdOut, getStdErr :: Shell Handle getStdIn = envStdIn <$> CSB.getEnv getStdOut = envStdOut <$> CSB.getEnv getStdErr = envStdErr <$> CSB.getEnv
valderman/shellmate
shellmate/Control/Shell.hs
Haskell
bsd-3-clause
4,736
module Network.Kontiki.SerializationSpec where import Data.Binary (Binary, decode, encode) import Network.Kontiki.Raft import Test.Hspec import Test.QuickCheck serializationSpec :: Spec serializationSpec = do describe "Messages" $ do it "Message Int" $ property (prop_serialization :: Message Int -> Bool) it "RequestVote" $ property (prop_serialization :: RequestVote -> Bool) it "RequestVoteResponse" $ property (prop_serialization :: RequestVoteResponse -> Bool) it "AppendEntries Int" $ property (prop_serialization :: AppendEntries Int -> Bool) it "AppendEntriesResponse" $ property (prop_serialization :: AppendEntriesResponse -> Bool) describe "State" $ do it "SomeState" $ property (prop_serialization :: SomeState -> Bool) it "Follower" $ property (prop_serialization :: Follower -> Bool) it "Candidate" $ property (prop_serialization :: Candidate -> Bool) it "Leader" $ property (prop_serialization :: Leader -> Bool) describe "Entry Int" $ do it "Entry Int" $ property (prop_serialization :: Entry Int -> Bool) prop_serialization :: (Eq a, Binary a) => a -> Bool prop_serialization a = decode (encode a) == a
abailly/kontiki
test/Network/Kontiki/SerializationSpec.hs
Haskell
bsd-3-clause
1,225
module Language.GhcHaskell.Parser where import Control.Monad import qualified Language.Haskell.Exts.Parser as P import Language.Haskell.AST.HSE import Language.GhcHaskell.AST parsePat :: String -> ParseResult (Parsed Pat) parsePat = P.parse >=> fromHsePat parseExp :: String -> ParseResult (Parsed Exp) parseExp = P.parse >=> fromHseExp parseType :: String -> ParseResult (Parsed Type) parseType = P.parse >=> fromHseType parseDecl :: String -> ParseResult (Parsed Decl) parseDecl = P.parse >=> fromHseDecl parseModule :: String -> ParseResult (Parsed Module) parseModule = P.parse >=> fromHseModule
jcpetruzza/haskell-ast
src/Language/GhcHaskell/Parser.hs
Haskell
bsd-3-clause
609
{-# LANGUAGE Haskell2010 #-} module Maybe1 where instance Functor Maybe' where fmap f m = m >>= pure . f instance Applicative Maybe' where pure = Just' f1 <*> f2 = f1 >>= \v1 -> f2 >>= (pure . v1) data Maybe' a = Nothing' | Just' a instance Monad Maybe' where return = pure Nothing' >>= _ = Nothing' Just' x >>= f = f x fail _ = Nothing'
hvr/Hs2010To201x
testcases/H2010/Maybe1.expected.hs
Haskell
bsd-3-clause
373
module Main where import ImageFlatten import Data.Maybe import Data.Char import Options.Applicative import System.IO import System.Environment import System.FilePath data Options = Options { input :: String, output :: String, combine :: Bool, remove :: Bool, avg :: Bool, thresh :: Maybe Float, quality :: Maybe Int } deriving (Show) main :: IO () main = do opt <- execParser $ info (helper <*> optParser) description let validated = validateOptions opt case validated of Left e -> hPutStrLn stderr e Right (op, inp, out) -> flatten op inp out description :: InfoMod Options description = fullDesc <> progDesc "Flatten DIRECTORY into OUTPUT" <> header "image-flatten - flatten multiple images into a single image, combining or hiding differences" optParser :: Parser Options optParser = Options <$> strOption (long "input" <> short 'i' <> metavar "DIRECTORY" <> help "A directory containing images to flatten") <*> strOption (long "output" <> short 'o' <> metavar "OUTPUT" <> help "File path to save result image to") <*> switch (long "combine" <> short 'c' <> help "Specifies that differences in images should be combined") <*> switch (long "remove" <> short 'r' <> help "Specifies that differences in images should be removed") <*> switch (long "average" <> short 'a' <> help "Specifies that images should be averaged") <*> optional (option auto (long "threshold" <> short 't' <> help "Adjust the sensitivity for detecting features. A low number is required to detect subtle differences eg a green jumper on grass. A high number will suffice for white stars against a black sky. Default is 10.")) <*> optional (option auto (long "quality" <> short 'q' <> help "If output is a JPEG, this specifies the quality to use when saving")) validateOptions :: Options -> Either String (Operation, InputSource, OutputDestination) validateOptions (Options i o c r a t q) | q' < 0 || q' > 100 = Left "Jpeg quality must be between 0 and 100 inclusive" | not (isPng || isJpg) = Left "Output file must be a .png or .jpg" | length (filter id [c,r,a]) > 1 = Left "Only one of remove (-r), combine (-c) and average (-a) can be specified" | otherwise = Right ( case (c,r,a) of (True,_,_) -> CombineDifferences t' (_,_,True) -> Average _ -> HideDifferences, Directory i, output) where isPng = extension == ".png" isJpg = extension == ".jpg" || extension == ".jpeg" output = if isJpg then JpgFile o q' else PngFile o q' = fromMaybe 100 q extension = map toLower $ takeExtension o t' = fromMaybe 10 t
iansullivan88/image-flatten
app/Main.hs
Haskell
bsd-3-clause
3,056
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, DeriveFunctor, DeriveDataTypeable, TypeSynonymInstances, PatternGuards #-} module Idris.AbsSyntaxTree where import Idris.Core.TT import Idris.Core.Evaluate import Idris.Core.Elaborate hiding (Tactic(..)) import Idris.Core.Typecheck import Idris.Docstrings import IRTS.Lang import IRTS.CodegenCommon import Util.Pretty import Util.DynamicLinker import Idris.Colours import System.Console.Haskeline import System.IO import Prelude hiding ((<$>)) import Control.Applicative ((<|>)) import Control.Monad.Trans.State.Strict import Control.Monad.Trans.Except import qualified Control.Monad.Trans.Class as Trans (lift) import Data.Data (Data) import Data.Function (on) import Data.Generics.Uniplate.Data (universe, children) import Data.List hiding (group) import Data.Char import qualified Data.Map.Strict as M import qualified Data.Text as T import Data.Either import qualified Data.Set as S import Data.Word (Word) import Data.Maybe (fromMaybe, mapMaybe, maybeToList) import Data.Traversable (Traversable) import Data.Typeable import Data.Foldable (Foldable) import Debug.Trace import Text.PrettyPrint.Annotated.Leijen data ElabWhat = ETypes | EDefns | EAll deriving (Show, Eq) -- Data to pass to recursively called elaborators; e.g. for where blocks, -- paramaterised declarations, etc. -- rec_elabDecl is used to pass the top level elaborator into other elaborators, -- so that we can have mutually recursive elaborators in separate modules without -- having to muck about with cyclic modules. data ElabInfo = EInfo { params :: [(Name, PTerm)], inblock :: Ctxt [Name], -- names in the block, and their params liftname :: Name -> Name, namespace :: Maybe [String], elabFC :: Maybe FC, rec_elabDecl :: ElabWhat -> ElabInfo -> PDecl -> Idris () } toplevel :: ElabInfo toplevel = EInfo [] emptyContext id Nothing Nothing (\_ _ _ -> fail "Not implemented") eInfoNames :: ElabInfo -> [Name] eInfoNames info = map fst (params info) ++ M.keys (inblock info) data IOption = IOption { opt_logLevel :: Int, opt_typecase :: Bool, opt_typeintype :: Bool, opt_coverage :: Bool, opt_showimp :: Bool, -- ^^ show implicits opt_errContext :: Bool, opt_repl :: Bool, opt_verbose :: Bool, opt_nobanner :: Bool, opt_quiet :: Bool, opt_codegen :: Codegen, opt_outputTy :: OutputType, opt_ibcsubdir :: FilePath, opt_importdirs :: [FilePath], opt_triple :: String, opt_cpu :: String, opt_cmdline :: [Opt], -- remember whole command line opt_origerr :: Bool, opt_autoSolve :: Bool, -- ^ automatically apply "solve" tactic in prover opt_autoImport :: [FilePath], -- ^ e.g. Builtins+Prelude opt_optimise :: [Optimisation], opt_printdepth :: Maybe Int, opt_evaltypes :: Bool, -- ^ normalise types in :t opt_desugarnats :: Bool } deriving (Show, Eq) defaultOpts = IOption { opt_logLevel = 0 , opt_typecase = False , opt_typeintype = False , opt_coverage = True , opt_showimp = False , opt_errContext = False , opt_repl = True , opt_verbose = True , opt_nobanner = False , opt_quiet = False , opt_codegen = Via "c" , opt_outputTy = Executable , opt_ibcsubdir = "" , opt_importdirs = [] , opt_triple = "" , opt_cpu = "" , opt_cmdline = [] , opt_origerr = False , opt_autoSolve = True , opt_autoImport = [] , opt_optimise = defaultOptimise , opt_printdepth = Just 5000 , opt_evaltypes = True , opt_desugarnats = False } data PPOption = PPOption { ppopt_impl :: Bool -- ^^ whether to show implicits , ppopt_desugarnats :: Bool , ppopt_pinames :: Bool -- ^^ whether to show names in pi bindings , ppopt_depth :: Maybe Int } deriving (Show) data Optimisation = PETransform -- partial eval and associated transforms deriving (Show, Eq) defaultOptimise = [PETransform] -- | Pretty printing options with default verbosity. defaultPPOption :: PPOption defaultPPOption = PPOption { ppopt_impl = False, ppopt_desugarnats = False, ppopt_pinames = False, ppopt_depth = Just 200 } -- | Pretty printing options with the most verbosity. verbosePPOption :: PPOption verbosePPOption = PPOption { ppopt_impl = True, ppopt_desugarnats = True, ppopt_pinames = True, ppopt_depth = Just 200 } -- | Get pretty printing options from the big options record. ppOption :: IOption -> PPOption ppOption opt = PPOption { ppopt_impl = opt_showimp opt, ppopt_pinames = False, ppopt_depth = opt_printdepth opt, ppopt_desugarnats = opt_desugarnats opt } -- | Get pretty printing options from an idris state record. ppOptionIst :: IState -> PPOption ppOptionIst = ppOption . idris_options data LanguageExt = TypeProviders | ErrorReflection deriving (Show, Eq, Read, Ord) -- | The output mode in use data OutputMode = RawOutput Handle -- ^ Print user output directly to the handle | IdeMode Integer Handle -- ^ Send IDE output for some request ID to the handle deriving Show -- | How wide is the console? data ConsoleWidth = InfinitelyWide -- ^ Have pretty-printer assume that lines should not be broken | ColsWide Int -- ^ Manually specified - must be positive | AutomaticWidth -- ^ Attempt to determine width, or 80 otherwise deriving (Show, Eq) -- | The global state used in the Idris monad data IState = IState { tt_ctxt :: Context, -- ^ All the currently defined names and their terms idris_constraints :: S.Set ConstraintFC, -- ^ A list of universe constraints and their corresponding source locations idris_infixes :: [FixDecl], -- ^ Currently defined infix operators idris_implicits :: Ctxt [PArg], idris_statics :: Ctxt [Bool], idris_classes :: Ctxt ClassInfo, idris_records :: Ctxt RecordInfo, idris_dsls :: Ctxt DSL, idris_optimisation :: Ctxt OptInfo, idris_datatypes :: Ctxt TypeInfo, idris_namehints :: Ctxt [Name], idris_patdefs :: Ctxt ([([Name], Term, Term)], [PTerm]), -- not exported -- ^ list of lhs/rhs, and a list of missing clauses idris_flags :: Ctxt [FnOpt], idris_callgraph :: Ctxt CGInfo, -- name, args used in each pos idris_calledgraph :: Ctxt [Name], idris_docstrings :: Ctxt (Docstring DocTerm, [(Name, Docstring DocTerm)]), idris_moduledocs :: Ctxt (Docstring DocTerm), -- ^ module documentation is saved in a special MN so the context -- mechanism can be used for disambiguation idris_tyinfodata :: Ctxt TIData, idris_fninfo :: Ctxt FnInfo, idris_transforms :: Ctxt [(Term, Term)], idris_autohints :: Ctxt [Name], idris_totcheck :: [(FC, Name)], -- names to check totality on idris_defertotcheck :: [(FC, Name)], -- names to check at the end idris_totcheckfail :: [(FC, String)], idris_options :: IOption, idris_name :: Int, idris_lineapps :: [((FilePath, Int), PTerm)], -- ^ Full application LHS on source line idris_metavars :: [(Name, (Maybe Name, Int, [Name], Bool))], -- ^ The currently defined but not proven metavariables. The Int -- is the number of vars to display as a context, the Maybe Name -- is its top-level function, the [Name] is the list of local variables -- available for proof search and the Bool is whether :p is -- allowed idris_coercions :: [Name], idris_errRev :: [(Term, Term)], syntax_rules :: SyntaxRules, syntax_keywords :: [String], imported :: [FilePath], -- ^ The imported modules idris_scprims :: [(Name, (Int, PrimFn))], idris_objs :: [(Codegen, FilePath)], idris_libs :: [(Codegen, String)], idris_cgflags :: [(Codegen, String)], idris_hdrs :: [(Codegen, String)], idris_imported :: [(FilePath, Bool)], -- ^ Imported ibc file names, whether public proof_list :: [(Name, (Bool, [String]))], errSpan :: Maybe FC, parserWarnings :: [(FC, Err)], lastParse :: Maybe Name, indent_stack :: [Int], brace_stack :: [Maybe Int], lastTokenSpan :: Maybe FC, -- ^ What was the span of the latest token parsed? idris_parsedSpan :: Maybe FC, hide_list :: [(Name, Maybe Accessibility)], default_access :: Accessibility, default_total :: Bool, ibc_write :: [IBCWrite], compiled_so :: Maybe String, idris_dynamic_libs :: [DynamicLib], idris_language_extensions :: [LanguageExt], idris_outputmode :: OutputMode, idris_colourRepl :: Bool, idris_colourTheme :: ColourTheme, idris_errorhandlers :: [Name], -- ^ Global error handlers idris_nameIdx :: (Int, Ctxt (Int, Name)), idris_function_errorhandlers :: Ctxt (M.Map Name (S.Set Name)), -- ^ Specific error handlers module_aliases :: M.Map [T.Text] [T.Text], idris_consolewidth :: ConsoleWidth, -- ^ How many chars wide is the console? idris_postulates :: S.Set Name, idris_externs :: S.Set (Name, Int), idris_erasureUsed :: [(Name, Int)], -- ^ Function/constructor name, argument position is used idris_whocalls :: Maybe (M.Map Name [Name]), idris_callswho :: Maybe (M.Map Name [Name]), idris_repl_defs :: [Name], -- ^ List of names that were defined in the repl, and can be re-/un-defined elab_stack :: [(Name, Bool)], -- ^ Stack of names currently being elaborated, Bool set if it's an instance -- (instances appear twice; also as a funtion name) idris_symbols :: M.Map Name Name, -- ^ Symbol table (preserves sharing of names) idris_exports :: [Name], -- ^ Functions with ExportList idris_highlightedRegions :: [(FC, OutputAnnotation)], -- ^ Highlighting information to output idris_parserHighlights :: [(FC, OutputAnnotation)] -- ^ Highlighting information from the parser } -- Required for parsers library, and therefore trifecta instance Show IState where show = const "{internal state}" data SizeChange = Smaller | Same | Bigger | Unknown deriving (Show, Eq) {-! deriving instance Binary SizeChange deriving instance NFData SizeChange !-} type SCGEntry = (Name, [Maybe (Int, SizeChange)]) type UsageReason = (Name, Int) -- fn_name, its_arg_number data CGInfo = CGInfo { argsdef :: [Name], calls :: [(Name, [[Name]])], scg :: [SCGEntry], argsused :: [Name], usedpos :: [(Int, [UsageReason])] } deriving Show {-! deriving instance Binary CGInfo deriving instance NFData CGInfo !-} primDefs = [sUN "unsafePerformPrimIO", sUN "mkLazyForeignPrim", sUN "mkForeignPrim", sUN "void"] -- information that needs writing for the current module's .ibc file data IBCWrite = IBCFix FixDecl | IBCImp Name | IBCStatic Name | IBCClass Name | IBCRecord Name | IBCInstance Bool Bool Name Name | IBCDSL Name | IBCData Name | IBCOpt Name | IBCMetavar Name | IBCSyntax Syntax | IBCKeyword String | IBCImport (Bool, FilePath) -- True = import public | IBCImportDir FilePath | IBCObj Codegen FilePath | IBCLib Codegen String | IBCCGFlag Codegen String | IBCDyLib String | IBCHeader Codegen String | IBCAccess Name Accessibility | IBCMetaInformation Name MetaInformation | IBCTotal Name Totality | IBCFlags Name [FnOpt] | IBCFnInfo Name FnInfo | IBCTrans Name (Term, Term) | IBCErrRev (Term, Term) | IBCCG Name | IBCDoc Name | IBCCoercion Name | IBCDef Name -- i.e. main context | IBCNameHint (Name, Name) | IBCLineApp FilePath Int PTerm | IBCErrorHandler Name | IBCFunctionErrorHandler Name Name Name | IBCPostulate Name | IBCExtern (Name, Int) | IBCTotCheckErr FC String | IBCParsedRegion FC | IBCModDocs Name -- ^ The name is the special name used to track module docs | IBCUsage (Name, Int) | IBCExport Name | IBCAutoHint Name Name deriving Show -- | The initial state for the compiler idrisInit :: IState idrisInit = IState initContext S.empty [] emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext emptyContext [] [] [] defaultOpts 6 [] [] [] [] emptySyntaxRules [] [] [] [] [] [] [] [] [] Nothing [] Nothing [] [] Nothing Nothing [] Hidden False [] Nothing [] [] (RawOutput stdout) True defaultTheme [] (0, emptyContext) emptyContext M.empty AutomaticWidth S.empty S.empty [] Nothing Nothing [] [] M.empty [] [] [] -- | The monad for the main REPL - reading and processing files and updating -- global state (hence the IO inner monad). --type Idris = WriterT [Either String (IO ())] (State IState a)) type Idris = StateT IState (ExceptT Err IO) catchError :: Idris a -> (Err -> Idris a) -> Idris a catchError = liftCatch catchE throwError :: Err -> Idris a throwError = Trans.lift . throwE -- Commands in the REPL data Codegen = Via String -- | ViaC -- | ViaJava -- | ViaNode -- | ViaJavaScript -- | ViaLLVM | Bytecode deriving (Show, Eq) {-! deriving instance NFData Codegen !-} data HowMuchDocs = FullDocs | OverviewDocs -- | REPL commands data Command = Quit | Help | Eval PTerm | NewDefn [PDecl] -- ^ Each 'PDecl' should be either a type declaration (at most one) or a clause defining the same name. | Undefine [Name] | Check PTerm | Core PTerm | DocStr (Either Name Const) HowMuchDocs | TotCheck Name | Reload | Load FilePath (Maybe Int) -- up to maximum line number | ChangeDirectory FilePath | ModImport String | Edit | Compile Codegen String | Execute PTerm | ExecVal PTerm | Metavars | Prove Bool Name -- ^ If false, use prover, if true, use elab shell | AddProof (Maybe Name) | RmProof Name | ShowProof Name | Proofs | Universes | LogLvl Int | Spec PTerm | WHNF PTerm | TestInline PTerm | Defn Name | Missing Name | DynamicLink FilePath | ListDynamic | Pattelab PTerm | Search [String] PTerm | CaseSplitAt Bool Int Name | AddClauseFrom Bool Int Name | AddProofClauseFrom Bool Int Name | AddMissing Bool Int Name | MakeWith Bool Int Name | MakeCase Bool Int Name | MakeLemma Bool Int Name | DoProofSearch Bool -- update file Bool -- recursive search Int -- depth Name -- top level name [Name] -- hints | SetOpt Opt | UnsetOpt Opt | NOP | SetColour ColourType IdrisColour | ColourOn | ColourOff | ListErrorHandlers | SetConsoleWidth ConsoleWidth | SetPrinterDepth (Maybe Int) | Apropos [String] String | WhoCalls Name | CallsWho Name | Browse [String] | MakeDoc String -- IdrisDoc | Warranty | PrintDef Name | PPrint OutputFmt Int PTerm | TransformInfo Name -- Debugging commands | DebugInfo Name | DebugUnify PTerm PTerm data OutputFmt = HTMLOutput | LaTeXOutput data Opt = Filename String | Quiet | NoBanner | ColourREPL Bool | Idemode | IdemodeSocket | ShowLibs | ShowLibdir | ShowIncs | ShowPkgs | NoBasePkgs | NoPrelude | NoBuiltins -- only for the really primitive stuff! | NoREPL | OLogging Int | Output String | Interface | TypeCase | TypeInType | DefaultTotal | DefaultPartial | WarnPartial | WarnReach | EvalTypes | NoCoverage | ErrContext | ShowImpl | Verbose | Port String -- REPL TCP port | IBCSubDir String | ImportDir String | PkgBuild String | PkgInstall String | PkgClean String | PkgCheck String | PkgREPL String | PkgMkDoc String -- IdrisDoc | PkgTest String | PkgIndex FilePath | WarnOnly | Pkg String | BCAsm String | DumpDefun String | DumpCases String | UseCodegen Codegen | CodegenArgs String | OutputTy OutputType | Extension LanguageExt | InterpretScript String | EvalExpr String | TargetTriple String | TargetCPU String | OptLevel Int | AddOpt Optimisation | RemoveOpt Optimisation | Client String | ShowOrigErr | AutoWidth -- ^ Automatically adjust terminal width | AutoSolve -- ^ Automatically issue "solve" tactic in interactive prover | UseConsoleWidth ConsoleWidth | DumpHighlights | DesugarNats deriving (Show, Eq) data ElabShellCmd = EQED | EAbandon | EUndo | EProofState | EProofTerm | EEval PTerm | ECheck PTerm | ESearch PTerm | EDocStr (Either Name Const) deriving (Show, Eq) -- Parsed declarations data Fixity = Infixl { prec :: Int } | Infixr { prec :: Int } | InfixN { prec :: Int } | PrefixN { prec :: Int } deriving Eq {-! deriving instance Binary Fixity deriving instance NFData Fixity !-} instance Show Fixity where show (Infixl i) = "infixl " ++ show i show (Infixr i) = "infixr " ++ show i show (InfixN i) = "infix " ++ show i show (PrefixN i) = "prefix " ++ show i data FixDecl = Fix Fixity String deriving Eq instance Show FixDecl where show (Fix f s) = show f ++ " " ++ s {-! deriving instance Binary FixDecl deriving instance NFData FixDecl !-} instance Ord FixDecl where compare (Fix x _) (Fix y _) = compare (prec x) (prec y) data Static = Static | Dynamic deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Static deriving instance NFData Static !-} -- Mark bindings with their explicitness, and laziness data Plicity = Imp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool, pscoped :: Maybe ImplicitInfo -- Nothing, if top level } | Exp { pargopts :: [ArgOpt], pstatic :: Static, pparam :: Bool } -- this is a param (rather than index) | Constraint { pargopts :: [ArgOpt], pstatic :: Static } | TacImp { pargopts :: [ArgOpt], pstatic :: Static, pscript :: PTerm } deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Plicity deriving instance NFData Plicity !-} is_scoped :: Plicity -> Maybe ImplicitInfo is_scoped (Imp _ _ _ s) = s is_scoped _ = Nothing impl = Imp [] Dynamic False Nothing forall_imp = Imp [] Dynamic False (Just (Impl False)) forall_constraint = Imp [] Dynamic False (Just (Impl True)) expl = Exp [] Dynamic False expl_param = Exp [] Dynamic True constraint = Constraint [] Static tacimpl t = TacImp [] Dynamic t data FnOpt = Inlinable -- always evaluate when simplifying | TotalFn | PartialFn | CoveringFn | Coinductive | AssertTotal | Dictionary -- type class dictionary, eval only when -- a function argument, and further evaluation resutls | Implicit -- implicit coercion | NoImplicit -- do not apply implicit coercions | CExport String -- export, with a C name | ErrorHandler -- ^^ an error handler for use with the ErrorReflection extension | ErrorReverse -- ^^ attempt to reverse normalise before showing in error | Reflection -- a reflecting function, compile-time only | Specialise [(Name, Maybe Int)] -- specialise it, freeze these names | Constructor -- Data constructor type | AutoHint -- use in auto implicit search | PEGenerated -- generated by partial evaluator deriving (Show, Eq) {-! deriving instance Binary FnOpt deriving instance NFData FnOpt !-} type FnOpts = [FnOpt] inlinable :: FnOpts -> Bool inlinable = elem Inlinable dictionary :: FnOpts -> Bool dictionary = elem Dictionary -- | Type provider - what to provide data ProvideWhat' t = ProvTerm t t -- ^ the first is the goal type, the second is the term | ProvPostulate t -- ^ goal type must be Type, so only term deriving (Show, Eq, Functor) type ProvideWhat = ProvideWhat' PTerm -- | Top-level declarations such as compiler directives, definitions, -- datatypes and typeclasses. data PDecl' t = PFix FC Fixity [String] -- ^ Fixity declaration | PTy (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC FnOpts Name FC t -- ^ Type declaration (last FC is precise name location) | PPostulate Bool -- external def if true (Docstring (Either Err t)) SyntaxInfo FC FC FnOpts Name t -- ^ Postulate, second FC is precise name location | PClauses FC FnOpts Name [PClause' t] -- ^ Pattern clause | PCAF FC Name t -- ^ Top level constant | PData (Docstring (Either Err t)) [(Name, Docstring (Either Err t))] SyntaxInfo FC DataOpts (PData' t) -- ^ Data declaration. | PParams FC [(Name, t)] [PDecl' t] -- ^ Params block | PNamespace String FC [PDecl' t] -- ^ New namespace, where FC is accurate location of the -- namespace in the file | PRecord (Docstring (Either Err t)) SyntaxInfo FC DataOpts Name -- Record name FC -- Record name precise location [(Name, FC, Plicity, t)] -- Parameters, where FC is precise name span [(Name, Docstring (Either Err t))] -- Param Docs [((Maybe (Name, FC)), Plicity, t, Maybe (Docstring (Either Err t)))] -- Fields (Maybe (Name, FC)) -- Optional constructor name and location (Docstring (Either Err t)) -- Constructor doc SyntaxInfo -- Constructor SyntaxInfo -- ^ Record declaration | PClass (Docstring (Either Err t)) SyntaxInfo FC [(Name, t)] -- constraints Name -- class name FC -- accurate location of class name [(Name, FC, t)] -- parameters and precise locations [(Name, Docstring (Either Err t))] -- parameter docstrings [(Name, FC)] -- determining parameters and precise locations [PDecl' t] -- declarations (Maybe (Name, FC)) -- instance constructor name and location (Docstring (Either Err t)) -- instance constructor docs -- ^ Type class: arguments are documentation, syntax info, source location, constraints, -- class name, class name location, parameters, method declarations, optional constructor name | PInstance (Docstring (Either Err t)) -- Instance docs [(Name, Docstring (Either Err t))] -- Parameter docs SyntaxInfo FC [(Name, t)] -- constraints Name -- class FC -- precise location of class [t] -- parameters t -- full instance type (Maybe Name) -- explicit name [PDecl' t] -- ^ Instance declaration: arguments are documentation, syntax info, source -- location, constraints, class name, parameters, full instance -- type, optional explicit name, and definitions | PDSL Name (DSL' t) -- ^ DSL declaration | PSyntax FC Syntax -- ^ Syntax definition | PMutual FC [PDecl' t] -- ^ Mutual block | PDirective Directive -- ^ Compiler directive. | PProvider (Docstring (Either Err t)) SyntaxInfo FC FC (ProvideWhat' t) Name -- ^ Type provider. The first t is the type, the second is the term. The second FC is precise highlighting location. | PTransform FC Bool t t -- ^ Source-to-source transformation rule. If -- bool is True, lhs and rhs must be convertible | PRunElabDecl FC t [String] -- ^ FC is decl-level, for errors, and -- Strings represent the namespace deriving Functor {-! deriving instance Binary PDecl' deriving instance NFData PDecl' !-} -- | The set of source directives data Directive = DLib Codegen String | DLink Codegen String | DFlag Codegen String | DInclude Codegen String | DHide Name | DFreeze Name | DAccess Accessibility | DDefault Bool | DLogging Integer | DDynamicLibs [String] | DNameHint Name FC [(Name, FC)] | DErrorHandlers Name FC Name FC [(Name, FC)] | DLanguage LanguageExt | DUsed FC Name Name -- | A set of instructions for things that need to happen in IState -- after a term elaboration when there's been reflected elaboration. data RDeclInstructions = RTyDeclInstrs Name FC [PArg] Type | RClausesInstrs Name [([Name], Term, Term)] | RAddInstance Name Name -- | For elaborator state data EState = EState { case_decls :: [(Name, PDecl)], delayed_elab :: [(Int, Elab' EState ())], new_tyDecls :: [RDeclInstructions], highlighting :: [(FC, OutputAnnotation)] } initEState :: EState initEState = EState [] [] [] [] type ElabD a = Elab' EState a highlightSource :: FC -> OutputAnnotation -> ElabD () highlightSource fc annot = updateAux (\aux -> aux { highlighting = (fc, annot) : highlighting aux }) -- | One clause of a top-level definition. Term arguments to constructors are: -- -- 1. The whole application (missing for PClauseR and PWithR because they're within a "with" clause) -- -- 2. The list of extra 'with' patterns -- -- 3. The right-hand side -- -- 4. The where block (PDecl' t) data PClause' t = PClause FC Name t [t] t [PDecl' t] -- ^ A normal top-level definition. | PWith FC Name t [t] t (Maybe (Name, FC)) [PDecl' t] | PClauseR FC [t] t [PDecl' t] | PWithR FC [t] t (Maybe (Name, FC)) [PDecl' t] deriving Functor {-! deriving instance Binary PClause' deriving instance NFData PClause' !-} -- | Data declaration data PData' t = PDatadecl { d_name :: Name, -- ^ The name of the datatype d_name_fc :: FC, -- ^ The precise location of the type constructor name d_tcon :: t, -- ^ Type constructor d_cons :: [(Docstring (Either Err PTerm), [(Name, Docstring (Either Err PTerm))], Name, FC, t, FC, [Name])] -- ^ Constructors } -- ^ Data declaration | PLaterdecl { d_name :: Name, d_name_fc :: FC, d_tcon :: t } -- ^ "Placeholder" for data whose constructors are defined later deriving Functor -- | Transform the FCs in a PData and its associated terms. The first -- function transforms the general-purpose FCs, and the second transforms -- those that are used for semantic source highlighting, so they can be -- treated specially. mapPDataFC :: (FC -> FC) -> (FC -> FC) -> PData -> PData mapPDataFC f g (PDatadecl n nfc tycon ctors) = PDatadecl n (g nfc) (mapPTermFC f g tycon) (map ctorFC ctors) where ctorFC (doc, argDocs, n, nfc, ty, fc, ns) = (doc, argDocs, n, g nfc, mapPTermFC f g ty, f fc, ns) mapPDataFC f g (PLaterdecl n nfc tycon) = PLaterdecl n (g nfc) (mapPTermFC f g tycon) {-! deriving instance Binary PData' deriving instance NFData PData' !-} -- Handy to get a free function for applying PTerm -> PTerm functions -- across a program, by deriving Functor type PDecl = PDecl' PTerm type PData = PData' PTerm type PClause = PClause' PTerm -- | Transform the FCs in a PTerm. The first function transforms the -- general-purpose FCs, and the second transforms those that are used -- for semantic source highlighting, so they can be treated specially. mapPDeclFC :: (FC -> FC) -> (FC -> FC) -> PDecl -> PDecl mapPDeclFC f g (PFix fc fixity ops) = PFix (f fc) fixity ops mapPDeclFC f g (PTy doc argdocs syn fc opts n nfc ty) = PTy doc argdocs syn (f fc) opts n (g nfc) (mapPTermFC f g ty) mapPDeclFC f g (PPostulate ext doc syn fc nfc opts n ty) = PPostulate ext doc syn (f fc) (g nfc) opts n (mapPTermFC f g ty) mapPDeclFC f g (PClauses fc opts n clauses) = PClauses (f fc) opts n (map (fmap (mapPTermFC f g)) clauses) mapPDeclFC f g (PCAF fc n tm) = PCAF (f fc) n (mapPTermFC f g tm) mapPDeclFC f g (PData doc argdocs syn fc opts dat) = PData doc argdocs syn (f fc) opts (mapPDataFC f g dat) mapPDeclFC f g (PParams fc params decls) = PParams (f fc) (map (\(n, ty) -> (n, mapPTermFC f g ty)) params) (map (mapPDeclFC f g) decls) mapPDeclFC f g (PNamespace ns fc decls) = PNamespace ns (f fc) (map (mapPDeclFC f g) decls) mapPDeclFC f g (PRecord doc syn fc opts n nfc params paramdocs fields ctor ctorDoc syn') = PRecord doc syn (f fc) opts n (g nfc) (map (\(pn, pnfc, plic, ty) -> (pn, g pnfc, plic, mapPTermFC f g ty)) params) paramdocs (map (\(fn, plic, ty, fdoc) -> (fmap (\(fn', fnfc) -> (fn', g fnfc)) fn, plic, mapPTermFC f g ty, fdoc)) fields) (fmap (\(ctorN, ctorNFC) -> (ctorN, g ctorNFC)) ctor) ctorDoc syn' mapPDeclFC f g (PClass doc syn fc constrs n nfc params paramDocs det body ctor ctorDoc) = PClass doc syn (f fc) (map (\(constrn, constr) -> (constrn, mapPTermFC f g constr)) constrs) n (g nfc) (map (\(n, nfc, pty) -> (n, g nfc, mapPTermFC f g pty)) params) paramDocs (map (\(dn, dnfc) -> (dn, g dnfc)) det) (map (mapPDeclFC f g) body) (fmap (\(n, nfc) -> (n, g nfc)) ctor) ctorDoc mapPDeclFC f g (PInstance doc paramDocs syn fc constrs cn cnfc params instTy instN body) = PInstance doc paramDocs syn (f fc) (map (\(constrN, constrT) -> (constrN, mapPTermFC f g constrT)) constrs) cn (g cnfc) (map (mapPTermFC f g) params) (mapPTermFC f g instTy) instN (map (mapPDeclFC f g) body) mapPDeclFC f g (PDSL n dsl) = PDSL n (fmap (mapPTermFC f g) dsl) mapPDeclFC f g (PSyntax fc syn) = PSyntax (f fc) $ case syn of Rule syms tm ctxt -> Rule syms (mapPTermFC f g tm) ctxt DeclRule syms decls -> DeclRule syms (map (mapPDeclFC f g) decls) mapPDeclFC f g (PMutual fc decls) = PMutual (f fc) (map (mapPDeclFC f g) decls) mapPDeclFC f g (PDirective d) = PDirective $ case d of DNameHint n nfc ns -> DNameHint n (g nfc) (map (\(hn, hnfc) -> (hn, g hnfc)) ns) DErrorHandlers n nfc n' nfc' ns -> DErrorHandlers n (g nfc) n' (g nfc') $ map (\(an, anfc) -> (an, g anfc)) ns mapPDeclFC f g (PProvider doc syn fc nfc what n) = PProvider doc syn (f fc) (g nfc) (fmap (mapPTermFC f g) what) n mapPDeclFC f g (PTransform fc safe l r) = PTransform (f fc) safe (mapPTermFC f g l) (mapPTermFC f g r) mapPDeclFC f g (PRunElabDecl fc script ns) = PRunElabDecl (f fc) (mapPTermFC f g script) ns -- | Get all the names declared in a declaration declared :: PDecl -> [Name] declared (PFix _ _ _) = [] declared (PTy _ _ _ _ _ n fc t) = [n] declared (PPostulate _ _ _ _ _ _ n t) = [n] declared (PClauses _ _ n _) = [] -- not a declaration declared (PCAF _ n _) = [n] declared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a declared (PData _ _ _ _ _ (PLaterdecl n _ _)) = [n] declared (PParams _ _ ds) = concatMap declared ds declared (PNamespace _ _ ds) = concatMap declared ds declared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) declared (PClass _ _ _ _ n _ _ _ _ ms cn cd) = n : (map fst (maybeToList cn) ++ concatMap declared ms) declared (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] declared (PDSL n _) = [n] declared (PSyntax _ _) = [] declared (PMutual _ ds) = concatMap declared ds declared (PDirective _) = [] declared _ = [] -- get the names declared, not counting nested parameter blocks tldeclared :: PDecl -> [Name] tldeclared (PFix _ _ _) = [] tldeclared (PTy _ _ _ _ _ n _ t) = [n] tldeclared (PPostulate _ _ _ _ _ _ n t) = [n] tldeclared (PClauses _ _ n _) = [] -- not a declaration tldeclared (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) tldeclared (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a tldeclared (PParams _ _ ds) = [] tldeclared (PMutual _ ds) = concatMap tldeclared ds tldeclared (PNamespace _ _ ds) = concatMap tldeclared ds tldeclared (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap tldeclared ms) tldeclared (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] tldeclared _ = [] defined :: PDecl -> [Name] defined (PFix _ _ _) = [] defined (PTy _ _ _ _ _ n _ t) = [] defined (PPostulate _ _ _ _ _ _ n t) = [] defined (PClauses _ _ n _) = [n] -- not a declaration defined (PCAF _ n _) = [n] defined (PData _ _ _ _ _ (PDatadecl n _ _ ts)) = n : map fstt ts where fstt (_, _, a, _, _, _, _) = a defined (PData _ _ _ _ _ (PLaterdecl n _ _)) = [] defined (PParams _ _ ds) = concatMap defined ds defined (PNamespace _ _ ds) = concatMap defined ds defined (PRecord _ _ _ _ n _ _ _ _ cn _ _) = n : map fst (maybeToList cn) defined (PClass _ _ _ _ n _ _ _ _ ms cn _) = n : (map fst (maybeToList cn) ++ concatMap defined ms) defined (PInstance _ _ _ _ _ _ _ _ _ _ _) = [] defined (PDSL n _) = [n] defined (PSyntax _ _) = [] defined (PMutual _ ds) = concatMap defined ds defined (PDirective _) = [] defined _ = [] updateN :: [(Name, Name)] -> Name -> Name updateN ns n | Just n' <- lookup n ns = n' updateN _ n = n updateNs :: [(Name, Name)] -> PTerm -> PTerm updateNs [] t = t updateNs ns t = mapPT updateRef t where updateRef (PRef fc fcs f) = PRef fc fcs (updateN ns f) updateRef t = t -- updateDNs :: [(Name, Name)] -> PDecl -> PDecl -- updateDNs [] t = t -- updateDNs ns (PTy s f n t) | Just n' <- lookup n ns = PTy s f n' t -- updateDNs ns (PClauses f n c) | Just n' <- lookup n ns = PClauses f n' (map updateCNs c) -- where updateCNs ns (PClause n l ts r ds) -- = PClause (updateN ns n) (fmap (updateNs ns) l) -- (map (fmap (updateNs ns)) ts) -- (fmap (updateNs ns) r) -- (map (updateDNs ns) ds) -- updateDNs ns c = c data PunInfo = IsType | IsTerm | TypeOrTerm deriving (Eq, Show, Data, Typeable) -- | High level language terms data PTerm = PQuote Raw -- ^ Inclusion of a core term into the high-level language | PRef FC [FC] Name -- ^ A reference to a variable. The FC is its precise source location for highlighting. The list of FCs is a collection of additional highlighting locations. | PInferRef FC [FC] Name -- ^ A name to be defined later | PPatvar FC Name -- ^ A pattern variable | PLam FC Name FC PTerm PTerm -- ^ A lambda abstraction. Second FC is name span. | PPi Plicity Name FC PTerm PTerm -- ^ (n : t1) -> t2, where the FC is for the precise location of the variable | PLet FC Name FC PTerm PTerm PTerm -- ^ A let binding (second FC is precise name location) | PTyped PTerm PTerm -- ^ Term with explicit type | PApp FC PTerm [PArg] -- ^ e.g. IO (), List Char, length x | PAppImpl PTerm [ImplicitInfo] -- ^ Implicit argument application (introduced during elaboration only) | PAppBind FC PTerm [PArg] -- ^ implicitly bound application | PMatchApp FC Name -- ^ Make an application by type matching | PIfThenElse FC PTerm PTerm PTerm -- ^ Conditional expressions - elaborated to an overloading of ifThenElse | PCase FC PTerm [(PTerm, PTerm)] -- ^ A case expression. Args are source location, scrutinee, and a list of pattern/RHS pairs | PTrue FC PunInfo -- ^ Unit type..? | PResolveTC FC -- ^ Solve this dictionary by type class resolution | PRewrite FC PTerm PTerm (Maybe PTerm) -- ^ "rewrite" syntax, with optional result type | PPair FC [FC] PunInfo PTerm PTerm -- ^ A pair (a, b) and whether it's a product type or a pair (solved by elaboration). The list of FCs is its punctuation. | PDPair FC [FC] PunInfo PTerm PTerm PTerm -- ^ A dependent pair (tm : a ** b) and whether it's a sigma type or a pair that inhabits one (solved by elaboration). The [FC] is its punctuation. | PAs FC Name PTerm -- ^ @-pattern, valid LHS only | PAlternative [(Name, Name)] PAltType [PTerm] -- ^ (| A, B, C|). Includes unapplied unique name mappings for mkUniqueNames. | PHidden PTerm -- ^ Irrelevant or hidden pattern | PType FC -- ^ 'Type' type | PUniverse Universe -- ^ Some universe | PGoal FC PTerm Name PTerm -- ^ quoteGoal, used for %reflection functions | PConstant FC Const -- ^ Builtin types | Placeholder -- ^ Underscore | PDoBlock [PDo] -- ^ Do notation | PIdiom FC PTerm -- ^ Idiom brackets | PReturn FC | PMetavar FC Name -- ^ A metavariable, ?name, and its precise location | PProof [PTactic] -- ^ Proof script | PTactics [PTactic] -- ^ As PProof, but no auto solving | PElabError Err -- ^ Error to report on elaboration | PImpossible -- ^ Special case for declaring when an LHS can't typecheck | PCoerced PTerm -- ^ To mark a coerced argument, so as not to coerce twice | PDisamb [[T.Text]] PTerm -- ^ Preferences for explicit namespaces | PUnifyLog PTerm -- ^ dump a trace of unifications when building term | PNoImplicits PTerm -- ^ never run implicit converions on the term | PQuasiquote PTerm (Maybe PTerm) -- ^ `(Term [: Term]) | PUnquote PTerm -- ^ ~Term | PQuoteName Name Bool FC -- ^ `{n} where the FC is the precise highlighting for the name in particular. If the Bool is False, then it's `{{n}} and the name won't be resolved. | PRunElab FC PTerm [String] -- ^ %runElab tm - New-style proof script. Args are location, script, enclosing namespace. | PConstSugar FC PTerm -- ^ A desugared constant. The FC is a precise source location that will be used to highlight it later. deriving (Eq, Data, Typeable) data PAltType = ExactlyOne Bool -- ^ flag sets whether delay is allowed | FirstSuccess | TryImplicit deriving (Eq, Data, Typeable) -- | Transform the FCs in a PTerm. The first function transforms the -- general-purpose FCs, and the second transforms those that are used -- for semantic source highlighting, so they can be treated specially. mapPTermFC :: (FC -> FC) -> (FC -> FC) -> PTerm -> PTerm mapPTermFC f g (PQuote q) = PQuote q mapPTermFC f g (PRef fc fcs n) = PRef (g fc) (map g fcs) n mapPTermFC f g (PInferRef fc fcs n) = PInferRef (g fc) (map g fcs) n mapPTermFC f g (PPatvar fc n) = PPatvar (g fc) n mapPTermFC f g (PLam fc n fc' t1 t2) = PLam (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PPi plic n fc t1 t2) = PPi plic n (g fc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PLet fc n fc' t1 t2 t3) = PLet (f fc) n (g fc') (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PTyped t1 t2) = PTyped (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PApp fc t args) = PApp (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args) mapPTermFC f g (PAppImpl t1 impls) = PAppImpl (mapPTermFC f g t1) impls mapPTermFC f g (PAppBind fc t args) = PAppBind (f fc) (mapPTermFC f g t) (map (fmap (mapPTermFC f g)) args) mapPTermFC f g (PMatchApp fc n) = PMatchApp (f fc) n mapPTermFC f g (PIfThenElse fc t1 t2 t3) = PIfThenElse (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PCase fc t cases) = PCase (f fc) (mapPTermFC f g t) (map (\(l,r) -> (mapPTermFC f g l, mapPTermFC f g r)) cases) mapPTermFC f g (PTrue fc info) = PTrue (f fc) info mapPTermFC f g (PResolveTC fc) = PResolveTC (f fc) mapPTermFC f g (PRewrite fc t1 t2 t3) = PRewrite (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (fmap (mapPTermFC f g) t3) mapPTermFC f g (PPair fc hls info t1 t2) = PPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PDPair fc hls info t1 t2 t3) = PDPair (f fc) (map g hls) info (mapPTermFC f g t1) (mapPTermFC f g t2) (mapPTermFC f g t3) mapPTermFC f g (PAs fc n t) = PAs (f fc) n (mapPTermFC f g t) mapPTermFC f g (PAlternative ns ty ts) = PAlternative ns ty (map (mapPTermFC f g) ts) mapPTermFC f g (PHidden t) = PHidden (mapPTermFC f g t) mapPTermFC f g (PType fc) = PType (f fc) mapPTermFC f g (PUniverse u) = PUniverse u mapPTermFC f g (PGoal fc t1 n t2) = PGoal (f fc) (mapPTermFC f g t1) n (mapPTermFC f g t2) mapPTermFC f g (PConstant fc c) = PConstant (f fc) c mapPTermFC f g Placeholder = Placeholder mapPTermFC f g (PDoBlock dos) = PDoBlock (map mapPDoFC dos) where mapPDoFC (DoExp fc t) = DoExp (f fc) (mapPTermFC f g t) mapPDoFC (DoBind fc n nfc t) = DoBind (f fc) n (g nfc) (mapPTermFC f g t) mapPDoFC (DoBindP fc t1 t2 alts) = DoBindP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) (map (\(l,r)-> (mapPTermFC f g l, mapPTermFC f g r)) alts) mapPDoFC (DoLet fc n nfc t1 t2) = DoLet (f fc) n (g nfc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPDoFC (DoLetP fc t1 t2) = DoLetP (f fc) (mapPTermFC f g t1) (mapPTermFC f g t2) mapPTermFC f g (PIdiom fc t) = PIdiom (f fc) (mapPTermFC f g t) mapPTermFC f g (PReturn fc) = PReturn (f fc) mapPTermFC f g (PMetavar fc n) = PMetavar (g fc) n mapPTermFC f g (PProof tacs) = PProof (map (fmap (mapPTermFC f g)) tacs) mapPTermFC f g (PTactics tacs) = PTactics (map (fmap (mapPTermFC f g)) tacs) mapPTermFC f g (PElabError err) = PElabError err mapPTermFC f g PImpossible = PImpossible mapPTermFC f g (PCoerced t) = PCoerced (mapPTermFC f g t) mapPTermFC f g (PDisamb msg t) = PDisamb msg (mapPTermFC f g t) mapPTermFC f g (PUnifyLog t) = PUnifyLog (mapPTermFC f g t) mapPTermFC f g (PNoImplicits t) = PNoImplicits (mapPTermFC f g t) mapPTermFC f g (PQuasiquote t1 t2) = PQuasiquote (mapPTermFC f g t1) (fmap (mapPTermFC f g) t2) mapPTermFC f g (PUnquote t) = PUnquote (mapPTermFC f g t) mapPTermFC f g (PRunElab fc tm ns) = PRunElab (f fc) (mapPTermFC f g tm) ns mapPTermFC f g (PConstSugar fc tm) = PConstSugar (g fc) (mapPTermFC f g tm) mapPTermFC f g (PQuoteName n x fc) = PQuoteName n x (g fc) {-! dg instance Binary PTerm deriving instance NFData PTerm !-} mapPT :: (PTerm -> PTerm) -> PTerm -> PTerm mapPT f t = f (mpt t) where mpt (PLam fc n nfc t s) = PLam fc n nfc (mapPT f t) (mapPT f s) mpt (PPi p n nfc t s) = PPi p n nfc (mapPT f t) (mapPT f s) mpt (PLet fc n nfc ty v s) = PLet fc n nfc (mapPT f ty) (mapPT f v) (mapPT f s) mpt (PRewrite fc t s g) = PRewrite fc (mapPT f t) (mapPT f s) (fmap (mapPT f) g) mpt (PApp fc t as) = PApp fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PAppBind fc t as) = PAppBind fc (mapPT f t) (map (fmap (mapPT f)) as) mpt (PCase fc c os) = PCase fc (mapPT f c) (map (pmap (mapPT f)) os) mpt (PIfThenElse fc c t e) = PIfThenElse fc (mapPT f c) (mapPT f t) (mapPT f e) mpt (PTyped l r) = PTyped (mapPT f l) (mapPT f r) mpt (PPair fc hls p l r) = PPair fc hls p (mapPT f l) (mapPT f r) mpt (PDPair fc hls p l t r) = PDPair fc hls p (mapPT f l) (mapPT f t) (mapPT f r) mpt (PAlternative ns a as) = PAlternative ns a (map (mapPT f) as) mpt (PHidden t) = PHidden (mapPT f t) mpt (PDoBlock ds) = PDoBlock (map (fmap (mapPT f)) ds) mpt (PProof ts) = PProof (map (fmap (mapPT f)) ts) mpt (PTactics ts) = PTactics (map (fmap (mapPT f)) ts) mpt (PUnifyLog tm) = PUnifyLog (mapPT f tm) mpt (PDisamb ns tm) = PDisamb ns (mapPT f tm) mpt (PNoImplicits tm) = PNoImplicits (mapPT f tm) mpt (PGoal fc r n sc) = PGoal fc (mapPT f r) n (mapPT f sc) mpt x = x data PTactic' t = Intro [Name] | Intros | Focus Name | Refine Name [Bool] | Rewrite t | DoUnify | Induction t | CaseTac t | Equiv t | Claim Name t | Unfocus | MatchRefine Name | LetTac Name t | LetTacTy Name t t | Exact t | Compute | Trivial | TCInstance | ProofSearch Bool Bool Int (Maybe Name) [Name] -- allowed local names [Name] -- hints -- ^ the bool is whether to search recursively | Solve | Attack | ProofState | ProofTerm | Undo | Try (PTactic' t) (PTactic' t) | TSeq (PTactic' t) (PTactic' t) | ApplyTactic t -- see Language.Reflection module | ByReflection t | Reflect t | Fill t | GoalType String (PTactic' t) | TCheck t | TEval t | TDocStr (Either Name Const) | TSearch t | Skip | TFail [ErrorReportPart] | Qed | Abandon | SourceFC deriving (Show, Eq, Functor, Foldable, Traversable, Data, Typeable) {-! deriving instance Binary PTactic' deriving instance NFData PTactic' !-} instance Sized a => Sized (PTactic' a) where size (Intro nms) = 1 + size nms size Intros = 1 size (Focus nm) = 1 + size nm size (Refine nm bs) = 1 + size nm + length bs size (Rewrite t) = 1 + size t size (Induction t) = 1 + size t size (LetTac nm t) = 1 + size nm + size t size (Exact t) = 1 + size t size Compute = 1 size Trivial = 1 size Solve = 1 size Attack = 1 size ProofState = 1 size ProofTerm = 1 size Undo = 1 size (Try l r) = 1 + size l + size r size (TSeq l r) = 1 + size l + size r size (ApplyTactic t) = 1 + size t size (Reflect t) = 1 + size t size (Fill t) = 1 + size t size Qed = 1 size Abandon = 1 size Skip = 1 size (TFail ts) = 1 + size ts size SourceFC = 1 size DoUnify = 1 size (CaseTac x) = 1 + size x size (Equiv t) = 1 + size t size (Claim x y) = 1 + size x + size y size Unfocus = 1 size (MatchRefine x) = 1 + size x size (LetTacTy x y z) = 1 + size x + size y + size z size TCInstance = 1 type PTactic = PTactic' PTerm data PDo' t = DoExp FC t | DoBind FC Name FC t -- ^ second FC is precise name location | DoBindP FC t t [(t,t)] | DoLet FC Name FC t t -- ^ second FC is precise name location | DoLetP FC t t deriving (Eq, Functor, Data, Typeable) {-! deriving instance Binary PDo' deriving instance NFData PDo' !-} instance Sized a => Sized (PDo' a) where size (DoExp fc t) = 1 + size fc + size t size (DoBind fc nm nfc t) = 1 + size fc + size nm + size nfc + size t size (DoBindP fc l r alts) = 1 + size fc + size l + size r + size alts size (DoLet fc nm nfc l r) = 1 + size fc + size nm + size l + size r size (DoLetP fc l r) = 1 + size fc + size l + size r type PDo = PDo' PTerm -- The priority gives a hint as to elaboration order. Best to elaborate -- things early which will help give a more concrete type to other -- variables, e.g. a before (interpTy a). data PArg' t = PImp { priority :: Int, machine_inf :: Bool, -- true if the machine inferred it argopts :: [ArgOpt], pname :: Name, getTm :: t } | PExp { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PConstraint { priority :: Int, argopts :: [ArgOpt], pname :: Name, getTm :: t } | PTacImplicit { priority :: Int, argopts :: [ArgOpt], pname :: Name, getScript :: t, getTm :: t } deriving (Show, Eq, Functor, Data, Typeable) data ArgOpt = AlwaysShow | HideDisplay | InaccessibleArg | UnknownImp deriving (Show, Eq, Data, Typeable) instance Sized a => Sized (PArg' a) where size (PImp p _ l nm trm) = 1 + size nm + size trm size (PExp p l nm trm) = 1 + size nm + size trm size (PConstraint p l nm trm) = 1 + size nm +size nm + size trm size (PTacImplicit p l nm scr trm) = 1 + size nm + size scr + size trm {-! deriving instance Binary PArg' deriving instance NFData PArg' !-} pimp n t mach = PImp 1 mach [] n t pexp t = PExp 1 [] (sMN 0 "arg") t pconst t = PConstraint 1 [] (sMN 0 "carg") t ptacimp n s t = PTacImplicit 2 [] n s t type PArg = PArg' PTerm -- | Get the highest FC in a term, if one exists highestFC :: PTerm -> Maybe FC highestFC (PQuote _) = Nothing highestFC (PRef fc _ _) = Just fc highestFC (PInferRef fc _ _) = Just fc highestFC (PPatvar fc _) = Just fc highestFC (PLam fc _ _ _ _) = Just fc highestFC (PPi _ _ _ _ _) = Nothing highestFC (PLet fc _ _ _ _ _) = Just fc highestFC (PTyped tm ty) = highestFC tm <|> highestFC ty highestFC (PApp fc _ _) = Just fc highestFC (PAppBind fc _ _) = Just fc highestFC (PMatchApp fc _) = Just fc highestFC (PCase fc _ _) = Just fc highestFC (PIfThenElse fc _ _ _) = Just fc highestFC (PTrue fc _) = Just fc highestFC (PResolveTC fc) = Just fc highestFC (PRewrite fc _ _ _) = Just fc highestFC (PPair fc _ _ _ _) = Just fc highestFC (PDPair fc _ _ _ _ _) = Just fc highestFC (PAs fc _ _) = Just fc highestFC (PAlternative _ _ args) = case mapMaybe highestFC args of [] -> Nothing (fc:_) -> Just fc highestFC (PHidden _) = Nothing highestFC (PType fc) = Just fc highestFC (PUniverse _) = Nothing highestFC (PGoal fc _ _ _) = Just fc highestFC (PConstant fc _) = Just fc highestFC Placeholder = Nothing highestFC (PDoBlock lines) = case map getDoFC lines of [] -> Nothing (fc:_) -> Just fc where getDoFC (DoExp fc t) = fc getDoFC (DoBind fc nm nfc t) = fc getDoFC (DoBindP fc l r alts) = fc getDoFC (DoLet fc nm nfc l r) = fc getDoFC (DoLetP fc l r) = fc highestFC (PIdiom fc _) = Just fc highestFC (PReturn fc) = Just fc highestFC (PMetavar fc _) = Just fc highestFC (PProof _) = Nothing highestFC (PTactics _) = Nothing highestFC (PElabError _) = Nothing highestFC PImpossible = Nothing highestFC (PCoerced tm) = highestFC tm highestFC (PDisamb _ opts) = highestFC opts highestFC (PUnifyLog tm) = highestFC tm highestFC (PNoImplicits tm) = highestFC tm highestFC (PQuasiquote _ _) = Nothing highestFC (PUnquote tm) = highestFC tm highestFC (PQuoteName _ _ fc) = Just fc highestFC (PRunElab fc _ _) = Just fc highestFC (PConstSugar fc _) = Just fc highestFC (PAppImpl t _) = highestFC t -- Type class data data ClassInfo = CI { instanceCtorName :: Name, class_methods :: [(Name, (FnOpts, PTerm))], class_defaults :: [(Name, (Name, PDecl))], -- method name -> default impl class_default_superclasses :: [PDecl], class_params :: [Name], class_instances :: [(Name, Bool)], -- the Bool is whether to include in instance search, so named instances are excluded class_determiners :: [Int] } deriving Show {-! deriving instance Binary ClassInfo deriving instance NFData ClassInfo !-} -- Record data data RecordInfo = RI { record_parameters :: [(Name,PTerm)], record_constructor :: Name, record_projections :: [Name] } deriving Show -- Type inference data data TIData = TIPartial -- ^ a function with a partially defined type | TISolution [Term] -- ^ possible solutions to a metavariable in a type deriving Show -- | Miscellaneous information about functions data FnInfo = FnInfo { fn_params :: [Int] } deriving Show {-! deriving instance Binary FnInfo deriving instance NFData FnInfo !-} data OptInfo = Optimise { inaccessible :: [(Int,Name)], -- includes names for error reporting detaggable :: Bool } deriving Show {-! deriving instance Binary OptInfo deriving instance NFData OptInfo !-} -- | Syntactic sugar info data DSL' t = DSL { dsl_bind :: t, dsl_return :: t, dsl_apply :: t, dsl_pure :: t, dsl_var :: Maybe t, index_first :: Maybe t, index_next :: Maybe t, dsl_lambda :: Maybe t, dsl_let :: Maybe t, dsl_pi :: Maybe t } deriving (Show, Functor) {-! deriving instance Binary DSL' deriving instance NFData DSL' !-} type DSL = DSL' PTerm data SynContext = PatternSyntax | TermSyntax | AnySyntax deriving Show {-! deriving instance Binary SynContext deriving instance NFData SynContext !-} data Syntax = Rule [SSymbol] PTerm SynContext | DeclRule [SSymbol] [PDecl] deriving Show syntaxNames :: Syntax -> [Name] syntaxNames (Rule syms _ _) = mapMaybe ename syms where ename (Keyword n) = Just n ename _ = Nothing syntaxNames (DeclRule syms _) = mapMaybe ename syms where ename (Keyword n) = Just n ename _ = Nothing syntaxSymbols :: Syntax -> [SSymbol] syntaxSymbols (Rule ss _ _) = ss syntaxSymbols (DeclRule ss _) = ss {-! deriving instance Binary Syntax deriving instance NFData Syntax !-} data SSymbol = Keyword Name | Symbol String | Binding Name | Expr Name | SimpleExpr Name deriving (Show, Eq) {-! deriving instance Binary SSymbol deriving instance NFData SSymbol !-} newtype SyntaxRules = SyntaxRules { syntaxRulesList :: [Syntax] } emptySyntaxRules :: SyntaxRules emptySyntaxRules = SyntaxRules [] updateSyntaxRules :: [Syntax] -> SyntaxRules -> SyntaxRules updateSyntaxRules rules (SyntaxRules sr) = SyntaxRules newRules where newRules = sortBy (ruleSort `on` syntaxSymbols) (rules ++ sr) ruleSort [] [] = EQ ruleSort [] _ = LT ruleSort _ [] = GT ruleSort (s1:ss1) (s2:ss2) = case symCompare s1 s2 of EQ -> ruleSort ss1 ss2 r -> r -- Better than creating Ord instance for SSymbol since -- in general this ordering does not really make sense. symCompare (Keyword n1) (Keyword n2) = compare n1 n2 symCompare (Keyword _) _ = LT symCompare (Symbol _) (Keyword _) = GT symCompare (Symbol s1) (Symbol s2) = compare s1 s2 symCompare (Symbol _) _ = LT symCompare (Binding _) (Keyword _) = GT symCompare (Binding _) (Symbol _) = GT symCompare (Binding b1) (Binding b2) = compare b1 b2 symCompare (Binding _) _ = LT symCompare (Expr _) (Keyword _) = GT symCompare (Expr _) (Symbol _) = GT symCompare (Expr _) (Binding _) = GT symCompare (Expr e1) (Expr e2) = compare e1 e2 symCompare (Expr _) _ = LT symCompare (SimpleExpr _) (Keyword _) = GT symCompare (SimpleExpr _) (Symbol _) = GT symCompare (SimpleExpr _) (Binding _) = GT symCompare (SimpleExpr _) (Expr _) = GT symCompare (SimpleExpr e1) (SimpleExpr e2) = compare e1 e2 initDSL = DSL (PRef f [] (sUN ">>=")) (PRef f [] (sUN "return")) (PRef f [] (sUN "<*>")) (PRef f [] (sUN "pure")) Nothing Nothing Nothing Nothing Nothing Nothing where f = fileFC "(builtin)" data Using = UImplicit Name PTerm | UConstraint Name [Name] deriving (Show, Eq, Data, Typeable) {-! deriving instance Binary Using deriving instance NFData Using !-} data SyntaxInfo = Syn { using :: [Using], syn_params :: [(Name, PTerm)], syn_namespace :: [String], no_imp :: [Name], imp_methods :: [Name], -- class methods. When expanding -- implicits, these should be expanded even under -- binders decoration :: Name -> Name, inPattern :: Bool, implicitAllowed :: Bool, maxline :: Maybe Int, mut_nesting :: Int, dsl_info :: DSL, syn_in_quasiquote :: Int } deriving Show {-! deriving instance NFData SyntaxInfo deriving instance Binary SyntaxInfo !-} defaultSyntax = Syn [] [] [] [] [] id False False Nothing 0 initDSL 0 expandNS :: SyntaxInfo -> Name -> Name expandNS syn n@(NS _ _) = n expandNS syn n = case syn_namespace syn of [] -> n xs -> sNS n xs -- For inferring types of things bi = fileFC "builtin" inferTy = sMN 0 "__Infer" inferCon = sMN 0 "__infer" inferDecl = PDatadecl inferTy NoFC (PType bi) [(emptyDocstring, [], inferCon, NoFC, PPi impl (sMN 0 "iType") NoFC (PType bi) ( PPi expl (sMN 0 "ival") NoFC (PRef bi [] (sMN 0 "iType")) (PRef bi [] inferTy)), bi, [])] inferOpts = [] infTerm t = PApp bi (PRef bi [] inferCon) [pimp (sMN 0 "iType") Placeholder True, pexp t] infP = P (TCon 6 0) inferTy (TType (UVal 0)) getInferTerm, getInferType :: Term -> Term getInferTerm (Bind n b sc) = Bind n b $ getInferTerm sc getInferTerm (App _ (App _ _ _) tm) = tm getInferTerm tm = tm -- error ("getInferTerm " ++ show tm) getInferType (Bind n b sc) = Bind n (toTy b) $ getInferType sc where toTy (Lam t) = Pi Nothing t (TType (UVar 0)) toTy (PVar t) = PVTy t toTy b = b getInferType (App _ (App _ _ ty) _) = ty -- Handy primitives: Unit, False, Pair, MkPair, =, mkForeign primNames = [inferTy, inferCon] unitTy = sUN "Unit" unitCon = sUN "MkUnit" falseDoc = fmap (const $ Msg "") . parseDocstring . T.pack $ "The empty type, also known as the trivially false proposition." ++ "\n\n" ++ "Use `void` or `absurd` to prove anything if you have a variable " ++ "of type `Void` in scope." falseTy = sUN "Void" pairTy = sNS (sUN "Pair") ["Builtins"] pairCon = sNS (sUN "MkPair") ["Builtins"] upairTy = sNS (sUN "UPair") ["Builtins"] upairCon = sNS (sUN "MkUPair") ["Builtins"] eqTy = sUN "=" eqCon = sUN "Refl" eqDoc = fmap (const (Left $ Msg "")) . parseDocstring . T.pack $ "The propositional equality type. A proof that `x` = `y`." ++ "\n\n" ++ "To use such a proof, pattern-match on it, and the two equal things will " ++ "then need to be the _same_ pattern." ++ "\n\n" ++ "**Note**: Idris's equality type is potentially _heterogeneous_, which means that it " ++ "is possible to state equalities between values of potentially different " ++ "types. However, Idris will attempt the homogeneous case unless it fails to typecheck." ++ "\n\n" ++ "You may need to use `(~=~)` to explicitly request heterogeneous equality." eqDecl = PDatadecl eqTy NoFC (piBindp impl [(n "A", PType bi), (n "B", PType bi)] (piBind [(n "x", PRef bi [] (n "A")), (n "y", PRef bi [] (n "B"))] (PType bi))) [(reflDoc, reflParamDoc, eqCon, NoFC, PPi impl (n "A") NoFC (PType bi) ( PPi impl (n "x") NoFC (PRef bi [] (n "A")) (PApp bi (PRef bi [] eqTy) [pimp (n "A") Placeholder False, pimp (n "B") Placeholder False, pexp (PRef bi [] (n "x")), pexp (PRef bi [] (n "x"))])), bi, [])] where n a = sUN a reflDoc = annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "A proof that `x` in fact equals `x`. To construct this, you must have already " ++ "shown that both sides are in fact equal." reflParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type at which the equality is proven"), (n "x", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the element shown to be equal to itself.")] eqParamDoc = [(n "A", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the left side of the equality"), (n "B", annotCode (const (Left $ Msg "")) . parseDocstring . T.pack $ "the type of the right side of the equality") ] where n a = sUN a eqOpts = [] -- | The special name to be used in the module documentation context - -- not for use in the main definition context. The namespace around it -- will determine the module to which the docs adhere. modDocName :: Name modDocName = sMN 0 "ModuleDocs" -- Defined in builtins.idr sigmaTy = sNS (sUN "Sigma") ["Builtins"] sigmaCon = sNS (sUN "MkSigma") ["Builtins"] piBind :: [(Name, PTerm)] -> PTerm -> PTerm piBind = piBindp expl piBindp :: Plicity -> [(Name, PTerm)] -> PTerm -> PTerm piBindp p [] t = t piBindp p ((n, ty):ns) t = PPi p n NoFC ty (piBindp p ns t) -- Pretty-printing declarations and terms -- These "show" instances render to an absurdly wide screen because inserted line breaks -- could interfere with interactive editing, which calls "show". instance Show PTerm where showsPrec _ tm = (displayS . renderPretty 1.0 10000000 . prettyImp defaultPPOption) tm instance Show PDecl where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDeclImp verbosePPOption) d instance Show PClause where showsPrec _ c = (displayS . renderPretty 1.0 10000000 . showCImp verbosePPOption) c instance Show PData where showsPrec _ d = (displayS . renderPretty 1.0 10000000 . showDImp defaultPPOption) d instance Pretty PTerm OutputAnnotation where pretty = prettyImp defaultPPOption -- | Colourise annotations according to an Idris state. It ignores the names -- in the annotation, as there's no good way to show extended information on a -- terminal. annotationColour :: IState -> OutputAnnotation -> Maybe IdrisColour annotationColour ist _ | not (idris_colourRepl ist) = Nothing annotationColour ist (AnnConst c) = let theme = idris_colourTheme ist in Just $ if constIsType c then typeColour theme else dataColour theme annotationColour ist (AnnData _ _) = Just $ dataColour (idris_colourTheme ist) annotationColour ist (AnnType _ _) = Just $ typeColour (idris_colourTheme ist) annotationColour ist (AnnBoundName _ True) = Just $ implicitColour (idris_colourTheme ist) annotationColour ist (AnnBoundName _ False) = Just $ boundVarColour (idris_colourTheme ist) annotationColour ist AnnKeyword = Just $ keywordColour (idris_colourTheme ist) annotationColour ist (AnnName n _ _ _) = let ctxt = tt_ctxt ist theme = idris_colourTheme ist in case () of _ | isDConName n ctxt -> Just $ dataColour theme _ | isFnName n ctxt -> Just $ functionColour theme _ | isTConName n ctxt -> Just $ typeColour theme _ | isPostulateName n ist -> Just $ postulateColour theme _ | otherwise -> Nothing -- don't colourise unknown names annotationColour ist (AnnTextFmt fmt) = Just (colour fmt) where colour BoldText = IdrisColour Nothing True False True False colour UnderlineText = IdrisColour Nothing True True False False colour ItalicText = IdrisColour Nothing True False False True annotationColour ist _ = Nothing -- | Colourise annotations according to an Idris state. It ignores the names -- in the annotation, as there's no good way to show extended -- information on a terminal. Note that strings produced this way will -- not be coloured on Windows, so the use of the colour rendering -- functions in Idris.Output is to be preferred. consoleDecorate :: IState -> OutputAnnotation -> String -> String consoleDecorate ist ann = maybe id colourise (annotationColour ist ann) isPostulateName :: Name -> IState -> Bool isPostulateName n ist = S.member n (idris_postulates ist) -- | Pretty-print a high-level closed Idris term with no information about precedence/associativity prettyImp :: PPOption -- ^^ pretty printing options -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation prettyImp impl = pprintPTerm impl [] [] [] -- | Serialise something to base64 using its Binary instance. -- | Do the right thing for rendering a term in an IState prettyIst :: IState -> PTerm -> Doc OutputAnnotation prettyIst ist = pprintPTerm (ppOptionIst ist) [] [] (idris_infixes ist) -- | Pretty-print a high-level Idris term in some bindings context with infix info pprintPTerm :: PPOption -- ^^ pretty printing options -> [(Name, Bool)] -- ^^ the currently-bound names and whether they are implicit -> [Name] -- ^^ names to always show in pi, even if not used -> [FixDecl] -- ^^ Fixity declarations -> PTerm -- ^^ the term to pretty-print -> Doc OutputAnnotation pprintPTerm ppo bnd docArgs infixes = prettySe (ppopt_depth ppo) startPrec bnd where startPrec = 0 funcAppPrec = 10 prettySe :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Doc OutputAnnotation prettySe d p bnd (PQuote r) = text "![" <> pretty r <> text "]" prettySe d p bnd (PPatvar fc n) = pretty n prettySe d p bnd e | Just str <- slist d p bnd e = depth d $ str | Just n <- snat ppo d p e = depth d $ annotate (AnnData "Nat" "") (text (show n)) prettySe d p bnd (PRef fc _ n) = prettyName True (ppopt_impl ppo) bnd n prettySe d p bnd (PLam fc n nfc ty sc) = depth d . bracket p startPrec . group . align . hang 2 $ text "\\" <> prettyBindingOf n False <+> text "=>" <$> prettySe (decD d) startPrec ((n, False):bnd) sc prettySe d p bnd (PLet fc n nfc ty v sc) = depth d . bracket p startPrec . group . align $ kwd "let" <+> (group . align . hang 2 $ prettyBindingOf n False <+> text "=" <$> prettySe (decD d) startPrec bnd v) </> kwd "in" <+> (group . align . hang 2 $ prettySe (decD d) startPrec ((n, False):bnd) sc) prettySe d p bnd (PPi (Exp l s _) n _ ty sc) | n `elem` allNamesIn sc || ppopt_impl ppo && uname n || n `elem` docArgs || ppopt_pinames ppo && uname n = depth d . bracket p startPrec . group $ enclose lparen rparen (group . align $ prettyBindingOf n False <+> colon <+> prettySe (decD d) startPrec bnd ty) <+> st <> text "->" <$> prettySe (decD d) startPrec ((n, False):bnd) sc | otherwise = depth d . bracket p startPrec . group $ group (prettySe (decD d) (startPrec + 1) bnd ty <+> st) <> text "->" <$> group (prettySe (decD d) startPrec ((n, False):bnd) sc) where uname (UN n) = case str n of ('_':_) -> False _ -> True uname _ = False st = case s of Static -> text "[static]" <> space _ -> empty prettySe d p bnd (PPi (Imp l s _ fa) n _ ty sc) | ppopt_impl ppo = depth d . bracket p startPrec $ lbrace <> prettyBindingOf n True <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> st <> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc | otherwise = depth d $ prettySe (decD d) startPrec ((n, True):bnd) sc where st = case s of Static -> text "[static]" <> space _ -> empty prettySe d p bnd (PPi (Constraint _ _) n _ ty sc) = depth d . bracket p startPrec $ prettySe (decD d) (startPrec + 1) bnd ty <+> text "=>" </> prettySe (decD d) startPrec ((n, True):bnd) sc prettySe d p bnd (PPi (TacImp _ _ (PTactics [ProofSearch _ _ _ _ _ _])) n _ ty sc) = lbrace <> kwd "auto" <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc prettySe d p bnd (PPi (TacImp _ _ s) n _ ty sc) = depth d . bracket p startPrec $ lbrace <> kwd "default" <+> prettySe (decD d) (funcAppPrec + 1) bnd s <+> pretty n <+> colon <+> prettySe (decD d) startPrec bnd ty <> rbrace <+> text "->" </> prettySe (decD d) startPrec ((n, True):bnd) sc -- This case preserves the behavior of the former constructor PEq. -- It should be removed if feasible when the pretty-printing of infix -- operators in general is improved. prettySe d p bnd (PApp _ (PRef _ _ n) [lt, rt, l, r]) | n == eqTy, ppopt_impl ppo = depth d . bracket p eqPrec $ enclose lparen rparen eq <+> align (group (vsep (map (prettyArgS (decD d) bnd) [lt, rt, l, r]))) | n == eqTy = depth d . bracket p eqPrec . align . group $ prettyTerm (getTm l) <+> eq <$> group (prettyTerm (getTm r)) where eq = annName eqTy (text "=") eqPrec = startPrec prettyTerm = prettySe (decD d) (eqPrec + 1) bnd prettySe d p bnd (PApp _ (PRef _ _ f) args) -- normal names, no explicit args | UN nm <- basename f , not (ppopt_impl ppo) && null (getShowArgs args) = prettyName True (ppopt_impl ppo) bnd f prettySe d p bnd (PAppBind _ (PRef _ _ f) []) | not (ppopt_impl ppo) = text "!" <> prettyName True (ppopt_impl ppo) bnd f prettySe d p bnd (PApp _ (PRef _ _ op) args) -- infix operators | UN nm <- basename op , not (tnull nm) && (not (ppopt_impl ppo)) && (not $ isAlpha (thead nm)) = case getShowArgs args of [] -> opName True [x] -> group (opName True <$> group (prettySe (decD d) startPrec bnd (getTm x))) [l,r] -> let precedence = maybe (startPrec - 1) prec f in depth d . bracket p precedence $ inFix (getTm l) (getTm r) (l@(PExp _ _ _ _) : r@(PExp _ _ _ _) : rest) -> depth d . bracket p funcAppPrec $ enclose lparen rparen (inFix (getTm l) (getTm r)) <+> align (group (vsep (map (prettyArgS d bnd) rest))) as -> opName True <+> align (vsep (map (prettyArgS d bnd) as)) where opName isPrefix = prettyName isPrefix (ppopt_impl ppo) bnd op f = getFixity (opStr op) left = case f of Nothing -> funcAppPrec + 1 Just (Infixl p') -> p' Just f' -> prec f' + 1 right = case f of Nothing -> funcAppPrec + 1 Just (Infixr p') -> p' Just f' -> prec f' + 1 inFix l r = align . group $ (prettySe (decD d) left bnd l <+> opName False) <$> group (prettySe (decD d) right bnd r) prettySe d p bnd (PApp _ hd@(PRef fc _ f) [tm]) -- symbols, like 'foo | PConstant NoFC (Idris.Core.TT.Str str) <- getTm tm, f == sUN "Symbol_" = annotate (AnnType ("'" ++ str) ("The symbol " ++ str)) $ char '\'' <> prettySe (decD d) startPrec bnd (PRef fc [] (sUN str)) prettySe d p bnd (PApp _ f as) = -- Normal prefix applications let args = getShowArgs as fp = prettySe (decD d) (startPrec + 1) bnd f shownArgs = if ppopt_impl ppo then as else args in depth d . bracket p funcAppPrec . group $ if null shownArgs then fp else fp <+> align (vsep (map (prettyArgS d bnd) shownArgs)) prettySe d p bnd (PCase _ scr cases) = align $ kwd "case" <+> prettySe (decD d) startPrec bnd scr <+> kwd "of" <$> depth d (indent 2 (vsep (map ppcase cases))) where ppcase (l, r) = let prettyCase = prettySe (decD d) startPrec ([(n, False) | n <- vars l] ++ bnd) in nest nestingSize $ prettyCase l <+> text "=>" <+> prettyCase r -- Warning: this is a bit of a hack. At this stage, we don't have the -- global context, so we can't determine which names are constructors, -- which are types, and which are pattern variables on the LHS of the -- case pattern. We use the heuristic that names without a namespace -- are patvars, because right now case blocks in PTerms are always -- delaborated from TT before being sent to the pretty-printer. If they -- start getting printed directly, THIS WILL BREAK. -- Potential solution: add a list of known patvars to the cases in -- PCase, and have the delaborator fill it out, kind of like the pun -- disambiguation on PDPair. vars tm = filter noNS (allNamesIn tm) noNS (NS _ _) = False noNS _ = True prettySe d p bnd (PIfThenElse _ c t f) = depth d . bracket p funcAppPrec . group . align . hang 2 . vsep $ [ kwd "if" <+> prettySe (decD d) startPrec bnd c , kwd "then" <+> prettySe (decD d) startPrec bnd t , kwd "else" <+> prettySe (decD d) startPrec bnd f ] prettySe d p bnd (PHidden tm) = text "." <> prettySe (decD d) funcAppPrec bnd tm prettySe d p bnd (PResolveTC _) = kwd "%instance" prettySe d p bnd (PTrue _ IsType) = annName unitTy $ text "()" prettySe d p bnd (PTrue _ IsTerm) = annName unitCon $ text "()" prettySe d p bnd (PTrue _ TypeOrTerm) = text "()" prettySe d p bnd (PRewrite _ l r _) = depth d . bracket p startPrec $ text "rewrite" <+> prettySe (decD d) (startPrec + 1) bnd l <+> text "in" <+> prettySe (decD d) startPrec bnd r prettySe d p bnd (PTyped l r) = lparen <> prettySe (decD d) startPrec bnd l <+> colon <+> prettySe (decD d) startPrec bnd r <> rparen prettySe d p bnd pair@(PPair _ _ pun _ _) -- flatten tuples to the right, like parser | Just elts <- pairElts pair = depth d . enclose (ann lparen) (ann rparen) . align . group . vsep . punctuate (ann comma) $ map (prettySe (decD d) startPrec bnd) elts where ann = case pun of TypeOrTerm -> id IsType -> annName pairTy IsTerm -> annName pairCon prettySe d p bnd (PDPair _ _ pun l t r) = depth d $ annotated lparen <> left <+> annotated (text "**") <+> prettySe (decD d) startPrec (addBinding bnd) r <> annotated rparen where annotated = case pun of IsType -> annName sigmaTy IsTerm -> annName sigmaCon TypeOrTerm -> id (left, addBinding) = case (l, pun) of (PRef _ _ n, IsType) -> (bindingOf n False <+> text ":" <+> prettySe (decD d) startPrec bnd t, ((n, False) :)) _ -> (prettySe (decD d) startPrec bnd l, id) prettySe d p bnd (PAlternative ns a as) = lparen <> text "|" <> prettyAs <> text "|" <> rparen where prettyAs = foldr (\l -> \r -> l <+> text "," <+> r) empty $ map (depth d . prettySe (decD d) startPrec bnd) as prettySe d p bnd (PType _) = annotate (AnnType "Type" "The type of types") $ text "Type" prettySe d p bnd (PUniverse u) = annotate (AnnType (show u) "The type of unique types") $ text (show u) prettySe d p bnd (PConstant _ c) = annotate (AnnConst c) (text (show c)) -- XXX: add pretty for tactics prettySe d p bnd (PProof ts) = kwd "proof" <+> lbrace <> ellipsis <> rbrace prettySe d p bnd (PTactics ts) = kwd "tactics" <+> lbrace <> ellipsis <> rbrace prettySe d p bnd (PMetavar _ n) = annotate (AnnName n (Just MetavarOutput) Nothing Nothing) $ text "?" <> pretty n prettySe d p bnd (PReturn f) = kwd "return" prettySe d p bnd PImpossible = kwd "impossible" prettySe d p bnd Placeholder = text "_" prettySe d p bnd (PDoBlock dos) = bracket p startPrec $ kwd "do" <+> align (vsep (map (group . align . hang 2) (ppdo bnd dos))) where ppdo bnd (DoExp _ tm:dos) = prettySe (decD d) startPrec bnd tm : ppdo bnd dos ppdo bnd (DoBind _ bn _ tm : dos) = (prettyBindingOf bn False <+> text "<-" <+> group (align (hang 2 (prettySe (decD d) startPrec bnd tm)))) : ppdo ((bn, False):bnd) dos ppdo bnd (DoBindP _ _ _ _ : dos) = -- ok because never made by delab text "no pretty printer for pattern-matching do binding" : ppdo bnd dos ppdo bnd (DoLet _ ln _ ty v : dos) = (kwd "let" <+> prettyBindingOf ln False <+> (if ty /= Placeholder then colon <+> prettySe (decD d) startPrec bnd ty <+> text "=" else text "=") <+> group (align (hang 2 (prettySe (decD d) startPrec bnd v)))) : ppdo ((ln, False):bnd) dos ppdo bnd (DoLetP _ _ _ : dos) = -- ok because never made by delab text "no pretty printer for pattern-matching do binding" : ppdo bnd dos ppdo _ [] = [] prettySe d p bnd (PCoerced t) = prettySe d p bnd t prettySe d p bnd (PElabError s) = pretty s -- Quasiquote pprinting ignores bound vars prettySe d p bnd (PQuasiquote t Nothing) = text "`(" <> prettySe (decD d) p [] t <> text ")" prettySe d p bnd (PQuasiquote t (Just g)) = text "`(" <> prettySe (decD d) p [] t <+> colon <+> prettySe (decD d) p [] g <> text ")" prettySe d p bnd (PUnquote t) = text "~" <> prettySe (decD d) p bnd t prettySe d p bnd (PQuoteName n res _) = text start <> prettyName True (ppopt_impl ppo) bnd n <> text end where start = if res then "`{" else "`{{" end = if res then "}" else "}}" prettySe d p bnd (PRunElab _ tm _) = bracket p funcAppPrec . group . align . hang 2 $ text "%runElab" <$> prettySe (decD d) funcAppPrec bnd tm prettySe d p bnd (PConstSugar fc tm) = prettySe d p bnd tm -- should never occur, but harmless prettySe d p bnd _ = text "missing pretty-printer for term" prettyBindingOf :: Name -> Bool -> Doc OutputAnnotation prettyBindingOf n imp = annotate (AnnBoundName n imp) (text (display n)) where display (UN n) = T.unpack n display (MN _ n) = T.unpack n -- If a namespace is specified on a binding form, we'd better show it regardless of the implicits settings display (NS n ns) = (concat . intersperse "." . map T.unpack . reverse) ns ++ "." ++ display n display n = show n prettyArgS d bnd (PImp _ _ _ n tm) = prettyArgSi d bnd (n, tm) prettyArgS d bnd (PExp _ _ _ tm) = prettyArgSe d bnd tm prettyArgS d bnd (PConstraint _ _ _ tm) = prettyArgSc d bnd tm prettyArgS d bnd (PTacImplicit _ _ n _ tm) = prettyArgSti d bnd (n, tm) prettyArgSe d bnd arg = prettySe d (funcAppPrec + 1) bnd arg prettyArgSi d bnd (n, val) = lbrace <> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace prettyArgSc d bnd val = lbrace <> lbrace <> prettySe (decD d) startPrec bnd val <> rbrace <> rbrace prettyArgSti d bnd (n, val) = lbrace <> kwd "auto" <+> pretty n <+> text "=" <+> prettySe (decD d) startPrec bnd val <> rbrace annName :: Name -> Doc OutputAnnotation -> Doc OutputAnnotation annName n = annotate (AnnName n Nothing Nothing Nothing) opStr :: Name -> String opStr (NS n _) = opStr n opStr (UN n) = T.unpack n slist' :: Maybe Int -> Int -> [(Name, Bool)] -> PTerm -> Maybe [Doc OutputAnnotation] slist' (Just d) _ _ _ | d <= 0 = Nothing slist' d _ _ e | containsHole e = Nothing slist' d p bnd (PApp _ (PRef _ _ nil) _) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' d p bnd (PRef _ _ nil) | not (ppopt_impl ppo) && nsroot nil == sUN "Nil" = Just [] slist' d p bnd (PApp _ (PRef _ _ cons) args) | nsroot cons == sUN "::", (PExp {getTm=tl}):(PExp {getTm=hd}):imps <- reverse args, all isImp imps, Just tl' <- slist' (decD d) p bnd tl = Just (prettySe d startPrec bnd hd : tl') where isImp (PImp {}) = True isImp _ = False slist' _ _ _ tm = Nothing slist d p bnd e | Just es <- slist' d p bnd e = Just $ case es of [] -> annotate (AnnData "" "") $ text "[]" [x] -> enclose left right . group $ x xs -> enclose left right . align . group . vsep . punctuate comma $ xs where left = (annotate (AnnData "" "") (text "[")) right = (annotate (AnnData "" "") (text "]")) comma = (annotate (AnnData "" "") (text ",")) slist _ _ _ _ = Nothing pairElts :: PTerm -> Maybe [PTerm] pairElts (PPair _ _ _ x y) | Just elts <- pairElts y = Just (x:elts) | otherwise = Just [x, y] pairElts _ = Nothing natns = "Prelude.Nat." snat :: PPOption -> Maybe Int -> Int -> PTerm -> Maybe Integer snat ppo d p e | ppopt_desugarnats ppo = Nothing | otherwise = snat' d p e where snat' :: Maybe Int -> Int -> PTerm -> Maybe Integer snat' (Just x) _ _ | x <= 0 = Nothing snat' d p (PRef _ _ z) | show z == (natns++"Z") || show z == "Z" = Just 0 snat' d p (PApp _ s [PExp {getTm=n}]) | show s == (natns++"S") || show s == "S", Just n' <- snat' (decD d) p n = Just $ 1 + n' snat' _ _ _ = Nothing bracket outer inner doc | outer > inner = lparen <> doc <> rparen | otherwise = doc ellipsis = text "..." depth Nothing = id depth (Just d) = if d <= 0 then const (ellipsis) else id decD = fmap (\x -> x - 1) kwd = annotate AnnKeyword . text fixities :: M.Map String Fixity fixities = M.fromList [(s, f) | (Fix f s) <- infixes] getFixity :: String -> Maybe Fixity getFixity = flip M.lookup fixities -- | Strip away namespace information basename :: Name -> Name basename (NS n _) = basename n basename n = n -- | Determine whether a name was the one inserted for a hole or -- guess by the delaborator isHoleName :: Name -> Bool isHoleName (UN n) = n == T.pack "[__]" isHoleName _ = False -- | Check whether a PTerm has been delaborated from a Term containing a Hole or Guess containsHole :: PTerm -> Bool containsHole pterm = or [isHoleName n | PRef _ _ n <- take 1000 $ universe pterm] -- | Pretty-printer helper for names that attaches the correct annotations prettyName :: Bool -- ^^ whether the name should be parenthesised if it is an infix operator -> Bool -- ^^ whether to show namespaces -> [(Name, Bool)] -- ^^ the current bound variables and whether they are implicit -> Name -- ^^ the name to pprint -> Doc OutputAnnotation prettyName infixParen showNS bnd n | (MN _ s) <- n, isPrefixOf "_" $ T.unpack s = text "_" | (UN n') <- n, T.unpack n' == "_" = text "_" | Just imp <- lookup n bnd = annotate (AnnBoundName n imp) fullName | otherwise = annotate (AnnName n Nothing Nothing Nothing) fullName where fullName = text nameSpace <> parenthesise (text (baseName n)) baseName (UN n) = T.unpack n baseName (NS n ns) = baseName n baseName (MN i s) = T.unpack s baseName other = show other nameSpace = case n of (NS n' ns) -> if showNS then (concatMap (++ ".") . map T.unpack . reverse) ns else "" _ -> "" isInfix = case baseName n of "" -> False (c : _) -> not (isAlpha c) parenthesise = if isInfix && infixParen then enclose lparen rparen else id showCImp :: PPOption -> PClause -> Doc OutputAnnotation showCImp ppo (PClause _ n l ws r w) = prettyImp ppo l <+> showWs ws <+> text "=" <+> prettyImp ppo r <+> text "where" <+> text (show w) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showCImp ppo (PWith _ n l ws r pn w) = prettyImp ppo l <+> showWs ws <+> text "with" <+> prettyImp ppo r <+> braces (text (show w)) where showWs [] = empty showWs (x : xs) = text "|" <+> prettyImp ppo x <+> showWs xs showDImp :: PPOption -> PData -> Doc OutputAnnotation showDImp ppo (PDatadecl n nfc ty cons) = text "data" <+> text (show n) <+> colon <+> prettyImp ppo ty <+> text "where" <$> (indent 2 $ vsep (map (\ (_, _, n, _, t, _, _) -> pipe <+> prettyName True False [] n <+> colon <+> prettyImp ppo t) cons)) showDecls :: PPOption -> [PDecl] -> Doc OutputAnnotation showDecls o ds = vsep (map (showDeclImp o) ds) showDeclImp _ (PFix _ f ops) = text (show f) <+> cat (punctuate (text ",") (map text ops)) showDeclImp o (PTy _ _ _ _ _ n _ t) = text "tydecl" <+> text (showCG n) <+> colon <+> prettyImp o t showDeclImp o (PClauses _ _ n cs) = text "pat" <+> text (showCG n) <+> text "\t" <+> indent 2 (vsep (map (showCImp o) cs)) showDeclImp o (PData _ _ _ _ _ d) = showDImp o { ppopt_impl = True } d showDeclImp o (PParams _ ns ps) = text "params" <+> braces (text (show ns) <> line <> showDecls o ps <> line) showDeclImp o (PNamespace n fc ps) = text "namespace" <+> text n <> braces (line <> showDecls o ps <> line) showDeclImp _ (PSyntax _ syn) = text "syntax" <+> text (show syn) showDeclImp o (PClass _ _ _ cs n _ ps _ _ ds _ _) = text "class" <+> text (show cs) <+> text (show n) <+> text (show ps) <> line <> showDecls o ds showDeclImp o (PInstance _ _ _ _ cs n _ _ t _ ds) = text "instance" <+> text (show cs) <+> text (show n) <+> prettyImp o t <> line <> showDecls o ds showDeclImp _ _ = text "..." -- showDeclImp (PImport o) = "import " ++ o getImps :: [PArg] -> [(Name, PTerm)] getImps [] = [] getImps (PImp _ _ _ n tm : xs) = (n, tm) : getImps xs getImps (_ : xs) = getImps xs getExps :: [PArg] -> [PTerm] getExps [] = [] getExps (PExp _ _ _ tm : xs) = tm : getExps xs getExps (_ : xs) = getExps xs getShowArgs :: [PArg] -> [PArg] getShowArgs [] = [] getShowArgs (e@(PExp _ _ _ tm) : xs) = e : getShowArgs xs getShowArgs (e : xs) | AlwaysShow `elem` argopts e = e : getShowArgs xs | PImp _ _ _ _ tm <- e , containsHole tm = e : getShowArgs xs getShowArgs (_ : xs) = getShowArgs xs getConsts :: [PArg] -> [PTerm] getConsts [] = [] getConsts (PConstraint _ _ _ tm : xs) = tm : getConsts xs getConsts (_ : xs) = getConsts xs getAll :: [PArg] -> [PTerm] getAll = map getTm -- | Show Idris name showName :: Maybe IState -- ^^ the Idris state, for information about names and colours -> [(Name, Bool)] -- ^^ the bound variables and whether they're implicit -> PPOption -- ^^ pretty printing options -> Bool -- ^^ whether to colourise -> Name -- ^^ the term to show -> String showName ist bnd ppo colour n = case ist of Just i -> if colour then colourise n (idris_colourTheme i) else showbasic n Nothing -> showbasic n where name = if ppopt_impl ppo then show n else showbasic n showbasic n@(UN _) = showCG n showbasic (MN i s) = str s showbasic (NS n s) = showSep "." (map str (reverse s)) ++ "." ++ showbasic n showbasic (SN s) = show s fst3 (x, _, _) = x colourise n t = let ctxt' = fmap tt_ctxt ist in case ctxt' of Nothing -> name Just ctxt | Just impl <- lookup n bnd -> if impl then colouriseImplicit t name else colouriseBound t name | isDConName n ctxt -> colouriseData t name | isFnName n ctxt -> colouriseFun t name | isTConName n ctxt -> colouriseType t name -- The assumption is that if a name is not bound and does not exist in the -- global context, then we're somewhere in which implicit info has been lost -- (like error messages). Thus, unknown vars are colourised as implicits. | otherwise -> colouriseImplicit t name showTm :: IState -- ^^ the Idris state, for information about identifiers and colours -> PTerm -- ^^ the term to show -> String showTm ist = displayDecorated (consoleDecorate ist) . renderPretty 0.8 100000 . prettyImp (ppOptionIst ist) -- | Show a term with implicits, no colours showTmImpls :: PTerm -> String showTmImpls = flip (displayS . renderCompact . prettyImp verbosePPOption) "" -- | Show a term with specific options showTmOpts :: PPOption -> PTerm -> String showTmOpts opt = flip (displayS . renderPretty 1.0 10000000 . prettyImp opt) "" instance Sized PTerm where size (PQuote rawTerm) = size rawTerm size (PRef fc _ name) = size name size (PLam fc name _ ty bdy) = 1 + size ty + size bdy size (PPi plicity name fc ty bdy) = 1 + size ty + size fc + size bdy size (PLet fc name nfc ty def bdy) = 1 + size ty + size def + size bdy size (PTyped trm ty) = 1 + size trm + size ty size (PApp fc name args) = 1 + size args size (PAppBind fc name args) = 1 + size args size (PCase fc trm bdy) = 1 + size trm + size bdy size (PIfThenElse fc c t f) = 1 + sum (map size [c, t, f]) size (PTrue fc _) = 1 size (PResolveTC fc) = 1 size (PRewrite fc left right _) = 1 + size left + size right size (PPair fc _ _ left right) = 1 + size left + size right size (PDPair fs _ _ left ty right) = 1 + size left + size ty + size right size (PAlternative _ a alts) = 1 + size alts size (PHidden hidden) = size hidden size (PUnifyLog tm) = size tm size (PDisamb _ tm) = size tm size (PNoImplicits tm) = size tm size (PType _) = 1 size (PUniverse _) = 1 size (PConstant fc const) = 1 + size fc + size const size Placeholder = 1 size (PDoBlock dos) = 1 + size dos size (PIdiom fc term) = 1 + size term size (PReturn fc) = 1 size (PMetavar _ name) = 1 size (PProof tactics) = size tactics size (PElabError err) = size err size PImpossible = 1 size _ = 0 getPArity :: PTerm -> Int getPArity (PPi _ _ _ _ sc) = 1 + getPArity sc getPArity _ = 0 -- Return all names, free or globally bound, in the given term. allNamesIn :: PTerm -> [Name] allNamesIn tm = nub $ ni 0 [] tm where -- TODO THINK added niTacImp, but is it right? ni 0 env (PRef _ _ n) | not (n `elem` env) = [n] ni 0 env (PPatvar _ n) = [n] ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os) ni 0 env (PIfThenElse _ c t f) = ni 0 env c ++ ni 0 env t ++ ni 0 env f ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PLet _ n _ ty val sc) = ni 0 env ty ++ ni 0 env val ++ ni 0 (n:env) sc ni 0 env (PHidden tm) = ni 0 env tm ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r ni 0 env (PDPair _ _ _ (PRef _ _ n) Placeholder r) = n : ni 0 env r ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r ni 0 env (PAlternative ns a ls) = concatMap (ni 0 env) ls ni 0 env (PUnifyLog tm) = ni 0 env tm ni 0 env (PDisamb _ tm) = ni 0 env tm ni 0 env (PNoImplicits tm) = ni 0 env tm ni i env (PQuasiquote tm ty) = ni (i+1) env tm ++ maybe [] (ni i env) ty ni i env (PUnquote tm) = ni (i - 1) env tm ni i env tm = concatMap (ni i env) (children tm) niTacImp i env (TacImp _ _ scr) = ni i env scr niTacImp _ _ _ = [] -- Return all names defined in binders in the given term boundNamesIn :: PTerm -> [Name] boundNamesIn tm = S.toList (ni 0 S.empty tm) where -- TODO THINK Added niTacImp, but is it right? ni :: Int -> S.Set Name -> PTerm -> S.Set Name ni 0 set (PApp _ f as) = niTms 0 (ni 0 set f) (map getTm as) ni 0 set (PAppBind _ f as) = niTms 0 (ni 0 set f) (map getTm as) ni 0 set (PCase _ c os) = niTms 0 (ni 0 set c) (map snd os) ni 0 set (PIfThenElse _ c t f) = niTms 0 set [c, t, f] ni 0 set (PLam fc n _ ty sc) = S.insert n $ ni 0 (ni 0 set ty) sc ni 0 set (PLet fc n nfc ty val sc) = S.insert n $ ni 0 (ni 0 (ni 0 set ty) val) sc ni 0 set (PPi p n _ ty sc) = niTacImp 0 (S.insert n $ ni 0 (ni 0 set ty) sc) p ni 0 set (PRewrite _ l r _) = ni 0 (ni 0 set l) r ni 0 set (PTyped l r) = ni 0 (ni 0 set l) r ni 0 set (PPair _ _ _ l r) = ni 0 (ni 0 set l) r ni 0 set (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 (ni 0 set t) r ni 0 set (PDPair _ _ _ l t r) = ni 0 (ni 0 (ni 0 set l) t) r ni 0 set (PAlternative ns a as) = niTms 0 set as ni 0 set (PHidden tm) = ni 0 set tm ni 0 set (PUnifyLog tm) = ni 0 set tm ni 0 set (PDisamb _ tm) = ni 0 set tm ni 0 set (PNoImplicits tm) = ni 0 set tm ni i set (PQuasiquote tm ty) = ni (i + 1) set tm `S.union` maybe S.empty (ni i set) ty ni i set (PUnquote tm) = ni (i - 1) set tm ni i set tm = foldr S.union set (map (ni i set) (children tm)) niTms :: Int -> S.Set Name -> [PTerm] -> S.Set Name niTms i set [] = set niTms i set (x : xs) = niTms i (ni i set x) xs niTacImp i set (TacImp _ _ scr) = ni i set scr niTacImp i set _ = set -- Return names which are valid implicits in the given term (type). implicitNamesIn :: [Name] -> IState -> PTerm -> [Name] implicitNamesIn uvars ist tm = nub $ ni 0 [] tm where ni 0 env (PRef _ _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` uvars then [n] else [] ni 0 env (PApp _ f@(PRef _ _ n) as) | n `elem` uvars = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) | otherwise = concatMap (ni 0 env) (map getTm as) ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PCase _ c os) = ni 0 env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni 0 env) (map snd os)) \\ nub (concatMap (ni 0 env) (map fst os))) ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f] ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PPi p n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as ni 0 env (PHidden tm) = ni 0 env tm ni 0 env (PUnifyLog tm) = ni 0 env tm ni 0 env (PDisamb _ tm) = ni 0 env tm ni 0 env (PNoImplicits tm) = ni 0 env tm ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty ni i env (PUnquote tm) = ni (i - 1) env tm ni i env tm = concatMap (ni i env) (children tm) -- Return names which are free in the given term. namesIn :: [(Name, PTerm)] -> IState -> PTerm -> [Name] namesIn uvars ist tm = nub $ ni 0 [] tm where ni 0 env (PRef _ _ n) | not (n `elem` env) = case lookupTy n (tt_ctxt ist) of [] -> [n] _ -> if n `elem` (map fst uvars) then [n] else [] ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PCase _ c os) = ni 0 env c ++ -- names in 'os', not counting the names bound in the cases (nub (concatMap (ni 0 env) (map snd os)) \\ nub (concatMap (ni 0 env) (map fst os))) ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f] ni 0 env (PLam fc n nfc ty sc) = ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as ni 0 env (PHidden tm) = ni 0 env tm ni 0 env (PUnifyLog tm) = ni 0 env tm ni 0 env (PDisamb _ tm) = ni 0 env tm ni 0 env (PNoImplicits tm) = ni 0 env tm ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty ni i env (PUnquote tm) = ni (i - 1) env tm ni i env tm = concatMap (ni i env) (children tm) niTacImp i env (TacImp _ _ scr) = ni i env scr niTacImp _ _ _ = [] -- Return which of the given names are used in the given term. usedNamesIn :: [Name] -> IState -> PTerm -> [Name] usedNamesIn vars ist tm = nub $ ni 0 [] tm where -- TODO THINK added niTacImp, but is it right? ni 0 env (PRef _ _ n) | n `elem` vars && not (n `elem` env) = case lookupDefExact n (tt_ctxt ist) of Nothing -> [n] _ -> [] ni 0 env (PApp _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PAppBind _ f as) = ni 0 env f ++ concatMap (ni 0 env) (map getTm as) ni 0 env (PCase _ c os) = ni 0 env c ++ concatMap (ni 0 env) (map snd os) ni 0 env (PIfThenElse _ c t f) = concatMap (ni 0 env) [c, t, f] ni 0 env (PLam fc n _ ty sc) = ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PPi p n _ ty sc) = niTacImp 0 env p ++ ni 0 env ty ++ ni 0 (n:env) sc ni 0 env (PRewrite _ l r _) = ni 0 env l ++ ni 0 env r ni 0 env (PTyped l r) = ni 0 env l ++ ni 0 env r ni 0 env (PPair _ _ _ l r) = ni 0 env l ++ ni 0 env r ni 0 env (PDPair _ _ _ (PRef _ _ n) t r) = ni 0 env t ++ ni 0 (n:env) r ni 0 env (PDPair _ _ _ l t r) = ni 0 env l ++ ni 0 env t ++ ni 0 env r ni 0 env (PAlternative ns a as) = concatMap (ni 0 env) as ni 0 env (PHidden tm) = ni 0 env tm ni 0 env (PUnifyLog tm) = ni 0 env tm ni 0 env (PDisamb _ tm) = ni 0 env tm ni 0 env (PNoImplicits tm) = ni 0 env tm ni i env (PQuasiquote tm ty) = ni (i + 1) env tm ++ maybe [] (ni i env) ty ni i env (PUnquote tm) = ni (i - 1) env tm ni i env tm = concatMap (ni i env) (children tm) niTacImp i env (TacImp _ _ scr) = ni i env scr niTacImp _ _ _ = [] -- Return the list of inaccessible (= dotted) positions for a name. getErasureInfo :: IState -> Name -> [Int] getErasureInfo ist n = case lookupCtxtExact n (idris_optimisation ist) of Just (Optimise inacc detagg) -> map fst inacc Nothing -> []
MetaMemoryT/Idris-dev
src/Idris/AbsSyntaxTree.hs
Haskell
bsd-3-clause
103,703
module Yesod.Helpers.Yaml ( module Yesod.Helpers.Yaml , DefaultEnv(..) ) where import Prelude import Data.Yaml import Yesod import Data.Text (Text) import Data.Aeson (withObject) import qualified Data.Text as T import Data.Maybe (isJust) import Data.List (find) import Yesod.Default.Config (DefaultEnv(..)) import Yesod.Helpers.Aeson -- | check whether a string is in the list identified by a key string -- some special strings: -- __any__ will match any string -- -- example yaml like this -- Develpment: -- dangerous-op: foo bar -- simple-op: -- - foo -- - bar -- safe-op: __any__ checkInListYaml :: (Show config, MonadIO m, MonadLogger m) => FilePath -> config -- ^ config section: Develpment/Production/... -> Text -- ^ the key -> Text -- ^ the name looking for -> m Bool checkInListYaml fp c key name = do checkInListYaml' fp c key (== name) checkInListYaml' :: (Show config, MonadIO m, MonadLogger m) => FilePath -> config -- ^ config section: Develpment/Production/... -> Text -- ^ the key -> (Text -> Bool) -- ^ the name looking for -> m Bool checkInListYaml' fp c key chk_name = do result <- liftIO $ decodeFileEither fp case result of Left ex -> do $(logError) $ T.pack $ "failed to parse YAML file " ++ show fp ++ ": " ++ show ex return False Right v -> do case parseEither look_for_names v of Left err -> do $(logError) $ T.pack $ "YAML " ++ show fp ++ " contains invalid content: " ++ show err return False Right names -> return $ isJust $ find match names where look_for_names = withObject "section-mapping" $ \obj -> do obj .:? (T.pack $ show c) >>= maybe (return []) (\section -> do section .:? key >>= maybe (return []) (parseWordList' "words") ) match x = if x == "__any__" then True else chk_name x
yoo-e/yesod-helpers
Yesod/Helpers/Yaml.hs
Haskell
bsd-3-clause
2,512
module QueryArrow.Control.Monad.Logger.HSLogger where import Control.Monad.Logger import System.Log.FastLogger import System.Log.Logger import qualified Data.Text as T import Data.Text.Encoding instance MonadLogger IO where monadLoggerLog loc logsource loglevel msg = do let priority = case loglevel of LevelDebug -> DEBUG LevelInfo -> INFO LevelWarn -> WARNING LevelError -> ERROR LevelOther _ -> NOTICE logM (show logsource) priority (T.unpack (decodeUtf8 (fromLogStr (toLogStr msg)))) instance MonadLoggerIO IO where askLoggerIO = return monadLoggerLog
xu-hao/QueryArrow
log-adapter/src/QueryArrow/Control/Monad/Logger/HSLogger.hs
Haskell
bsd-3-clause
706
{-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} -- | Wiki page view. module HL.V.Wiki where import HL.V import HL.V.Code import HL.V.Template import Data.List (isPrefixOf) import Data.Text (unpack,pack) import Language.Haskell.HsColour.CSS (hscolour) import Prelude hiding (readFile) import Text.Pandoc.Definition import Text.Pandoc.Options import Text.Pandoc.Walk import Text.Pandoc.Writers.HTML -- | Wiki view. wikiV :: (Route App -> Text) -> Either Text (Text,Pandoc) -> FromSenza App wikiV urlr result = template ([WikiHomeR] ++ [WikiR n | Right (n,_) <- [result]]) (case result of Left{} -> "Wiki error!" Right (t,_) -> t) (\_ -> container (row (span12 [] (case result of Left err -> do h1 [] "Wiki page retrieval problem!" p [] (toHtml err) Right (t,pan) -> do h1 [] (toHtml t) writeHtml writeOptions (cleanup urlr pan))))) where cleanup url = highlightBlock . highlightInline . relativize url writeOptions = def { writerTableOfContents = True } -- | Make all wiki links use the wiki route. relativize :: (Route App -> Text) -> Pandoc -> Pandoc relativize url = walk links where links asis@(Link is (ref,t)) | isPrefixOf "http://" ref || isPrefixOf "https://" ref = asis | otherwise = Link is (unpack (url (WikiR (pack ref))),t) links x = x -- | Highlight code blocks and inline code samples with a decent -- Haskell syntax highlighter. highlightBlock :: Pandoc -> Pandoc highlightBlock = walk codes where codes (CodeBlock ("",["haskell"],[]) text) = RawBlock "html" (hscolour False text) codes x = x -- | Highlight code blocks and inline code samples with a decent -- Haskell syntax highlighter. highlightInline :: Pandoc -> Pandoc highlightInline = walk codes where codes (Code ("",["haskell"],[]) text) = RawInline "html" (preToCode (hscolour False text)) codes x = x
yogsototh/hl
src/HL/V/Wiki.hs
Haskell
bsd-3-clause
2,130
module Yesod.Helpers.Auth where import Prelude import Yesod import Yesod.Auth import Control.Monad.Catch (MonadThrow) import Control.Monad import qualified Data.Text as T yesodAuthIdDo :: (YesodAuth master, MonadIO m, MonadThrow m, MonadBaseControl IO m) => (AuthId master -> HandlerT master m a) -> HandlerT master m a yesodAuthIdDo f = do liftHandlerT maybeAuthId >>= maybe (permissionDeniedI $ (T.pack "Login Required")) return >>= f yesodAuthIdDoSub :: (YesodAuth master, MonadIO m, MonadThrow m, MonadBaseControl IO m) => (AuthId master -> HandlerT site (HandlerT master m) a) -> HandlerT site (HandlerT master m) a yesodAuthIdDoSub f = do (lift $ liftHandlerT maybeAuthId) >>= maybe (permissionDeniedI $ (T.pack "Login Required")) return >>= f yesodAuthEntityDo :: (YesodAuthPersist master, MonadIO m, MonadThrow m, MonadBaseControl IO m) => ((AuthId master, AuthEntity master) -> HandlerT master m a) -> HandlerT master m a yesodAuthEntityDo f = do user_id <- liftHandlerT maybeAuthId >>= maybe (permissionDeniedI $ (T.pack "Login Required")) return let get_user = #if MIN_VERSION_yesod_core(1, 4, 0) getAuthEntity #else runDB . get #endif user <- liftHandlerT (get_user user_id) >>= maybe (permissionDeniedI $ (T.pack "AuthEntity not found")) return f (user_id, user) yesodAuthEntityDoSub :: (YesodAuthPersist master, MonadIO m, MonadThrow m, MonadBaseControl IO m) => ((AuthId master, AuthEntity master) -> HandlerT site (HandlerT master m) a) -> HandlerT site (HandlerT master m) a yesodAuthEntityDoSub f = do let get_user = #if MIN_VERSION_yesod_core(1, 4, 0) getAuthEntity #else runDB . get #endif user_id <- lift (liftHandlerT maybeAuthId) >>= maybe (permissionDeniedI $ (T.pack "Login Required")) return user <- lift (liftHandlerT $ get_user user_id) >>= maybe (permissionDeniedI $ (T.pack "AuthEntity not found")) return f (user_id, user) -- | 用于实现一种简单的身份认证手段:使用 google email 作为用户标识 newtype GoogleEmail = GoogleEmail { unGoogleEmail :: T.Text } deriving (Show, Eq, PathPiece) -- | used to implement 'authenticate' method of 'YesodAuth' class authenticateGeImpl :: (MonadHandler m, AuthId master ~ GoogleEmail) => Creds master -> m (AuthenticationResult master) authenticateGeImpl creds = do setSession "authed_gmail" raw_email return $ Authenticated $ GoogleEmail raw_email where raw_email = credsIdent creds -- | used to implement 'manybeAuthId' method of 'YesodAuth' class maybeAuthIdGeImpl :: MonadHandler m => m (Maybe GoogleEmail) maybeAuthIdGeImpl = do liftM (fmap GoogleEmail) $ lookupSession "authed_gmail" eitherGetLoggedInUserId :: YesodAuth master => HandlerT master IO (Either AuthResult (AuthId master)) eitherGetLoggedInUserId = do m_uid <- maybeAuthId case m_uid of Nothing -> return $ Left AuthenticationRequired Just uid -> return $ Right uid
yoo-e/yesod-helpers
Yesod/Helpers/Auth.hs
Haskell
bsd-3-clause
3,357
module Main where import Language.ECMAScript3.Syntax import Language.ECMAScript3.Syntax.Annotations import Language.ECMAScript3.Parser import Language.ECMAScript3.PrettyPrint import Data.Set (Set) import qualified Data.Set as Set import Data.Data (Data) --import System.IO import Data.Generics.Uniplate.Data import Data.List main :: IO () main = getContents >>= parseJavaScript >>= (print . apiAnalysis) parseJavaScript :: String -> IO (JavaScript SourcePos) parseJavaScript source = case parse parseScript "stdin" source of Left perr -> fail $ show perr Right js -> return js data APIAnalysisResults = APIAnalysisResults {apiElements :: Set APIElement ,warnings :: [Warning]} instance Show APIAnalysisResults where show r = "The following API methods and fields are used: " ++ intercalate ", " (map show $ Set.toList $ apiElements r) ++ ".\n" ++ if null $ warnings r then "No warnings to report" else "Warning, the analysis results might not be sound: " ++ intercalate "\n" (map show $ warnings r) data APIElement = APIElement [String] deriving (Eq, Ord) data Warning = Warning SourcePos String instance Show APIElement where show (APIElement elems) = intercalate "." elems instance Show Warning where show (Warning pos msg) = show pos ++ ": " ++ msg topLevelAPIVars = ["window", "document", "XMLHttpRequest", "Object" ,"Function", "Array", "String", "Boolean", "Number", "Date" ,"RegExp", "Error", "EvalError", "RangeError" ,"ReferenceError", "SyntaxError", "TypeError", "URIError" ,"Math", "JSON"] -- | The API analysis function. Returns a 'Set' of API -- functions/fields and a list of warnings apiAnalysis :: JavaScript SourcePos -> APIAnalysisResults apiAnalysis script = APIAnalysisResults (Set.fromList $ genApiElements script) (genWarnings script) genApiElements :: JavaScript SourcePos -> [APIElement] genApiElements = map toAPIElement . filter isAnAPIAccessor . universeBi where isAnAPIAccessor :: Expression SourcePos -> Bool isAnAPIAccessor e = case e of DotRef _ o _ -> isAnAPIAccessor o BracketRef _ o _ -> isAnAPIAccessor o VarRef _ (Id _ v) -> v `elem` topLevelAPIVars _ -> False toAPIElement e = case e of DotRef _ o (Id _ fld) -> toAPIElement o `addElement` fld BracketRef _ o (StringLit _ s) -> toAPIElement o `addElement` s VarRef _ (Id _ vn) -> APIElement [vn] _ -> APIElement [] addElement :: APIElement -> String -> APIElement addElement (APIElement elems) elem = APIElement (elems ++ [elem]) genWarnings :: JavaScript SourcePos -> [Warning] genWarnings script = concatMap warnAliased topLevelAPIVars ++warnEvalUsed where warnAliased varName = [Warning (getAnnotation e) $ varName ++ " is aliased (in " ++ renderExpression e ++ ")" |e@(AssignExpr _ _ _ (VarRef _ (Id _ vn))) <- universeBi script, vn == varName]++ [Warning (getAnnotation vd) $ varName ++ " is aliased (in " ++ show vd ++ ")" |vd@(VarDecl _ _ (Just (VarRef _ (Id _ vn)))) <- universeBi script, vn == varName] warnEvalUsed = [Warning (getAnnotation e) "Eval used" |e@(CallExpr _ f _) <- universeBi script, isEvalRef f] isEvalRef e = case e of VarRef _ (Id _ "eval") -> True DotRef _ (VarRef _ (Id _ "window")) (Id _ "eval") -> True _ -> False -- | returns true if inside the expression there is a reference to the -- variable usesVariable :: (Data a) => String -> Expression a -> Bool usesVariable v e = and [v' == v | VarRef _ (Id _ v') <- universe e]
achudnov/jsapia
Main.hs
Haskell
bsd-3-clause
4,038
module Main where import MenuIO main :: IO () main = menu []
arthurmgo/regex-ftc
app/Main.hs
Haskell
bsd-3-clause
63
module OutputDirectory (outdir) where outdir = "_data"
pnlbwh/test-tensormasking
config-output-paths/OutputDirectory.hs
Haskell
bsd-3-clause
58
{-# LANGUAGE DeriveDataTypeable #-} module WFF where import qualified Data.Map as M import Test.QuickCheck hiding ((.||.), (==>), (.&&.)) import qualified Data.Set as S import Data.Data import Data.Generics.Uniplate.Data import Data.List hiding (lookup, union) import Prelude hiding (lookup) import Control.Applicative hiding (empty) data WFF = Var String | And WFF WFF | Or WFF WFF | Not WFF | Impl WFF WFF | Eqv WFF WFF deriving (Data) instance Show WFF where show (Var s) = s show (And x y) = "("++(show x) ++ " && "++(show y)++")" show (Or x y) ="("++(show x) ++ " || "++(show y)++")" show (Not x) = "~"++(show x) show (Impl x y) = "("++(show x) ++ "=>" ++ (show y)++")" show (Eqv x y) = "("++(show x) ++ "=" ++ (show y) ++ ")" instance Arbitrary WFF where arbitrary = sized myArbitrary where myArbitrary 0 = do s <- oneof (map (return . show) [1..30]) return (Var s) myArbitrary n = oneof [ binary n And, binary n Or, binary n Impl, binary n Eqv, fmap Not (myArbitrary (n-1)), var ] where var = do s <- oneof (map (return . show) [1..30]) return (Var s) binary n f = do s <- myArbitrary (div n 2) t <- myArbitrary (div n 2) return (f s t) t `xor` t' = (t .|| t') .&& (n (t .&& t')) t .&& t' = And t t' t .|| t' = Or t t' t ==> t' = Impl t t' t <=> t' = Eqv t t' n t = Not t v s = Var s variables wff = [v | Var v <- universe wff] fromJust (Just x) = x fromJust _ = undefined eval :: M.Map String Bool -> WFF -> Bool eval m (Var s) = fromJust $ M.lookup s m eval m (And x y) = (&&) (eval m x) (eval m y) eval m (Or x y) = (||) (eval m x) (eval m y) eval m (Not y) = not (eval m y) eval m (Impl x y) = (not (eval m x)) || (eval m y) eval m (Eqv x y) = (==) (eval m x) (eval m y)
patrikja/GRACeFUL
ConstraintModelling/WFF.hs
Haskell
bsd-3-clause
2,457
#!/usr/bin/env runhaskell {-# LANGUAGE BangPatterns #-} {-| The Sphere Online Judge is a collection of problems. One problem, problem 450, came up on the mailing list as a sensible benchmark for fast integer parsing. -} {- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - https://www.spoj.pl/problems/INTEST/ Slow IO? http://www.nabble.com/Slow-IO--td25210251.html - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -} import Data.List import Prelude hiding (drop, take) import System.IO (stdin, stdout, stderr, Handle, putStrLn) import Control.Monad import Data.ByteString hiding (putStrLn, foldl') import Data.ByteString.Nums.Careless main = do (n, k) <- breakByte 0x20 `fmap` hGetLine stdin count <- show `fmap` obvious (int n) (int k) putStrLn count obvious n k = sum `fmap` sequence (numbers n stdin) where sum = foldl' (check k) 0 numbers :: Int -> Handle -> [IO Int] numbers n h = const (int `fmap` hGetLine h) `fmap` [1..n] check :: Int -> Int -> Int -> Int check k acc n | n `mod` k == 0 = acc + 1 | otherwise = acc
solidsnack/bytestring-nums
SPOJObvious.hs
Haskell
bsd-3-clause
1,328
squareM = #x -> `(,x * ,x) -- `#` indicates macro-lambda unittest "squareM" [ (squareM 3, 9), (let a = 3 in squareM a, 9), ] a = "a" unittest "macro_expand" [ (macro_expand {squareM 3}, (*) 3 3), (macro_expand {(squareM 3) + 1}, (+) ((*) 3 3) 1), (macro_expand {squareM a}, (*) a a), (macro_expand {let a = 1 in squareM a}, (\a.(*) a a) 1), (macro_expand {let a = 1 in squareM (a+1)}, (\a.(*) ((+) a 1) ((+) a 1)) 1), ] evalN 0 ((squareM 3) + 1) evalN 1 ((squareM 3) + 1) evalN 2 ((squareM 3) + 1) evalN 3 ((squareM 3) + 1) evalN 4 ((squareM 3) + 1) -- (+) ((*) 3 3) 1 -- (+) ((3 *) 3) 1 -- (+) 9 1 -- (9 +) 1 -- 10 lazyevalN 0 ((squareM 3) + 1) lazyevalN 1 ((squareM 3) + 1) lazyevalN 2 ((squareM 3) + 1) lazyevalN 3 ((squareM 3) + 1) lazyevalN 4 ((squareM 3) + 1) -- (+) ((*) 3 3) 1 -- (+) ((*) 3 3) 1 -- (+) 9 1 -- (9 +) 1 -- 10
ocean0yohsuke/Simply-Typed-Lambda
Start/UnitTest/Macro.hs
Haskell
bsd-3-clause
926
import Control.Arrow ((***)) import Control.Monad (join) {-- snippet adler32 --} import Data.Char (ord) import Data.Bits (shiftL, (.&.), (.|.)) base = 65521 adler32 xs = helper 1 0 xs where helper a b (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base b' = (a' + b) `mod` base in helper a' b' xs helper a b _ = (b `shiftL` 16) .|. a {-- /snippet adler32 --} {-- snippet adler32_try2 --} adler32_try2 xs = helper (1,0) xs where helper (a,b) (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base b' = (a' + b) `mod` base in helper (a',b') xs helper (a,b) _ = (b `shiftL` 16) .|. a {-- /snippet adler32_try2 --} {-- snippet adler32_foldl --} adler32_foldl xs = let (a, b) = foldl step (1, 0) xs in (b `shiftL` 16) .|. a where step (a, b) x = let a' = a + (ord x .&. 0xff) in (a' `mod` base, (a' + b) `mod` base) {-- /snippet adler32_foldl --} adler32_golf = uncurry (flip ((.|.) . (`shiftL` 16))) . foldl f (1,0) where f (a,b) x = join (***) ((`mod` base) . (a + (ord x .&. 0xff) +)) (0,b)
binesiyu/ifl
examples/ch04/Adler32.hs
Haskell
mit
1,188
{-@ LIQUID "--no-termination" @-} module Lec02 where import Text.Printf (printf) import Debug.Trace (trace) incr :: Int -> Int incr x = x + 1 zincr :: Int -> Int zincr = \x -> x + 1 eleven = incr (10 + 2) -- sumList xs = case xs of -- [] -> 0 -- (x:xs) -> x + sumList xs sumList :: [Int] -> Int sumList [] = 0 sumList (x:xs) = x + sumList xs isOdd x = x `mod` 2 == 1 oddsBelow100 = myfilter isOdd [0..100] myfilter f [] = [] myfilter f (x:xs') = if f x then x : rest else rest where rest = myfilter f xs' neg :: (a -> Bool) -> (a -> Bool) neg f = \x -> not (f x) isEven = neg isOdd partition p xs = (myfilter p xs, myfilter (neg p) xs) sort [] = [] sort (x:xs) = sort ls ++ [x] ++ sort rs where ls = [ y | y <- xs, y < x ] rs = [ z | z <- xs, x <= z ] quiz = [x * 10 | x <- xs, x > 3] where xs = [0..5] data Expr = Number Double | Plus Expr Expr | Minus Expr Expr | Times Expr Expr deriving (Eq, Ord, Show) eval :: Expr -> Double eval e = case e of Number n -> n Plus e1 e2 -> eval e1 + eval e2 Minus e1 e2 -> eval e1 - eval e2 Times e1 e2 -> eval e1 * eval e2 ex0 :: Expr ex0 = Number 5 ex1 :: Expr ex1 = Plus ex0 (Number 7) ex2 :: Expr ex2 = Minus (Number 4) (Number 2) ex3 :: Expr ex3 = Times ex1 ex2 fact :: Int -> Int fact n = trace msg res where msg = printf "Fact n = %d res = %d\n" n res res = if n <= 0 then 0 else n * fact (n-1) {- -- fact :: Int -> Int let rec fact n = let res = if n <= 0 then 0 else n * fact (n-1) in let _ = Printf.printf "Fact n = %d res = %d\n" n res in res -} ----
ucsd-progsys/131-web
static/hs/lec-1-17-2018.hs
Haskell
mit
1,707
module Main where comb :: [([Char], [Char])] color = ["blue", "red", "green"] comb = [(x, y) | x <- color, y <- color, x < y]
momo9/seven-lang
haskell/src/combination.hs
Haskell
mit
125
{-# LANGUAGE DataKinds, PolyKinds, TypeOperators, TypeFamilies , TypeApplications #-} module DumpTypecheckedAst where import Data.Kind data Peano = Zero | Succ Peano type family Length (as :: [k]) :: Peano where Length (a : as) = Succ (Length as) Length '[] = Zero data T f (a :: k) = MkT (f a) type family F (a :: k) (f :: k -> Type) :: Type where F @Peano a f = T @Peano f a main = putStrLn "hello"
sdiehl/ghc
testsuite/tests/parser/should_compile/DumpTypecheckedAst.hs
Haskell
bsd-3-clause
431
-- | Settings are centralized, as much as possible, into this file. This -- includes database connection settings, static file locations, etc. -- In addition, you can configure a number of different aspects of Yesod -- by overriding methods in the Yesod typeclass. That instance is -- declared in the Foundation.hs file. module Settings where import Prelude import Text.Shakespeare.Text (st) import Language.Haskell.TH.Syntax import Database.Persist.Sqlite (SqliteConf) import Yesod.Default.Config import Yesod.Default.Util import Data.Text (Text) import Data.Yaml import Control.Applicative import Settings.Development import Data.Default (def) import Text.Hamlet -- | Which Persistent backend this site is using. type PersistConf = SqliteConf -- Static setting below. Changing these requires a recompile -- | The location of static files on your system. This is a file system -- path. The default value works properly with your scaffolded site. staticDir :: FilePath staticDir = "static" -- | The base URL for your static files. As you can see by the default -- value, this can simply be "static" appended to your application root. -- A powerful optimization can be serving static files from a separate -- domain name. This allows you to use a web server optimized for static -- files, more easily set expires and cache values, and avoid possibly -- costly transference of cookies on static files. For more information, -- please see: -- http://code.google.com/speed/page-speed/docs/request.html#ServeFromCookielessDomain -- -- If you change the resource pattern for StaticR in Foundation.hs, you will -- have to make a corresponding change here. -- -- To see how this value is used, see urlRenderOverride in Foundation.hs staticRoot :: AppConfig DefaultEnv x -> Text staticRoot conf = [st|#{appRoot conf}/lab/nom/static|] -- | Settings for 'widgetFile', such as which template languages to support and -- default Hamlet settings. -- -- For more information on modifying behavior, see: -- -- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile widgetFileSettings :: WidgetFileSettings widgetFileSettings = def { wfsHamletSettings = defaultHamletSettings { hamletNewlines = AlwaysNewlines } } -- The rest of this file contains settings which rarely need changing by a -- user. widgetFile :: String -> Q Exp widgetFile = (if development then widgetFileReload else widgetFileNoReload) widgetFileSettings data Extra = Extra { extraCopyright :: Text , extraAnalytics :: Maybe Text -- ^ Google Analytics } deriving Show parseExtra :: DefaultEnv -> Object -> Parser Extra parseExtra _ o = Extra <$> o .: "copyright" <*> o .:? "analytics"
SuetakeY/nomnichi_yesod
Settings.hs
Haskell
bsd-2-clause
2,742
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude , RecordWildCards , BangPatterns , NondecreasingIndentation , RankNTypes #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : GHC.IO.Handle.Internals -- Copyright : (c) The University of Glasgow, 1994-2001 -- License : see libraries/base/LICENSE -- -- Maintainer : libraries@haskell.org -- Stability : internal -- Portability : non-portable -- -- This module defines the basic operations on I\/O \"handles\". All -- of the operations defined here are independent of the underlying -- device. -- ----------------------------------------------------------------------------- module GHC.IO.Handle.Internals ( withHandle, withHandle', withHandle_, withHandle__', withHandle_', withAllHandles__, wantWritableHandle, wantReadableHandle, wantReadableHandle_, wantSeekableHandle, mkHandle, mkFileHandle, mkDuplexHandle, openTextEncoding, closeTextCodecs, initBufferState, dEFAULT_CHAR_BUFFER_SIZE, flushBuffer, flushWriteBuffer, flushCharReadBuffer, flushCharBuffer, flushByteReadBuffer, flushByteWriteBuffer, readTextDevice, writeCharBuffer, readTextDeviceNonBlocking, decodeByteBuf, augmentIOError, ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable, ioe_finalizedHandle, ioe_bufsiz, hClose_help, hLookAhead_, HandleFinalizer, handleFinalizer, debugIO, ) where import GHC.IO import GHC.IO.IOMode import GHC.IO.Encoding as Encoding import GHC.IO.Encoding.Types (CodeBuffer) import GHC.IO.Handle.Types import GHC.IO.Buffer import GHC.IO.BufferedIO (BufferedIO) import GHC.IO.Exception import GHC.IO.Device (IODevice, SeekMode(..)) import qualified GHC.IO.Device as IODevice import qualified GHC.IO.BufferedIO as Buffered import GHC.Conc.Sync import GHC.Real import GHC.Base import GHC.Exception import GHC.Num ( Num(..) ) import GHC.Show import GHC.IORef import GHC.MVar import Data.Typeable import Control.Monad import Data.Maybe import Foreign.Safe import System.Posix.Internals hiding (FD) import Foreign.C c_DEBUG_DUMP :: Bool c_DEBUG_DUMP = False -- --------------------------------------------------------------------------- -- Creating a new handle type HandleFinalizer = FilePath -> MVar Handle__ -> IO () newFileHandle :: FilePath -> Maybe HandleFinalizer -> Handle__ -> IO Handle newFileHandle filepath mb_finalizer hc = do m <- newMVar hc case mb_finalizer of Just finalizer -> addMVarFinalizer m (finalizer filepath m) Nothing -> return () return (FileHandle filepath m) -- --------------------------------------------------------------------------- -- Working with Handles {- In the concurrent world, handles are locked during use. This is done by wrapping an MVar around the handle which acts as a mutex over operations on the handle. To avoid races, we use the following bracketing operations. The idea is to obtain the lock, do some operation and replace the lock again, whether the operation succeeded or failed. We also want to handle the case where the thread receives an exception while processing the IO operation: in these cases we also want to relinquish the lock. There are three versions of @withHandle@: corresponding to the three possible combinations of: - the operation may side-effect the handle - the operation may return a result If the operation generates an error or an exception is raised, the original handle is always replaced. -} {-# INLINE withHandle #-} withHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a withHandle fun h@(FileHandle _ m) act = withHandle' fun h m act withHandle fun h@(DuplexHandle _ m _) act = withHandle' fun h m act withHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO (Handle__,a)) -> IO a withHandle' fun h m act = mask_ $ do (h',v) <- do_operation fun h act m checkHandleInvariants h' putMVar m h' return v {-# INLINE withHandle_ #-} withHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a withHandle_ fun h@(FileHandle _ m) act = withHandle_' fun h m act withHandle_ fun h@(DuplexHandle _ m _) act = withHandle_' fun h m act withHandle_' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a withHandle_' fun h m act = withHandle' fun h m $ \h_ -> do a <- act h_ return (h_,a) withAllHandles__ :: String -> Handle -> (Handle__ -> IO Handle__) -> IO () withAllHandles__ fun h@(FileHandle _ m) act = withHandle__' fun h m act withAllHandles__ fun h@(DuplexHandle _ r w) act = do withHandle__' fun h r act withHandle__' fun h w act withHandle__' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO Handle__) -> IO () withHandle__' fun h m act = mask_ $ do h' <- do_operation fun h act m checkHandleInvariants h' putMVar m h' return () do_operation :: String -> Handle -> (Handle__ -> IO a) -> MVar Handle__ -> IO a do_operation fun h act m = do h_ <- takeMVar m checkHandleInvariants h_ act h_ `catchException` handler h_ where handler h_ e = do putMVar m h_ case () of _ | Just ioe <- fromException e -> ioError (augmentIOError ioe fun h) _ | Just async_ex <- fromException e -> do -- see Note [async] let _ = async_ex :: SomeAsyncException t <- myThreadId throwTo t e do_operation fun h act m _otherwise -> throwIO e -- Note [async] -- -- If an asynchronous exception is raised during an I/O operation, -- normally it is fine to just re-throw the exception synchronously. -- However, if we are inside an unsafePerformIO or an -- unsafeInterleaveIO, this would replace the enclosing thunk with the -- exception raised, which is wrong (#3997). We have to release the -- lock on the Handle, but what do we replace the thunk with? What -- should happen when the thunk is subsequently demanded again? -- -- The only sensible choice we have is to re-do the IO operation on -- resumption, but then we have to be careful in the IO library that -- this is always safe to do. In particular we should -- -- never perform any side-effects before an interruptible operation -- -- because the interruptible operation may raise an asynchronous -- exception, which may cause the operation and its side effects to be -- subsequently performed again. -- -- Re-doing the IO operation is achieved by: -- - using throwTo to re-throw the asynchronous exception asynchronously -- in the current thread -- - on resumption, it will be as if throwTo returns. In that case, we -- recursively invoke the original operation (see do_operation above). -- -- Interruptible operations in the I/O library are: -- - threadWaitRead/threadWaitWrite -- - fillReadBuffer/flushWriteBuffer -- - readTextDevice/writeTextDevice augmentIOError :: IOException -> String -> Handle -> IOException augmentIOError ioe@IOError{ ioe_filename = fp } fun h = ioe { ioe_handle = Just h, ioe_location = fun, ioe_filename = filepath } where filepath | Just _ <- fp = fp | otherwise = case h of FileHandle path _ -> Just path DuplexHandle path _ _ -> Just path -- --------------------------------------------------------------------------- -- Wrapper for write operations. wantWritableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a wantWritableHandle fun h@(FileHandle _ m) act = wantWritableHandle' fun h m act wantWritableHandle fun h@(DuplexHandle _ _ m) act = wantWritableHandle' fun h m act -- we know it's not a ReadHandle or ReadWriteHandle, but we have to -- check for ClosedHandle/SemiClosedHandle. (#4808) wantWritableHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a wantWritableHandle' fun h m act = withHandle_' fun h m (checkWritableHandle act) checkWritableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkWritableHandle act h_@Handle__{..} = case haType of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle ReadHandle -> ioe_notWritable ReadWriteHandle -> do buf <- readIORef haCharBuffer when (not (isWriteBuffer buf)) $ do flushCharReadBuffer h_ flushByteReadBuffer h_ buf <- readIORef haCharBuffer writeIORef haCharBuffer buf{ bufState = WriteBuffer } buf <- readIORef haByteBuffer buf' <- Buffered.emptyWriteBuffer haDevice buf writeIORef haByteBuffer buf' act h_ _other -> act h_ -- --------------------------------------------------------------------------- -- Wrapper for read operations. wantReadableHandle :: String -> Handle -> (Handle__ -> IO (Handle__,a)) -> IO a wantReadableHandle fun h act = withHandle fun h (checkReadableHandle act) wantReadableHandle_ :: String -> Handle -> (Handle__ -> IO a) -> IO a wantReadableHandle_ fun h@(FileHandle _ m) act = wantReadableHandle' fun h m act wantReadableHandle_ fun h@(DuplexHandle _ m _) act = wantReadableHandle' fun h m act -- we know it's not a WriteHandle or ReadWriteHandle, but we have to -- check for ClosedHandle/SemiClosedHandle. (#4808) wantReadableHandle' :: String -> Handle -> MVar Handle__ -> (Handle__ -> IO a) -> IO a wantReadableHandle' fun h m act = withHandle_' fun h m (checkReadableHandle act) checkReadableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkReadableHandle act h_@Handle__{..} = case haType of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle AppendHandle -> ioe_notReadable WriteHandle -> ioe_notReadable ReadWriteHandle -> do -- a read/write handle and we want to read from it. We must -- flush all buffered write data first. bbuf <- readIORef haByteBuffer when (isWriteBuffer bbuf) $ do when (not (isEmptyBuffer bbuf)) $ flushByteWriteBuffer h_ cbuf' <- readIORef haCharBuffer writeIORef haCharBuffer cbuf'{ bufState = ReadBuffer } bbuf <- readIORef haByteBuffer writeIORef haByteBuffer bbuf{ bufState = ReadBuffer } act h_ _other -> act h_ -- --------------------------------------------------------------------------- -- Wrapper for seek operations. wantSeekableHandle :: String -> Handle -> (Handle__ -> IO a) -> IO a wantSeekableHandle fun h@(DuplexHandle _ _ _) _act = ioException (IOError (Just h) IllegalOperation fun "handle is not seekable" Nothing Nothing) wantSeekableHandle fun h@(FileHandle _ m) act = withHandle_' fun h m (checkSeekableHandle act) checkSeekableHandle :: (Handle__ -> IO a) -> Handle__ -> IO a checkSeekableHandle act handle_@Handle__{haDevice=dev} = case haType handle_ of ClosedHandle -> ioe_closedHandle SemiClosedHandle -> ioe_closedHandle AppendHandle -> ioe_notSeekable _ -> do b <- IODevice.isSeekable dev if b then act handle_ else ioe_notSeekable -- ----------------------------------------------------------------------------- -- Handy IOErrors ioe_closedHandle, ioe_EOF, ioe_notReadable, ioe_notWritable, ioe_cannotFlushNotSeekable, ioe_notSeekable :: IO a ioe_closedHandle = ioException (IOError Nothing IllegalOperation "" "handle is closed" Nothing Nothing) ioe_EOF = ioException (IOError Nothing EOF "" "" Nothing Nothing) ioe_notReadable = ioException (IOError Nothing IllegalOperation "" "handle is not open for reading" Nothing Nothing) ioe_notWritable = ioException (IOError Nothing IllegalOperation "" "handle is not open for writing" Nothing Nothing) ioe_notSeekable = ioException (IOError Nothing IllegalOperation "" "handle is not seekable" Nothing Nothing) ioe_cannotFlushNotSeekable = ioException (IOError Nothing IllegalOperation "" "cannot flush the read buffer: underlying device is not seekable" Nothing Nothing) ioe_finalizedHandle :: FilePath -> Handle__ ioe_finalizedHandle fp = throw (IOError Nothing IllegalOperation "" "handle is finalized" Nothing (Just fp)) ioe_bufsiz :: Int -> IO a ioe_bufsiz n = ioException (IOError Nothing InvalidArgument "hSetBuffering" ("illegal buffer size " ++ showsPrec 9 n []) Nothing Nothing) -- 9 => should be parens'ified. -- --------------------------------------------------------------------------- -- Wrapper for Handle encoding/decoding. -- The interface for TextEncoding changed so that a TextEncoding doesn't raise -- an exception if it encounters an invalid sequnce. Furthermore, encoding -- returns a reason as to why encoding stopped, letting us know if it was due -- to input/output underflow or an invalid sequence. -- -- This code adapts this elaborated interface back to the original TextEncoding -- interface. -- -- FIXME: it is possible that Handle code using the haDecoder/haEncoder fields -- could be made clearer by using the 'encode' interface directly. I have not -- looked into this. streamEncode :: BufferCodec from to state -> Buffer from -> Buffer to -> IO (Buffer from, Buffer to) streamEncode codec from to = fmap (\(_, from', to') -> (from', to')) $ recoveringEncode codec from to -- | Just like 'encode', but interleaves calls to 'encode' with calls to 'recover' in order to make as much progress as possible recoveringEncode :: BufferCodec from to state -> CodeBuffer from to recoveringEncode codec from to = go from to where go from to = do (why, from', to') <- encode codec from to -- When we are dealing with Handles, we don't care about input/output -- underflow particularly, and we want to delay errors about invalid -- sequences as far as possible. case why of InvalidSequence | bufL from == bufL from' -> do -- NB: it is OK to call recover here. Because we saw InvalidSequence, by the invariants -- on "encode" it must be the case that there is at least one elements available in the output -- buffer. Furthermore, clearly there is at least one element in the input buffer since we found -- something invalid there! (from', to') <- recover codec from' to' go from' to' _ -> return (why, from', to') -- ----------------------------------------------------------------------------- -- Handle Finalizers -- For a duplex handle, we arrange that the read side points to the write side -- (and hence keeps it alive if the read side is alive). This is done by -- having the haOtherSide field of the read side point to the read side. -- The finalizer is then placed on the write side, and the handle only gets -- finalized once, when both sides are no longer required. -- NOTE about finalized handles: It's possible that a handle can be -- finalized and then we try to use it later, for example if the -- handle is referenced from another finalizer, or from a thread that -- has become unreferenced and then resurrected (arguably in the -- latter case we shouldn't finalize the Handle...). Anyway, -- we try to emit a helpful message which is better than nothing. -- -- [later; 8/2010] However, a program like this can yield a strange -- error message: -- -- main = writeFile "out" loop -- loop = let x = x in x -- -- because the main thread and the Handle are both unreachable at the -- same time, the Handle may get finalized before the main thread -- receives the NonTermination exception, and the exception handler -- will then report an error. We'd rather this was not an error and -- the program just prints "<<loop>>". handleFinalizer :: FilePath -> MVar Handle__ -> IO () handleFinalizer fp m = do handle_ <- takeMVar m (handle_', _) <- hClose_help handle_ putMVar m handle_' return () -- --------------------------------------------------------------------------- -- Allocating buffers -- using an 8k char buffer instead of 32k improved performance for a -- basic "cat" program by ~30% for me. --SDM dEFAULT_CHAR_BUFFER_SIZE :: Int dEFAULT_CHAR_BUFFER_SIZE = 2048 -- 8k/sizeof(HsChar) getCharBuffer :: IODevice dev => dev -> BufferState -> IO (IORef CharBuffer, BufferMode) getCharBuffer dev state = do buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state ioref <- newIORef buffer is_tty <- IODevice.isTerminal dev let buffer_mode | is_tty = LineBuffering | otherwise = BlockBuffering Nothing return (ioref, buffer_mode) mkUnBuffer :: BufferState -> IO (IORef CharBuffer, BufferMode) mkUnBuffer state = do buffer <- newCharBuffer dEFAULT_CHAR_BUFFER_SIZE state -- See [note Buffer Sizing], GHC.IO.Handle.Types ref <- newIORef buffer return (ref, NoBuffering) -- ----------------------------------------------------------------------------- -- Flushing buffers -- | syncs the file with the buffer, including moving the -- file pointer backwards in the case of a read buffer. This can fail -- on a non-seekable read Handle. flushBuffer :: Handle__ -> IO () flushBuffer h_@Handle__{..} = do buf <- readIORef haCharBuffer case bufState buf of ReadBuffer -> do flushCharReadBuffer h_ flushByteReadBuffer h_ WriteBuffer -> do flushByteWriteBuffer h_ -- | flushes the Char buffer only. Works on all Handles. flushCharBuffer :: Handle__ -> IO () flushCharBuffer h_@Handle__{..} = do cbuf <- readIORef haCharBuffer case bufState cbuf of ReadBuffer -> do flushCharReadBuffer h_ WriteBuffer -> when (not (isEmptyBuffer cbuf)) $ error "internal IO library error: Char buffer non-empty" -- ----------------------------------------------------------------------------- -- Writing data (flushing write buffers) -- flushWriteBuffer flushes the buffer iff it contains pending write -- data. Flushes both the Char and the byte buffer, leaving both -- empty. flushWriteBuffer :: Handle__ -> IO () flushWriteBuffer h_@Handle__{..} = do buf <- readIORef haByteBuffer when (isWriteBuffer buf) $ flushByteWriteBuffer h_ flushByteWriteBuffer :: Handle__ -> IO () flushByteWriteBuffer h_@Handle__{..} = do bbuf <- readIORef haByteBuffer when (not (isEmptyBuffer bbuf)) $ do bbuf' <- Buffered.flushWriteBuffer haDevice bbuf writeIORef haByteBuffer bbuf' -- write the contents of the CharBuffer to the Handle__. -- The data will be encoded and pushed to the byte buffer, -- flushing if the buffer becomes full. writeCharBuffer :: Handle__ -> CharBuffer -> IO () writeCharBuffer h_@Handle__{..} !cbuf = do -- bbuf <- readIORef haByteBuffer debugIO ("writeCharBuffer: cbuf=" ++ summaryBuffer cbuf ++ " bbuf=" ++ summaryBuffer bbuf) (cbuf',bbuf') <- case haEncoder of Nothing -> latin1_encode cbuf bbuf Just encoder -> (streamEncode encoder) cbuf bbuf debugIO ("writeCharBuffer after encoding: cbuf=" ++ summaryBuffer cbuf' ++ " bbuf=" ++ summaryBuffer bbuf') -- flush if the write buffer is full if isFullBuffer bbuf' -- or we made no progress || not (isEmptyBuffer cbuf') && bufL cbuf' == bufL cbuf -- or the byte buffer has more elements than the user wanted buffered || (case haBufferMode of BlockBuffering (Just s) -> bufferElems bbuf' >= s NoBuffering -> True _other -> False) then do bbuf'' <- Buffered.flushWriteBuffer haDevice bbuf' writeIORef haByteBuffer bbuf'' else writeIORef haByteBuffer bbuf' if not (isEmptyBuffer cbuf') then writeCharBuffer h_ cbuf' else return () -- ----------------------------------------------------------------------------- -- Flushing read buffers -- It is always possible to flush the Char buffer back to the byte buffer. flushCharReadBuffer :: Handle__ -> IO () flushCharReadBuffer Handle__{..} = do cbuf <- readIORef haCharBuffer if isWriteBuffer cbuf || isEmptyBuffer cbuf then return () else do -- haLastDecode is the byte buffer just before we did our last batch of -- decoding. We're going to re-decode the bytes up to the current char, -- to find out where we should revert the byte buffer to. (codec_state, bbuf0) <- readIORef haLastDecode cbuf0 <- readIORef haCharBuffer writeIORef haCharBuffer cbuf0{ bufL=0, bufR=0 } -- if we haven't used any characters from the char buffer, then just -- re-install the old byte buffer. if bufL cbuf0 == 0 then do writeIORef haByteBuffer bbuf0 return () else do case haDecoder of Nothing -> do writeIORef haByteBuffer bbuf0 { bufL = bufL bbuf0 + bufL cbuf0 } -- no decoder: the number of bytes to decode is the same as the -- number of chars we have used up. Just decoder -> do debugIO ("flushCharReadBuffer re-decode, bbuf=" ++ summaryBuffer bbuf0 ++ " cbuf=" ++ summaryBuffer cbuf0) -- restore the codec state setState decoder codec_state (bbuf1,cbuf1) <- (streamEncode decoder) bbuf0 cbuf0{ bufL=0, bufR=0, bufSize = bufL cbuf0 } debugIO ("finished, bbuf=" ++ summaryBuffer bbuf1 ++ " cbuf=" ++ summaryBuffer cbuf1) writeIORef haByteBuffer bbuf1 -- When flushing the byte read buffer, we seek backwards by the number -- of characters in the buffer. The file descriptor must therefore be -- seekable: attempting to flush the read buffer on an unseekable -- handle is not allowed. flushByteReadBuffer :: Handle__ -> IO () flushByteReadBuffer h_@Handle__{..} = do bbuf <- readIORef haByteBuffer if isEmptyBuffer bbuf then return () else do seekable <- IODevice.isSeekable haDevice when (not seekable) $ ioe_cannotFlushNotSeekable let seek = negate (bufR bbuf - bufL bbuf) debugIO ("flushByteReadBuffer: new file offset = " ++ show seek) IODevice.seek haDevice RelativeSeek (fromIntegral seek) writeIORef haByteBuffer bbuf{ bufL=0, bufR=0 } -- ---------------------------------------------------------------------------- -- Making Handles mkHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> HandleType -> Bool -- buffered? -> Maybe TextEncoding -> NewlineMode -> Maybe HandleFinalizer -> Maybe (MVar Handle__) -> IO Handle mkHandle dev filepath ha_type buffered mb_codec nl finalizer other_side = do openTextEncoding mb_codec ha_type $ \ mb_encoder mb_decoder -> do let buf_state = initBufferState ha_type bbuf <- Buffered.newBuffer dev buf_state bbufref <- newIORef bbuf last_decode <- newIORef (error "codec_state", bbuf) (cbufref,bmode) <- if buffered then getCharBuffer dev buf_state else mkUnBuffer buf_state spares <- newIORef BufferListNil newFileHandle filepath finalizer (Handle__ { haDevice = dev, haType = ha_type, haBufferMode = bmode, haByteBuffer = bbufref, haLastDecode = last_decode, haCharBuffer = cbufref, haBuffers = spares, haEncoder = mb_encoder, haDecoder = mb_decoder, haCodec = mb_codec, haInputNL = inputNL nl, haOutputNL = outputNL nl, haOtherSide = other_side }) -- | makes a new 'Handle' mkFileHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -- ^ the underlying IO device, which must support -- 'IODevice', 'BufferedIO' and 'Typeable' -> FilePath -- ^ a string describing the 'Handle', e.g. the file -- path for a file. Used in error messages. -> IOMode -- The mode in which the 'Handle' is to be used -> Maybe TextEncoding -- Create the 'Handle' with no text encoding? -> NewlineMode -- Translate newlines? -> IO Handle mkFileHandle dev filepath iomode mb_codec tr_newlines = do mkHandle dev filepath (ioModeToHandleType iomode) True{-buffered-} mb_codec tr_newlines (Just handleFinalizer) Nothing{-other_side-} -- | like 'mkFileHandle', except that a 'Handle' is created with two -- independent buffers, one for reading and one for writing. Used for -- full-duplex streams, such as network sockets. mkDuplexHandle :: (IODevice dev, BufferedIO dev, Typeable dev) => dev -> FilePath -> Maybe TextEncoding -> NewlineMode -> IO Handle mkDuplexHandle dev filepath mb_codec tr_newlines = do write_side@(FileHandle _ write_m) <- mkHandle dev filepath WriteHandle True mb_codec tr_newlines (Just handleFinalizer) Nothing -- no othersie read_side@(FileHandle _ read_m) <- mkHandle dev filepath ReadHandle True mb_codec tr_newlines Nothing -- no finalizer (Just write_m) return (DuplexHandle filepath read_m write_m) ioModeToHandleType :: IOMode -> HandleType ioModeToHandleType ReadMode = ReadHandle ioModeToHandleType WriteMode = WriteHandle ioModeToHandleType ReadWriteMode = ReadWriteHandle ioModeToHandleType AppendMode = AppendHandle initBufferState :: HandleType -> BufferState initBufferState ReadHandle = ReadBuffer initBufferState _ = WriteBuffer openTextEncoding :: Maybe TextEncoding -> HandleType -> (forall es ds . Maybe (TextEncoder es) -> Maybe (TextDecoder ds) -> IO a) -> IO a openTextEncoding Nothing ha_type cont = cont Nothing Nothing openTextEncoding (Just TextEncoding{..}) ha_type cont = do mb_decoder <- if isReadableHandleType ha_type then do decoder <- mkTextDecoder return (Just decoder) else return Nothing mb_encoder <- if isWritableHandleType ha_type then do encoder <- mkTextEncoder return (Just encoder) else return Nothing cont mb_encoder mb_decoder closeTextCodecs :: Handle__ -> IO () closeTextCodecs Handle__{..} = do case haDecoder of Nothing -> return (); Just d -> Encoding.close d case haEncoder of Nothing -> return (); Just d -> Encoding.close d -- --------------------------------------------------------------------------- -- closing Handles -- hClose_help is also called by lazyRead (in GHC.IO.Handle.Text) when -- EOF is read or an IO error occurs on a lazy stream. The -- semi-closed Handle is then closed immediately. We have to be -- careful with DuplexHandles though: we have to leave the closing to -- the finalizer in that case, because the write side may still be in -- use. hClose_help :: Handle__ -> IO (Handle__, Maybe SomeException) hClose_help handle_ = case haType handle_ of ClosedHandle -> return (handle_,Nothing) _ -> do mb_exc1 <- trymaybe $ flushWriteBuffer handle_ -- interruptible -- it is important that hClose doesn't fail and -- leave the Handle open (#3128), so we catch -- exceptions when flushing the buffer. (h_, mb_exc2) <- hClose_handle_ handle_ return (h_, if isJust mb_exc1 then mb_exc1 else mb_exc2) trymaybe :: IO () -> IO (Maybe SomeException) trymaybe io = (do io; return Nothing) `catchException` \e -> return (Just e) hClose_handle_ :: Handle__ -> IO (Handle__, Maybe SomeException) hClose_handle_ h_@Handle__{..} = do -- close the file descriptor, but not when this is the read -- side of a duplex handle. -- If an exception is raised by the close(), we want to continue -- to close the handle and release the lock if it has one, then -- we return the exception to the caller of hClose_help which can -- raise it if necessary. maybe_exception <- case haOtherSide of Nothing -> trymaybe $ IODevice.close haDevice Just _ -> return Nothing -- free the spare buffers writeIORef haBuffers BufferListNil writeIORef haCharBuffer noCharBuffer writeIORef haByteBuffer noByteBuffer -- release our encoder/decoder closeTextCodecs h_ -- we must set the fd to -1, because the finalizer is going -- to run eventually and try to close/unlock it. -- ToDo: necessary? the handle will be marked ClosedHandle -- XXX GHC won't let us use record update here, hence wildcards return (Handle__{ haType = ClosedHandle, .. }, maybe_exception) {-# NOINLINE noCharBuffer #-} noCharBuffer :: CharBuffer noCharBuffer = unsafePerformIO $ newCharBuffer 1 ReadBuffer {-# NOINLINE noByteBuffer #-} noByteBuffer :: Buffer Word8 noByteBuffer = unsafePerformIO $ newByteBuffer 1 ReadBuffer -- --------------------------------------------------------------------------- -- Looking ahead hLookAhead_ :: Handle__ -> IO Char hLookAhead_ handle_@Handle__{..} = do buf <- readIORef haCharBuffer -- fill up the read buffer if necessary new_buf <- if isEmptyBuffer buf then readTextDevice handle_ buf else return buf writeIORef haCharBuffer new_buf peekCharBuf (bufRaw buf) (bufL buf) -- --------------------------------------------------------------------------- -- debugging debugIO :: String -> IO () debugIO s | c_DEBUG_DUMP = do _ <- withCStringLen (s ++ "\n") $ \(p, len) -> c_write 1 (castPtr p) (fromIntegral len) return () | otherwise = return () -- ---------------------------------------------------------------------------- -- Text input/output -- Read characters into the provided buffer. Return when any -- characters are available; raise an exception if the end of -- file is reached. -- -- In uses of readTextDevice within base, the input buffer is either: -- * empty -- * or contains a single \r (when doing newline translation) -- -- The input character buffer must have a capacity at least 1 greater -- than the number of elements it currently contains. -- -- Users of this function expect that the buffer returned contains -- at least 1 more character than the input buffer. readTextDevice :: Handle__ -> CharBuffer -> IO CharBuffer readTextDevice h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer debugIO ("readTextDevice: cbuf=" ++ summaryBuffer cbuf ++ " bbuf=" ++ summaryBuffer bbuf0) bbuf1 <- if not (isEmptyBuffer bbuf0) then return bbuf0 else do (r,bbuf1) <- Buffered.fillReadBuffer haDevice bbuf0 if r == 0 then ioe_EOF else do -- raise EOF return bbuf1 debugIO ("readTextDevice after reading: bbuf=" ++ summaryBuffer bbuf1) (bbuf2,cbuf') <- case haDecoder of Nothing -> do writeIORef haLastDecode (error "codec_state", bbuf1) latin1_decode bbuf1 cbuf Just decoder -> do state <- getState decoder writeIORef haLastDecode (state, bbuf1) (streamEncode decoder) bbuf1 cbuf debugIO ("readTextDevice after decoding: cbuf=" ++ summaryBuffer cbuf' ++ " bbuf=" ++ summaryBuffer bbuf2) -- We can't return from readTextDevice without reading at least a single extra character, -- so check that we have managed to achieve that writeIORef haByteBuffer bbuf2 if bufR cbuf' == bufR cbuf -- we need more bytes to make a Char. NB: bbuf2 may be empty (even though bbuf1 wasn't) when we -- are using an encoding that can skip bytes without outputting characters, such as UTF8//IGNORE then readTextDevice' h_ bbuf2 cbuf else return cbuf' -- we have an incomplete byte sequence at the end of the buffer: try to -- read more bytes. readTextDevice' :: Handle__ -> Buffer Word8 -> CharBuffer -> IO CharBuffer readTextDevice' h_@Handle__{..} bbuf0 cbuf0 = do -- -- copy the partial sequence to the beginning of the buffer, so we have -- room to read more bytes. bbuf1 <- slideContents bbuf0 -- readTextDevice only calls us if we got some bytes but not some characters. -- This can't occur if haDecoder is Nothing because latin1_decode accepts all bytes. let Just decoder = haDecoder (r,bbuf2) <- Buffered.fillReadBuffer haDevice bbuf1 if r == 0 then do -- bbuf2 can be empty here when we encounter an invalid byte sequence at the end of the input -- with a //IGNORE codec which consumes bytes without outputting characters if isEmptyBuffer bbuf2 then ioe_EOF else do (bbuf3, cbuf1) <- recover decoder bbuf2 cbuf0 debugIO ("readTextDevice' after recovery: bbuf=" ++ summaryBuffer bbuf3 ++ ", cbuf=" ++ summaryBuffer cbuf1) writeIORef haByteBuffer bbuf3 -- We should recursively invoke readTextDevice after recovery, -- if recovery did not add at least one new character to the buffer: -- 1. If we were using IgnoreCodingFailure it might be the case that -- cbuf1 is the same length as cbuf0 and we need to raise ioe_EOF -- 2. If we were using TransliterateCodingFailure we might have *mutated* -- the byte buffer without changing the pointers into either buffer. -- We need to try and decode it again - it might just go through this time. if bufR cbuf1 == bufR cbuf0 then readTextDevice h_ cbuf1 else return cbuf1 else do debugIO ("readTextDevice' after reading: bbuf=" ++ summaryBuffer bbuf2) (bbuf3,cbuf1) <- do state <- getState decoder writeIORef haLastDecode (state, bbuf2) (streamEncode decoder) bbuf2 cbuf0 debugIO ("readTextDevice' after decoding: cbuf=" ++ summaryBuffer cbuf1 ++ " bbuf=" ++ summaryBuffer bbuf3) writeIORef haByteBuffer bbuf3 if bufR cbuf0 == bufR cbuf1 then readTextDevice' h_ bbuf3 cbuf1 else return cbuf1 -- Read characters into the provided buffer. Do not block; -- return zero characters instead. Raises an exception on end-of-file. readTextDeviceNonBlocking :: Handle__ -> CharBuffer -> IO CharBuffer readTextDeviceNonBlocking h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer when (isEmptyBuffer bbuf0) $ do (r,bbuf1) <- Buffered.fillReadBuffer0 haDevice bbuf0 if isNothing r then ioe_EOF else do -- raise EOF writeIORef haByteBuffer bbuf1 decodeByteBuf h_ cbuf -- Decode bytes from the byte buffer into the supplied CharBuffer. decodeByteBuf :: Handle__ -> CharBuffer -> IO CharBuffer decodeByteBuf h_@Handle__{..} cbuf = do -- bbuf0 <- readIORef haByteBuffer (bbuf2,cbuf') <- case haDecoder of Nothing -> do writeIORef haLastDecode (error "codec_state", bbuf0) latin1_decode bbuf0 cbuf Just decoder -> do state <- getState decoder writeIORef haLastDecode (state, bbuf0) (streamEncode decoder) bbuf0 cbuf writeIORef haByteBuffer bbuf2 return cbuf'
frantisekfarka/ghc-dsi
libraries/base/GHC/IO/Handle/Internals.hs
Haskell
bsd-3-clause
35,776
{-# LANGUAGE TypeOperators #-} module Language.LSP.Server ( module Language.LSP.Server.Control , VFSData(..) , ServerDefinition(..) -- * Handlers , Handlers(..) , Handler , transmuteHandlers , mapHandlers , notificationHandler , requestHandler , ClientMessageHandler(..) , Options(..) , defaultOptions -- * LspT and LspM , LspT(..) , LspM , MonadLsp(..) , runLspT , LanguageContextEnv(..) , type (<~>)(..) , getClientCapabilities , getConfig , getRootPath , getWorkspaceFolders , sendRequest , sendNotification -- * VFS , getVirtualFile , getVirtualFiles , persistVirtualFile , getVersionedTextDoc , reverseFileMap , snapshotVirtualFiles -- * Diagnostics , publishDiagnostics , flushDiagnosticsBySource -- * Progress , withProgress , withIndefiniteProgress , ProgressAmount(..) , ProgressCancellable(..) , ProgressCancelledException -- * Dynamic registration , registerCapability , unregisterCapability , RegistrationToken , setupLogger , reverseSortEdit ) where import Language.LSP.Server.Control import Language.LSP.Server.Core
wz1000/haskell-lsp
lsp/src/Language/LSP/Server.hs
Haskell
mit
1,139
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module Data.Modable.Tests where import Data.Maybe (isNothing) import Data.Modable import Test.Framework import Test.Framework.Providers.QuickCheck2 import Test.QuickCheck testModable :: forall a b. ( Eq a, Show a, Arbitrary a , Eq (Relative a), Show (Relative a), Arbitrary (Relative a) , Relative a ~ Maybe b , Modable a ) => a -> Test testModable _ = testGroup "maybe math" [ testProperty "plus→minus" (\(a::a) (b::Relative a) -> minus (plus a b) b == a) , testProperty "minus→plus" (\(a::a) (b::Relative a) -> plus (minus a b) b == a) , testProperty "clobber" (\(a::a) (b::Relative a) -> if isNothing b then clobber a b == a else clobber a b `like` b) , testProperty "absify relify" (\(a::a) -> absify (relify a) == Just a) , testProperty "like" (\(a::a) -> a `like` relify a) ]
Soares/Dater.hs
test/Data/Modable/Tests.hs
Haskell
mit
980
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module HttpApp.BotKey.Api.Types where import Data.Aeson (FromJSON, ToJSON) import GHC.Generics (Generic) import HttpApp.BotKey.Types (BotKey, Label, Secret) data BKNewResp = BKNewResp { _nrespBotKey :: BotKey } deriving (Generic, ToJSON) data BKAllResp = BKAllResp { _arespBotKeys :: [BotKey] } deriving (Generic, ToJSON) data BKSetLabelRq = BKSetLabelRq { _slrqSecret :: Secret , _slrqLabel :: Label } deriving (Generic, FromJSON) data BKSetLabelResp = BKSetLabelResp { _slrespLabel :: Label } deriving (Generic, ToJSON) data BKDeleteRq = BKDeleteRq { _drqSecret :: Secret } deriving (Generic, FromJSON)
rubenmoor/skull
skull-server/src/HttpApp/BotKey/Api/Types.hs
Haskell
mit
749
module Main.DB ( session, oneRow, unit, integerDatetimes, serverVersion, ) where import Main.Prelude hiding (unit) import Control.Monad.Trans.Reader import Control.Monad.IO.Class import qualified Database.PostgreSQL.LibPQ as LibPQ import qualified Data.ByteString as ByteString; import Data.ByteString (ByteString) type Session = ExceptT ByteString (ReaderT LibPQ.Connection IO) session :: Session a -> IO (Either ByteString a) session m = do c <- connect initConnection c r <- runReaderT (runExceptT m) c LibPQ.finish c return r oneRow :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> LibPQ.Format -> Session ByteString oneRow statement params outFormat = do Just result <- result statement params outFormat Just result <- liftIO $ LibPQ.getvalue result 0 0 return result unit :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> Session () unit statement params = void $ result statement params LibPQ.Binary result :: ByteString -> [Maybe (LibPQ.Oid, ByteString, LibPQ.Format)] -> LibPQ.Format -> Session (Maybe LibPQ.Result) result statement params outFormat = do result <- ExceptT $ ReaderT $ \connection -> fmap Right $ LibPQ.execParams connection statement params outFormat checkResult result return result checkResult :: Maybe LibPQ.Result -> Session () checkResult result = ExceptT $ ReaderT $ \connection -> do case result of Just result -> do LibPQ.resultErrorField result LibPQ.DiagMessagePrimary >>= maybe (return (Right ())) (return . Left) Nothing -> do m <- LibPQ.errorMessage connection return $ Left $ maybe "Fatal PQ error" (\m -> "Fatal PQ error: " <> m) m integerDatetimes :: Session Bool integerDatetimes = lift (ReaderT getIntegerDatetimes) serverVersion :: Session Int serverVersion = lift (ReaderT LibPQ.serverVersion) -- * ------------------------- connect :: IO LibPQ.Connection connect = LibPQ.connectdb bs where bs = ByteString.intercalate " " components where components = [ "host=" <> host, "port=" <> (fromString . show) port, "user=" <> user, "password=" <> password, "dbname=" <> db ] where host = "localhost" port = 5432 user = "postgres" password = "" db = "postgres" initConnection :: LibPQ.Connection -> IO () initConnection c = void $ LibPQ.exec c $ mconcat $ map (<> ";") $ [ "SET client_min_messages TO WARNING", "SET client_encoding = 'UTF8'", "SET intervalstyle = 'postgres'" ] getIntegerDatetimes :: LibPQ.Connection -> IO Bool getIntegerDatetimes c = fmap parseResult $ LibPQ.parameterStatus c "integer_datetimes" where parseResult = \case Just "on" -> True _ -> False
nikita-volkov/postgresql-binary
tasty/Main/DB.hs
Haskell
mit
2,908
{-# LANGUAGE OverloadedStrings #-} -- | Entry point to the Post Correspondence Programming Language module Language.PCPL ( module Language.PCPL.Syntax , module Language.PCPL.Pretty , module Language.PCPL.CompileTM -- * Execute PCPL programs , runProgram -- * Utility , topString -- * Examples , unaryAdder , parensMatcher ) where import qualified Data.Map as Map import Language.UTM.Syntax import Language.PCPL.Syntax import Language.PCPL.Pretty import Language.PCPL.Solver import Language.PCPL.CompileTM -- | Run a PCPL program on the given input, producing a PCP match. runProgram :: Program -> Input -> [Domino] runProgram pgm w = map (dss !!) indices where dss@(d : ds) = (startDomino pgm w) : dominos pgm Just initialConfig = updateConf (Top []) d indices = reverse $ search (zip [1..] ds) [Node [0] initialConfig] -- | Return the string across the top of a list of Dominos. -- Useful after finding a match. topString :: [Domino] -> String topString ds = concat [ s | Domino xs _ <- ds, Symbol s <- xs] -- | Turing machine that adds unary numbers. -- For example: @1+11@ becomes @111@. unaryAdder :: TuringMachine unaryAdder = TuringMachine { startState = "x" , acceptState = "a" , rejectState = "reject" , blankSymbol = "_" , inputAlphabet = ["1", "+"] , transitionFunction = Map.fromList [ (("x", "1"), ("x", "1", R)) , (("x", "+"), ("y", "1", R)) , (("y", "1"), ("y", "1", R)) , (("y", "_"), ("z", "_", L)) , (("z", "1"), ("a", "_", R)) , (("z", "+"), ("a", "_", R)) ] } -- | Turing machine that accepts strings of balanced parentheses. -- Note: due to the restrictions described in 'compileTM', the input must -- start with a @$@ symbol. For example: the input @$(())()@ is accepted. -- This Turing machine is based on: -- <http://www2.lns.mit.edu/~dsw/turing/examples/paren.tm>. parensMatcher :: TuringMachine parensMatcher = TuringMachine { startState = "S" , acceptState = "Y" , rejectState = "N" , blankSymbol = "_" , inputAlphabet = syms "$()A" , transitionFunction = Map.fromList [ (("S", "$"), ("0", "$", R)) , (("0", "("), ("0", "(", R)) , (("0", ")"), ("1", "A", L)) , (("0", "A"), ("0", "A", R)) , (("0", "_"), ("2", "_", L)) , (("1", "("), ("0", "A", R)) , (("1", "A"), ("1", "A", L)) , (("2", "A"), ("2", "A", L)) , (("2", "$"), ("Y", "$", R)) ] }
davidlazar/PCPL
src/Language/PCPL.hs
Haskell
mit
2,530
module Ch2 where import Test.QuickCheck import Test.Hspec ch2 :: IO () ch2 = hspec $ do describe "_______________________Chapter 2 tests_______________________" $ do it "should have tests" $ do True
Kiandr/CrackingCodingInterview
Haskell/src/chapter-2/Ch2.hs
Haskell
mit
214
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-| Module : Data.Nat.Peano Description : Peano natural numbers Copyright : (c) Lars Brünjes, 2016 License : MIT Maintainer : brunjlar@gmail.com Stability : experimental Portability : portable Defines Peano natural numbers, i.e. natural numbers with unary representation. They are far less efficient than binary natural numbers, but much easier to reason about. -} module Data.Nat.Peano ( Peano(..) ) where import Data.Constraint import Data.Logic import Data.Ordered -- | Peano natural numbers: @Z = 0@, @S Z = 1@, @S S Z = 2@ and so on. data Peano = Z -- ^ zero | S !Peano -- ^ successor deriving (Show, Read, Eq) infix 4 ??? type family (m :: Peano) ??? (n :: Peano) :: Ordering where 'Z ??? 'Z = 'EQ 'Z ??? _ = 'LT 'S _ ??? 'Z = 'GT 'S m ??? 'S n = m ??? n instance Ordered Peano where type m ?? n = m ??? n data Sing Peano n where SZ :: Sing Peano 'Z SS :: Sing Peano n -> Sing Peano ('S n) dec SZ SZ = DecEQ Dict dec SZ (SS _) = DecLT Dict dec (SS _) SZ = DecGT Dict dec (SS m) (SS n) = case dec m n of DecLT Dict -> DecLT Dict DecEQ Dict -> DecEQ Dict DecGT Dict -> DecGT Dict {-# INLINE dec #-} symm SZ SZ = Dict symm SZ (SS _) = Dict symm (SS _) SZ = Dict symm (SS m) (SS n) = using (symm m n) Dict {-# INLINE symm #-} eqSame SZ SZ = Dict eqSame (SS m) (SS n) = using (eqSame m n) Dict {-# INLINE eqSame #-} instance Nat Peano where type Zero Peano = 'Z type Succ Peano n = 'S n zero = SZ {-# INLINE zero #-} succ' = SS {-# INLINE succ' #-} toSING 0 = SING SZ toSING n = case toSING (pred n) of SING n' -> SING (SS n') {-# INLINE toSING #-} toNatural SZ = 0 toNatural (SS n) = succ $ toNatural n {-# INLINE toNatural #-}
brunjlar/heap
src/Data/Nat/Peano.hs
Haskell
mit
2,067
{-# OPTIONS_GHC -fglasgow-exts -fallow-undecidable-instances #-} {-| This library provides a collection of monad transformers that can be combined to produce various monads. -} module MonadLibMorph ( -- * Types -- $Types Id, Lift, ReaderT, WriterT, StateT, ExceptionT, ContT, -- * Lifting -- $Lifting MonadT(..), BaseM(..), -- * Effect Classes -- $Effects ReaderM(..), WriterM(..), StateM(..), ExceptionM(..), ContM(..), Label, labelCC, jump, -- * Execution -- ** Eliminating Effects -- $Execution runId, runLift, runReaderT, runWriterT, runStateT, runExceptionT, runContT, -- ** Nested Execution -- $Nested_Exec RunReaderM(..), RunWriterM(..), RunStateM(..), RunExceptionM(..), -- * Miscellaneous version, module Control.Monad ) where import Control.Monad import Control.Monad.Fix import Data.Monoid -- | The current version of the library. version :: (Int,Int,Int) version = (3,1,0) -- $Types -- -- The following types define the representations of the -- computation types supported by the library. -- Each type adds support for a different effect. -- | Computations with no effects. newtype Id a = I a -- | Computation with no effects (stritc). data Lift a = L a -- | Add support for propagating a context. newtype ReaderT i m a = R (i -> m a) -- | Add support for collecting values. newtype WriterT i m a = W (m (a,i)) -- | Add support for threading state. newtype StateT i m a = S (i -> m (a,i)) -- | Add support for exceptions. newtype ExceptionT i m a = X (m (Either i a)) -- | Add support for jumps. newtype ContT i m a = C ((a -> m i) -> m i) -- $Execution -- -- The following functions eliminate the outermost effect -- of a computation by translating a computation into an -- equivalent computation in the underlying monad. -- (The exception is 'Id' which is not a monad transformer -- but an ordinary monad, and so, its run operation simply -- eliminates the monad.) -- | Get the result of a pure computation. runId :: Id a -> a runId (I a) = a -- | Get the result of a pure strict computation. runLift :: Lift a -> a runLift (L a) = a -- | Execute a reader computation in the given context. runReaderT :: i -> ReaderT i m a -> m a runReaderT i (R m) = m i -- | Execute a writer computation. -- Returns the result and the collected output. runWriterT :: WriterT i m a -> m (a,i) runWriterT (W m) = m -- | Execute a stateful computation in the given initial state. -- The second component of the result is the final state. runStateT :: i -> StateT i m a -> m (a,i) runStateT i (S m) = m i -- | Execute a computation with exceptions. -- Successful results are tagged with 'Right', -- exceptional results are tagged with 'Left'. runExceptionT :: ExceptionT i m a -> m (Either i a) runExceptionT (X m) = m -- | Execute a computation with the given continuation. runContT :: (a -> m i) -> ContT i m a -> m i runContT i (C m) = m i -- $Lifting -- -- The following operations allow us to promote computations -- in the underlying monad to computations that support an extra -- effect. Computations defined in this way do not make use of -- the new effect but can be combined with other operations that -- utilize the effect. class MonadT t where -- | Promote a computation from the underlying monad. lift :: (Monad m) => m a -> t m a -- It is interesting to note that these use something the resembles -- the non-transformer 'return's. instance MonadT (ReaderT i) where lift m = R (\_ -> m) instance MonadT (StateT i) where lift m = S (\s -> liftM (\a -> (a,s)) m) instance (Monoid i) => MonadT (WriterT i) where lift m = W (liftM (\a -> (a,mempty)) m) instance MonadT (ExceptionT i) where lift m = X (liftM Right m) instance MonadT (ContT i) where lift m = C (m >>=) class (Monad m, Monad n) => BaseM m n | m -> n where -- | Promote a computation from the base monad. inBase :: n a -> m a instance BaseM IO IO where inBase = id instance BaseM Maybe Maybe where inBase = id instance BaseM [] [] where inBase = id instance BaseM Id Id where inBase = id instance BaseM Lift Lift where inBase = id instance (BaseM m n) => BaseM (ReaderT i m) n where inBase = lift . inBase instance (BaseM m n) => BaseM (StateT i m) n where inBase = lift . inBase instance (BaseM m n,Monoid i) => BaseM (WriterT i m) n where inBase = lift . inBase instance (BaseM m n) => BaseM (ExceptionT i m) n where inBase = lift . inBase instance (BaseM m n) => BaseM (ContT i m) n where inBase = lift . inBase instance Monad Id where return x = I x fail x = error x m >>= k = k (runId m) instance Monad Lift where return x = L x fail x = error x L x >>= k = k x -- For the monad transformers, the definition of 'return' -- is completely determined by the 'lift' operations. -- None of the transformers make essential use of the 'fail' method. -- Instead they delegate its behavior to the underlying monad. instance (Monad m) => Monad (ReaderT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = R $ \r -> runReaderT r m >>= \a -> runReaderT r (k a) instance (Monad m) => Monad (StateT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = S $ \s -> runStateT s m >>= \ ~(a,s') -> runStateT s' (k a) instance (Monad m,Monoid i) => Monad (WriterT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = W $ runWriterT m >>= \ ~(a,w1) -> runWriterT (k a) >>= \ ~(b,w2) -> return (b,mappend w1 w2) instance (Monad m) => Monad (ExceptionT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = X $ runExceptionT m >>= \a -> case a of Left x -> return (Left x) Right a -> runExceptionT (k a) instance (Monad m) => Monad (ContT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = C $ \c -> runContT (\a -> runContT c (k a)) m instance Functor Id where fmap = liftM instance Functor Lift where fmap = liftM instance (Monad m) => Functor (ReaderT i m) where fmap = liftM instance (Monad m) => Functor (StateT i m) where fmap = liftM instance (Monad m,Monoid i) => Functor (WriterT i m) where fmap = liftM instance (Monad m) => Functor (ExceptionT i m) where fmap = liftM instance (Monad m) => Functor (ContT i m) where fmap = liftM -- $Monadic_Value_Recursion -- -- Recursion that does not duplicate side-effects. -- For details see Levent Erkok's dissertation. -- -- Monadic types built with 'ContT' do not support -- monadic value recursion. instance MonadFix Id where mfix f = let m = f (runId m) in m instance MonadFix Lift where mfix f = let m = f (runLift m) in m instance (MonadFix m) => MonadFix (ReaderT i m) where mfix f = R $ \r -> mfix (runReaderT r . f) instance (MonadFix m) => MonadFix (StateT i m) where mfix f = S $ \s -> mfix (runStateT s . f . fst) instance (MonadFix m,Monoid i) => MonadFix (WriterT i m) where mfix f = W $ mfix (runWriterT . f . fst) instance (MonadFix m) => MonadFix (ExceptionT i m) where mfix f = X $ mfix (runExceptionT . f . fromRight) where fromRight (Right a) = a fromRight _ = error "ExceptionT: mfix looped." instance (MonadPlus m) => MonadPlus (ReaderT i m) where mzero = lift mzero mplus (R m) (R n) = R (\r -> mplus (m r) (n r)) instance (MonadPlus m) => MonadPlus (StateT i m) where mzero = lift mzero mplus (S m) (S n) = S (\s -> mplus (m s) (n s)) instance (MonadPlus m,Monoid i) => MonadPlus (WriterT i m) where mzero = lift mzero mplus (W m) (W n) = W (mplus m n) instance (MonadPlus m) => MonadPlus (ExceptionT i m) where mzero = lift mzero mplus (X m) (X n) = X (mplus m n) -- $Effects -- -- The following classes define overloaded operations -- that can be used to define effectful computations. -- | Classifies monads that provide access to a context of type @i@. class (Monad m) => ReaderM m i | m -> i where -- | Get the context. ask :: m i instance (Monad m) => ReaderM (ReaderT i m) i where ask = R return instance (ReaderM m j,Monoid i) => ReaderM (WriterT i m) j where ask = lift ask instance (ReaderM m j) => ReaderM (StateT i m) j where ask = lift ask instance (ReaderM m j) => ReaderM (ExceptionT i m) j where ask = lift ask instance (ReaderM m j) => ReaderM (ContT i m) j where ask = lift ask -- | Classifies monads that can collect values of type @i@. class (Monad m) => WriterM m i | m -> i where -- | Add a value to the collection. put :: i -> m () instance (Monad m,Monoid i) => WriterM (WriterT i m) i where put x = W (return ((),x)) instance (WriterM m j) => WriterM (ReaderT i m) j where put = lift . put instance (WriterM m j) => WriterM (StateT i m) j where put = lift . put instance (WriterM m j) => WriterM (ExceptionT i m) j where put = lift . put instance (WriterM m j) => WriterM (ContT i m) j where put = lift . put -- | Classifies monads that propagate a state component of type @i@. class (Monad m) => StateM m i | m -> i where -- | Get the state. get :: m i -- | Set the state. set :: i -> m () instance (Monad m) => StateM (StateT i m) i where get = S (\s -> return (s,s)) set s = S (\_ -> return ((),s)) instance (StateM m j) => StateM (ReaderT i m) j where get = lift get set = lift . set instance (StateM m j,Monoid i) => StateM (WriterT i m) j where get = lift get set = lift . set instance (StateM m j) => StateM (ExceptionT i m) j where get = lift get set = lift . set instance (StateM m j) => StateM (ContT i m) j where get = lift get set = lift . set -- | Classifies monads that support raising exceptions of type @i@. class (Monad m) => ExceptionM m i | m -> i where -- | Raise an exception. raise :: i -> m a instance (Monad m) => ExceptionM (ExceptionT i m) i where raise x = X (return (Left x)) instance (ExceptionM m j) => ExceptionM (ReaderT i m) j where raise = lift . raise instance (ExceptionM m j,Monoid i) => ExceptionM (WriterT i m) j where raise = lift . raise instance (ExceptionM m j) => ExceptionM (StateT i m) j where raise = lift . raise instance (ExceptionM m j) => ExceptionM (ContT i m) j where raise = lift . raise -- The following instances differ from the others because the -- liftings are not as uniform (although they certainly follow a pattern). -- | Classifies monads that provide access to a computation's continuation. class Monad m => ContM m where -- | Capture the current continuation. callCC :: ((a -> m b) -> m a) -> m a instance (ContM m) => ContM (ReaderT i m) where callCC f = R $ \r -> callCC $ \k -> runReaderT r $ f $ \a -> lift $ k a instance (ContM m) => ContM (StateT i m) where callCC f = S $ \s -> callCC $ \k -> runStateT s $ f $ \a -> lift $ k (a,s) instance (ContM m,Monoid i) => ContM (WriterT i m) where callCC f = W $ callCC $ \k -> runWriterT $ f $ \a -> lift $ k (a,mempty) instance (ContM m) => ContM (ExceptionT i m) where callCC f = X $ callCC $ \k -> runExceptionT $ f $ \a -> lift $ k $ Right a instance (Monad m) => ContM (ContT i m) where callCC f = C $ \k -> runContT k $ f $ \a -> C $ \_ -> k a -- $Nested_Exec -- -- The following classes define operations that are overloaded -- versions of the @run@ operations. Unlike the @run@ operations, -- functions do not change the type of the computation (i.e, they -- do not remove a layer). However, they do not perform any -- side-effects in the corresponding layer. Instead, they execute -- a computation in a ``separate thread'' with respect to the -- corresponding effect. -- | Classifies monads that support changing the context for a -- sub-computation. class (ReaderM m i) => RunReaderM m i | m -> i where -- | Change the context for the duration of a computation. local :: i -> m a -> m a instance (Monad m) => RunReaderM (ReaderT i m) i where local i m = lift (runReaderT i m) instance (RunReaderM m j,Monoid i) => RunReaderM (WriterT i m) j where local i (W m) = W (local i m) instance (RunReaderM m j) => RunReaderM (StateT i m) j where local i (S m) = S (local i . m) instance (RunReaderM m j) => RunReaderM (ExceptionT i m) j where local i (X m) = X (local i m) -- | Classifies monads that support collecting the output of -- a sub-computation. class WriterM m i => RunWriterM m i | m -> i where -- | Collect the output from a computation. collect :: m a -> m (a,i) instance (RunWriterM m j) => RunWriterM (ReaderT i m) j where collect (R m) = R (collect . m) instance (Monad m,Monoid i) => RunWriterM (WriterT i m) i where collect (W m) = lift m instance (RunWriterM m j) => RunWriterM (StateT i m) j where collect (S m) = S (liftM swap . collect . m) where swap (~(a,s),w) = ((a,w),s) instance (RunWriterM m j) => RunWriterM (ExceptionT i m) j where collect (X m) = X (liftM swap (collect m)) where swap (Right a,w) = Right (a,w) swap (Left x,_) = Left x -- NOTE: If the local computation fails, then the output -- is discarded because the result type cannot accommodate it. -- | Classifies monads that support separate state threads. class (StateM m i) => RunStateM m i | m -> i where -- | Modify the state for the duration of a computation. -- Returns the final state. runS :: i -> m a -> m (a,i) instance (RunStateM m j) => RunStateM (ReaderT i m) j where runS s (R m) = R (runS s . m) instance (RunStateM m j,Monoid i) => RunStateM (WriterT i m) j where runS s (W m) = W (liftM swap (runS s m)) where swap (~(a,s),w) = ((a,w),s) instance (Monad m) => RunStateM (StateT i m) i where runS s m = lift (runStateT s m) instance (RunStateM m j) => RunStateM (ExceptionT i m) j where runS s (X m) = X (liftM swap (runS s m)) where swap (Left e,_) = Left e swap (Right a,s) = Right (a,s) -- NOTE: If the local computation fails, then the modifications -- are discarded because the result type cannot accommodate it. -- | Classifies monads that support handling of exceptions. class ExceptionM m i => RunExceptionM m i | m -> i where -- | Exceptions are explicit in the result. try :: m a -> m (Either i a) instance (RunExceptionM m i) => RunExceptionM (ReaderT j m) i where try (R m) = R (try . m) instance (RunExceptionM m i,Monoid j) => RunExceptionM (WriterT j m) i where try (W m) = W (liftM swap (try m)) where swap (Right ~(a,w)) = (Right a,w) swap (Left e) = (Left e, mempty) instance (RunExceptionM m i) => RunExceptionM (StateT j m) i where try (S m) = S (\s -> liftM (swap s) (try (m s))) where swap _ (Right ~(a,s)) = (Right a,s) swap s (Left e) = (Left e, s) instance (Monad m) => RunExceptionM (ExceptionT i m) i where try m = lift (runExceptionT m) -- Some convenient functions for working with continuations. -- | An explicit representation for continuations that store a value. newtype Label m a = Lab ((a, Label m a) -> m ()) -- | Capture the current continuation. -- This function is like 'return', except that it also captures -- the current continuation. Later we can use 'jump' to go back to -- the continuation with a possibly different value. labelCC :: (ContM m) => a -> m (a, Label m a) labelCC x = callCC (\k -> return (x, Lab k)) -- | Change the value passed to a previously captured continuation. jump :: (ContM m) => a -> Label m a -> m b jump x (Lab k) = k (x, Lab k) >> return unreachable where unreachable = error "(bug) jump: unreachable" newtype Morph m n = M (forall a. m a -> n a) -- indexed monad on the category of monads class (MonadT (t i), MonadT (t j), MonadT (t k)) => TMon t i j k | t i j -> k where bindT :: (Monad m) => Morph m (t i m) -> t j m a -> t k m a instance TMon ReaderT i j (i,j) where bindT (M f) m = do ~(i,j) <- ask lift (runReaderT i (f (runReaderT j m))) instance TMon StateT i j (i,j) where bindT (M f) m = do ~(i,j) <- get ~(~(a,i'),j') <- lift (runStateT i (f (runStateT j m))) set (i,j) return a instance (Monoid i, Monoid j) => TMon WriterT i j (i,j) where bindT (M f) m = do ~(~(a,j),i) <- lift (runWriterT (f (runWriterT m))) put (i,j) return a instance TMon ExceptionT i j (Either i j) where bindT (M f) m = do x <- lift (runExceptionT (f (runExceptionT m))) case x of Left i -> raise (Left i) Right (Left j) -> raise (Right j) Right (Right a) -> return a {- Continuation are tricky: C i (C j m) a = (a -> C j m i) -> C j m i = (a -> (i -> m j) -> m j) -> (i -> m j) -> m j = (uncurry) (a -> (i -> m j) -> m j, i -> m j) -> m j = (uncurry) ((a,i -> m j) -> m j, i -> m j) -> m j = (sum) (Either (a,i -> m j) i -> m j) -> m j = C j m (Either (a,i -> m j) i) -}
yav/monadlib
experimental/MonadLibMorph.hs
Haskell
mit
17,481
import Data.Char (digitToInt) main = print problem40Value problem40Value :: Int problem40Value = d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000 where d1 = digitToInt $ list !! 0 d10 = digitToInt $ list !! 9 d100 = digitToInt $ list !! 99 d1000 = digitToInt $ list !! 999 d10000 = digitToInt $ list !! 9999 d100000 = digitToInt $ list !! 99999 d1000000 = digitToInt $ list !! 999999 list = concat $ map show [1..]
jchitel/ProjectEuler.hs
Problems/Problem0040.hs
Haskell
mit
496
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} module Arith where import Control.Exception import Data.Int import Data.Text as T type T = Int64 zero :: T zero = 0 neg :: T -> T neg x | x == minBound = throw Overflow | otherwise = -x add :: T -> T -> T add x y = if | p x && p y && n sum -> throw Overflow | n x && n y && p sum -> throw Underflow | otherwise -> sum where sum = x + y p x = x > 0 n x = x < 0 sub x y = add x (neg y) fromText :: Int -> Text -> T fromText scale txt = case splitOn "." txt of [i] -> read . unpack $ T.concat [i, padding scale] [i, d] -> if T.any (/= '0') post then throw LossOfPrecision else read . unpack $ T.concat [i, pre, padding $ scale - T.length pre] where (pre, post) = T.splitAt scale d _ -> error "no parse" where padding n = T.replicate n "0" -- TODO: can we simplify this? Sounds very complex toText :: Int -> T -> Text toText 0 x = pack $ show x toText scale x = if | x == 0 -> "0" | x > 0 -> toTextPos x | otherwise -> T.concat ["-", toTextPos $ neg x] where toTextPos x = case T.splitAt (T.length textPadded - scale) textPadded of ("", d) -> T.concat ["0.", d] (i, d) -> T.concat [i, ".", d] where text = pack $ show x textPadded = T.concat [padding $ scale - T.length text, text] padding n = T.replicate n "0"
gip/cinq-cloches-ledger
src/Arith.hs
Haskell
mit
1,475
module TestLib (mkTestSuite, run, (<$>)) where import Test.HUnit import AsciiMath hiding (run) import Prelude hiding ((<$>)) import Control.Applicative ((<$>)) unComment :: [String] -> [String] unComment [] = [] unComment ("":ss) = "" : unComment ss unComment (('#':_):ss) = unComment ss unComment (s:ss) = s : unComment ss readSrc :: String -> IO [String] readSrc = (unComment . lines <$>) . readFile . ("tests/spec/"++) mkTest :: String -> String -> Test mkTest inp out = case compile inp of Right s -> TestCase $ assertEqual ("for " ++ inp ++ ",") out s Left err -> TestCase $ assertFailure $ "Error while compiling \"" ++ inp ++ "\":\n" ++ renderError err ++ ".\n" mkTestSuite :: String -> String -> IO Test mkTestSuite name filename = do { inp <- readSrc $ filename ++ ".txt"; out <- readSrc $ filename ++ ".latex"; return $ TestLabel name . TestList $ zipWith mkTest inp out } run :: Test -> IO () run t = do { c <- runTestTT t; if errors c == 0 && failures c == 0 then return () else error "fail"; }
Kerl13/AsciiMath
tests/TestLib.hs
Haskell
mit
1,037
module Language.Egison.Typing where import Data.Set (Set) import qualified Data.Set as S import Data.Map (Map) import qualified Data.Map as M import Language.Egison.Types -- I will deprecate this synonym type EgisonType = EgisonTypeExpr type TypeVar = String type ConsName = String data TypeCons = TCons ConsName -- Name Int -- Arity type ClassName = String type TypeContext = [(ClassName, TypeVar)] type TypeVarEnv = Set TypeVar type TypeConsEnv = Map TypeCons Int type
tokiwoousaka/egison4
hs-src/Language/Egison/Typing.hs
Haskell
mit
504
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Spark.Core.GroupsSpec where import Test.Hspec import Data.Text(Text) import Spark.Core.Context import Spark.Core.Functions import Spark.Core.ColumnFunctions import Spark.Core.Column import Spark.Core.IntegrationUtilities import Spark.Core.CollectSpec(run) import Spark.Core.Internal.Groups sumGroup :: [MyPair] -> [(Text, Int)] -> IO () sumGroup l lexp = do let ds = dataset l let keys = ds // myKey' let values = ds // myVal' let g = groupByKey keys values let ds2 = g `aggKey` sumCol l2 <- exec1Def $ collect (asCol ds2) l2 `shouldBe` lexp spec :: Spec spec = do describe "Integration test - groups on (text, int)" $ do run "empty" $ sumGroup [] [] run "one" $ sumGroup [MyPair "x" 1] [("x", 1)] run "two" $ sumGroup [MyPair "x" 1, MyPair "x" 2, MyPair "y" 1] [("x", 3), ("y", 1)]
krapsh/kraps-haskell
test-integration/Spark/Core/GroupsSpec.hs
Haskell
apache-2.0
915
sequence' :: Monad m => [m a] -> m [a] sequence' [] = return [] sequence' (m:ms) = m >>= \ a -> do as <- sequence' ms return (a: as) sequence'' ms = foldr func (return []) ms where func :: (Monad m) => m a -> m [a] -> m [a] func m acc = do x <- m xs <- acc return (x: xs) sequence''' [] = return [] sequence''' (m : ms) = do a <- m as <- sequence''' ms return (a:as) {-- sequence'''' [] = return [] sequence'''' (m : ms) = m >>= \ a -> do as <- sequence'''' ms return (a : as) --} mapM' :: Monad m => (a -> m b) -> [a] -> m [b] mapM' f as = sequence' (map f as) mapM'' f [] = return [] mapM'' f (a : as) = f a >>= \ b -> mapM'' f as >>= \ bs -> return (b : bs) sequence_' :: Monad m => [m a] -> m () sequence_' [] = return () sequence_' (m : ms) = m >> sequence_' ms --mapM''' :: Monad m => (a -> m b) -> [a] -> m [b] --mapM''' f as = sequence_' (map f as) mapMM f [] = return [] mapMM f (a : as) = do b <- f a bs <- mapMM f as return (b : bs) mapMM' f [] = return [] mapMM' f (a : as) = f a >>= \ b -> do bs <- mapMM' f as return (b : bs) mapMM'' f [] = return [] mapMM'' f (a : as) = f a >>= \ b -> do bs <- mapMM'' f as return (bs ++ [b]) filterM' :: Monad m => (a -> m Bool) -> [a] -> m [a] filterM' _ [] = return [] filterM' p (x : xs) = do flag <- p x ys <- filterM' p xs if flag then return (x: ys) else return ys foldLeftM :: Monad m => (a -> b -> m a) -> a -> [b] -> m a foldLeftM f a [] = return a foldLeftM f a (x: xs) = do z <- f a x foldLeftM f z xs foldRightM :: Monad m => (a -> b -> m b) -> b -> [a] -> m b foldRightM f a [] = return a foldRightM f a as = do z <- f (last as) a foldRightM f z $ init as liftM :: Monad m => (a -> b) -> m a -> m b liftM f m = do a <- m return (f a) liftM' :: Monad m => (a -> b) -> m a -> m b liftM' f m = m >>= \ a -> return (f a) liftM'' :: Monad m => (a -> b) -> m a -> m b liftM'' f m = m >>= \ a -> m >>= \ b -> return (f a) liftM''' :: Monad m => (a -> b) -> m a -> m b liftM''' f m = m >>= \ a -> m >>= \ b -> return (f b) --liftMM f m = mapM f [m]
dongarerahul/edx-haskell
chapter-8-hw.hs
Haskell
apache-2.0
2,479
import Controller (withOR) import System.IO (hPutStrLn, stderr) import Network.Wai.Middleware.Debug (debug) import Network.Wai.Handler.Warp (run) main :: IO () main = do let port = 3000 hPutStrLn stderr $ "Application launched, listening on port " ++ show port withOR $ run port . debug
snoyberg/orangeroster
test.hs
Haskell
bsd-2-clause
300
-- |Interactions with the user. module Ovid.Interactions ( tell , options ) where import Ovid.Prelude import qualified System.Console.Editline.Readline as R -- |Prompt the user. tell s = liftIO (putStrLn s) -- |Asks the user to pick an item from a list. options :: (MonadIO m, Show a) => [a] -> m a options xs = do let numOptions = length xs let showOption (n,x) = tell $ show n ++ " - " ++ show x mapM_ showOption (zip [1..] xs) tell $ "Select one (1 .. " ++ show numOptions ++ ") >" let makeSelection = do ch <- liftIO $ R.readKey case tryInt "ch" of Nothing -> do tell $ "Enter a number between 1 and " ++ show numOptions makeSelection Just n -> if n >= 1 && n <= numOptions then return (xs !! (n-1)) else do tell $ "Enter a number between 1 and " ++ show numOptions makeSelection makeSelection
brownplt/ovid
src/Ovid/Interactions.hs
Haskell
bsd-2-clause
972
-- | Helper functions for dealing with text values module Language.Terraform.Util.Text( template, show ) where import Prelude hiding(show) import qualified Prelude(show) import qualified Data.Text as T show :: (Show a) => a -> T.Text show = T.pack . Prelude.show -- | `template src substs` will replace all occurences the string $i -- in src with `substs !! i` template :: T.Text -> [T.Text] -> T.Text template t substs = foldr replace t (zip [1,2..] substs) where replace (i,s) t = T.replace (T.pack ('$':Prelude.show i)) s t
timbod7/terraform-hs
src/Language/Terraform/Util/Text.hs
Haskell
bsd-3-clause
547
module Validations.Types ( module Validations.Types.Checker ) where import Validations.Types.Checker
mavenraven/validations
src/Validations/Types.hs
Haskell
bsd-3-clause
106
{-# LANGUAGE OverloadedStrings #-} module Futhark.Compiler ( runPipelineOnProgram , runCompilerOnProgram , runPipelineOnSource , interpretAction' , FutharkConfig (..) , newFutharkConfig , dumpError ) where import Data.Monoid import Control.Monad import Control.Monad.IO.Class import Data.Maybe import System.Exit (exitWith, ExitCode(..)) import System.IO import qualified Data.Text as T import qualified Data.Text.IO as T import Prelude import Language.Futhark.Parser import Futhark.Internalise import Futhark.Pipeline import Futhark.Actions import qualified Language.Futhark as E import qualified Language.Futhark.TypeChecker as E import Futhark.MonadFreshNames import Futhark.Representation.AST import qualified Futhark.Representation.SOACS as I import qualified Futhark.TypeCheck as I data FutharkConfig = FutharkConfig { futharkVerbose :: Maybe (Maybe FilePath) } newFutharkConfig :: FutharkConfig newFutharkConfig = FutharkConfig { futharkVerbose = Nothing } dumpError :: FutharkConfig -> CompileError -> IO () dumpError config err = do T.hPutStrLn stderr $ errorDesc err case (errorData err, futharkVerbose config) of (s, Just outfile) -> maybe (T.hPutStr stderr) T.writeFile outfile $ s <> "\n" _ -> return () runCompilerOnProgram :: FutharkConfig -> Pipeline I.SOACS lore -> Action lore -> FilePath -> IO () runCompilerOnProgram config pipeline action file = do res <- runFutharkM compile $ isJust $ futharkVerbose config case res of Left err -> liftIO $ do dumpError config err exitWith $ ExitFailure 2 Right () -> return () where compile = do source <- liftIO $ T.readFile file prog <- runPipelineOnSource config pipeline file source when (isJust $ futharkVerbose config) $ liftIO $ hPutStrLn stderr $ "Running action " ++ actionName action actionProcedure action prog runPipelineOnProgram :: FutharkConfig -> Pipeline I.SOACS tolore -> FilePath -> FutharkM (Prog tolore) runPipelineOnProgram config pipeline file = do source <- liftIO $ T.readFile file runPipelineOnSource config pipeline file source runPipelineOnSource :: FutharkConfig -> Pipeline I.SOACS tolore -> FilePath -> T.Text -> FutharkM (Prog tolore) runPipelineOnSource config pipeline filename srccode = do parsed_prog <- parseSourceProgram filename srccode (tagged_ext_prog, namesrc) <- typeCheckSourceProgram parsed_prog putNameSource namesrc res <- internaliseProg tagged_ext_prog case res of Left err -> compileErrorS "During internalisation:" err Right int_prog -> do typeCheckInternalProgram int_prog runPasses pipeline pipeline_config int_prog where pipeline_config = PipelineConfig { pipelineVerbose = isJust $ futharkVerbose config , pipelineValidate = True } parseSourceProgram :: FilePath -> T.Text -> FutharkM E.UncheckedProg parseSourceProgram filename file_contents = do parsed <- liftIO $ parseFuthark filename file_contents case parsed of Left err -> compileError (T.pack $ show err) () Right prog -> return prog typeCheckSourceProgram :: E.UncheckedProg -> FutharkM (E.Prog, VNameSource) typeCheckSourceProgram prog = case E.checkProg prog of Left err -> compileError (T.pack $ show err) () Right prog' -> return prog' typeCheckInternalProgram :: I.Prog -> FutharkM () typeCheckInternalProgram prog = case I.checkProg prog of Left err -> compileError (T.pack $ "After internalisation:\n" ++ show err) prog Right () -> return () interpretAction' :: Action I.SOACS interpretAction' = interpretAction parseValues' where parseValues' :: FilePath -> T.Text -> Either ParseError [I.Value] parseValues' path s = fmap concat $ mapM internalise =<< parseValues path s internalise v = maybe (Left $ ParseError $ "Invalid input value: " ++ I.pretty v) Right $ internaliseValue v
mrakgr/futhark
src/Futhark/Compiler.hs
Haskell
bsd-3-clause
4,305
{-# LANGUAGE OverloadedStrings,GADTs,DeriveDataTypeable,DeriveFunctor,GeneralizedNewtypeDeriving,MultiParamTypeClasses,QuasiQuotes,TemplateHaskell,TypeFamilies,PackageImports,NamedFieldPuns,RecordWildCards,TypeSynonymInstances,FlexibleContexts #-} module Main where import Data.Crawler import Data.CrawlerParameters import Misc import WWW.SimpleTable import Control.Applicative import Control.Concurrent import qualified Control.Exception as Ex import Control.Monad import Control.Monad.Catch import Control.Monad.Error import Control.Monad.IO.Class import Control.Monad.Reader import Control.Monad.Trans.Control (MonadBaseControl) import Control.Monad.Writer.Lazy import Data.Attoparsec.Text (Parser) import qualified Data.Attoparsec.Text as AP import Data.ByteString (ByteString,empty,writeFile) import qualified Data.ByteString as B (empty,writeFile) import Data.Char import Data.List import Data.Maybe import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.IO as T import qualified Data.Text.Read as T import Data.Time import Data.Word import Database.Persist import qualified Database.Persist.MongoDB as Mongo import Database.Persist.TH import Language.Haskell.TH.Syntax (Type(ConT)) import Network (PortID (PortNumber)) import Network.Curl import Network.Socket (PortNumber(..)) import "network" Network.URI import System.Console.CmdArgs.Implicit import System.Exit (ExitCode(..),exitWith) import System.FilePath.Posix import Text.HTML.TagSoup import qualified Text.Pandoc as P import Text.Poppler main :: IO () main = do (mongoP,crawlP) <- processParams docs <- crawlBisBcbsPublications (courtesyPeriod crawlP) (publishedFrom crawlP) (publishedUntil crawlP) Ex.catch (do Mongo.withMongoDBConn (db mongoP) (host mongoP) (port mongoP) (auth mongoP) (dt mongoP) $ \pool -> do Mongo.runMongoDBPool Mongo.master (writeDocs (courtesyPeriod crawlP) docs (pdfPath crawlP)) pool) gobalExceptionHandler gobalExceptionHandler :: Ex.SomeException -> IO () gobalExceptionHandler e = do putStrLn $ "gobalExceptionHandler: Got an exception --> " ++ show e writeDocs :: Int -> [BisDoc] -> FilePath -> Mongo.Action IO () writeDocs ct docs pdfPath = do liftIO $ putStrLn "Insert publications..." forM_ docs (\d -> writeOneDoc d ct pdfPath) writeDocsHandler :: Ex.SomeException -> IO (Either (Int, String) Text) writeDocsHandler e = do putStrLn $ "writeDocsHandler: Got an exception --> " ++ show e return $ Left (-1,show e) writeOneDoc :: BisDoc -> Int -> FilePath -> Mongo.Action IO () writeOneDoc d ct pdfPath = do let title = T.unpack $ bisDocTitle d liftIO $ putStrLn $ "Download and process '"++title++"'" case bisDocDetails d of Just det -> case bisDocumentDetailsFullTextLink det of Just url -> do mFullPdf <- liftIO $ getFile ct url case mFullPdf of Just fullPdf -> do fullHtml <- liftIO $ Ex.handle writeDocsHandler $ do let fname = snd (splitFileName (uriPath (fromJust (parseURI url)))) B.writeFile (pdfPath++fname) fullPdf fullHtml <- pdfToHtmlTextOnly [] fullPdf return fullHtml case fullHtml of Right html -> do let fullMd = htmlToMarkdown html let det' = det{bisDocumentDetailsFullTextMarkdown=Just fullMd} Mongo.insert_ (d {bisDocDetails=Just det'}) Left (e,stderr) -> do liftIO $ putStrLn $ "Error: "++show e liftIO $ putStrLn stderr Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "Error: Could not load pdf file." Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "No file to download for '"++title++"'" Mongo.insert_ d Nothing -> do liftIO $ putStrLn $ "No details for '"++title++"'" Mongo.insert_ d type TTag = Tag Text getFile :: Int -> URLString -> IO (Maybe ByteString) getFile ct url = Ex.catch (do resp <- curlGetResponse_ url [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return $ Just $ respBody resp) handler where handler :: Ex.SomeException -> IO (Maybe ByteString) handler e = do putStrLn $ "getFile: Got an exception --> " ++ show e return Nothing openUrlUtf8 :: Int -> URLString -> IO Text openUrlUtf8 ct url = Ex.catch (do resp <- curlGetResponse_ url [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return (T.decodeUtf8 (respBody resp))) handler where handler :: Ex.SomeException -> IO Text handler e = do putStrLn $ "openUrlUtf8: Got an exception --> " ++ show e return "" collectWhile :: Monad m => Maybe t -> (t -> m [a]) -> (t -> m (Maybe t)) -> [a] -> m [a] collectWhile (Just jx) process next bag = do x1 <- next jx new <- process jx collectWhile x1 process next (bag++new) collectWhile Nothing _ _ bag = return bag ppTags tags = putStrLns (map showT tags) bisSite :: URLString bisSite = "http://www.bis.org" crawlBisBcbsPublications :: Int -> Maybe Day -> Maybe Day -> IO [BisDoc] crawlBisBcbsPublications ct t0 t1 = withCurlDo $ do putStrLn $ "Start with page "++startingPoint src <- openUrlUtf8 ct startingPoint if src=="" then do T.putStrLn "Cannot get page." return [] else do let tags = parseTags src collectWhile (Just tags) (processBISDocPage ct t0 t1) (getNextBISDocPage ct) [] where startingPoint = bisSite++"/bcbs/publications.htm" processBISDocPage :: Int -> Maybe Day -> Maybe Day -> [TTag] -> IO [BisDoc] processBISDocPage ct t0 t1 tags = do let ts = simpleTables tags if null ts then do T.putStrLn "No table found on page." return [] else do let ts1 = head ts docs <- catMaybes <$> mapM (processDoc ct t0 t1) (rows ts1) T.putStrLn "Found: " T.putStrLn $ T.intercalate "\n" (map (\ d -> "-- " `T.append` (bisDocTitle d)) docs) return docs processDoc :: Int -> Maybe Day -> Maybe Day -> TableRow -> IO (Maybe BisDoc) processDoc ct t0 t1 row = do let es = elements row dt = getDateFromRow es typ = getTypeFromRow es lnk = getLinkFromRow es ttl = getTitleFromRow es if not (between dt t0 t1) then return Nothing else do details <- case lnk of Nothing -> return Nothing Just l -> if "pdf" `isSuffixOf` l then do resp <- curlGetResponse_ l [] :: IO (CurlResponse_ [(String,String)] ByteString) threadDelay ct return $ Just BisDocumentDetails { bisDocumentDetailsDocumentTitle=ttl, bisDocumentDetailsSummary = "", bisDocumentDetailsFullTextLink = Just l, bisDocumentDetailsFullTextMarkdown = Nothing, bisDocumentDetailsLocalFile = Just $ filenameFromUrl l, bisDocumentDetailsOtherLinks = []} else analyzeBisSingleDocPage ct l return $ Just $ BisDoc dt typ lnk ttl details getDateFromRow tags = let ds = deleteAll ["\n","\t","\r"] $ fromTagText (head (head tags)) in case AP.parseOnly parseDate ds of Left m -> error $ "Parse error while processing a date: "++m Right d -> d getTypeFromRow tags = let tag = (tags!!1)!!3 in if isTagOpen tag then let attr = fromAttrib "title" tag in if attr=="" then Nothing else Just attr else Nothing getLinkFromRow :: [[TTag]] -> Maybe URLString getLinkFromRow tags = let tag = (tags!!2)!!3 in if isTagOpen tag then Just $ bisSite++(T.unpack $ fromAttrib "href" tag) else Nothing getTitleFromRow tags = let tag = (tags!!2)!!4 in if isTagText tag then deleteAll ["\t","\r","\n"] $ fromTagText tag else "" getNextBISDocPage :: Int -> [TTag] -> IO (Maybe [TTag]) getNextBISDocPage ct tags = do let nextLink = getNextDocLink tags case nextLink of Just lnk -> do putStrLn $ "Follow link: "++lnk src <- openUrlUtf8 ct lnk let tags1 = parseTags src return (Just tags1) Nothing -> return Nothing getNextDocLink :: [TTag] -> Maybe URLString getNextDocLink tags = let s = sections (~== (TagOpen ("a"::Text) [("class","next")])) tags in if null s then Nothing else let t = head (head s) in let href = fromAttrib "href" t in if href=="" then Nothing else Just (if T.head href=='/' then bisSite++(T.unpack href) else T.unpack href) analyzeBisSingleDocPage :: Int -> URLString -> IO (Maybe BisDocumentDetails) analyzeBisSingleDocPage ct url = do putStrLn $ "Analyse "++url allTags <- return . partitionIt =<< (return . parseTags) =<< openUrlUtf8 ct url if not (null allTags) then if length allTags==3 then do let contentTags = allTags!!0 annotationTags = allTags!!1 docTitle = fromTagText (contentTags!!1) docSummary = let divSections = sections (~== (TagClose ("div"::Text))) contentTags summaryHtml = if length divSections>=2 then purgeHtmlText $ tail (divSections!!1) else error "Cannot parse page because structure has changed." in T.pack $ P.writeMarkdown P.def $ P.readHtml P.def $ T.unpack $ renderTags summaryHtml fullTextLink = let fBox = sections (~==divFullText) annotationTags in if not (null fBox) then let aTag = sections (~==aLinkTag) (head fBox) link = T.unpack $ fromAttrib "href" (head $ head aTag) in if "/" `isPrefixOf` link then Just $ bisSite++link else Just link else Nothing let otherBoxes = partitions (~== otherBox) annotationTags let others = map processOtherBox otherBoxes return $ Just $ BisDocumentDetails docTitle docSummary fullTextLink Nothing (fmap filenameFromUrl fullTextLink) others else do putStrLn $ "Cannot parse page because structure has changed. " ++"Content:\n" ++show allTags return Nothing else do putStrLn "No input. Probably You are not connected to the internet." return Nothing where tagContent = TagOpen "h1" [] :: TTag tagAnnotations = TagOpen "div" [("id","right"), ("class","column"), ("role","complementary")] :: TTag tagFooter = TagOpen "div" [("id","footer"),("role","contentinfo")] :: TTag partitionIt = partitions (\tag -> tag~==tagContent || tag~==tagAnnotations || tag~==tagFooter) divFullText = TagOpen "div" [("class","list_box full_text")] :: TTag otherBox = TagOpen "div" [("class","list_box")] :: TTag processOtherBox :: [Tag Text] -> DocumentLink processOtherBox tags = let t1 = sections (~== (TagOpen "h4" [] :: TTag)) tags typ = fromTagText ((head t1)!!1) t2 = partitions (~==aLinkTag) tags link tags = if null tags then "" else let lnk' = T.unpack $ fromAttrib "href" (head tags) lnk = if lnk'=="" then "" else if "/" `isPrefixOf` lnk' then bisSite++lnk' else lnk' in lnk links = map link t2 in (DocumentLink typ links)
tkemps/bcbs-crawler
src/BcbsCrawler-old.hs
Haskell
bsd-3-clause
13,475
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Main where import System.Remote.Monitoring import Web.Auth.OAuth2 import Web.Auth.Service import Web.Orion import Web.Scotty.Trans import Web.Template import Web.Template.Renderer import Web.Session import Database import Text.Blaze.Html import Text.Blaze.Html5 hiding (param, object, map, b) import qualified Data.Text.Lazy as LT import qualified Data.ByteString.Lazy.Char8 as LB import qualified Data.Map as Map main :: IO () main = do _ <- forkServer "localhost" 9989 orion $ do createUserDatabaseIfNeeded get "/" $ (blaze $ authdWrapper "Home" "Home") `ifAuthorizedOr` (blaze $ wrapper "Home" "Home") get "/authCheck" $ do mU <- readUserCookie blaze $ wrapper "Auth Check" $ do h3 "Auth Check" pre $ toHtml $ show mU get "/user" $ withAuthUser $ \u -> blaze $ authdWrapper "User" $ userTable u get "/error/:err" $ do err <- fmap errorMessage $ param "err" blaze $ wrapper "Error" err get "/login" $ do dest <- defaultParam "redirect" "" (blaze $ authdWrapper "Login" $ loginOptions $ Just dest) `ifAuthorizedOr` (blaze $ wrapper "Login" $ loginOptions $ Just dest) get "/logout" $ do expireUserCookie blaze $ wrapper "Logout" $ p "You have been logged out." get "/login/:service" $ do service <- param "service" let Just key = oauth2serviceKey service url <- prepareServiceLogin service key redirect url get "/login/:service/complete" $ do dest <- popRedirectDestination eUser <- oauthenticate case eUser of Left err -> blaze $ wrapper "OAuth Error" $ do h3 "Authentication Error" p $ toHtml $ LB.unpack err Right u -> do c <- futureCookieForUser u writeUserCookie c redirect dest --get "/link/:service" $ withAuthUser $ \u -> do -- service <- param "service" -- if service `elem` linkedServices u -- then blaze $ wrapper "Link Service" $ do -- h3 "Blarg" -- p "You've already linked that service." -- else do let key = serviceKey service -- baseUrl <- readCfg getCfgBaseUrl -- let call = concat [ baseUrl -- , "/link/" -- , serviceToString service -- , "/complete" -- ] -- call' = B.pack call -- key' = key{oauthCallback= Just call'} -- url <- prepareServiceLogin service key' -- redirect url --get "/link/:service/complete" $ withAuthUser $ \OrionUser{..} -> do -- dest <- popRedirectDestination -- service <- param "service" -- eUdat <- fetchRemoteUserData -- case eUdat of -- Left err -> blaze $ authdWrapper "Link Error" $ do -- h3 $ toHtml $ "Error linking " ++ serviceToString service -- p $ toHtml $ LB.unpack err -- Right udat -> do mUser <- addAccountToUser service _ouId udat -- case mUser of -- Nothing -> blaze $ authdWrapper "Link Error" $ do -- h3 $ toHtml $ "Error linking " ++ serviceToString service -- p $ "Failed to add account." -- Just _ -> redirect dest popRedirectDestination :: ActionOM LT.Text popRedirectDestination = do state <- param "state" states <- readAuthStates modifyAuthStates $ Map.delete state case Map.lookup state states of Nothing -> redirect "error/stateMismatch" Just dest -> return dest
schell/orion
src/Main.hs
Haskell
bsd-3-clause
4,457
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveFunctor #-} module Data.Queue ( Queue , empty, singleton, fromList , toList, enqueue, dequeue, enqueueAll ) where import Control.DeepSeq (NFData) import GHC.Generics (Generic) data Queue a = Q [a] [a] deriving (Show, Eq, Functor, NFData, Generic) empty ∷ Queue a empty = Q [] [] singleton ∷ a → Queue a singleton a = Q [a] [] fromList ∷ [a] → Queue a fromList as = Q as [] toList ∷ Queue a → [a] toList (Q h t) = h ++ reverse t enqueue ∷ Queue a → a → Queue a enqueue (Q h t) a = Q (a:h) t enqueueAll ∷ Queue a → [a] → Queue a enqueueAll (Q h t) as = Q (as ++ h) t dequeue ∷ Queue a → Maybe (Queue a, a) dequeue (Q [] []) = Nothing dequeue (Q h []) = let (h':t) = reverse h in Just (Q [] t, h') dequeue (Q h (h':t)) = Just (Q h t, h')
stefan-hoeck/labeled-graph
Data/Queue.hs
Haskell
bsd-3-clause
898
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif module Text.RE.PCRE.ByteString ( -- * Tutorial -- $tutorial -- * The Match Operators (*=~) , (?=~) , (=~) , (=~~) -- * The Toolkit -- $toolkit , module Text.RE -- * The 'RE' Type -- $re , module Text.RE.PCRE.RE ) where import Prelude.Compat import qualified Data.ByteString as B import Data.Typeable import Text.Regex.Base import Text.RE import Text.RE.Internal.AddCaptureNames import Text.RE.PCRE.RE import qualified Text.Regex.PCRE as PCRE -- | find all matches in text (*=~) :: B.ByteString -> RE -> Matches B.ByteString (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ match (reRegex rex) bs -- | find first match in text (?=~) :: B.ByteString -> RE -> Match B.ByteString (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base polymorphic match operator (=~) :: ( Typeable a , RegexContext PCRE.Regex B.ByteString a , RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String ) => B.ByteString -> RE -> a (=~) bs rex = addCaptureNames (reCaptureNames rex) $ match (reRegex rex) bs -- | the regex-base monadic, polymorphic match operator (=~~) :: ( Monad m , Functor m , Typeable a , RegexContext PCRE.Regex B.ByteString a , RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption String ) => B.ByteString -> RE -> m a (=~~) bs rex = addCaptureNames (reCaptureNames rex) <$> matchM (reRegex rex) bs instance IsRegex RE B.ByteString where matchOnce = flip (?=~) matchMany = flip (*=~) regexSource = reSource -- $tutorial -- We have a regex tutorial at <http://tutorial.regex.uk>. These API -- docs are mainly for reference. -- $toolkit -- -- Beyond the above match operators and the regular expression type -- below, "Text.RE" contains the toolkit for replacing captures, -- specifying options, etc. -- $re -- -- "Text.RE.PCRE.RE" contains the toolkit specific to the 'RE' type, -- the type generated by the gegex compiler.
cdornan/idiot
Text/RE/PCRE/ByteString.hs
Haskell
bsd-3-clause
2,516
module SlaeGauss where import Data.Bifunctor import qualified Data.Matrix as Mx import qualified Data.Vector as Vec import Library compute :: Matrix -> Either ComputeError Vector compute = fmap backtrackPermuted . triangulate where backtrackPermuted (mx, permutations) = Vec.map (backtrack mx Vec.!) permutations triangulate :: Matrix -> Either ComputeError (Matrix, Permutations) triangulate mx = first Mx.fromRows <$> go 0 permutations rows where rows = Mx.toRows mx permutations = Vec.fromList [0..(length rows - 1)] go :: Int -> Permutations -> [Vector] -> Either ComputeError ([Vector], Permutations) go _ ps [] = Right ([], ps) go j ps m@(as:ass) | isLastCol = Right (m, ps) | isZeroPivot = Left SingularMatrix | otherwise = first (as':) <$> go (j + 1) ps' (map updRow ass') where isLastCol = j + 2 >= Vec.length as isZeroPivot = nearZero as'j as'j = as' Vec.! j (as':ass', ps') = permuteToMax j ps m updRow bs = Vec.zipWith op as' bs where k = bs Vec.! j / as'j op a b = b - a * k permuteToMax :: Int -> Permutations -> [Vector] -> ([Vector], Permutations) permuteToMax col ps m = ( Mx.toRows $ permuteRows 0 i $ permuteCols col j $ Mx.fromRows m , swapComponents col j ps ) where (i, j, _) = foldr imax (0, 0, 0) $ zip [0..] m imax :: (Int, Vec.Vector Double) -> (Int, Int, Double) -> (Int, Int, Double) imax (i, v) oldMax@(_, _, max) | rowMax > max = (i, j + col, rowMax) | otherwise = oldMax where (j, rowMax) = Vec.ifoldl vimax (0, 0) (Vec.drop col $ Vec.init v) vimax :: (Int, Double) -> Int -> Double -> (Int, Double) vimax (i, max) k a | a > max = (k, a) | otherwise = (i, max) permuteRows :: Int -> Int -> Matrix -> Matrix permuteRows i k = Mx.fromColumns . map (swapComponents i k) . Mx.toColumns permuteCols :: Int -> Int -> Matrix -> Matrix permuteCols i k = Mx.fromRows . map (swapComponents i k) . Mx.toRows swapComponents :: Int -> Int -> Vec.Vector a -> Vec.Vector a swapComponents i k v = Vec.imap cmpSelector v where cmpSelector j el | j == i = v Vec.! k | j == k = v Vec.! i | otherwise = el backtrack :: Matrix -> Vector backtrack = foldr eqSolver Vec.empty . Mx.toRows eqSolver :: Vector -> Vector -> Vector eqSolver as xs = Vec.cons ((Vec.last as' - Vec.sum (resolveKnown as' xs)) / Vec.head as') xs where as' = Vec.dropWhile nearZero as resolveKnown :: Vector -> Vector -> Vector resolveKnown as xs = Vec.zipWith (*) xs (Vec.tail $ Vec.init as)
hrsrashid/nummet
lib/SlaeGauss.hs
Haskell
bsd-3-clause
2,689
module Paths_variants ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version [0,1,0,0] [] bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/Users/jo/.cabal/bin" libdir = "/Users/jo/.cabal/lib/x86_64-osx-ghc-7.10.2/varia_5wCMPNeYlGhAk0qTYbHvsm" datadir = "/Users/jo/.cabal/share/x86_64-osx-ghc-7.10.2/variants-0.1.0.0" libexecdir = "/Users/jo/.cabal/libexec" sysconfdir = "/Users/jo/.cabal/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "variants_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "variants_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "variants_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "variants_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "variants_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
josephDunne/variants
dist/build/autogen/Paths_variants.hs
Haskell
bsd-3-clause
1,313
{-# LANGUAGE PatternSignatures #-} module Main where import GHC.Conc import Control.Exception import Foreign.StablePtr import System.IO import GHC.Conc.Sync (atomicallyWithIO) inittvar :: STM (TVar String) inittvar = newTVar "Hello world" deadlock0 :: STM String deadlock0 = retry deadlock1 :: TVar String -> STM String deadlock1 v1 = do s1 <- readTVar v1 retry atomically_ x = atomicallyWithIO x (\x -> putStrLn "IO" >> return x) -- Basic single-threaded operations with retry main = do newStablePtr stdout putStr "Before\n" t1 <- atomically ( newTVar 0 ) -- Atomic block that contains a retry but does not perform it r <- atomically_ ( do r1 <- readTVar t1 if (r1 /= 0) then retry else return () return r1 ) putStr ("Survived unused retry\n") -- Atomic block that retries after reading 0 TVars s1 <- Control.Exception.catch (atomically_ retry ) (\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n")) putStr s1 -- Atomic block that retries after reading 1 TVar t1 <- atomically ( inittvar ) s1 <- Control.Exception.catch (atomically_ ( deadlock1 t1 )) (\(e::SomeException) -> return ("Caught: " ++ (show e) ++ "\n")) putStr s1 return ()
mcschroeder/ghc
libraries/base/tests/Concurrent/stmio047.hs
Haskell
bsd-3-clause
1,402
{-# LANGUAGE RecordWildCards #-} module Main (main) where import GeoLabel (toString, fromString') import GeoLabel.Strings (format, parse) import GeoLabel.Strings.Wordlist (wordlist) import GeoLabel.Geometry.QuadTree (Subface(A,B,C,D)) import GeoLabel.Geometry.Point (lengthOf, (<->)) import GeoLabel.Geometry.Conversion (cartesian) import GeoLabel.Geometry.Polar (Polar(..)) import GeoLabel.Geodesic.Earth (earthRadius) import GeoLabel.Unit.Location (Location(..), idOf, fromId) import Numeric.Units.Dimensional ((*~), one) import Numeric.Units.Dimensional.SIUnits (meter) import System.Exit (exitFailure) import Test.QuickCheck (quickCheckResult, Result(..), forAll, vector, vectorOf, elements, choose) import Data.Maybe (fromJust) import GeoLabel.Real (R) import Data.Number.BigFloat (BigFloat, Prec50, Epsilon) import System.Random (Random, randomR, random) instance Epsilon e => Random (BigFloat e) where randomR (a,b) g = (c,g') where (d,g') = randomR (realToFrac a :: Double, realToFrac b) g c = realToFrac d random g = (realToFrac (d :: Double), g') where (d,g') = random g main :: IO () main = do print "testing location -> bits -> location" try $ quickCheckResult idTest print "testing location -> String -> location" try $ quickCheckResult locTest print "testing coordinate -> String -> coordinate" try $ quickCheckResult coordTest try :: (IO Result) -> IO () try test = do result <- test case result of Failure{..} -> exitFailure _ -> return () idTest = forAll (choose (0,19)) $ \face -> forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces -> let loc = Location face subfaces in loc == (fromJust . fromId . idOf $ loc) locTest = forAll (choose (0,19)) $ \face -> forAll (vectorOf 25 (elements [A,B,C,D])) $ \subfaces -> let loc = Location face subfaces in loc == (fromJust . parse . format $ loc) coordTest = forAll (choose (0.0, pi)) $ \lat -> forAll (choose (0.0, pi)) $ \lon -> acceptableError (lat, lon) (fromString' . toString $ (lat, lon)) acceptableError :: (R, R) -> (R, R) -> Bool acceptableError (a1, b1) (a2, b2) = difference <= 0.2 *~ meter where point1 = cartesian (Polar earthRadius (a1 *~ one) (b1 *~ one)) point2 = cartesian (Polar earthRadius (a2 *~ one) (b2 *~ one)) difference = lengthOf (point1 <-> point2) -- Infinite loop? -- 1.1477102348032477 -- 2.5287052457281303 -- toString (1.1477102348032477, 2.5287052457281303) -- It's resulting in a lot of kicks -- It's landing really far away -- V3 -1615695.0421316223 m 3918971.9410642236 m 582344.6221676043 m --0.5342809894312989 --2.434338807577105 -- V3 2089283.5979154985 m 1236191.1378369904 m -2840087.204665418 m
wyager/GeoLabel
src/GeoLabel/Test.hs
Haskell
bsd-3-clause
2,776
{-| Module : Reactive.DOM.Children.MonotoneList Description : Definition of the MonotoneList children container. Copyright : (c) Alexander Vieth, 2016 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE TypeFamilies #-} module Reactive.DOM.Children.MonotoneList where import Data.Semigroup import Data.Functor.Compose import Reactive.DOM.Internal.ChildrenContainer import Reactive.DOM.Internal.Mutation newtype MonotoneList t inp out f = MonotoneList { runMonotoneList :: [f t] } deriving instance Semigroup (MonotoneList t inp out f) deriving instance Monoid (MonotoneList t inp out f) instance FunctorTransformer (MonotoneList inp out t) where functorTrans trans (MonotoneList fts) = MonotoneList (trans <$> fts) functorCommute (MonotoneList fts) = MonotoneList <$> sequenceA (getCompose <$> fts) instance ChildrenContainer (MonotoneList inp out t) where type Change (MonotoneList t inp out) = MonotoneList t inp out getChange get (MonotoneList news) (MonotoneList olds) = let nextList = MonotoneList (olds <> news) mutations = AppendChild . get <$> news in (nextList, mutations) childrenContainerList get (MonotoneList ts) = get <$> ts
avieth/reactive-dom
Reactive/DOM/Children/MonotoneList.hs
Haskell
bsd-3-clause
1,438
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} ----------------------------------------------------------------------------- -- | DBSocketT transformer which signs and issues network requests. ----------------------------------------------------------------------------- module Azure.DocDB.SocketMonad.DBSocketT ( DBSocketState, DBSocketT, execDBSocketT, mkDBSocketState ) where import Control.Applicative import Control.Lens (Lens', lens, (%~), (.=), (%=)) import Control.Monad.Except import Control.Monad.Reader import Control.Monad.State import Control.Monad.Catch (MonadThrow) import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Time.Clock (getCurrentTime) import qualified Data.Text as T import qualified Data.Text.IO as T import qualified Data.Text.Encoding as T import Network.HTTP.Client as HC import qualified Network.HTTP.Types as HT import Web.HttpApiData (ToHttpApiData(..)) import Azure.DocDB.Auth import Azure.DocDB.ResourceId import qualified Azure.DocDB.ServiceHeader as AH import Azure.DocDB.SocketMonad.Class -- | Socket state for DB connections data DBSocketState = DBSocketState { dbSSRequest :: Request, -- ^ Verb, uri, body, and additional headers being sent sbSSSigning :: SigningParams -> DocDBSignature, -- ^ Method to sign requests sendHttps :: Request -> IO (Response L.ByteString) } newtype DBSocketT m a = DBSocketT { runDBSocketT :: ExceptT DBError (ReaderT DBSocketState m) a } deriving (Functor, Applicative, Monad, MonadIO) instance MonadTrans DBSocketT where lift = DBSocketT . lift . lift -- Lenses for a request method' :: Lens' Request HT.Method method' = lens method (\req m -> req { method = m }) path' :: Lens' Request B.ByteString path' = lens path (\req m -> req { path = m }) requestBody' :: Lens' Request RequestBody requestBody' = lens requestBody (\req m -> req { requestBody = m }) requestHeaders' :: Lens' Request [HT.Header] requestHeaders' = lens requestHeaders (\req m -> req { requestHeaders = m }) -- | Execute the DB operation execDBSocketT :: MonadIO m => DBSocketT m a -> DBSocketState -> m (Either DBError a) execDBSocketT (DBSocketT m) = runReaderT (runExceptT m) --- | DBSocketState constructor mkDBSocketState :: (MonadThrow m, MonadIO m, Alternative m) => B.ByteString -- ^ Signing key -> T.Text -- ^ Root url -> Manager -- ^ Network manager -> m DBSocketState mkDBSocketState signingKey root mgr = do r <- parseRequest $ T.unpack root return DBSocketState { dbSSRequest = r { requestHeaders = [AH.version] } , sbSSSigning = signRequestInfo signingKey , sendHttps = mkDebuggable (`httpLbs` mgr) } -- | Add IO printing to network activity mkDebuggable :: MonadIO m => (Request -> m (Response L.ByteString)) -> Request -> m (Response L.ByteString) mkDebuggable f req = do liftIO $ do print req T.putStrLn (case requestBody req of RequestBodyLBS lb -> T.decodeUtf8 $ L.toStrict lb RequestBodyBS sb -> T.decodeUtf8 sb _ -> "Unknown response") rspTmp <- f req liftIO $ print rspTmp return rspTmp instance Monad m => MonadError DBError (DBSocketT m) where throwError e = DBSocketT $ throwError e catchError (DBSocketT ma) fema = DBSocketT $ catchError ma (runDBSocketT . fema) instance MonadIO m => DBSocketMonad (DBSocketT m) where sendSocketRequest socketRequest = DBSocketT $ do (DBSocketState req fsign sendHttpsProc) <- ask -- Pick a timestamp for signing now <- MSDate <$> liftIO getCurrentTime -- Sign the request let signature = fsign SigningParams { spMethod = srMethod socketRequest, spResourceType = srResourceType socketRequest, spPath = srResourceLink socketRequest, spWhen = now } -- Build and issue the request response <- liftIO . sendHttpsProc . applySocketRequest . applySignature now signature $ req let status = responseStatus response let statusText = T.decodeUtf8 . HT.statusMessage $ status case HT.statusCode status of 403 -> throwError DBForbidden 404 -> throwError DBNotFound 409 -> throwError DBConflict 412 -> throwError DBPreconditionFailure 413 -> throwError DBEntityTooLarge code | code >= 400 && code < 500 -> throwError $ DBBadRequest statusText code | code >= 500 -> throwError $ DBServiceError statusText _ -> return . responseToSocketResponse $ response -- where -- Update the request to match the top level socketRequest parameters applySocketRequest :: Request -> Request applySocketRequest = execState $ do method' .= HT.renderStdMethod (srMethod socketRequest) path' %= (</> T.encodeUtf8 (srUriPath socketRequest)) requestBody' .= RequestBodyLBS (srContent socketRequest) requestHeaders' %= (srHeaders socketRequest ++) -- Apply the signature info applySignature :: ToHttpApiData a => MSDate -> a -> Request -> Request applySignature dateWhen docDBSignature = requestHeaders' %~ execState (do AH.header' AH.msDate .= Just (toHeader dateWhen) AH.header' HT.hAuthorization .= Just (toHeader docDBSignature) ) responseToSocketResponse :: Response L.ByteString -> SocketResponse responseToSocketResponse response = SocketResponse (HT.statusCode $ responseStatus response) (responseHeaders response) (responseBody response)
jnonce/azure-docdb
lib/Azure/DocDB/SocketMonad/DBSocketT.hs
Haskell
bsd-3-clause
5,678
import Test.Hspec import Control.Comonad.Cofree.Cofreer.Spec import Control.Monad.Free.Freer.Spec import GL.Shader.Spec import UI.Layout.Spec main :: IO () main = hspec . parallel $ do describe "Control.Comonad.Cofree.Cofreer.Spec" Control.Comonad.Cofree.Cofreer.Spec.spec describe "Control.Monad.Free.Freer.Spec" Control.Monad.Free.Freer.Spec.spec describe "GL.Shader.Spec" GL.Shader.Spec.spec describe "UI.Layout.Spec" UI.Layout.Spec.spec
robrix/ui-effects
test/Spec.hs
Haskell
bsd-3-clause
450
-- | A name binding context, or environment. module Hpp.Env where import Hpp.Types (Macro) -- | A macro binding environment. type Env = [(String, Macro)] -- | Delete an entry from an association list. deleteKey :: Eq a => a -> [(a,b)] -> [(a,b)] deleteKey k = go where go [] = [] go (h@(x,_) : xs) = if x == k then xs else h : go xs -- | Looks up a value in an association list. If the key is found, the -- value is returned along with an updated association list with that -- key at the front. lookupKey :: Eq a => a -> [(a,b)] -> Maybe (b, [(a,b)]) lookupKey k = go id where go _ [] = Nothing go acc (h@(x,v) : xs) | k == x = Just (v, h : acc [] ++ xs) | otherwise = go (acc . (h:)) xs
bitemyapp/hpp
src/Hpp/Env.hs
Haskell
bsd-3-clause
731
module Dice where import Control.Monad (liftM) import Control.Monad.Random import Data.List (intercalate) data DiceBotCmd = Start | Quit | Roll { cmdDice :: [Die] } | None | Bad { cmdBad :: String } deriving (Show, Eq) data Die = Const { dieConst :: Int } | Die { dieNum :: Int, dieType :: Int } deriving (Show, Eq) showDice :: [Die] -> String showDice = intercalate " + " . map showDie where showDie (Const n) = show n showDie (Die n t) = show n ++ "d" ++ show t showResult :: [Int] -> String showResult = intercalate " + " . map show randomFace :: RandomGen g => Int -> Rand g Int randomFace t = getRandomR (1, t) rollDie :: RandomGen g => Die -> Rand g [Int] rollDie (Const n) = return [n] rollDie (Die n t) = sequence . replicate n $ randomFace t rollDice :: [Die] -> IO [Int] rollDice = evalRandIO . liftM concat . mapM rollDie
haskell-ro/hs-dicebot
Dice.hs
Haskell
bsd-3-clause
873
import Data.Either import Test.Hspec import qualified Text.Parsec as P import Lib import Lexer as L import Parser as P program = unlines [ "dong inflate." , "[ 3 ] value." , "[ :x | x name ] value: 9." ] lexerSpec = do describe "parseToken" $ do let parseToken = P.parse L.parseToken "(spec)" it "parses LBracket" $ do parseToken "[" `shouldBe` Right LBracket it "parses RBracket" $ do parseToken "]" `shouldBe` Right RBracket it "parses Period" $ do parseToken "." `shouldBe` Right Period it "parses Pipe" $ do parseToken "|" `shouldBe` Right Pipe it "parses Bind" $ do parseToken ":=" `shouldBe` Right Bind it "parses Name" $ do parseToken "abc" `shouldBe` Right (Name "abc") it "parses a Name with a number" $ do parseToken "abc1" `shouldBe` Right (Name "abc1") it "parses Keyword" $ do parseToken "abc:" `shouldBe` Right (Keyword "abc") it "parses Arg" $ do parseToken ":abc" `shouldBe` Right (Arg "abc") it "parses Symbol" $ do parseToken "+" `shouldBe` Right (Symbol "+") it "parses StringLiteral" $ do parseToken "'hello'" `shouldBe` Right (StringLiteral "hello") it "parses CharLiteral" $ do parseToken "$a" `shouldBe` Right (CharLiteral 'a') it "parses Number" $ do parseToken "32" `shouldBe` Right (Number 32) parserSpec = do let parse p s = do lexed <- P.parse L.parseTokens "(spec)" s P.parse p "(spec)" lexed describe "parseLiteral" $ do let parseLiteral = parse P.parseLiteral it "parses string literal" $ do parseLiteral "'hi'" `shouldBe` Right (LiteralString "hi") it "parses number literal" $ do parseLiteral "23" `shouldBe` Right (LiteralNumber 23) describe "parseStatement" $ do let parseStatement = parse P.parseStatement it "parses unary message" $ do parseStatement "abc def." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [UnaryMessage "def"] [] [])] Nothing) it "parses binary message" $ do parseStatement "abc + def." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [] [BinaryMessage "+" (OperandIdentifier "def")] [])] Nothing) it "parses keyword message" $ do parseStatement "abc def: xyz." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "abc") [] [] [KeywordMessage "def" (OperandIdentifier "xyz")])] Nothing) it "parses combined message" $ do parseStatement "a b - c d: e." `shouldBe` Right (Statement [(ExpressionSend (OperandIdentifier "a") [UnaryMessage "b"] [BinaryMessage "-" (OperandIdentifier "c")] [KeywordMessage "d" (OperandIdentifier "e")])] Nothing) it "parses message to nested expression" $ do parseStatement "(a b) c." `shouldBe` Right (Statement [(ExpressionSend (OperandNested (ExpressionSend (OperandIdentifier "a") [UnaryMessage "b"] [] [])) [UnaryMessage "c"] [] [])] Nothing) it "parses a naked expression as a statement" $ do parseStatement "3" `shouldBe` Right (Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] [])) it "parses block without args" $ do parseStatement "[ 3 ]" `shouldBe` Right (Statement [] (Just $ (ExpressionSend (OperandBlock (Block [] [Statement [] (Just $ ExpressionSend (OperandLiteral (LiteralNumber 3)) [] [] [])])) [] [] [] ) )) it "parses block with args" $ do parseStatement "[ :x | x ]" `shouldBe` Right (Statement [] (Just $ (ExpressionSend (OperandBlock (Block ["x"] [Statement [] (Just $ ExpressionSend (OperandIdentifier "x") [] [] [])]) ) [] [] [] ))) it "parses block with multiple args and statements" $ do parseStatement "[ :x :y | 2 negate. x + y / 2 ]" `shouldBe` Right (Statement [] (Just $ ExpressionSend (OperandBlock (Block ["x", "y"] [Statement [ExpressionSend (OperandLiteral (LiteralNumber 2)) [UnaryMessage "negate"] [] []] (Just $ ExpressionSend (OperandIdentifier "x") [] [BinaryMessage "+" (OperandIdentifier "y"), BinaryMessage "/" (OperandLiteral (LiteralNumber 2))] [] )] ) ) [] [] [])) it "does not parse statement with malformed binop" $ do parseStatement "a + + b" `shouldSatisfy` isLeft it "does not parse statement with malformed keyword message" $ do parseStatement "a b: c: d" `shouldSatisfy` isLeft main = do hspec lexerSpec hspec parserSpec
rjeli/luatalk
test/Spec.hs
Haskell
bsd-3-clause
5,511
{-# LANGUAGE LambdaCase #-} module Main (main) where import System.Environment (getArgs) eyes = cycle ["⦿⦿", "⦾⦾", "⟐⟐", "⪽⪾", "⨷⨷", "⨸⨸", "☯☯", "⊙⊙", "⊚⊚", "⊛⊛", "⨕⨕", "⊗⊗", "⊘⊘", "⊖⊖", "⁌⁍", "✩✩", "❈❈"] shells = cycle ["()", "{}", "[]", "⨭⨮", "⨴⨵", "⊆⊇", "∣∣"] bodies = cycle ["███", "XXX", "⧱⧰⧱", "⧯⧮⧯", "⧲⧳⧲","🁢🁢🁢", "✚✚✚", "⧓⧒⧑", "⦁⦁⦁", "☗☗☗", "❝❝❝"] arthropod k = (face k):(repeat $ body k) face k = let (l:r:[]) = eyes !! k in "╚" ++ l:" " ++ r:"╝" body k = let (l:r:[]) = shells !! k c = bodies !! k in "╚═" ++ l:c ++ r:"═╝" wiggle = map (flip replicate ' ') (4 : cycle [2,1,0,1,2,3,4,3]) millipede = zipWith (++) wiggle . arthropod main :: IO () main = getArgs >>= \case [] -> beautiful $ millipede 0 (x:[]) -> beautiful $ millipede (read x) where beautiful = putStrLn . unlines . take 20
getmillipede/millipede-haskell
app/Main.hs
Haskell
bsd-3-clause
1,023
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} -- | This module builds Docker (OpenContainer) images. module Stack.Image (stageContainerImageArtifacts, createContainerImageFromStage, imgCmdName, imgDockerCmdName, imgOptsFromMonoid, imgDockerOptsFromMonoid, imgOptsParser, imgDockerOptsParser) where import Control.Applicative import Control.Exception.Lifted hiding (finally) import Control.Monad import Control.Monad.Catch hiding (bracket) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Char (toLower) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Monoid import qualified Data.Text as T import Data.Typeable import Options.Applicative import Path import Path.Extra import Path.IO import Stack.Constants import Stack.Types import Stack.Types.Internal import System.Process.Run type Build e m = (HasBuildConfig e, HasConfig e, HasEnvConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadReader e m) type Assemble e m = (HasConfig e, HasTerminal e, MonadBaseControl IO m, MonadCatch m, MonadIO m, MonadLogger m, MonadMask m, MonadReader e m) -- | Stages the executables & additional content in a staging -- directory under '.stack-work' stageContainerImageArtifacts :: Build e m => m () stageContainerImageArtifacts = do imageDir <- imageStagingDir <$> getWorkingDir removeTreeIfExists imageDir createTree imageDir stageExesInDir imageDir syncAddContentToDir imageDir -- | Builds a Docker (OpenContainer) image extending the `base` image -- specified in the project's stack.yaml. Then new image will be -- extended with an ENTRYPOINT specified for each `entrypoint` listed -- in the config file. createContainerImageFromStage :: Assemble e m => m () createContainerImageFromStage = do imageDir <- imageStagingDir <$> getWorkingDir createDockerImage imageDir extendDockerImageWithEntrypoint imageDir -- | Stage all the Package executables in the usr/local/bin -- subdirectory of a temp directory. stageExesInDir :: Build e m => Path Abs Dir -> m () stageExesInDir dir = do srcBinPath <- (</> $(mkRelDir "bin")) <$> installationRootLocal let destBinPath = dir </> $(mkRelDir "usr/local/bin") createTree destBinPath copyDirectoryRecursive srcBinPath destBinPath -- | Add any additional files into the temp directory, respecting the -- (Source, Destination) mapping. syncAddContentToDir :: Build e m => Path Abs Dir -> m () syncAddContentToDir dir = do config <- asks getConfig bconfig <- asks getBuildConfig let imgAdd = maybe Map.empty imgDockerAdd (imgDocker (configImage config)) forM_ (Map.toList imgAdd) (\(source,dest) -> do sourcePath <- parseRelDir source destPath <- parseAbsDir dest let destFullPath = dir </> dropRoot destPath createTree destFullPath copyDirectoryRecursive (bcRoot bconfig </> sourcePath) destFullPath) -- | Derive an image name from the project directory. imageName :: Path Abs Dir -> String imageName = map toLower . toFilePathNoTrailingSep . dirname -- | Create a general purpose docker image from the temporary -- directory of executables & static content. createDockerImage :: Assemble e m => Path Abs Dir -> m () createDockerImage dir = do menv <- getMinimalEnvOverride config <- asks getConfig let dockerConfig = imgDocker (configImage config) case imgDockerBase =<< dockerConfig of Nothing -> throwM StackImageDockerBaseUnspecifiedException Just base -> do liftIO (writeFile (toFilePath (dir </> $(mkRelFile "Dockerfile"))) (unlines ["FROM " ++ base, "ADD ./ /"])) callProcess Nothing menv "docker" [ "build" , "-t" , fromMaybe (imageName (parent (parent dir))) (imgDockerImageName =<< dockerConfig) , toFilePathNoTrailingSep dir] -- | Extend the general purpose docker image with entrypoints (if -- specified). extendDockerImageWithEntrypoint :: Assemble e m => Path Abs Dir -> m () extendDockerImageWithEntrypoint dir = do menv <- getMinimalEnvOverride config <- asks getConfig let dockerConfig = imgDocker (configImage config) let dockerImageName = fromMaybe (imageName (parent (parent dir))) (imgDockerImageName =<< dockerConfig) let imgEntrypoints = maybe Nothing imgDockerEntrypoints dockerConfig case imgEntrypoints of Nothing -> return () Just eps -> forM_ eps (\ep -> do liftIO (writeFile (toFilePath (dir </> $(mkRelFile "Dockerfile"))) (unlines [ "FROM " ++ dockerImageName , "ENTRYPOINT [\"/usr/local/bin/" ++ ep ++ "\"]" , "CMD []"])) callProcess Nothing menv "docker" [ "build" , "-t" , dockerImageName ++ "-" ++ ep , toFilePathNoTrailingSep dir]) -- | The command name for dealing with images. imgCmdName :: String imgCmdName = "image" -- | The command name for building a docker container. imgDockerCmdName :: String imgDockerCmdName = "container" -- | A parser for ImageOptsMonoid. imgOptsParser :: Parser ImageOptsMonoid imgOptsParser = ImageOptsMonoid <$> optional (subparser (command imgDockerCmdName (info imgDockerOptsParser (progDesc "Create a container image (EXPERIMENTAL)")))) -- | A parser for ImageDockerOptsMonoid. imgDockerOptsParser :: Parser ImageDockerOptsMonoid imgDockerOptsParser = ImageDockerOptsMonoid <$> optional (option str (long (imgDockerCmdName ++ "-" ++ T.unpack imgDockerBaseArgName) <> metavar "NAME" <> help "Docker base image name")) <*> pure Nothing <*> pure Nothing <*> pure Nothing -- | Convert image opts monoid to image options. imgOptsFromMonoid :: ImageOptsMonoid -> ImageOpts imgOptsFromMonoid ImageOptsMonoid{..} = ImageOpts { imgDocker = imgDockerOptsFromMonoid <$> imgMonoidDocker } -- | Convert Docker image opts monoid to Docker image options. imgDockerOptsFromMonoid :: ImageDockerOptsMonoid -> ImageDockerOpts imgDockerOptsFromMonoid ImageDockerOptsMonoid{..} = ImageDockerOpts { imgDockerBase = emptyToNothing imgDockerMonoidBase , imgDockerEntrypoints = emptyToNothing imgDockerMonoidEntrypoints , imgDockerAdd = fromMaybe Map.empty imgDockerMonoidAdd , imgDockerImageName = emptyToNothing imgDockerMonoidImageName } where emptyToNothing Nothing = Nothing emptyToNothing (Just s) | null s = Nothing | otherwise = Just s -- | Stack image exceptions. data StackImageException = StackImageDockerBaseUnspecifiedException deriving (Typeable) instance Exception StackImageException instance Show StackImageException where show StackImageDockerBaseUnspecifiedException = "You must specify a base docker image on which to place your haskell executables."
rvion/stack
src/Stack/Image.hs
Haskell
bsd-3-clause
8,426
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Auxilary definitions for 'Semigroup' -- -- This module provides some @newtype@ wrappers and helpers which are -- reexported from the "Data.Semigroup" module or imported directly -- by some other modules. -- -- This module also provides internal definitions related to the -- 'Semigroup' class some. -- -- This module exists mostly to simplify or workaround import-graph -- issues; there is also a .hs-boot file to allow "GHC.Base" and other -- modules to import method default implementations for 'stimes' -- -- @since 4.11.0.0 module Data.Semigroup.Internal where import GHC.Base hiding (Any) import GHC.Enum import GHC.Num import GHC.Read import GHC.Show import GHC.Generics import GHC.Real -- | This is a valid definition of 'stimes' for an idempotent 'Semigroup'. -- -- When @x <> x = x@, this definition should be preferred, because it -- works in /O(1)/ rather than /O(log n)/. stimesIdempotent :: Integral b => b -> a -> a stimesIdempotent n x | n <= 0 = errorWithoutStackTrace "stimesIdempotent: positive multiplier expected" | otherwise = x -- | This is a valid definition of 'stimes' for an idempotent 'Monoid'. -- -- When @mappend x x = x@, this definition should be preferred, because it -- works in /O(1)/ rather than /O(log n)/ stimesIdempotentMonoid :: (Integral b, Monoid a) => b -> a -> a stimesIdempotentMonoid n x = case compare n 0 of LT -> errorWithoutStackTrace "stimesIdempotentMonoid: negative multiplier" EQ -> mempty GT -> x -- | This is a valid definition of 'stimes' for a 'Monoid'. -- -- Unlike the default definition of 'stimes', it is defined for 0 -- and so it should be preferred where possible. stimesMonoid :: (Integral b, Monoid a) => b -> a -> a stimesMonoid n x0 = case compare n 0 of LT -> errorWithoutStackTrace "stimesMonoid: negative multiplier" EQ -> mempty GT -> f x0 n where f x y | even y = f (x `mappend` x) (y `quot` 2) | y == 1 = x | otherwise = g (x `mappend` x) (y `quot` 2) x -- See Note [Half of y - 1] g x y z | even y = g (x `mappend` x) (y `quot` 2) z | y == 1 = x `mappend` z | otherwise = g (x `mappend` x) (y `quot` 2) (x `mappend` z) -- See Note [Half of y - 1] -- this is used by the class definitionin GHC.Base; -- it lives here to avoid cycles stimesDefault :: (Integral b, Semigroup a) => b -> a -> a stimesDefault y0 x0 | y0 <= 0 = errorWithoutStackTrace "stimes: positive multiplier expected" | otherwise = f x0 y0 where f x y | even y = f (x <> x) (y `quot` 2) | y == 1 = x | otherwise = g (x <> x) (y `quot` 2) x -- See Note [Half of y - 1] g x y z | even y = g (x <> x) (y `quot` 2) z | y == 1 = x <> z | otherwise = g (x <> x) (y `quot` 2) (x <> z) -- See Note [Half of y - 1] {- Note [Half of y - 1] ~~~~~~~~~~~~~~~~~~~~~ Since y is guaranteed to be odd and positive here, half of y - 1 can be computed as y `quot` 2, optimising subtraction away. -} stimesMaybe :: (Integral b, Semigroup a) => b -> Maybe a -> Maybe a stimesMaybe _ Nothing = Nothing stimesMaybe n (Just a) = case compare n 0 of LT -> errorWithoutStackTrace "stimes: Maybe, negative multiplier" EQ -> Nothing GT -> Just (stimes n a) stimesList :: Integral b => b -> [a] -> [a] stimesList n x | n < 0 = errorWithoutStackTrace "stimes: [], negative multiplier" | otherwise = rep n where rep 0 = [] rep i = x ++ rep (i - 1) -- | The dual of a 'Monoid', obtained by swapping the arguments of 'mappend'. -- -- >>> getDual (mappend (Dual "Hello") (Dual "World")) -- "WorldHello" newtype Dual a = Dual { getDual :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1) -- | @since 4.9.0.0 instance Semigroup a => Semigroup (Dual a) where Dual a <> Dual b = Dual (b <> a) stimes n (Dual a) = Dual (stimes n a) -- | @since 2.01 instance Monoid a => Monoid (Dual a) where mempty = Dual mempty -- | @since 4.8.0.0 instance Functor Dual where fmap = coerce -- | @since 4.8.0.0 instance Applicative Dual where pure = Dual (<*>) = coerce -- | @since 4.8.0.0 instance Monad Dual where m >>= k = k (getDual m) -- | The monoid of endomorphisms under composition. -- -- >>> let computation = Endo ("Hello, " ++) <> Endo (++ "!") -- >>> appEndo computation "Haskell" -- "Hello, Haskell!" newtype Endo a = Endo { appEndo :: a -> a } deriving (Generic) -- | @since 4.9.0.0 instance Semigroup (Endo a) where (<>) = coerce ((.) :: (a -> a) -> (a -> a) -> (a -> a)) stimes = stimesMonoid -- | @since 2.01 instance Monoid (Endo a) where mempty = Endo id -- | Boolean monoid under conjunction ('&&'). -- -- >>> getAll (All True <> mempty <> All False) -- False -- -- >>> getAll (mconcat (map (\x -> All (even x)) [2,4,6,7,8])) -- False newtype All = All { getAll :: Bool } deriving (Eq, Ord, Read, Show, Bounded, Generic) -- | @since 4.9.0.0 instance Semigroup All where (<>) = coerce (&&) stimes = stimesIdempotentMonoid -- | @since 2.01 instance Monoid All where mempty = All True -- | Boolean monoid under disjunction ('||'). -- -- >>> getAny (Any True <> mempty <> Any False) -- True -- -- >>> getAny (mconcat (map (\x -> Any (even x)) [2,4,6,7,8])) -- True newtype Any = Any { getAny :: Bool } deriving (Eq, Ord, Read, Show, Bounded, Generic) -- | @since 4.9.0.0 instance Semigroup Any where (<>) = coerce (||) stimes = stimesIdempotentMonoid -- | @since 2.01 instance Monoid Any where mempty = Any False -- | Monoid under addition. -- -- >>> getSum (Sum 1 <> Sum 2 <> mempty) -- 3 newtype Sum a = Sum { getSum :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num) -- | @since 4.9.0.0 instance Num a => Semigroup (Sum a) where (<>) = coerce ((+) :: a -> a -> a) stimes n (Sum a) = Sum (fromIntegral n * a) -- | @since 2.01 instance Num a => Monoid (Sum a) where mempty = Sum 0 -- | @since 4.8.0.0 instance Functor Sum where fmap = coerce -- | @since 4.8.0.0 instance Applicative Sum where pure = Sum (<*>) = coerce -- | @since 4.8.0.0 instance Monad Sum where m >>= k = k (getSum m) -- | Monoid under multiplication. -- -- >>> getProduct (Product 3 <> Product 4 <> mempty) -- 12 newtype Product a = Product { getProduct :: a } deriving (Eq, Ord, Read, Show, Bounded, Generic, Generic1, Num) -- | @since 4.9.0.0 instance Num a => Semigroup (Product a) where (<>) = coerce ((*) :: a -> a -> a) stimes n (Product a) = Product (a ^ n) -- | @since 2.01 instance Num a => Monoid (Product a) where mempty = Product 1 -- | @since 4.8.0.0 instance Functor Product where fmap = coerce -- | @since 4.8.0.0 instance Applicative Product where pure = Product (<*>) = coerce -- | @since 4.8.0.0 instance Monad Product where m >>= k = k (getProduct m) -- | Monoid under '<|>'. -- -- @since 4.8.0.0 newtype Alt f a = Alt {getAlt :: f a} deriving (Generic, Generic1, Read, Show, Eq, Ord, Num, Enum, Monad, MonadPlus, Applicative, Alternative, Functor) -- | @since 4.9.0.0 instance Alternative f => Semigroup (Alt f a) where (<>) = coerce ((<|>) :: f a -> f a -> f a) stimes = stimesMonoid -- | @since 4.8.0.0 instance Alternative f => Monoid (Alt f a) where mempty = Alt empty
ezyang/ghc
libraries/base/Data/Semigroup/Internal.hs
Haskell
bsd-3-clause
7,619
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "System/Process/Common.hs" #-} {-# LANGUAGE CPP #-} {-# LANGUAGE RecordWildCards #-} module System.Process.Common ( CreateProcess (..) , CmdSpec (..) , StdStream (..) , ProcessHandle(..) , ProcessHandle__(..) , ProcRetHandles (..) , withFilePathException , PHANDLE , modifyProcessHandle , withProcessHandle , fd_stdin , fd_stdout , fd_stderr , mbFd , mbPipe , pfdToHandle -- Avoid a warning on Windows , CGid ) where import Control.Concurrent import Control.Exception import Data.String import Foreign.Ptr import Foreign.Storable import System.Posix.Internals import GHC.IO.Exception import GHC.IO.Encoding import qualified GHC.IO.FD as FD import GHC.IO.Device import GHC.IO.Handle.FD import GHC.IO.Handle.Internals import GHC.IO.Handle.Types hiding (ClosedHandle) import System.IO.Error import Data.Typeable import GHC.IO.IOMode -- We do a minimal amount of CPP here to provide uniform data types across -- Windows and POSIX. import System.Posix.Types type PHANDLE = CPid data CreateProcess = CreateProcess{ cmdspec :: CmdSpec, -- ^ Executable & arguments, or shell command. If 'cwd' is 'Nothing', relative paths are resolved with respect to the current working directory. If 'cwd' is provided, it is implementation-dependent whether relative paths are resolved with respect to 'cwd' or the current working directory, so absolute paths should be used to ensure portability. cwd :: Maybe FilePath, -- ^ Optional path to the working directory for the new process env :: Maybe [(String,String)], -- ^ Optional environment (otherwise inherit from the current process) std_in :: StdStream, -- ^ How to determine stdin std_out :: StdStream, -- ^ How to determine stdout std_err :: StdStream, -- ^ How to determine stderr close_fds :: Bool, -- ^ Close all file descriptors except stdin, stdout and stderr in the new process (on Windows, only works if std_in, std_out, and std_err are all Inherit) create_group :: Bool, -- ^ Create a new process group delegate_ctlc:: Bool, -- ^ Delegate control-C handling. Use this for interactive console processes to let them handle control-C themselves (see below for details). -- -- On Windows this has no effect. -- -- @since 1.2.0.0 detach_console :: Bool, -- ^ Use the windows DETACHED_PROCESS flag when creating the process; does nothing on other platforms. -- -- @since 1.3.0.0 create_new_console :: Bool, -- ^ Use the windows CREATE_NEW_CONSOLE flag when creating the process; does nothing on other platforms. -- -- Default: @False@ -- -- @since 1.3.0.0 new_session :: Bool, -- ^ Use posix setsid to start the new process in a new session; does nothing on other platforms. -- -- @since 1.3.0.0 child_group :: Maybe GroupID, -- ^ Use posix setgid to set child process's group id; does nothing on other platforms. -- -- Default: @Nothing@ -- -- @since 1.4.0.0 child_user :: Maybe UserID, -- ^ Use posix setuid to set child process's user id; does nothing on other platforms. -- -- Default: @Nothing@ -- -- @since 1.4.0.0 use_process_jobs :: Bool -- ^ On Windows systems this flag indicates that we should wait for the entire process tree -- to finish before unblocking. On POSIX systems this flag is ignored. -- -- Default: @False@ -- -- @since 1.5.0.0 } deriving (Show, Eq) -- | contains the handles returned by a call to createProcess_Internal data ProcRetHandles = ProcRetHandles { hStdInput :: Maybe Handle , hStdOutput :: Maybe Handle , hStdError :: Maybe Handle , procHandle :: ProcessHandle } data CmdSpec = ShellCommand String -- ^ A command line to execute using the shell | RawCommand FilePath [String] -- ^ The name of an executable with a list of arguments -- -- The 'FilePath' argument names the executable, and is interpreted -- according to the platform's standard policy for searching for -- executables. Specifically: -- -- * on Unix systems the -- <http://pubs.opengroup.org/onlinepubs/9699919799/functions/execvp.html execvp(3)> -- semantics is used, where if the executable filename does not -- contain a slash (@/@) then the @PATH@ environment variable is -- searched for the executable. -- -- * on Windows systems the Win32 @CreateProcess@ semantics is used. -- Briefly: if the filename does not contain a path, then the -- directory containing the parent executable is searched, followed -- by the current directory, then some standard locations, and -- finally the current @PATH@. An @.exe@ extension is added if the -- filename does not already have an extension. For full details -- see the -- <http://msdn.microsoft.com/en-us/library/windows/desktop/aa365527%28v=vs.85%29.aspx documentation> -- for the Windows @SearchPath@ API. deriving (Show, Eq) -- | construct a `ShellCommand` from a string literal -- -- @since 1.2.1.0 instance IsString CmdSpec where fromString = ShellCommand data StdStream = Inherit -- ^ Inherit Handle from parent | UseHandle Handle -- ^ Use the supplied Handle | CreatePipe -- ^ Create a new pipe. The returned -- @Handle@ will use the default encoding -- and newline translation mode (just -- like @Handle@s created by @openFile@). | NoStream -- ^ No stream handle will be passed deriving (Eq, Show) -- ---------------------------------------------------------------------------- -- ProcessHandle type {- | A handle to a process, which can be used to wait for termination of the process using 'System.Process.waitForProcess'. None of the process-creation functions in this library wait for termination: they all return a 'ProcessHandle' which may be used to wait for the process later. On Windows a second wait method can be used to block for event completion. This requires two handles. A process job handle and a events handle to monitor. -} data ProcessHandle__ = OpenHandle PHANDLE | OpenExtHandle PHANDLE PHANDLE PHANDLE | ClosedHandle ExitCode data ProcessHandle = ProcessHandle { phandle :: !(MVar ProcessHandle__) , mb_delegate_ctlc :: !Bool , waitpidLock :: !(MVar ()) } withFilePathException :: FilePath -> IO a -> IO a withFilePathException fpath act = handle mapEx act where mapEx ex = ioError (ioeSetFileName ex fpath) modifyProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO (ProcessHandle__, a)) -> IO a modifyProcessHandle (ProcessHandle m _ _) io = modifyMVar m io withProcessHandle :: ProcessHandle -> (ProcessHandle__ -> IO a) -> IO a withProcessHandle (ProcessHandle m _ _) io = withMVar m io fd_stdin, fd_stdout, fd_stderr :: FD fd_stdin = 0 fd_stdout = 1 fd_stderr = 2 mbFd :: String -> FD -> StdStream -> IO FD mbFd _ _std CreatePipe = return (-1) mbFd _fun std Inherit = return std mbFd _fn _std NoStream = return (-2) mbFd fun _std (UseHandle hdl) = withHandle fun hdl $ \Handle__{haDevice=dev,..} -> case cast dev of Just fd -> do -- clear the O_NONBLOCK flag on this FD, if it is set, since -- we're exposing it externally (see #3316) fd' <- FD.setNonBlockingMode fd False return (Handle__{haDevice=fd',..}, FD.fdFD fd') Nothing -> ioError (mkIOError illegalOperationErrorType "createProcess" (Just hdl) Nothing `ioeSetErrorString` "handle is not a file descriptor") mbPipe :: StdStream -> Ptr FD -> IOMode -> IO (Maybe Handle) mbPipe CreatePipe pfd mode = fmap Just (pfdToHandle pfd mode) mbPipe _std _pfd _mode = return Nothing pfdToHandle :: Ptr FD -> IOMode -> IO Handle pfdToHandle pfd mode = do fd <- peek pfd let filepath = "fd:" ++ show fd (fD,fd_type) <- FD.mkFD (fromIntegral fd) mode (Just (Stream,0,0)) -- avoid calling fstat() False {-is_socket-} False {-non-blocking-} fD' <- FD.setNonBlockingMode fD True -- see #3316 enc <- getLocaleEncoding mkHandleFromFD fD' fd_type filepath mode False {-is_socket-} (Just enc)
phischu/fragnix
tests/packages/scotty/System.Process.Common.hs
Haskell
bsd-3-clause
9,966
<?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="ko-KR"> <title>Revisit | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
0xkasun/security-tools
src/org/zaproxy/zap/extension/revisit/resources/help_ko_KR/helpset_ko_KR.hs
Haskell
apache-2.0
969
{-# LANGUAGE TypeOperators, MultiParamTypeClasses, FlexibleInstances #-} {-# OPTIONS_GHC -Wall #-} module Mixin where import Prelude hiding (log) class a <: b where up :: a -> b instance (t1 <: t2) => (t -> t1) <: (t -> t2) where up f = up . f instance (t1 <: t2) => (t2 -> t) <: (t1 -> t) where up f = f . up type Class t = t -> t type Mixin s t = s -> t -> t new :: Class a -> a new f = let r = f r in r with :: (t <: s) => Class s -> Mixin s t -> Class t klass `with` mixin = \this -> mixin (klass (up this)) this -- The below provides an example. fib' :: Class (Int -> Int) fib' _ 1 = 1 fib' _ 2 = 1 fib' this n = this (n-1) + this (n-2) instance (Int, String) <: Int where up = fst logging :: Mixin (Int -> Int) (Int -> (Int, String)) logging super _ 1 = (super 1, "1") logging super _ 2 = (super 2, "2 1") logging super this n = (super n, show n ++ " " ++ log1 ++ " " ++ log2) where (_, log1) = this (n-1) (_, log2) = this (n-2) fibWithLogging :: Int -> (Int, String) fibWithLogging = new (fib' `with` logging)
bixuanzju/fcore
lib/Mixin.hs
Haskell
bsd-2-clause
1,062
module Head where {-@ measure hd :: [a] -> a hd (x:xs) = x @-} -- Strengthened constructors -- data [a] where -- [] :: [a] -- as before -- (:) :: x:a -> xs:[a] -> {v:[a] | hd v = x} {-@ cons :: x:a -> _ -> {v:[a] | hd v = x} @-} cons x xs = x : xs {-@ test :: {v:_ | hd v = 0} @-} test :: [Int] test = cons 0 [1,2,3,4]
abakst/liquidhaskell
tests/todo/partialmeasureOld.hs
Haskell
bsd-3-clause
356
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} module Bug where import Data.Kind type HRank1 ty = forall k1. k1 -> ty type HRank2 ty = forall k2. k2 -> ty data HREFL11 :: HRank1 (HRank1 Type) -- FAILS data HREFL12 :: HRank1 (HRank2 Type) data HREFL21 :: HRank2 (HRank1 Type) data HREFL22 :: HRank2 (HRank2 Type) -- FAILS
sdiehl/ghc
testsuite/tests/polykinds/T14515.hs
Haskell
bsd-3-clause
359
module Main where import GHC import MonadUtils import System.Environment main :: IO () main = do [libdir] <- getArgs runGhc (Just libdir) doit doit :: Ghc () doit = do getSessionDynFlags >>= setSessionDynFlags dyn <- dynCompileExpr "()" liftIO $ print dyn
siddhanathan/ghc
testsuite/tests/ghc-api/dynCompileExpr/dynCompileExpr.hs
Haskell
bsd-3-clause
278
{-# LANGUAGE TypeFamilies #-} module T1897b where import Control.Monad import Data.Maybe class Bug s where type Depend s next :: s -> Depend s -> Maybe s start :: s -- isValid :: (Bug s) => [Depend s] -> Bool -- Inferred type should be rejected as ambiguous isValid ds = isJust $ foldM next start ds
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/indexed-types/should_fail/T1897b.hs
Haskell
bsd-3-clause
316
{-# OPTIONS_GHC -fno-safe-infer #-} -- | Basic test to see if no safe infer flag compiles -- This module would usually infer safely, so it shouldn't be safe now. -- We don't actually check that here though, see test '' for that. module SafeFlags27 where f :: Int f = 1
wxwxwwxxx/ghc
testsuite/tests/safeHaskell/flags/SafeFlags27.hs
Haskell
bsd-3-clause
271