code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE DeriveDataTypeable #-} module Transient.EVars where import Transient.Base import Transient.Internals(runTransState,onNothing, EventF(..), killChildren) import qualified Data.Map as M import Data.Typeable import Control.Concurrent import Control.Applicative import Control.Concurrent.STM import Control.Monad.IO.Class import Control.Exception(SomeException) import Data.List(nub) import Control.Monad.State data EVar a= EVar Int (TVar (Int,Int)) (TChan (StreamData a)) deriving Typeable -- | creates an EVar. -- -- Evars are event vars. `writeEVar` trigger the execution of all the continuations associated to the `readEVar` of this variable -- (the code that is after them). -- -- It is like the publish-subscribe pattern but without inversion of control, since a readEVar can be inserted at any place in the -- Transient flow. -- -- EVars are created upstream and can be used to communicate two sub-threads of the monad. Following the Transient philosophy they -- do not block his own thread if used with alternative operators, unlike the IORefs and TVars. And unlike STM vars, that are composable, -- they wait for their respective events, while TVars execute the whole expression when any variable is modified. -- -- The execution continues after the writeEVar when all subscribers have been executed. -- -- Now the continuations are executed in parallel. -- -- see https://www.fpcomplete.com/user/agocorona/publish-subscribe-variables-transient-effects-v -- newEVar :: TransIO (EVar a) newEVar = Transient $ do id <- genId rn <- liftIO $ newTVarIO (0,0) ref <-liftIO newTChanIO return . Just $ EVar id rn ref -- | delete al the subscriptions for an evar. cleanEVar :: EVar a -> TransIO () cleanEVar (EVar id rn ref1)= liftIO $ atomically $ do writeTChan ref1 SDone writeTVar rn (0,0) -- | read the EVar. It only succeed when the EVar is being updated -- The continuation gets registered to be executed whenever the variable is updated. -- -- if readEVar is re-executed in any kind of loop, since each continuation is different, this will register -- again. The effect is that the continuation will be executed multiple times -- To avoid multiple registrations, use `cleanEVar` readEVar (EVar id rn ref1)= freeThreads $ do liftIO $ atomically $ readTVar rn >>= \(n,n') -> writeTVar rn $ (n+1,n'+1) r <- parallel $ atomically $ do r <- peekTChan ref1 ---- return () !> "peekTChan executed" (n,n') <- readTVar rn -- !> "readtvar rn" -- return () !> ("rn",n) if n'> 1 then do writeTVar rn (n,n'-1) return r else do readTChan ref1 writeTVar rn (n,n) return r case r of SDone -> empty SMore x -> return x SLast x -> return x SError e -> liftIO $ do atomically $ readTVar rn >>= \(n,n') -> writeTVar rn $ (n-1,n'-1) myThreadId >>= killThread error $ "readEVar: "++ show e -- | update the EVar and execute all readEVar blocks with "last in-first out" priority -- writeEVar (EVar id rn ref1) x= liftIO $ atomically $ do writeTChan ref1 $ SMore x -- | write the EVar and drop all the `readEVar` handlers. -- -- It is like a combination of `writeEVar` and `cleanEVar` lastWriteEVar (EVar id rn ref1) x= liftIO $ atomically $ do writeTChan ref1 $ SLast x -- Finalization type FinishReason= Maybe SomeException data Finish= Finish (EVar FinishReason) deriving Typeable -- | initialize the event variable for finalization. -- all the following computations in different threads will share it -- it also isolate this event from other branches that may have his own finish variable initFinish :: TransIO Finish initFinish= do fin <- newEVar let f = Finish fin setData f return f -- | set a computation to be called when the finish event happens onFinish :: (FinishReason ->TransIO ()) -> TransIO () onFinish close= do Finish finish <- getSData <|> initFinish e <- readEVar finish close e -- !!> "CLOSE" stop <|> return () -- | trigger the event, so this closes all the resources finish :: FinishReason -> TransIO () finish e= do liftIO $ putStr "finish: " >> print e Finish finish <- getSData <|> initFinish lastWriteEVar finish e -- | deregister all the finalization actions. -- A initFinish is needed to register actions again unFinish= do Finish fin <- getSData cleanEVar fin -- !!> "DELEVAR" <|> return () -- !!> "NOT DELEVAR" -- | kill all the processes generated by the parameter when finish event occurs killOnFinish comp= do chs <- liftIO $ newTVarIO [] onFinish $ const $ liftIO $ killChildren chs -- !> "killOnFinish event" r <- comp modify $ \ s -> s{children= chs} return r -- | trigger finish when the stream data return SDone checkFinalize v= case v of SDone -> finish Nothing >> stop SLast x -> return x SError e -> liftIO ( print e) >> finish Nothing >> stop SMore x -> return x
agocorona/transient
src/Transient/EVars.old.hs
mit
5,308
0
18
1,390
1,096
558
538
85
5
module Issue215A where import Issue215.B main = print $ f 2
fpco/fay
tests/Issue215A.hs
bsd-3-clause
62
0
6
13
21
12
9
3
1
{-# OPTIONS -cpp #-} ------------------------------------------------------------------ -- A primop-table mangling program -- ------------------------------------------------------------------ module Main where import Parser import Syntax import Data.Char import Data.List import Data.Maybe ( catMaybes ) import System.Environment ( getArgs ) vecOptions :: Entry -> [(String,String,Int)] vecOptions i = concat [vecs | OptionVector vecs <- opts i] desugarVectorSpec :: Entry -> [Entry] desugarVectorSpec i@(Section {}) = [i] desugarVectorSpec i = case vecOptions i of [] -> [i] vos -> map genVecEntry vos where genVecEntry :: (String,String,Int) -> Entry genVecEntry (con,repCon,n) = case i of PrimOpSpec {} -> PrimVecOpSpec { cons = "(" ++ concat (intersperse " " [cons i, vecCat, show n, vecWidth]) ++ ")" , name = name' , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , ty = desugarTy (ty i) , cat = cat i , desc = desc i , opts = opts i } PrimTypeSpec {} -> PrimVecTypeSpec { ty = desugarTy (ty i) , prefix = pfx , veclen = n , elemrep = con ++ "ElemRep" , desc = desc i , opts = opts i } _ -> error "vector options can only be given for primops and primtypes" where vecCons = con++"X"++show n++"#" vecCat = conCat con vecWidth = conWidth con pfx = lowerHead con++"X"++show n vecTyName = pfx++"PrimTy" name' | Just pre <- splitSuffix (name i) "Array#" = pre++vec++"Array#" | Just pre <- splitSuffix (name i) "OffAddr#" = pre++vec++"OffAddr#" | Just pre <- splitSuffix (name i) "ArrayAs#" = pre++con++"ArrayAs"++vec++"#" | Just pre <- splitSuffix (name i) "OffAddrAs#" = pre++con++"OffAddrAs"++vec++"#" | otherwise = init (name i)++vec ++"#" where vec = con++"X"++show n splitSuffix :: Eq a => [a] -> [a] -> Maybe [a] splitSuffix s suf | drop len s == suf = Just (take len s) | otherwise = Nothing where len = length s - length suf lowerHead s = toLower (head s) : tail s desugarTy :: Ty -> Ty desugarTy (TyF s d) = TyF (desugarTy s) (desugarTy d) desugarTy (TyC s d) = TyC (desugarTy s) (desugarTy d) desugarTy (TyApp SCALAR []) = TyApp (TyCon repCon) [] desugarTy (TyApp VECTOR []) = TyApp (VecTyCon vecCons vecTyName) [] desugarTy (TyApp VECTUPLE []) = TyUTup (replicate n (TyApp (TyCon repCon) [])) desugarTy (TyApp tycon ts) = TyApp tycon (map desugarTy ts) desugarTy t@(TyVar {}) = t desugarTy (TyUTup ts) = TyUTup (map desugarTy ts) conCat :: String -> String conCat "Int8" = "IntVec" conCat "Int16" = "IntVec" conCat "Int32" = "IntVec" conCat "Int64" = "IntVec" conCat "Word8" = "WordVec" conCat "Word16" = "WordVec" conCat "Word32" = "WordVec" conCat "Word64" = "WordVec" conCat "Float" = "FloatVec" conCat "Double" = "FloatVec" conCat con = error $ "conCat: unknown type constructor " ++ con ++ "\n" conWidth :: String -> String conWidth "Int8" = "W8" conWidth "Int16" = "W16" conWidth "Int32" = "W32" conWidth "Int64" = "W64" conWidth "Word8" = "W8" conWidth "Word16" = "W16" conWidth "Word32" = "W32" conWidth "Word64" = "W64" conWidth "Float" = "W32" conWidth "Double" = "W64" conWidth con = error $ "conWidth: unknown type constructor " ++ con ++ "\n" main :: IO () main = getArgs >>= \args -> if length args /= 1 || head args `notElem` known_args then error ("usage: genprimopcode command < primops.txt > ...\n" ++ " where command is one of\n" ++ unlines (map (" "++) known_args) ) else do s <- getContents case parse s of Left err -> error ("parse error at " ++ (show err)) Right p_o_specs@(Info _ _) -> seq (sanityTop p_o_specs) ( case head args of "--data-decl" -> putStr (gen_data_decl p_o_specs) "--has-side-effects" -> putStr (gen_switch_from_attribs "has_side_effects" "primOpHasSideEffects" p_o_specs) "--out-of-line" -> putStr (gen_switch_from_attribs "out_of_line" "primOpOutOfLine" p_o_specs) "--commutable" -> putStr (gen_switch_from_attribs "commutable" "commutableOp" p_o_specs) "--code-size" -> putStr (gen_switch_from_attribs "code_size" "primOpCodeSize" p_o_specs) "--can-fail" -> putStr (gen_switch_from_attribs "can_fail" "primOpCanFail" p_o_specs) "--strictness" -> putStr (gen_switch_from_attribs "strictness" "primOpStrictness" p_o_specs) "--fixity" -> putStr (gen_switch_from_attribs "fixity" "primOpFixity" p_o_specs) "--primop-primop-info" -> putStr (gen_primop_info p_o_specs) "--primop-tag" -> putStr (gen_primop_tag p_o_specs) "--primop-list" -> putStr (gen_primop_list p_o_specs) "--primop-vector-uniques" -> putStr (gen_primop_vector_uniques p_o_specs) "--primop-vector-tys" -> putStr (gen_primop_vector_tys p_o_specs) "--primop-vector-tys-exports" -> putStr (gen_primop_vector_tys_exports p_o_specs) "--primop-vector-tycons" -> putStr (gen_primop_vector_tycons p_o_specs) "--make-haskell-wrappers" -> putStr (gen_wrappers p_o_specs) "--make-haskell-source" -> putStr (gen_hs_source p_o_specs) "--make-latex-doc" -> putStr (gen_latex_doc p_o_specs) _ -> error "Should not happen, known_args out of sync?" ) known_args :: [String] known_args = [ "--data-decl", "--has-side-effects", "--out-of-line", "--commutable", "--code-size", "--can-fail", "--strictness", "--fixity", "--primop-primop-info", "--primop-tag", "--primop-list", "--primop-vector-uniques", "--primop-vector-tys", "--primop-vector-tys-exports", "--primop-vector-tycons", "--make-haskell-wrappers", "--make-haskell-source", "--make-latex-doc" ] ------------------------------------------------------------------ -- Code generators ----------------------------------------------- ------------------------------------------------------------------ gen_hs_source :: Info -> String gen_hs_source (Info defaults entries) = "{-\n" ++ "This is a generated file (generated by genprimopcode).\n" ++ "It is not code to actually be used. Its only purpose is to be\n" ++ "consumed by haddock.\n" ++ "-}\n" ++ "\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "-- |\n" ++ "-- Module : GHC.Prim\n" ++ "-- \n" ++ "-- Maintainer : [email protected]\n" ++ "-- Stability : internal\n" ++ "-- Portability : non-portable (GHC extensions)\n" ++ "--\n" ++ "-- GHC\'s primitive types and operations.\n" ++ "-- Use GHC.Exts from the base package instead of importing this\n" ++ "-- module directly.\n" ++ "--\n" ++ (replicate 77 '-' ++ "\n") -- For 80-col cleanliness ++ "{-# LANGUAGE Unsafe #-}\n" ++ "{-# LANGUAGE MagicHash #-}\n" ++ "{-# LANGUAGE MultiParamTypeClasses #-}\n" ++ "{-# LANGUAGE NoImplicitPrelude #-}\n" ++ "{-# LANGUAGE UnboxedTuples #-}\n" ++ "{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}\n" -- We generate a binding for coerce, like -- coerce :: Coercible a b => a -> b -- coerce = let x = x in x -- and we don't want a complaint that the constraint is redundant -- Remember, this silly file is only for Haddock's consumption ++ "module GHC.Prim (\n" ++ unlines (map ((" " ++) . hdr) entries') ++ ") where\n" ++ "\n" ++ "{-\n" ++ unlines (map opt defaults) ++ "-}\n" ++ "import GHC.Types (Coercible)\n" ++ "default ()" -- If we don't say this then the default type include Integer -- so that runs off and loads modules that are not part of -- pacakge ghc-prim at all. And that in turn somehow ends up -- with Declaration for $fEqMaybe: -- attempting to use module ‘GHC.Classes’ -- (libraries/ghc-prim/./GHC/Classes.hs) which is not loaded -- coming from LoadIface.homeModError -- I'm not sure precisely why; but I *am* sure that we don't need -- any type-class defaulting; and it's clearly wrong to need -- the base package when haddocking ghc-prim -- Now the main payload ++ unlines (concatMap ent entries') ++ "\n\n\n" where entries' = concatMap desugarVectorSpec entries opt (OptionFalse n) = n ++ " = False" opt (OptionTrue n) = n ++ " = True" opt (OptionString n v) = n ++ " = { " ++ v ++ "}" opt (OptionInteger n v) = n ++ " = " ++ show v opt (OptionVector _) = "" opt (OptionFixity mf) = "fixity" ++ " = " ++ show mf hdr s@(Section {}) = sec s hdr (PrimOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimVecOpSpec { name = n }) = wrapOp n ++ "," hdr (PseudoOpSpec { name = n }) = wrapOp n ++ "," hdr (PrimTypeSpec { ty = TyApp (TyCon n) _ }) = wrapTy n ++ "," hdr (PrimTypeSpec {}) = error $ "Illegal type spec" hdr (PrimVecTypeSpec { ty = TyApp (VecTyCon n _) _ }) = wrapTy n ++ "," hdr (PrimVecTypeSpec {}) = error $ "Illegal type spec" ent (Section {}) = [] ent o@(PrimOpSpec {}) = spec o ent o@(PrimVecOpSpec {}) = spec o ent o@(PrimTypeSpec {}) = spec o ent o@(PrimVecTypeSpec {}) = spec o ent o@(PseudoOpSpec {}) = spec o sec s = "\n-- * " ++ escape (title s) ++ "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ desc s) ++ "\n" spec o = comm : decls where decls = case o of -- See Note [Placeholder declarations] PrimOpSpec { name = n, ty = t, opts = options } -> prim_fixity n options ++ prim_decl n t PrimVecOpSpec { name = n, ty = t, opts = options } -> prim_fixity n options ++ prim_decl n t PseudoOpSpec { name = n, ty = t } -> prim_decl n t PrimTypeSpec { ty = t } -> [ "data " ++ pprTy t ] PrimVecTypeSpec { ty = t } -> [ "data " ++ pprTy t ] Section { } -> [] comm = case (desc o) of [] -> "" d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d) prim_fixity n options = [ pprFixity fixity n | OptionFixity (Just fixity) <- options ] prim_decl n t = [ wrapOp n ++ " :: " ++ pprTy t, wrapOp n ++ " = " ++ wrapOpRhs n ] wrapOp nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" wrapTy nm | isAlpha (head nm) = nm | otherwise = "(" ++ nm ++ ")" wrapOpRhs "tagToEnum#" = "let x = x in x" wrapOpRhs nm = wrapOp nm -- Special case for tagToEnum#: see Note [Placeholder declarations] unlatex s = case s of '\\':'t':'e':'x':'t':'t':'t':'{':cs -> markup "@" "@" cs '{':'\\':'t':'t':cs -> markup "@" "@" cs '{':'\\':'i':'t':cs -> markup "/" "/" cs c : cs -> c : unlatex cs [] -> [] markup s t xs = s ++ mk (dropWhile isSpace xs) where mk "" = t mk ('\n':cs) = ' ' : mk cs mk ('}':cs) = t ++ unlatex cs mk (c:cs) = c : mk cs escape = concatMap (\c -> if c `elem` special then '\\':c:[] else c:[]) where special = "/'`\"@<" pprFixity (Fixity i d) n = pprFixityDir d ++ " " ++ show i ++ " " ++ n {- Note [Placeholder declarations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We are generating fake declarations for things in GHC.Prim, just to keep GHC's renamer and typechecker happy enough for what Haddock needs. Our main plan is to say foo :: <type> foo = foo We have to silence GHC's complaints about unboxed-top-level declarations with an ad-hoc fix in TcBinds: see Note [Compiling GHC.Prim] in TcBinds. That works for all the primitive functions except tagToEnum#. If we generate the binding tagToEnum# = tagToEnum# GHC will complain about "tagToEnum# must appear applied to one argument". We could hack GHC to silence this complaint when compiling GHC.Prim, but it seems easier to generate tagToEnum# = let x = x in x We don't do this for *all* bindings because for ones with an unboxed RHS we would get other complaints (e.g.can't unify "*" with "#"). -} pprTy :: Ty -> String pprTy = pty where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ concat (map (' ' :) (map paty ts)) pbty (TyUTup ts) = "(# " ++ concat (intersperse "," (map pty ts)) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" gen_latex_doc :: Info -> String gen_latex_doc (Info defaults entries) = "\\primopdefaults{" ++ mk_options defaults ++ "}\n" ++ (concat (map mk_entry entries)) where mk_entry (PrimOpSpec {cons=constr,name=n,ty=t,cat=c,desc=d,opts=o}) = "\\primopdesc{" ++ latex_encode constr ++ "}{" ++ latex_encode n ++ "}{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (show c) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecOpSpec {}) = "" mk_entry (Section {title=ti,desc=d}) = "\\primopsection{" ++ latex_encode ti ++ "}{" ++ d ++ "}\n" mk_entry (PrimTypeSpec {ty=t,desc=d,opts=o}) = "\\primtypespec{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_entry (PrimVecTypeSpec {}) = "" mk_entry (PseudoOpSpec {name=n,ty=t,desc=d,opts=o}) = "\\pseudoopspec{" ++ latex_encode (zencode n) ++ "}{" ++ latex_encode (mk_source_ty t) ++ "}{" ++ latex_encode (mk_core_ty t) ++ "}{" ++ d ++ "}{" ++ mk_options o ++ "}\n" mk_source_ty typ = pty typ where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = show tc ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = "(# " ++ (concat (intersperse "," (map pty ts))) ++ " #)" pbty t = paty t paty (TyVar tv) = tv paty t = "(" ++ pty t ++ ")" mk_core_ty typ = foralls ++ (pty typ) where pty (TyF t1 t2) = pbty t1 ++ " -> " ++ pty t2 pty (TyC t1 t2) = pbty t1 ++ " => " ++ pty t2 pty t = pbty t pbty (TyApp tc ts) = (zencode (show tc)) ++ (concat (map (' ':) (map paty ts))) pbty (TyUTup ts) = (zencode (utuplenm (length ts))) ++ (concat ((map (' ':) (map paty ts)))) pbty t = paty t paty (TyVar tv) = zencode tv paty (TyApp tc []) = zencode (show tc) paty t = "(" ++ pty t ++ ")" utuplenm 1 = "(# #)" utuplenm n = "(#" ++ (replicate (n-1) ',') ++ "#)" foralls = if tvars == [] then "" else "%forall " ++ (tbinds tvars) tvars = tvars_of typ tbinds [] = ". " tbinds ("o":tbs) = "(o::?) " ++ (tbinds tbs) tbinds (tv:tbs) = tv ++ " " ++ (tbinds tbs) tvars_of (TyF t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyC t1 t2) = tvars_of t1 `union` tvars_of t2 tvars_of (TyApp _ ts) = foldl union [] (map tvars_of ts) tvars_of (TyUTup ts) = foldr union [] (map tvars_of ts) tvars_of (TyVar tv) = [tv] mk_options o = "\\primoptions{" ++ mk_has_side_effects o ++ "}{" ++ mk_out_of_line o ++ "}{" ++ mk_commutable o ++ "}{" ++ mk_needs_wrapper o ++ "}{" ++ mk_can_fail o ++ "}{" ++ mk_fixity o ++ "}{" ++ latex_encode (mk_strictness o) ++ "}{" ++ "}" mk_has_side_effects o = mk_bool_opt o "has_side_effects" "Has side effects." "Has no side effects." mk_out_of_line o = mk_bool_opt o "out_of_line" "Implemented out of line." "Implemented in line." mk_commutable o = mk_bool_opt o "commutable" "Commutable." "Not commutable." mk_needs_wrapper o = mk_bool_opt o "needs_wrapper" "Needs wrapper." "Needs no wrapper." mk_can_fail o = mk_bool_opt o "can_fail" "Can fail." "Cannot fail." mk_bool_opt o opt_name if_true if_false = case lookup_attrib opt_name o of Just (OptionTrue _) -> if_true Just (OptionFalse _) -> if_false Just (OptionString _ _) -> error "String value for boolean option" Just (OptionInteger _ _) -> error "Integer value for boolean option" Just (OptionFixity _) -> error "Fixity value for boolean option" Just (OptionVector _) -> error "vector template for boolean option" Nothing -> "" mk_strictness o = case lookup_attrib "strictness" o of Just (OptionString _ s) -> s -- for now Just _ -> error "Wrong value for strictness" Nothing -> "" mk_fixity o = case lookup_attrib "fixity" o of Just (OptionFixity (Just (Fixity i d))) -> pprFixityDir d ++ " " ++ show i _ -> "" zencode xs = case maybe_tuple xs of Just n -> n -- Tuples go to Z2T etc Nothing -> concat (map encode_ch xs) where maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs) unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar 'Z' = False unencodedChar 'z' = False unencodedChar c = isAlphaNum c encode_ch :: Char -> String encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" encode_ch 'Z' = "ZZ" -- Variables encode_ch 'z' = "zz" encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '_' = "zu" encode_ch '%' = "zv" encode_ch c = 'z' : shows (ord c) "U" latex_encode [] = [] latex_encode (c:cs) | c `elem` "#$%&_^{}" = "\\" ++ c:(latex_encode cs) latex_encode ('~':cs) = "\\verb!~!" ++ (latex_encode cs) latex_encode ('\\':cs) = "$\\backslash$" ++ (latex_encode cs) latex_encode (c:cs) = c:(latex_encode cs) gen_wrappers :: Info -> String gen_wrappers (Info _ entries) = "{-# LANGUAGE MagicHash, NoImplicitPrelude, UnboxedTuples #-}\n" -- Dependencies on Prelude must be explicit in libraries/base, but we -- don't need the Prelude here so we add NoImplicitPrelude. ++ "module GHC.PrimopWrappers where\n" ++ "import qualified GHC.Prim\n" ++ "import GHC.Tuple ()\n" ++ "import GHC.Prim (" ++ types ++ ")\n" ++ unlines (concatMap f specs) where specs = filter (not.dodgy) $ filter (not.is_llvm_only) $ filter is_primop entries tycons = foldr union [] $ map (tyconsIn . ty) specs tycons' = filter (`notElem` [TyCon "()", TyCon "Bool"]) tycons types = concat $ intersperse ", " $ map show tycons' f spec = let args = map (\n -> "a" ++ show n) [1 .. arity (ty spec)] src_name = wrap (name spec) lhs = src_name ++ " " ++ unwords args rhs = "(GHC.Prim." ++ name spec ++ ") " ++ unwords args in ["{-# NOINLINE " ++ src_name ++ " #-}", src_name ++ " :: " ++ pprTy (ty spec), lhs ++ " = " ++ rhs] wrap nm | isLower (head nm) = nm | otherwise = "(" ++ nm ++ ")" dodgy spec = name spec `elem` [-- tagToEnum# is really magical, and can't have -- a wrapper since its implementation depends on -- the type of its result "tagToEnum#" ] is_llvm_only :: Entry -> Bool is_llvm_only entry = case lookup_attrib "llvm_only" (opts entry) of Just (OptionTrue _) -> True _ -> False gen_primop_list :: Info -> String gen_primop_list (Info _ entries) = unlines ( [ " [" ++ cons first ] ++ map (\p -> " , " ++ cons p) rest ++ [ " ]" ] ) where (first:rest) = concatMap desugarVectorSpec (filter is_primop entries) mIN_VECTOR_UNIQUE :: Int mIN_VECTOR_UNIQUE = 300 gen_primop_vector_uniques :: Info -> String gen_primop_vector_uniques (Info _ entries) = unlines $ concatMap mkVecUnique (specs `zip` [mIN_VECTOR_UNIQUE..]) where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecUnique :: (Entry, Int) -> [String] mkVecUnique (i, unique) = [ key_id ++ " :: Unique" , key_id ++ " = mkPreludeTyConUnique " ++ show unique ] where key_id = prefix i ++ "PrimTyConKey" gen_primop_vector_tys :: Info -> String gen_primop_vector_tys (Info _ entries) = unlines $ concatMap mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> [String] mkVecTypes i = [ name_id ++ " :: Name" , name_id ++ " = mkPrimTc (fsLit \"" ++ pprTy (ty i) ++ "\") " ++ key_id ++ " " ++ tycon_id , ty_id ++ " :: Type" , ty_id ++ " = mkTyConTy " ++ tycon_id , tycon_id ++ " :: TyCon" , tycon_id ++ " = pcPrimTyCon0 " ++ name_id ++ " (VecRep " ++ show (veclen i) ++ " " ++ elemrep i ++ ")" ] where key_id = prefix i ++ "PrimTyConKey" name_id = prefix i ++ "PrimTyConName" ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tys_exports :: Info -> String gen_primop_vector_tys_exports (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " " ++ ty_id ++ ", " ++ tycon_id ++ "," where ty_id = prefix i ++ "PrimTy" tycon_id = prefix i ++ "PrimTyCon" gen_primop_vector_tycons :: Info -> String gen_primop_vector_tycons (Info _ entries) = unlines $ map mkVecTypes specs where specs = concatMap desugarVectorSpec (filter is_vector (filter is_primtype entries)) mkVecTypes :: Entry -> String mkVecTypes i = " , " ++ tycon_id where tycon_id = prefix i ++ "PrimTyCon" gen_primop_tag :: Info -> String gen_primop_tag (Info _ entries) = unlines (max_def_type : max_def : tagOf_type : zipWith f primop_entries [1 :: Int ..]) where primop_entries = concatMap desugarVectorSpec $ filter is_primop entries tagOf_type = "tagOf_PrimOp :: PrimOp -> FastInt" f i n = "tagOf_PrimOp " ++ cons i ++ " = _ILIT(" ++ show n ++ ")" max_def_type = "maxPrimOpTag :: Int" max_def = "maxPrimOpTag = " ++ show (length primop_entries) gen_data_decl :: Info -> String gen_data_decl (Info _ entries) = "data PrimOp\n = " ++ head conss ++ "\n" ++ unlines (map (" | "++) (tail conss)) where conss = map genCons (filter is_primop entries) genCons :: Entry -> String genCons entry = case vecOptions entry of [] -> cons entry _ -> cons entry ++ " PrimOpVecCat Length Width" gen_switch_from_attribs :: String -> String -> Info -> String gen_switch_from_attribs attrib_name fn_name (Info defaults entries) = let defv = lookup_attrib attrib_name defaults alternatives = catMaybes (map mkAlt (filter is_primop entries)) getAltRhs (OptionFalse _) = "False" getAltRhs (OptionTrue _) = "True" getAltRhs (OptionInteger _ i) = show i getAltRhs (OptionString _ s) = s getAltRhs (OptionVector _) = "True" getAltRhs (OptionFixity mf) = show mf mkAlt po = case lookup_attrib attrib_name (opts po) of Nothing -> Nothing Just xx -> case vecOptions po of [] -> Just (fn_name ++ " " ++ cons po ++ " = " ++ getAltRhs xx) _ -> Just (fn_name ++ " (" ++ cons po ++ " _ _ _) = " ++ getAltRhs xx) in case defv of Nothing -> error ("gen_switch_from: " ++ attrib_name) Just xx -> unlines alternatives ++ fn_name ++ " _ = " ++ getAltRhs xx ++ "\n" ------------------------------------------------------------------ -- Create PrimOpInfo text from PrimOpSpecs ----------------------- ------------------------------------------------------------------ gen_primop_info :: Info -> String gen_primop_info (Info _ entries) = unlines (map mkPOItext (concatMap desugarVectorSpec (filter is_primop entries))) mkPOItext :: Entry -> String mkPOItext i = mkPOI_LHS_text i ++ mkPOI_RHS_text i mkPOI_LHS_text :: Entry -> String mkPOI_LHS_text i = "primOpInfo " ++ cons i ++ " = " mkPOI_RHS_text :: Entry -> String mkPOI_RHS_text i = case cat i of Compare -> case ty i of TyF t1 (TyF _ _) -> "mkCompare " ++ sl_name i ++ ppType t1 _ -> error "Type error in comparison op" Monadic -> case ty i of TyF t1 _ -> "mkMonadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in monadic op" Dyadic -> case ty i of TyF t1 (TyF _ _) -> "mkDyadic " ++ sl_name i ++ ppType t1 _ -> error "Type error in dyadic op" GenPrimOp -> let (argTys, resTy) = flatTys (ty i) tvs = nub (tvsIn (ty i)) in "mkGenPrimOp " ++ sl_name i ++ " " ++ listify (map ppTyVar tvs) ++ " " ++ listify (map ppType argTys) ++ " " ++ "(" ++ ppType resTy ++ ")" sl_name :: Entry -> String sl_name i = "(fsLit \"" ++ name i ++ "\") " ppTyVar :: String -> String ppTyVar "a" = "alphaTyVar" ppTyVar "b" = "betaTyVar" ppTyVar "c" = "gammaTyVar" ppTyVar "s" = "deltaTyVar" ppTyVar "o" = "openAlphaTyVar" ppTyVar _ = error "Unknown type var" ppType :: Ty -> String ppType (TyApp (TyCon "Any") []) = "anyTy" ppType (TyApp (TyCon "Bool") []) = "boolTy" ppType (TyApp (TyCon "Int#") []) = "intPrimTy" ppType (TyApp (TyCon "Int32#") []) = "int32PrimTy" ppType (TyApp (TyCon "Int64#") []) = "int64PrimTy" ppType (TyApp (TyCon "Char#") []) = "charPrimTy" ppType (TyApp (TyCon "Word#") []) = "wordPrimTy" ppType (TyApp (TyCon "Word32#") []) = "word32PrimTy" ppType (TyApp (TyCon "Word64#") []) = "word64PrimTy" ppType (TyApp (TyCon "Addr#") []) = "addrPrimTy" ppType (TyApp (TyCon "Float#") []) = "floatPrimTy" ppType (TyApp (TyCon "Double#") []) = "doublePrimTy" ppType (TyApp (TyCon "ByteArray#") []) = "byteArrayPrimTy" ppType (TyApp (TyCon "RealWorld") []) = "realWorldTy" ppType (TyApp (TyCon "ThreadId#") []) = "threadIdPrimTy" ppType (TyApp (TyCon "ForeignObj#") []) = "foreignObjPrimTy" ppType (TyApp (TyCon "BCO#") []) = "bcoPrimTy" ppType (TyApp (TyCon "()") []) = "unitTy" -- unitTy is TysWiredIn's name for () ppType (TyVar "a") = "alphaTy" ppType (TyVar "b") = "betaTy" ppType (TyVar "c") = "gammaTy" ppType (TyVar "s") = "deltaTy" ppType (TyVar "o") = "openAlphaTy" ppType (TyApp (TyCon "State#") [x]) = "mkStatePrimTy " ++ ppType x ppType (TyApp (TyCon "MutVar#") [x,y]) = "mkMutVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArray#") [x,y]) = "mkMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableArrayArray#") [x]) = "mkMutableArrayArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "SmallMutableArray#") [x,y]) = "mkSmallMutableArrayPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "MutableByteArray#") [x]) = "mkMutableByteArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Array#") [x]) = "mkArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "ArrayArray#") []) = "mkArrayArrayPrimTy" ppType (TyApp (TyCon "SmallArray#") [x]) = "mkSmallArrayPrimTy " ++ ppType x ppType (TyApp (TyCon "Weak#") [x]) = "mkWeakPrimTy " ++ ppType x ppType (TyApp (TyCon "StablePtr#") [x]) = "mkStablePtrPrimTy " ++ ppType x ppType (TyApp (TyCon "StableName#") [x]) = "mkStableNamePrimTy " ++ ppType x ppType (TyApp (TyCon "MVar#") [x,y]) = "mkMVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (TyCon "TVar#") [x,y]) = "mkTVarPrimTy " ++ ppType x ++ " " ++ ppType y ppType (TyApp (VecTyCon _ pptc) []) = pptc ppType (TyUTup ts) = "(mkTupleTy Unboxed " ++ listify (map ppType ts) ++ ")" ppType (TyF s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType (TyC s d) = "(mkFunTy (" ++ ppType s ++ ") (" ++ ppType d ++ "))" ppType other = error ("ppType: can't handle: " ++ show other ++ "\n") pprFixityDir :: FixityDirection -> String pprFixityDir InfixN = "infix" pprFixityDir InfixL = "infixl" pprFixityDir InfixR = "infixr" listify :: [String] -> String listify ss = "[" ++ concat (intersperse ", " ss) ++ "]" flatTys :: Ty -> ([Ty],Ty) flatTys (TyF t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys (TyC t1 t2) = case flatTys t2 of (ts,t) -> (t1:ts,t) flatTys other = ([],other) tvsIn :: Ty -> [TyVar] tvsIn (TyF t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyC t1 t2) = tvsIn t1 ++ tvsIn t2 tvsIn (TyApp _ tys) = concatMap tvsIn tys tvsIn (TyVar tv) = [tv] tvsIn (TyUTup tys) = concatMap tvsIn tys tyconsIn :: Ty -> [TyCon] tyconsIn (TyF t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyC t1 t2) = tyconsIn t1 `union` tyconsIn t2 tyconsIn (TyApp tc tys) = foldr union [tc] $ map tyconsIn tys tyconsIn (TyVar _) = [] tyconsIn (TyUTup tys) = foldr union [] $ map tyconsIn tys arity :: Ty -> Int arity = length . fst . flatTys
TomMD/ghc
utils/genprimopcode/Main.hs
bsd-3-clause
36,808
0
39
14,592
9,909
4,989
4,920
686
74
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.SrcDist -- Copyright : Simon Marlow 2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This handles the @sdist@ command. The module exports an 'sdist' action but -- also some of the phases that make it up so that other tools can use just the -- bits they need. In particular the preparation of the tree of files to go -- into the source tarball is separated from actually building the source -- tarball. -- -- The 'createArchive' action uses the external @tar@ program and assumes that -- it accepts the @-z@ flag. Neither of these assumptions are valid on Windows. -- The 'sdist' action now also does some distribution QA checks. -- NOTE: FIX: we don't have a great way of testing this module, since -- we can't easily look inside a tarball once its created. module Distribution.Simple.SrcDist ( -- * The top level action sdist, -- ** Parts of 'sdist' printPackageProblems, prepareTree, createArchive, -- ** Snapshots prepareSnapshotTree, snapshotPackage, snapshotVersion, dateToSnapshotNumber, -- * Extracting the source files listPackageSources ) where import Distribution.PackageDescription hiding (Flag) import Distribution.PackageDescription.Check hiding (doesFileExist) import Distribution.Package import Distribution.ModuleName import qualified Distribution.ModuleName as ModuleName import Distribution.Version import Distribution.Simple.Utils import Distribution.Simple.Setup import Distribution.Simple.PreProcess import Distribution.Simple.LocalBuildInfo import Distribution.Simple.BuildPaths import Distribution.Simple.Program import Distribution.Text import Distribution.Verbosity import Control.Monad(when, unless, forM) import Data.Char (toLower) import Data.List (partition, isPrefixOf) import qualified Data.Map as Map import Data.Maybe (isNothing, catMaybes) import Data.Time (UTCTime, getCurrentTime, toGregorian, utctDay) import System.Directory ( doesFileExist ) import System.IO (IOMode(WriteMode), hPutStrLn, withFile) import System.FilePath ( (</>), (<.>), dropExtension, isAbsolute ) -- |Create a source distribution. sdist :: PackageDescription -- ^information from the tarball -> Maybe LocalBuildInfo -- ^Information from configure -> SDistFlags -- ^verbosity & snapshot -> (FilePath -> FilePath) -- ^build prefix (temp dir) -> [PPSuffixHandler] -- ^ extra preprocessors (includes suffixes) -> IO () sdist pkg mb_lbi flags mkTmpDir pps = -- When given --list-sources, just output the list of sources to a file. case (sDistListSources flags) of Flag path -> withFile path WriteMode $ \outHandle -> do (ordinary, maybeExecutable) <- listPackageSources verbosity pkg pps mapM_ (hPutStrLn outHandle) ordinary mapM_ (hPutStrLn outHandle) maybeExecutable notice verbosity $ "List of package sources written to file '" ++ path ++ "'" NoFlag -> do -- do some QA printPackageProblems verbosity pkg when (isNothing mb_lbi) $ warn verbosity "Cannot run preprocessors. Run 'configure' command first." date <- getCurrentTime let pkg' | snapshot = snapshotPackage date pkg | otherwise = pkg case flagToMaybe (sDistDirectory flags) of Just targetDir -> do generateSourceDir targetDir pkg' info verbosity $ "Source directory created: " ++ targetDir Nothing -> do createDirectoryIfMissingVerbose verbosity True tmpTargetDir withTempDirectory verbosity tmpTargetDir "sdist." $ \tmpDir -> do let targetDir = tmpDir </> tarBallName pkg' generateSourceDir targetDir pkg' targzFile <- createArchive verbosity pkg' mb_lbi tmpDir targetPref notice verbosity $ "Source tarball created: " ++ targzFile where generateSourceDir targetDir pkg' = do setupMessage verbosity "Building source dist for" (packageId pkg') prepareTree verbosity pkg' mb_lbi targetDir pps when snapshot $ overwriteSnapshotPackageDesc verbosity pkg' targetDir verbosity = fromFlag (sDistVerbosity flags) snapshot = fromFlag (sDistSnapshot flags) distPref = fromFlag $ sDistDistPref flags targetPref = distPref tmpTargetDir = mkTmpDir distPref -- | List all source files of a package. Returns a tuple of lists: first -- component is a list of ordinary files, second one is a list of those files -- that may be executable. listPackageSources :: Verbosity -- ^ verbosity -> PackageDescription -- ^ info from the cabal file -> [PPSuffixHandler] -- ^ extra preprocessors (include -- suffixes) -> IO ([FilePath], [FilePath]) listPackageSources verbosity pkg_descr0 pps = do -- Call helpers that actually do all work. ordinary <- listPackageSourcesOrdinary verbosity pkg_descr pps maybeExecutable <- listPackageSourcesMaybeExecutable pkg_descr return (ordinary, maybeExecutable) where pkg_descr = filterAutogenModule pkg_descr0 -- | List those source files that may be executable (e.g. the configure script). listPackageSourcesMaybeExecutable :: PackageDescription -> IO [FilePath] listPackageSourcesMaybeExecutable pkg_descr = -- Extra source files. fmap concat . forM (extraSrcFiles pkg_descr) $ \fpath -> matchFileGlob fpath -- | List those source files that should be copied with ordinary permissions. listPackageSourcesOrdinary :: Verbosity -> PackageDescription -> [PPSuffixHandler] -> IO [FilePath] listPackageSourcesOrdinary verbosity pkg_descr pps = fmap concat . sequence $ [ -- Library sources. fmap concat . withAllLib $ \Library { exposedModules = modules, libBuildInfo = libBi } -> allSourcesBuildInfo libBi pps modules -- Executables sources. , fmap concat . withAllExe $ \Executable { modulePath = mainPath, buildInfo = exeBi } -> do biSrcs <- allSourcesBuildInfo exeBi pps [] mainSrc <- findMainExeFile exeBi pps mainPath return (mainSrc:biSrcs) -- Test suites sources. , fmap concat . withAllTest $ \t -> do let bi = testBuildInfo t case testInterface t of TestSuiteExeV10 _ mainPath -> do biSrcs <- allSourcesBuildInfo bi pps [] srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp return (srcMainFile:biSrcs) TestSuiteLibV09 _ m -> allSourcesBuildInfo bi pps [m] TestSuiteUnsupported tp -> die $ "Unsupported test suite type: " ++ show tp -- Benchmarks sources. , fmap concat . withAllBenchmark $ \bm -> do let bi = benchmarkBuildInfo bm case benchmarkInterface bm of BenchmarkExeV10 _ mainPath -> do biSrcs <- allSourcesBuildInfo bi pps [] srcMainFile <- do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs bi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs bi) mainPath Just pp -> return pp return (srcMainFile:biSrcs) BenchmarkUnsupported tp -> die $ "Unsupported benchmark type: " ++ show tp -- Data files. , fmap concat . forM (dataFiles pkg_descr) $ \filename -> matchFileGlob (dataDir pkg_descr </> filename) -- Extra doc files. , fmap concat . forM (extraDocFiles pkg_descr) $ \ filename -> matchFileGlob filename -- License file(s). , return (licenseFiles pkg_descr) -- Install-include files. , fmap concat . withAllLib $ \ l -> do let lbi = libBuildInfo l relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) mapM (fmap snd . findIncludeFile relincdirs) (installIncludes lbi) -- Setup script, if it exists. , fmap (maybe [] (\f -> [f])) $ findSetupFile "" -- The .cabal file itself. , fmap (\d -> [d]) (defaultPackageDesc verbosity) ] where -- We have to deal with all libs and executables, so we have local -- versions of these functions that ignore the 'buildable' attribute: withAllLib action = mapM action (libraries pkg_descr) withAllExe action = mapM action (executables pkg_descr) withAllTest action = mapM action (testSuites pkg_descr) withAllBenchmark action = mapM action (benchmarks pkg_descr) -- |Prepare a directory tree of source files. prepareTree :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> Maybe LocalBuildInfo -> FilePath -- ^source tree to populate -> [PPSuffixHandler] -- ^extra preprocessors (includes suffixes) -> IO () prepareTree verbosity pkg_descr0 mb_lbi targetDir pps = do -- If the package was configured then we can run platform-independent -- pre-processors and include those generated files. case mb_lbi of Just lbi | not (null pps) -> do let lbi' = lbi{ buildDir = targetDir </> buildDir lbi } withAllComponentsInBuildOrder pkg_descr lbi' $ \c clbi -> preprocessComponent pkg_descr c lbi' clbi True verbosity pps _ -> return () (ordinary, mExecutable) <- listPackageSources verbosity pkg_descr0 pps installOrdinaryFiles verbosity targetDir (zip (repeat []) ordinary) installMaybeExecutableFiles verbosity targetDir (zip (repeat []) mExecutable) maybeCreateDefaultSetupScript targetDir where pkg_descr = filterAutogenModule pkg_descr0 -- | Find the setup script file, if it exists. findSetupFile :: FilePath -> IO (Maybe FilePath) findSetupFile targetDir = do hsExists <- doesFileExist setupHs lhsExists <- doesFileExist setupLhs if hsExists then return (Just setupHs) else if lhsExists then return (Just setupLhs) else return Nothing where setupHs = targetDir </> "Setup.hs" setupLhs = targetDir </> "Setup.lhs" -- | Create a default setup script in the target directory, if it doesn't exist. maybeCreateDefaultSetupScript :: FilePath -> IO () maybeCreateDefaultSetupScript targetDir = do mSetupFile <- findSetupFile targetDir case mSetupFile of Just _setupFile -> return () Nothing -> do writeUTF8File (targetDir </> "Setup.hs") $ unlines [ "import Distribution.Simple", "main = defaultMain"] -- | Find the main executable file. findMainExeFile :: BuildInfo -> [PPSuffixHandler] -> FilePath -> IO FilePath findMainExeFile exeBi pps mainPath = do ppFile <- findFileWithExtension (ppSuffixes pps) (hsSourceDirs exeBi) (dropExtension mainPath) case ppFile of Nothing -> findFile (hsSourceDirs exeBi) mainPath Just pp -> return pp -- | Given a list of include paths, try to find the include file named -- @f@. Return the name of the file and the full path, or exit with error if -- there's no such file. findIncludeFile :: [FilePath] -> String -> IO (String, FilePath) findIncludeFile [] f = die ("can't find include file " ++ f) findIncludeFile (d:ds) f = do let path = (d </> f) b <- doesFileExist path if b then return (f,path) else findIncludeFile ds f -- | Remove the auto-generated module ('Paths_*') from 'exposed-modules' and -- 'other-modules'. filterAutogenModule :: PackageDescription -> PackageDescription filterAutogenModule pkg_descr0 = mapLib filterAutogenModuleLib $ mapAllBuildInfo filterAutogenModuleBI pkg_descr0 where mapLib f pkg = pkg { libraries = map f (libraries pkg) } filterAutogenModuleLib lib = lib { exposedModules = filter (/=autogenModule) (exposedModules lib) } filterAutogenModuleBI bi = bi { otherModules = filter (/=autogenModule) (otherModules bi) } autogenModule = autogenModuleName pkg_descr0 -- | Prepare a directory tree of source files for a snapshot version. -- It is expected that the appropriate snapshot version has already been set -- in the package description, eg using 'snapshotPackage' or 'snapshotVersion'. -- prepareSnapshotTree :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> Maybe LocalBuildInfo -> FilePath -- ^source tree to populate -> [PPSuffixHandler] -- ^extra preprocessors (includes -- suffixes) -> IO () prepareSnapshotTree verbosity pkg mb_lbi targetDir pps = do prepareTree verbosity pkg mb_lbi targetDir pps overwriteSnapshotPackageDesc verbosity pkg targetDir overwriteSnapshotPackageDesc :: Verbosity -- ^verbosity -> PackageDescription -- ^info from the cabal file -> FilePath -- ^source tree -> IO () overwriteSnapshotPackageDesc verbosity pkg targetDir = do -- We could just writePackageDescription targetDescFile pkg_descr, -- but that would lose comments and formatting. descFile <- defaultPackageDesc verbosity withUTF8FileContents descFile $ writeUTF8File (targetDir </> descFile) . unlines . map (replaceVersion (packageVersion pkg)) . lines where replaceVersion :: Version -> String -> String replaceVersion version line | "version:" `isPrefixOf` map toLower line = "version: " ++ display version | otherwise = line -- | Modifies a 'PackageDescription' by appending a snapshot number -- corresponding to the given date. -- snapshotPackage :: UTCTime -> PackageDescription -> PackageDescription snapshotPackage date pkg = pkg { package = pkgid { pkgVersion = snapshotVersion date (pkgVersion pkgid) } } where pkgid = packageId pkg -- | Modifies a 'Version' by appending a snapshot number corresponding -- to the given date. -- snapshotVersion :: UTCTime -> Version -> Version snapshotVersion date version = version { versionBranch = versionBranch version ++ [dateToSnapshotNumber date] } -- | Given a date produce a corresponding integer representation. -- For example given a date @18/03/2008@ produce the number @20080318@. -- dateToSnapshotNumber :: UTCTime -> Int dateToSnapshotNumber date = case toGregorian (utctDay date) of (year, month, day) -> fromIntegral year * 10000 + month * 100 + day -- | Callback type for use by sdistWith. type CreateArchiveFun = Verbosity -- ^verbosity -> PackageDescription -- ^info from cabal file -> Maybe LocalBuildInfo -- ^info from configure -> FilePath -- ^source tree to archive -> FilePath -- ^name of archive to create -> IO FilePath -- | Create an archive from a tree of source files, and clean up the tree. createArchive :: CreateArchiveFun createArchive verbosity pkg_descr mb_lbi tmpDir targetPref = do let tarBallFilePath = targetPref </> tarBallName pkg_descr <.> "tar.gz" (tarProg, _) <- requireProgram verbosity tarProgram (maybe defaultProgramConfiguration withPrograms mb_lbi) let formatOptSupported = maybe False (== "YES") $ Map.lookup "Supports --format" (programProperties tarProg) runProgram verbosity tarProg $ -- Hmm: I could well be skating on thinner ice here by using the -C option -- (=> seems to be supported at least by GNU and *BSD tar) [The -- prev. solution used pipes and sub-command sequences to set up the paths -- correctly, which is problematic in a Windows setting.] ["-czf", tarBallFilePath, "-C", tmpDir] ++ (if formatOptSupported then ["--format", "ustar"] else []) ++ [tarBallName pkg_descr] return tarBallFilePath -- | Given a buildinfo, return the names of all source files. allSourcesBuildInfo :: BuildInfo -> [PPSuffixHandler] -- ^ Extra preprocessors -> [ModuleName] -- ^ Exposed modules -> IO [FilePath] allSourcesBuildInfo bi pps modules = do let searchDirs = hsSourceDirs bi sources <- fmap concat $ sequence $ [ let file = ModuleName.toFilePath module_ in findAllFilesWithExtension suffixes searchDirs file >>= nonEmpty (notFound module_) return | module_ <- modules ++ otherModules bi ] bootFiles <- sequence [ let file = ModuleName.toFilePath module_ fileExts = ["hs-boot", "lhs-boot"] in findFileWithExtension fileExts (hsSourceDirs bi) file | module_ <- modules ++ otherModules bi ] return $ sources ++ catMaybes bootFiles ++ cSources bi ++ jsSources bi where nonEmpty x _ [] = x nonEmpty _ f xs = f xs suffixes = ppSuffixes pps ++ ["hs", "lhs"] notFound m = die $ "Error: Could not find module: " ++ display m ++ " with any suffix: " ++ show suffixes printPackageProblems :: Verbosity -> PackageDescription -> IO () printPackageProblems verbosity pkg_descr = do ioChecks <- checkPackageFiles pkg_descr "." let pureChecks = checkConfiguredPackage pkg_descr isDistError (PackageDistSuspicious _) = False isDistError (PackageDistSuspiciousWarn _) = False isDistError _ = True (errors, warnings) = partition isDistError (pureChecks ++ ioChecks) unless (null errors) $ notice verbosity $ "Distribution quality errors:\n" ++ unlines (map explanation errors) unless (null warnings) $ notice verbosity $ "Distribution quality warnings:\n" ++ unlines (map explanation warnings) unless (null errors) $ notice verbosity "Note: the public hackage server would reject this package." ------------------------------------------------------------ -- | The name of the tarball without extension -- tarBallName :: PackageDescription -> String tarBallName = display . packageId mapAllBuildInfo :: (BuildInfo -> BuildInfo) -> (PackageDescription -> PackageDescription) mapAllBuildInfo f pkg = pkg { libraries = fmap mapLibBi (libraries pkg), executables = fmap mapExeBi (executables pkg), testSuites = fmap mapTestBi (testSuites pkg), benchmarks = fmap mapBenchBi (benchmarks pkg) } where mapLibBi lib = lib { libBuildInfo = f (libBuildInfo lib) } mapExeBi exe = exe { buildInfo = f (buildInfo exe) } mapTestBi t = t { testBuildInfo = f (testBuildInfo t) } mapBenchBi bm = bm { benchmarkBuildInfo = f (benchmarkBuildInfo bm) }
kolmodin/cabal
Cabal/Distribution/Simple/SrcDist.hs
bsd-3-clause
19,380
0
24
5,097
3,944
2,014
1,930
322
6
{-# LANGUAGE CPP, RankNTypes #-} import Control.Concurrent.Async import Control.Monad import System.Environment import Control.Concurrent.Chan import Control.Concurrent.STM -- The TQueue and TBQueue in the stm package are optimised with UNPACKs, -- so we measure with those rather than these local versions. -- -- import TQueue -- import TBQueue -- Using CPP rather than a runtime choice between channel types, -- because we want the compiler to be able to optimise the calls. -- #define CHAN -- #define TCHAN -- #define TQUEUE -- #define TBQUEUE #ifdef CHAN newc = newChan readc c = readChan c writec c x = writeChan c x #elif defined(TCHAN) newc = newTChanIO readc c = atomically $ readTChan c writec c x = atomically $ writeTChan c x #elif defined(TQUEUE) newc = atomically $ newTQueue readc c = atomically $ readTQueue c writec c x = atomically $ writeTQueue c x #elif defined(TBQUEUE) newc = atomically $ newTBQueue bufsiz readc c = atomically $ readTBQueue c writec c x = atomically $ writeTBQueue c x #endif bufsiz=4096 -- Invoke this program with two command-line parameters. -- The first should be 0, 1, or 2, specifying one of three -- different benchmarks. The second specifies the size of the -- test. main = do [stest,sn] <- getArgs -- 2000000 is a good number let n = read sn :: Int test = read stest :: Int runtest n test runtest :: Int -> Int -> IO () runtest n test = do c <- newc case test of 0 -> do a <- async $ replicateM_ n $ writec c (1 :: Int) b <- async $ replicateM_ n $ readc c waitBoth a b return () 1 -> do replicateM_ n $ writec c (1 :: Int) replicateM_ n $ readc c 2 -> do replicateM_ (n `quot` bufsiz) $ do replicateM_ bufsiz $ writec c (1 :: Int) replicateM_ bufsiz $ readc c
prt2121/haskell-practice
parconc/chanbench.hs
apache-2.0
1,804
0
17
411
350
180
170
28
3
----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.Parsec.Error -- Copyright : (c) Paolo Martini 2007 -- License : BSD-style (see the LICENSE file) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Parsec compatibility module -- ----------------------------------------------------------------------------- module Text.ParserCombinators.Parsec.Error ( Message (SysUnExpect,UnExpect,Expect,Message), messageString, messageCompare, messageEq, ParseError, errorPos, errorMessages, errorIsUnknown, showErrorMessages, newErrorMessage, newErrorUnknown, addErrorMessage, setErrorPos, setErrorMessage, mergeError ) where import Text.Parsec.Error messageCompare :: Message -> Message -> Ordering messageCompare = compare messageEq :: Message -> Message -> Bool messageEq = (==)
maurer/15-411-Haskell-Base-Code
src/Text/ParserCombinators/Parsec/Error.hs
bsd-3-clause
1,009
0
6
205
122
85
37
23
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE AutoDeriveTypeable, BangPatterns #-} {-# OPTIONS_GHC -funbox-strict-fields #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent.QSem -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (concurrency) -- -- Simple quantity semaphores. -- ----------------------------------------------------------------------------- module Control.Concurrent.QSem ( -- * Simple Quantity Semaphores QSem, -- abstract newQSem, -- :: Int -> IO QSem waitQSem, -- :: QSem -> IO () signalQSem -- :: QSem -> IO () ) where import Control.Concurrent.MVar ( MVar, newEmptyMVar, takeMVar, tryTakeMVar , putMVar, newMVar, tryPutMVar) import Control.Exception import Data.Maybe -- | 'QSem' is a quantity semaphore in which the resource is aqcuired -- and released in units of one. It provides guaranteed FIFO ordering -- for satisfying blocked `waitQSem` calls. -- -- The pattern -- -- > bracket_ waitQSem signalQSem (...) -- -- is safe; it never loses a unit of the resource. -- data QSem = QSem !(MVar (Int, [MVar ()], [MVar ()])) -- The semaphore state (i, xs, ys): -- -- i is the current resource value -- -- (xs,ys) is the queue of blocked threads, where the queue is -- given by xs ++ reverse ys. We can enqueue new blocked threads -- by consing onto ys, and dequeue by removing from the head of xs. -- -- A blocked thread is represented by an empty (MVar ()). To unblock -- the thread, we put () into the MVar. -- -- A thread can dequeue itself by also putting () into the MVar, which -- it must do if it receives an exception while blocked in waitQSem. -- This means that when unblocking a thread in signalQSem we must -- first check whether the MVar is already full; the MVar lock on the -- semaphore itself resolves race conditions between signalQSem and a -- thread attempting to dequeue itself. -- |Build a new 'QSem' with a supplied initial quantity. -- The initial quantity must be at least 0. newQSem :: Int -> IO QSem newQSem initial | initial < 0 = fail "newQSem: Initial quantity must be non-negative" | otherwise = do sem <- newMVar (initial, [], []) return (QSem sem) -- |Wait for a unit to become available waitQSem :: QSem -> IO () waitQSem (QSem m) = mask_ $ do (i,b1,b2) <- takeMVar m if i == 0 then do b <- newEmptyMVar putMVar m (i, b1, b:b2) wait b else do let !z = i-1 putMVar m (z, b1, b2) return () where wait b = takeMVar b `onException` do (uninterruptibleMask_ $ do -- Note [signal uninterruptible] (i,b1,b2) <- takeMVar m r <- tryTakeMVar b r' <- if isJust r then signal (i,b1,b2) else do putMVar b (); return (i,b1,b2) putMVar m r') -- |Signal that a unit of the 'QSem' is available signalQSem :: QSem -> IO () signalQSem (QSem m) = uninterruptibleMask_ $ do -- Note [signal uninterruptible] r <- takeMVar m r' <- signal r putMVar m r' -- Note [signal uninterruptible] -- -- If we have -- -- bracket waitQSem signalQSem (...) -- -- and an exception arrives at the signalQSem, then we must not lose -- the resource. The signalQSem is masked by bracket, but taking -- the MVar might block, and so it would be interruptible. Hence we -- need an uninterruptibleMask here. -- -- This isn't ideal: during high contention, some threads won't be -- interruptible. The QSemSTM implementation has better behaviour -- here, but it performs much worse than this one in some -- benchmarks. signal :: (Int,[MVar ()],[MVar ()]) -> IO (Int,[MVar ()],[MVar ()]) signal (i,a1,a2) = if i == 0 then loop a1 a2 else let !z = i+1 in return (z, a1, a2) where loop [] [] = return (1, [], []) loop [] b2 = loop (reverse b2) [] loop (b:bs) b2 = do r <- tryPutMVar b () if r then return (0, bs, b2) else loop bs b2
frantisekfarka/ghc-dsi
libraries/base/Control/Concurrent/QSem.hs
bsd-3-clause
4,346
0
19
1,156
810
448
362
60
5
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, BangPatterns #-} -- | -- Module : Data.Vector.Mutable -- Copyright : (c) Roman Leshchinskiy 2008-2010 -- License : BSD-style -- -- Maintainer : Roman Leshchinskiy <[email protected]> -- Stability : experimental -- Portability : non-portable -- -- Mutable boxed vectors. -- module Data.Vector.Mutable ( -- * Mutable boxed vectors MVector(..), IOVector, STVector, -- * Accessors -- ** Length information length, null, -- ** Extracting subvectors slice, init, tail, take, drop, splitAt, unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop, -- ** Overlapping overlaps, -- * Construction -- ** Initialisation new, unsafeNew, replicate, replicateM, clone, -- ** Growing grow, unsafeGrow, -- ** Restricting memory usage clear, -- * Accessing individual elements read, write, swap, unsafeRead, unsafeWrite, unsafeSwap, -- * Modifying vectors -- ** Filling and copying set, copy, move, unsafeCopy, unsafeMove ) where import Control.Monad (when) import qualified Data.Vector.Generic.Mutable as G import Data.Primitive.Array import Control.Monad.Primitive import Control.DeepSeq ( NFData, rnf ) import Prelude hiding ( length, null, replicate, reverse, map, read, take, drop, splitAt, init, tail ) import Data.Typeable ( Typeable ) #include "vector.h" -- | Mutable boxed vectors keyed on the monad they live in ('IO' or @'ST' s@). data MVector s a = MVector {-# UNPACK #-} !Int {-# UNPACK #-} !Int {-# UNPACK #-} !(MutableArray s a) deriving ( Typeable ) type IOVector = MVector RealWorld type STVector s = MVector s -- NOTE: This seems unsafe, see http://trac.haskell.org/vector/ticket/54 {- instance NFData a => NFData (MVector s a) where rnf (MVector i n arr) = unsafeInlineST $ force i where force !ix | ix < n = do x <- readArray arr ix rnf x `seq` force (ix+1) | otherwise = return () -} instance G.MVector MVector a where {-# INLINE basicLength #-} basicLength (MVector _ n _) = n {-# INLINE basicUnsafeSlice #-} basicUnsafeSlice j m (MVector i n arr) = MVector (i+j) m arr {-# INLINE basicOverlaps #-} basicOverlaps (MVector i m arr1) (MVector j n arr2) = sameMutableArray arr1 arr2 && (between i j (j+n) || between j i (i+m)) where between x y z = x >= y && x < z {-# INLINE basicUnsafeNew #-} basicUnsafeNew n = do arr <- newArray n uninitialised return (MVector 0 n arr) {-# INLINE basicUnsafeReplicate #-} basicUnsafeReplicate n x = do arr <- newArray n x return (MVector 0 n arr) {-# INLINE basicUnsafeRead #-} basicUnsafeRead (MVector i n arr) j = readArray arr (i+j) {-# INLINE basicUnsafeWrite #-} basicUnsafeWrite (MVector i n arr) j x = writeArray arr (i+j) x {-# INLINE basicUnsafeCopy #-} basicUnsafeCopy (MVector i n dst) (MVector j _ src) = copyMutableArray dst i src j n basicUnsafeMove dst@(MVector iDst n arrDst) src@(MVector iSrc _ arrSrc) = case n of 0 -> return () 1 -> readArray arrSrc iSrc >>= writeArray arrDst iDst 2 -> do x <- readArray arrSrc iSrc y <- readArray arrSrc (iSrc + 1) writeArray arrDst iDst x writeArray arrDst (iDst + 1) y _ | overlaps dst src -> case compare iDst iSrc of LT -> moveBackwards arrDst iDst iSrc n EQ -> return () GT | (iDst - iSrc) * 2 < n -> moveForwardsLargeOverlap arrDst iDst iSrc n | otherwise -> moveForwardsSmallOverlap arrDst iDst iSrc n | otherwise -> G.basicUnsafeCopy dst src {-# INLINE basicClear #-} basicClear v = G.set v uninitialised {-# INLINE moveBackwards #-} moveBackwards :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m () moveBackwards !arr !dstOff !srcOff !len = INTERNAL_CHECK(check) "moveBackwards" "not a backwards move" (dstOff < srcOff) $ loopM len $ \ i -> readArray arr (srcOff + i) >>= writeArray arr (dstOff + i) {-# INLINE moveForwardsSmallOverlap #-} -- Performs a move when dstOff > srcOff, optimized for when the overlap of the intervals is small. moveForwardsSmallOverlap :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m () moveForwardsSmallOverlap !arr !dstOff !srcOff !len = INTERNAL_CHECK(check) "moveForwardsSmallOverlap" "not a forward move" (dstOff > srcOff) $ do tmp <- newArray overlap uninitialised loopM overlap $ \ i -> readArray arr (dstOff + i) >>= writeArray tmp i loopM nonOverlap $ \ i -> readArray arr (srcOff + i) >>= writeArray arr (dstOff + i) loopM overlap $ \ i -> readArray tmp i >>= writeArray arr (dstOff + nonOverlap + i) where nonOverlap = dstOff - srcOff; overlap = len - nonOverlap -- Performs a move when dstOff > srcOff, optimized for when the overlap of the intervals is large. moveForwardsLargeOverlap :: PrimMonad m => MutableArray (PrimState m) a -> Int -> Int -> Int -> m () moveForwardsLargeOverlap !arr !dstOff !srcOff !len = INTERNAL_CHECK(check) "moveForwardsLargeOverlap" "not a forward move" (dstOff > srcOff) $ do queue <- newArray nonOverlap uninitialised loopM nonOverlap $ \ i -> readArray arr (srcOff + i) >>= writeArray queue i let mov !i !qTop = when (i < dstOff + len) $ do x <- readArray arr i y <- readArray queue qTop writeArray arr i y writeArray queue qTop x mov (i+1) (if qTop + 1 >= nonOverlap then 0 else qTop + 1) mov dstOff 0 where nonOverlap = dstOff - srcOff {-# INLINE loopM #-} loopM :: Monad m => Int -> (Int -> m a) -> m () loopM !n k = let go i = when (i < n) (k i >> go (i+1)) in go 0 uninitialised :: a uninitialised = error "Data.Vector.Mutable: uninitialised element" -- Length information -- ------------------ -- | Length of the mutable vector. length :: MVector s a -> Int {-# INLINE length #-} length = G.length -- | Check whether the vector is empty null :: MVector s a -> Bool {-# INLINE null #-} null = G.null -- Extracting subvectors -- --------------------- -- | Yield a part of the mutable vector without copying it. slice :: Int -> Int -> MVector s a -> MVector s a {-# INLINE slice #-} slice = G.slice take :: Int -> MVector s a -> MVector s a {-# INLINE take #-} take = G.take drop :: Int -> MVector s a -> MVector s a {-# INLINE drop #-} drop = G.drop {-# INLINE splitAt #-} splitAt :: Int -> MVector s a -> (MVector s a, MVector s a) splitAt = G.splitAt init :: MVector s a -> MVector s a {-# INLINE init #-} init = G.init tail :: MVector s a -> MVector s a {-# INLINE tail #-} tail = G.tail -- | Yield a part of the mutable vector without copying it. No bounds checks -- are performed. unsafeSlice :: Int -- ^ starting index -> Int -- ^ length of the slice -> MVector s a -> MVector s a {-# INLINE unsafeSlice #-} unsafeSlice = G.unsafeSlice unsafeTake :: Int -> MVector s a -> MVector s a {-# INLINE unsafeTake #-} unsafeTake = G.unsafeTake unsafeDrop :: Int -> MVector s a -> MVector s a {-# INLINE unsafeDrop #-} unsafeDrop = G.unsafeDrop unsafeInit :: MVector s a -> MVector s a {-# INLINE unsafeInit #-} unsafeInit = G.unsafeInit unsafeTail :: MVector s a -> MVector s a {-# INLINE unsafeTail #-} unsafeTail = G.unsafeTail -- Overlapping -- ----------- -- Check whether two vectors overlap. overlaps :: MVector s a -> MVector s a -> Bool {-# INLINE overlaps #-} overlaps = G.overlaps -- Initialisation -- -------------- -- | Create a mutable vector of the given length. new :: PrimMonad m => Int -> m (MVector (PrimState m) a) {-# INLINE new #-} new = G.new -- | Create a mutable vector of the given length. The length is not checked. unsafeNew :: PrimMonad m => Int -> m (MVector (PrimState m) a) {-# INLINE unsafeNew #-} unsafeNew = G.unsafeNew -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with an initial value. replicate :: PrimMonad m => Int -> a -> m (MVector (PrimState m) a) {-# INLINE replicate #-} replicate = G.replicate -- | Create a mutable vector of the given length (0 if the length is negative) -- and fill it with values produced by repeatedly executing the monadic action. replicateM :: PrimMonad m => Int -> m a -> m (MVector (PrimState m) a) {-# INLINE replicateM #-} replicateM = G.replicateM -- | Create a copy of a mutable vector. clone :: PrimMonad m => MVector (PrimState m) a -> m (MVector (PrimState m) a) {-# INLINE clone #-} clone = G.clone -- Growing -- ------- -- | Grow a vector by the given number of elements. The number must be -- positive. grow :: PrimMonad m => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE grow #-} grow = G.grow -- | Grow a vector by the given number of elements. The number must be -- positive but this is not checked. unsafeGrow :: PrimMonad m => MVector (PrimState m) a -> Int -> m (MVector (PrimState m) a) {-# INLINE unsafeGrow #-} unsafeGrow = G.unsafeGrow -- Restricting memory usage -- ------------------------ -- | Reset all elements of the vector to some undefined value, clearing all -- references to external objects. This is usually a noop for unboxed vectors. clear :: PrimMonad m => MVector (PrimState m) a -> m () {-# INLINE clear #-} clear = G.clear -- Accessing individual elements -- ----------------------------- -- | Yield the element at the given position. read :: PrimMonad m => MVector (PrimState m) a -> Int -> m a {-# INLINE read #-} read = G.read -- | Replace the element at the given position. write :: PrimMonad m => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE write #-} write = G.write -- | Swap the elements at the given positions. swap :: PrimMonad m => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE swap #-} swap = G.swap -- | Yield the element at the given position. No bounds checks are performed. unsafeRead :: PrimMonad m => MVector (PrimState m) a -> Int -> m a {-# INLINE unsafeRead #-} unsafeRead = G.unsafeRead -- | Replace the element at the given position. No bounds checks are performed. unsafeWrite :: PrimMonad m => MVector (PrimState m) a -> Int -> a -> m () {-# INLINE unsafeWrite #-} unsafeWrite = G.unsafeWrite -- | Swap the elements at the given positions. No bounds checks are performed. unsafeSwap :: PrimMonad m => MVector (PrimState m) a -> Int -> Int -> m () {-# INLINE unsafeSwap #-} unsafeSwap = G.unsafeSwap -- Filling and copying -- ------------------- -- | Set all elements of the vector to the given value. set :: PrimMonad m => MVector (PrimState m) a -> a -> m () {-# INLINE set #-} set = G.set -- | Copy a vector. The two vectors must have the same length and may not -- overlap. copy :: PrimMonad m => MVector (PrimState m) a -> MVector (PrimState m) a -> m () {-# INLINE copy #-} copy = G.copy -- | Copy a vector. The two vectors must have the same length and may not -- overlap. This is not checked. unsafeCopy :: PrimMonad m => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeCopy #-} unsafeCopy = G.unsafeCopy -- | Move the contents of a vector. The two vectors must have the same -- length. -- -- If the vectors do not overlap, then this is equivalent to 'copy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. move :: PrimMonad m => MVector (PrimState m) a -> MVector (PrimState m) a -> m () {-# INLINE move #-} move = G.move -- | Move the contents of a vector. The two vectors must have the same -- length, but this is not checked. -- -- If the vectors do not overlap, then this is equivalent to 'unsafeCopy'. -- Otherwise, the copying is performed as if the source vector were -- copied to a temporary vector and then the temporary vector was copied -- to the target vector. unsafeMove :: PrimMonad m => MVector (PrimState m) a -- ^ target -> MVector (PrimState m) a -- ^ source -> m () {-# INLINE unsafeMove #-} unsafeMove = G.unsafeMove
mightymoose/liquidhaskell
benchmarks/vector-0.10.0.1/Data/Vector/Mutable.hs
bsd-3-clause
12,569
0
19
3,114
3,075
1,605
1,470
221
2
-- An example of RelaxedPolyRec in action which came up -- on Haskell Cafe June 2010 (Job Vranish) module Foo where import Data.Maybe -- The fixed point datatype data Y f = Y (f (Y f)) -- Silly dummy function maybeToInt :: Maybe a -> Int maybeToInt = length . maybeToList --------------------------- -- f and g are mutually recursive -- Even though f has a totally monomorphic -- signature, g has a very polymorphic one f :: Y Maybe -> Int f (Y x) = g maybeToInt x -- With RelaxedPolyRec we can infer this type -- g :: Functor f => (f Int -> b) -> f (Y Maybe) -> b g h x = h $ fmap f x -- 'test' checks that g's type is polymophic enough test :: Functor f => (f Int -> b) -> f (Y Maybe) -> b test = g
siddhanathan/ghc
testsuite/tests/typecheck/should_compile/PolyRec.hs
bsd-3-clause
738
0
10
185
157
86
71
10
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.DocumentAndElementEventHandlers (copy, cut, paste, beforeCopy, beforeCut, beforeinput, beforePaste, DocumentAndElementEventHandlers(..), gTypeDocumentAndElementEventHandlers, IsDocumentAndElementEventHandlers, toDocumentAndElementEventHandlers) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.oncopy Mozilla DocumentAndElementEventHandlers.oncopy documentation> copy :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent copy = unsafeEventName (toJSString "copy") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.oncut Mozilla DocumentAndElementEventHandlers.oncut documentation> cut :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent cut = unsafeEventName (toJSString "cut") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.onpaste Mozilla DocumentAndElementEventHandlers.onpaste documentation> paste :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent paste = unsafeEventName (toJSString "paste") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.onbeforecopy Mozilla DocumentAndElementEventHandlers.onbeforecopy documentation> beforeCopy :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent beforeCopy = unsafeEventName (toJSString "beforecopy") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.onbeforecut Mozilla DocumentAndElementEventHandlers.onbeforecut documentation> beforeCut :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent beforeCut = unsafeEventName (toJSString "beforecut") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.onbeforeinput Mozilla DocumentAndElementEventHandlers.onbeforeinput documentation> beforeinput :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self onbeforeinput beforeinput = unsafeEventName (toJSString "beforeinput") -- | <https://developer.mozilla.org/en-US/docs/Web/API/DocumentAndElementEventHandlers.onbeforepaste Mozilla DocumentAndElementEventHandlers.onbeforepaste documentation> beforePaste :: (IsDocumentAndElementEventHandlers self, IsEventTarget self) => EventName self ClipboardEvent beforePaste = unsafeEventName (toJSString "beforepaste")
ghcjs/jsaddle-dom
src/JSDOM/Generated/DocumentAndElementEventHandlers.hs
mit
3,613
0
7
451
599
361
238
50
1
module Main where import qualified PactSpec as P import qualified ServiceSpec as S main :: IO () main = P.main >> S.main >> return ()
mannersio/manners
cli/test/Main.hs
mit
135
0
7
26
48
29
19
5
1
module GHCJS.DOM.XMLHttpRequestProgressEvent ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/XMLHttpRequestProgressEvent.hs
mit
57
0
3
7
10
7
3
1
0
module Wobsurv.TemplateModels.Index where import BasePrelude import Data.Text (Text) import Data.ByteString (ByteString) data Index = Index { path :: Text, contents :: [Text] } deriving (Show, Data, Typeable)
nikita-volkov/wobsurv
library/Wobsurv/TemplateModels/Index.hs
mit
227
0
9
45
69
42
27
9
0
import Sound.VAD.WebRTC main = create
chpatrick/haskell-webrtc-vad
src/Test.hs
mit
38
0
4
5
12
7
5
2
1
module Y2017.M11.D01.Exercise where {-- So, yesterday, we read in source NYT article archives and scanned them. We've saved the special characters, and then, manually, we've provided the replacement ASCII equivalents, where applicable. Now what? First, let's read in that file of special characters into a memoizing table. Why? We will see. --} import Data.Set (Set) -- below imports available via 1HaskellADay git repository import Control.Scan.Config import Data.MemoizingTable import Y2017.M10.D02.Exercise -- for block import Y2017.M10.D30.Exercise -- for special char parsing specialCharsFile :: FilePath specialCharsFile = "Y2017/M10/D31/spcChars.prop" data AsciiEquiv = DELETE | REPLACE String deriving (Eq, Show) {-- So, the mappings for just the special characters (no replacement) is DELETE, otherwise it's REPLACE with the replacement, e.g.:  £ EUR becomes  -> DELETE £ -> REPLACE "EUR" How would you affect this transition? --} parseAscii :: [String] -> AsciiEquiv parseAscii asciival = undefined type SpecialCharTable = MemoizingTable SpecialChars AsciiEquiv readSpecialChars :: FilePath -> IO SpecialCharTable readSpecialChars config = undefined {-- Once you've done that, scan the repository here for special characters. Are there any diffs? What are they? If there are new special characters you've encountered, add them to the memoizing table (hint: triageMT) n.b.: since we are not 'mapping back' from ASCII to the special characters, the readIndex table in the MemoizingTable can be ignored. --} repository :: FilePath repository = "Y2017/M11/D01/NYTOnline_08-29-17_09-05-17_pt3a.txt.gz" scanArchive :: SpecialCharTable -> FilePath -> IO (Either () [Context]) scanArchive archive specialChars = undefined -- Returns Left (), meaning no new special chars in the new archive, or -- Right set, with the new special chars not found in our config. {-- Now, from the result returned by scanArchive, call a function that either replaces the special characters in the target archive or adds the new characters to the config file for manual update. --} replaceSpecialChars :: SpecialCharTable -> Block -> Block replaceSpecialChars specialCharTable block = undefined -- updates block with special chars to block with ASCII-equivalents -- hint: you need to extract then replace special characters in block. -- ... now where have we written an extract function. Hm. updateConfig :: SpecialCharTable -> FilePath -> [Context] -> IO () updateConfig specialCharTable config ctxn = undefined -- n.b. updateConfig needs to preserve the special character replacements -- you've previously defined. Hint: appendFile? -- If you like, you can print out a friendly message saying what you're doing, -- based on the function called. {-- BONUS ----------------------------------------------------------------- With the updated config file, you should now be clear to replace the special characters in the archive. Repeat all the steps above. Does it do a replace of the special characters in your archive? Let's find out. In the updated archive, are there any special characters? List them. Hint: Y2017.M10.D30.Exercise.identify Also: write an application that does all the above. --} main' :: [String] -> IO () main' (configfile:archivefiles) = undefined -- do it main' [] = undefined -- print help message {-- I'm of two minds. On the one hand, I could just simply, instead of writing out a new, sanitized, archive, simply upload the in-memory sanitized version to the database. On the other hand, I do have physical evidence of the transition: from original archive to sanitized one. That artifact has worth when things go South and the transition states are useful for debugging, so ... You can save out the resulting sanitized version to the file system or you can upload the revised archive right to the database. Your choice. Why did you go with the option you chose? --}
geophf/1HaskellADay
exercises/HAD/Y2017/M11/D01/Exercise.hs
mit
3,932
0
10
631
298
174
124
26
1
import Control.Monad.State --import Control.Monad.Identity test1 :: State int int test1 = do -- fuck a <- get -- modify (+1) -- b <- get return (a+1)
Muzietto/transformerz
haskell/sigfpe/grok_1.hs
mit
154
0
9
30
46
25
21
5
1
module PhotoClassifier ( processDir ,DateStuff ,toDateStuffFromString ) where import System.IO import System.Directory import System.FilePath.Posix import System.Posix.Files import System.Environment import Graphics.Exif import Data.String.Utils import Data.Time.Calendar data DateStuff = DateStuff (String, String, String) deriving (Show) data PictureStuff = PictureStuff { picName :: String , picDate :: DateStuff } deriving (Show) -- Constants --sTART_DATE :: DateStuff --sTART_DATE = DateStuff ("2013", "02", "09") -- Date extraction functions exYear :: [String] -> String exYear (x:xs) = x exMonth :: [String] -> String exMonth (x:y:xs) = y exDay :: [String] -> String exDay [x] = x exDay (x:xs) = exDay xs toDateStuffFromString :: String -> DateStuff toDateStuffFromString d = let dd = split "-" d in DateStuff ((exYear dd), (exMonth dd), (exDay dd)) toDayFromDateStuff :: DateStuff -> Day toDayFromDateStuff (DateStuff (y,m,d)) = fromGregorian (read y :: Integer) (read m :: Int) (read d :: Int) -- calcWeek: Calculates the week number, starting from d2 until d1. If d2 happened before d1, then -- the result will be the abs value, prepended with '_'. E.g 3 weeks since..., _3 weeks before calcWeek :: DateStuff -> DateStuff -> String calcWeek d2 d1 = toString $ floor (fromIntegral (diffDays (toDayFromDateStuff d2) (toDayFromDateStuff d1)) / 7.0) where toString :: Integer -> String toString i | i < 0 = ("_" ++) $ show $ (i * (-1)) | otherwise = show i -- cleanExifDate :: converts a String into a DateStuff cleanExifDate :: Maybe String -> DateStuff --cleanExifDate Nothing = sTART_DATE cleanExifDate (Just d) = toDateStuff $ head $ split " " d where toDateStuff :: String -> DateStuff toDateStuff s = let s' = split ":" s in DateStuff (exYear s', exMonth s', exDay s') -- end cleanExifDate -- classifyPhoto: Takes a PictureStuff, DateStuff, Week (String) and Output dir (String) and -- puts the photo in the OUTPUT dir and creates links in the year-month, year-week subfolders classifyPhoto :: PictureStuff -> DateStuff -> String -> IO () classifyPhoto p (DateStuff (y,m,d)) w = let f = takeFileName (picName p) in let dout = takeDirectory (picName p) in cDir True (outDir dout)>> copyFile (picName p) (outDirFile dout f) >> cDir True (outDirYear dout y) >> cDir True (outDirMonth dout y m) >> cDir True (outDirWeek dout y w) >> createSymbolicLink (outDirFile dout f) (joinPath [outDirMonth dout y m, f]) >> createSymbolicLink (outDirFile dout f) (joinPath [outDirWeek dout y w, f]) where cDir = createDirectoryIfMissing outDir d = joinPath [d, "output"] outDirFile d f = joinPath [outDir d, f] outDirYear d y = joinPath [outDir d, y] outDirMonth d y m = joinPath [outDirYear d y, m] outDirWeek d y w = joinPath [outDirYear d y, w] processPhoto :: PictureStuff -> DateStuff -> IO () processPhoto p sd = putStrLn (picName p) >> putStrLn "Date " >> print (picDate p) >> putStrLn "Week " >> let w = (calcWeek (picDate p) (sd)) in let d = picDate p in print ("Name: " ++ (picName p)) >> print ("FileName: " ++ takeFileName (picName p)) >> print w >> classifyPhoto p d w sepLn :: String sepLn = concat $ replicate 20 "=" printExif :: (String, DateStuff) -> IO() printExif (file, sd) = do exif <- fromFile file putStr sepLn >> putStr " Processing Image: " putStr file >> putStr " " putStrLn sepLn dt_tag <- getTag exif "DateTime" processPhoto (PictureStuff {picName = file, picDate = cleanExifDate dt_tag}) sd printTag (n,v) = putStrLn $ n ++ ": " ++ v showMe :: FilePath -> IO () showMe x = putStrLn x processDir :: FilePath -> FilePath -> String -> IO () processDir dir outDir startDate = do files <- getDirectoryContents dir putStr "Processing Directory " putStrLn dir let sd = toDateStuffFromString startDate mapM_ printExif (map (\f -> (dir ++ "/" ++ f, sd)) (filter (endswith ".jpg") files))
neurogeek/photo-classifier
PhotoClassifier.hs
mit
5,163
0
18
1,983
1,414
722
692
90
1
module Db.Course (selectCourse, selectCourses, insertCourse, insertCourses, deleteCourses) where import Database.Persist.Postgresql (Entity (..), Filter, (==.), (>.), insertMany_, selectFirst, selectList, insert, deleteWhere, toSqlKey) import Config (WithConfig, Action) import Db.Model selectCourse :: [Filter Course] -> WithConfig (Maybe (Entity Course)) selectCourse filter = do course <- runDb $ selectFirst filter [] return course selectCourses :: [Filter Course] -> WithConfig [Entity Course] selectCourses filter = do courses <- runDb $ selectList filter [] return courses insertCourse :: Course -> WithConfig (Key Course) insertCourse course = do key <- runDb $ insert course return key insertCourses :: [Course] -> WithConfig () insertCourses courses = do runDb $ insertMany_ courses deleteCourses :: WithConfig () deleteCourses = do runDb $ deleteWhere [CourseId >. toSqlKey 0]
SebastianCallh/liu-courses
src/Db/Course.hs
mit
1,080
0
11
309
319
167
152
26
1
-- Demo myDrop n xs = if n <= 0 || null xs then xs else myDrop (n - 1) (tail xs) lastButOne = last . init
zhangjiji/real-world-haskell
ch2.hs
mit
136
0
8
57
58
30
28
4
2
module TerminationChecker where import Expr import TypeChecker import Data.List import Data.Maybe import Control.Monad import Control.Monad.Error import Control.Monad.Reader import Control.Monad.Identity -- General functions -- | Finds the sublist starting from the first element for which the predicate holds. subListFrom :: (a -> Bool) -> [a] -> [a] subListFrom f [] = [] subListFrom f (x:xs) = if f x then x : xs else subListFrom f xs -- | Creates an association list from a list of triples assocListFromTriples :: (Eq a, Ord a) => [(a, b, c)] -> [(a, [(a, b, c)])] assocListFromTriples [] = [] assocListFromTriples xs = let groups = groupBy (\(a,_,_) -> \(d,_,_) -> a == d) $ sortBy (\(a,_,_) -> \(d,_,_) -> compare a d) xs tripleFst (a,_,_) = a in map (\group -> (tripleFst $ head group, group)) groups -- Handle input type Program = [TypedExpr] -- | Split a list of typed expressions into ([TEData], [TEGlobLet]) splitProgram :: Program -> ([TypedExpr], [TypedExpr]) splitProgram [] = ([], []) splitProgram (gl@(TEGlobLet _ _ _ _) : tes) = (fst $ splitProgram tes, gl : (snd $ splitProgram tes)) splitProgram (dt@(TEData _ _) : tes) = (dt : (fst $ splitProgram tes), snd $ splitProgram tes) splitProgram (_ : tes) = splitProgram tes -- Size terms data Size = Min -- Minimal value, e.g. Z for Nat and Nil for List | NotMin Size | D Size -- Destructor. D (Param "x") < Param "x" | Param Sym -- Function parameter | Var Sym -- Non-parameter value | C Size -- Constructor application. C (Param "x") > Param "x" | Unknown -- When the size is unknown | Multiple [Size] -- Non-deterministic choice. Used when a term can have several possible sizes. | Deferred TypedExpr deriving (Eq, Show) reduceSize :: Size -> Size reduceSize Min = Min reduceSize (NotMin s) = NotMin (reduceSize s) reduceSize (D (C s)) = reduceSize s reduceSize (D s) = case (reduceSize s) of Min -> Min s' -> D s' reduceSize (Param x) = Param x reduceSize (Var x) = Var x reduceSize (C (D s)) = reduceSize s reduceSize (C s) = C (reduceSize s) reduceSize Unknown = Unknown reduceSize (Multiple ss) = Multiple $ map reduceSize ss reduceSize (Deferred e) = Deferred e instance Ord Size where compare x y = compare' (reduceSize x) (reduceSize y) where -- Min compare' Min Min = EQ compare' Min (NotMin _) = LT compare' Min (C _) = LT compare' Min (D s) = case s of Min -> EQ _ -> LT compare' Min (Param _) = EQ compare' Min (Var _) = EQ -- NotMin compare' (NotMin s) Min = GT compare' (NotMin s) (NotMin s') = compare' s s' compare' (NotMin s) (C s') = case s' of Min -> compare' (D s) Min _ -> compare' s (C s') compare' (NotMin s) (D s') = case s' of Min -> GT _ -> compare' s (D s') compare' (NotMin s) (Param x) = compare' s (Param x) compare' (NotMin s) (Var x) = compare' s (Var x) -- D compare' (D s) Min = case s of Min -> EQ _ -> GT compare' (D s) (NotMin s') = case s of Min -> LT _ -> compare' (D s) s' compare' (D _) (C _) = LT compare' (D s) (D s') = compare' s s' compare' (D _) (Param _) = LT compare' (D _) (Var _) = LT -- Param compare' (Param _) Min = GT compare' (Param x) (NotMin s) = compare' (Param x) s compare' (Param _) (C _) = LT compare' (Param _) (D _) = GT compare' (Param x) (Param y) = if x == y then EQ else GT compare' (Param _) (Var _) = EQ -- Var compare' (Var _) Min = GT compare' (Var x) (NotMin s) = compare' (Var x) s compare' (Var _) (C _) = LT compare' (Var _) (D _) = GT compare' (Var _) (Param _) = EQ compare' (Var x) (Var y) = if x == y then EQ else GT -- C compare' (C _) Min = GT compare' (C s) (NotMin s') = case s of Min -> compare' Min (D s) _ -> compare' (C s) s' compare' (C s) (C s') = compare' s s' compare' (C s) (D s') = GT compare' (C _) (Param _) = GT compare' (C _) (Var _) = GT -- Unknown compare' Unknown Unknown = EQ compare' _ Unknown = LT -- Multiple compare' (Multiple ss) s' = foldl1 compare (map (\s'' -> compare' s'' s') ss) compare' s (Multiple ss') = foldl1 compare (map (compare' s) ss') -- Catch-all compare' _ _ = GT -- Control-flow graphs data ControlPoint a = Global Sym a | Local Sym (ControlPoint a) a deriving (Show) instance Eq (ControlPoint a) where f == g = controlPointId f == controlPointId g instance Ord (ControlPoint a) where compare f g = compare (controlPointId f) (controlPointId g) -- A Call is a connection between two control points, establishing interdependency type Substitution a = [(Sym, DataPosition a)] type Call a b = (ControlPoint a, b, ControlPoint a) type CallSequence a b = [Call a b] -- type ControlFlowGraph a b = [Call a b] controlPointId :: ControlPoint a -> Sym controlPointId (Global id _) = id controlPointId (Local id _ _) = id controlPointData :: ControlPoint a -> a controlPointData (Global _ a) = a controlPointData (Local _ _ a) = a -- Size-change graphs data Arrow = Descending | NonIncreasing deriving (Eq, Show) -- Data positions represent the terms that (may) change size newtype DataPosition a = DataPos { getData :: a } deriving Eq instance Show a => Show (DataPosition a) where show dpos = show (getData dpos) -- A size-change arc describes a change between two data positions type SCArc a = (DataPosition a, Arrow, DataPosition a) -- A size-change graph is a set of size-change arcs. type SizeChangeGraph a b = (ControlPoint a, [SCArc b], ControlPoint a) type Multipath a b = [SizeChangeGraph a b] type Thread a = [SCArc a] -- Functions on size-change graphs hasArc :: Eq b => SizeChangeGraph a b -> SCArc b -> Bool hasArc (_, arcs, _) arc = any (== arc) arcs isArcSafe :: Ord b => SizeChangeGraph a b -> Bool isArcSafe (as, arcs, bs) = all (\arc -> isSafeArc arc) arcs && hasConsistentArcs arcs where isSafeArc :: Ord b => SCArc b -> Bool isSafeArc (DataPos a, Descending, DataPos b) = a < b isSafeArc (DataPos a, NonIncreasing, DataPos b) = a <= b hasConsistentArcs :: Eq a => [SCArc a] -> Bool -- Consistency = no duplicate arcs with different arrows hasConsistentArcs arcs = null $ [ (a, y) | (a, arr, b) <- arcs, (x, arr', y) <- arcs, a == x, b == y, not (arr == arr') ] areComposable :: Eq a => SizeChangeGraph a b -> SizeChangeGraph a b -> Bool areComposable (_, _, y) (y', _, _) = y == y' -- | Composes two size-change graphs. compose :: Eq a => SizeChangeGraph a (Sym, Size) -> SizeChangeGraph a (Sym, Size) -> Maybe (SizeChangeGraph a (Sym, Size)) compose g@(x, xy, y) g'@(y', yz, z) | areComposable g g' = Just (x, composeArrows xy yz, z) | otherwise = Nothing where composeArrows :: [SCArc (Sym, Size)] -> [SCArc (Sym, Size)] -> [SCArc (Sym, Size)] composeArrows xy yz = [ (DataPos (x,xs), Descending, DataPos (z,zs)) | (DataPos (x,xs), arr, DataPos (y,_)) <- xy, (DataPos (y',_), arr', DataPos (z,zs)) <- yz, y == y', arr == Descending || arr' == Descending ] ++ [ (DataPos (x,xs), NonIncreasing, DataPos (z,zs)) | (DataPos (x,xs), arr, DataPos (y,_)) <- xy, (DataPos (y',_), arr', DataPos (z,zs)) <- yz, y == y', arr == NonIncreasing && arr' == NonIncreasing ] -- | Finds all cyclic multipaths from a list of size-change graphs. -- | The size-change graphs are generated from the calls in the call graph. cyclicMultipaths :: Eq a => [SizeChangeGraph a b] -> [Multipath a b] cyclicMultipaths [] = [] cyclicMultipaths (scgs@((f,_,g):_)) = cycles f (assocListFromTriples scgs) [] [] where -- Current node Adjacency list Path cycles :: Eq a => ControlPoint a -> [(ControlPoint a, [SizeChangeGraph a b])] -> [SizeChangeGraph a b] -> -- Visited Cycles [ControlPoint a] -> [Multipath a b] cycles node graph path visited = let backtracking = node `elem` visited nodesVisited = if not backtracking then node : visited else visited nodeEdges = case lookup node graph of Just edges -> edges Nothing -> [] -- cycleEdges create a cycle -- (cycleEdges, unexploredEdges) = partition (\(f, _, g) -> g `elem` nodesVisited) nodeEdges (cycleEdges, otherEdges) = partition (\(f,_,g) -> let inPath = any (\(m,_,n) -> g == m) path in if backtracking then inPath else inPath || g `elem` nodesVisited) nodeEdges unexploredEdges = filter (\(f, _, g) -> g `notElem` nodesVisited) otherEdges cyclePaths = map (\(f,x,g) -> (subListFrom (\(m,_,n) -> g == m) path) ++ [(f,x,g)]) cycleEdges unexploredPaths = case unexploredEdges of [] -> case path of -- Find out if any nodes have not been considered [] -> case find (\(n, _) -> n `notElem` nodesVisited) graph of Just (n, _) -> cycles n graph [] [] -- Found one! Nothing -> [] -- All nodes have been considered, terminate ((f,_,_):p) -> cycles f graph p nodesVisited -- Backtrack unexplored -> concat $ map (\(f,x,g) -> cycles g graph (path ++ [(f,x,g)]) nodesVisited) unexplored in cyclePaths ++ unexploredPaths cycledUntilHead :: Eq a => [a] -> a -> [a] cycledUntilHead (x:xs) y | y `elem` (x:xs) = if x == y then (x:xs) else cycledUntilHead (xs ++ [x]) y | otherwise = (x:xs) allMultipaths :: (Eq a, Eq b) => Multipath a b -> [Multipath a b] allMultipaths multipath = map (\scg -> cycledUntilHead multipath scg) multipath collapse :: Eq a => Multipath a (Sym, Size) -> Maybe (SizeChangeGraph a (Sym, Size)) collapse multipath | not (null multipath) = foldM compose (head multipath) (tail multipath) | otherwise = Nothing -- Functions for determining termination isLoop :: Eq a => SizeChangeGraph a b -> Bool isLoop (f, _, g) = f == g -- | Determines whether a size-change graph G is equal to G composed with G (i.e. G;G) isSelfComposition :: Eq a => SizeChangeGraph a (Sym, Size) -> Bool isSelfComposition g = case g `compose` g of Just g' -> g == g' Nothing -> False -- Implementation-specific functions -- All control points have a set of initial data positions -- All data positions have a size -- All calls map arguments to data positions type DataEnv = [(Sym, DataPosition Size)] type Hints = [(TypedExpr, Sym)] paramsAsData :: Maybe Params -> [(Sym, DataPosition Size)] paramsAsData Nothing = [] paramsAsData (Just params) = map (\(sym, _) -> (sym, DataPos $ Param sym)) params globalControlPoints :: [TypedExpr] -> [(ControlPoint DataEnv, TypedExpr)] globalControlPoints [] = [] globalControlPoints (TEGlobLet ty name params body : globs) = (Global name (paramsAsData params), body) : globalControlPoints globs globalControlPoints (_ : globs) = globalControlPoints globs data ParameterType = Recursive | NonRecursive deriving Eq data Constructor = Constructor { constructorName :: Sym, constructorParameters :: [ParameterType] } globalDataConstructors :: [TypedExpr] -> [Constructor] globalDataConstructors [] = [] globalDataConstructors ((TEData ty@(TRecInd _ (TVari constructors)) _):ds) = let name = fst parameterTypes = map (\t -> if t == ty then Recursive else NonRecursive) in map (\(name,params) -> Constructor name (parameterTypes params)) constructors ++ globalDataConstructors ds globalDataConstructors (_:ds) = globalDataConstructors ds controlPointFromExpr :: TypedExpr -> [ControlPoint a] -> Maybe (ControlPoint a) controlPointFromExpr (TEVar _ f) cps = find (\cp -> f == controlPointId cp) cps controlPointFromExpr _ _ = Nothing constructorFromExpr :: TypedExpr -> [Constructor] -> Maybe (Constructor) constructorFromExpr (TEVar _ f) constrs = find (\c -> f == constructorName c) constrs constructorFromExpr _ _ = Nothing data CallGraphEnv = CallGraphEnv { controlPoints :: [ControlPoint DataEnv], constructors :: [Constructor], dataPositions :: DataEnv, hints :: Hints } updateControlPoint :: ControlPoint DataEnv -> Size -> (Size -> Size) -> ControlPoint DataEnv updateControlPoint (Global name params) size f = Global name (updateDataEnv params size f) updateControlPoint (Local name parent params) size f = Local name parent (updateDataEnv params size f) updateDataEnv :: DataEnv -> Size -> (Size -> Size) -> DataEnv updateDataEnv [] size f = [] updateDataEnv ((name, DataPos s):sizes) size f = if s == size then (name, DataPos $ f s) : updateDataEnv sizes size f else (name, DataPos s) : updateDataEnv sizes size f addControlPoint :: ControlPoint DataEnv -> CallGraphEnv -> CallGraphEnv addControlPoint cp (CallGraphEnv cps cos dpos hs) = CallGraphEnv (cp:cps) cos dpos hs addData :: DataEnv -> CallGraphEnv -> CallGraphEnv addData d (CallGraphEnv cps cos dpos hs) = CallGraphEnv cps cos (d ++ dpos) hs addHints :: Hints -> CallGraphEnv -> CallGraphEnv addHints h (CallGraphEnv cps cos dpos hs) = CallGraphEnv cps cos dpos (h ++ hs) getVariantType :: Type -> ErrorT CallGraphError Identity [(Sym, [Type])] getVariantType (TVari ts) = return ts getVariantType (TRecInd _ (TVari ts)) = return ts getVariantType _ = throwError $ CallGraphError "Matched expression does not have a variant type" type CallGraphError = NonTermination type WithCallGraphEnv m a = ReaderT CallGraphEnv m a type CallGraph = WithCallGraphEnv (ErrorT CallGraphError Identity) [Call DataEnv (Substitution Size)] runCallGraph cp expr env = runIdentity (runErrorT $ runReaderT (callGraph' cp expr) env) -- | Builds a call graph of function definitions callGraph' :: ControlPoint DataEnv -> TypedExpr -> CallGraph callGraph' f (TEApp _ (TEFold _ _) [tag@(TETag _ _ _)]) = callGraph' f tag callGraph' f (TEApp _ (TEUnfold _ _) [arg]) = callGraph' f arg callGraph' f (TEApp _ g args) = do env <- ask case controlPointFromExpr g (controlPoints env) of -- Is g a function? Just target -> do let targetData cp = map fst $ controlPointData cp let call h argd = (f, zip (targetData h) argd, h) argGraphs <- mapM (callGraph' f) args argData <- mapM (sizeOf' f) args let argPositions = map DataPos argData return $ call target argPositions : (concat argGraphs) Nothing -> case constructorFromExpr g (constructors env) of -- Is g a data constructor? Just _ -> do argGraphs <- mapM (callGraph' f) args return $ concat argGraphs Nothing -> throwError $ CallGraphError "Called function does not exist. This is a type checking issue." callGraph' f (TELet ty id exprty params expr body) = do let paramData = paramsAsData params let localDef = Local id f paramData let exprEnv = addData paramData . addControlPoint localDef exprGraph <- local exprEnv $ callGraph' localDef expr exprSize <- local exprEnv $ sizeOf' f expr case exprGraph of [] -> case params of Just _ -> let env = addData [(id, DataPos $ Deferred expr)] . addControlPoint localDef in local env $ callGraph' f body Nothing -> let env = addData [(id, DataPos exprSize)] in local env $ callGraph' f body eg -> do bodyGraph <- local (addControlPoint localDef) $ callGraph' f body return $ eg ++ bodyGraph callGraph' f (TECase ty expr cases) = do env <- ask exprSize <- sizeOf' f expr let exprType = getTypeAnno expr let isRecType = (== exprType) variant <- lift $ getVariantType exprType caseGraphs <- forM cases $ \(id, (vars, caseExpr)) -> do caseTypes <- case lookup id variant of Just ts -> return ts Nothing -> throwError $ CallGraphError "Incompatible pattern" let annoVars = zip vars caseTypes let argEnv = map (\(v, t) -> if isRecType t then (v, DataPos $ D exprSize) else (v, DataPos $ Var v)) annoVars let isBaseCase = all (\(v,t) -> not $ isRecType t) annoVars if isBaseCase then let newF = updateControlPoint f exprSize (const Min) caseEnv = addData argEnv . addHints [(expr, id)] . addControlPoint newF . addData (map (\(name, size) -> (name, DataPos Min)) $ filter (\(_, DataPos size) -> size == exprSize) (dataPositions env)) in local caseEnv $ callGraph' newF caseExpr else let newF = updateControlPoint f exprSize NotMin caseEnv = addData argEnv . addHints [(expr, id)] . addControlPoint newF . addData (map (\(name, DataPos size) -> (name, DataPos $ NotMin size)) $ filter (\(_, DataPos size) -> size == exprSize) (dataPositions env)) in local caseEnv $ callGraph' newF caseExpr return $ concat caseGraphs callGraph' f (TETag ty id args) = do argGraphs <- mapM (callGraph' f) args return $ concat argGraphs callGraph' f@(Global id dataenv) (TEGlobLet _ id' _ body) | id == id' = callGraph' f body | otherwise = throwError $ CallGraphError "Attempt to generate call graph for mismatching control point and definition." callGraph' _ _ = return [] type SizeError = CallGraphError type ExprSize = WithCallGraphEnv (ErrorT SizeError Identity) Size -- | Finds the size of an expression sizeOf' :: ControlPoint DataEnv -> TypedExpr -> ExprSize sizeOf' f (TEVar _ id) = do env <- ask case lookup id (dataPositions env) of Just (DataPos (Deferred e)) -> sizeOf' f e Just (DataPos s) -> return s Nothing -> case find (\entry -> constructorName entry == id) (constructors env) of Just (Constructor _ []) -> return Min _ -> return Unknown sizeOf' f (TEApp _ (TEFold _ _) [tag@(TETag _ _ _)]) = sizeOf' f tag sizeOf' f (TEApp _ (TEUnfold _ _) [arg]) = sizeOf' f arg sizeOf' cp (TEApp _ f args) = do env <- ask case controlPointFromExpr f (controlPoints env) of Just target -> do let targetData = controlPointData target argSizes <- mapM (sizeOf' cp) args let argEnv = map DataPos argSizes local (addData $ zip (map fst targetData) argEnv) $ sizeOf' cp f Nothing -> case constructorFromExpr f (constructors env) of Just constructor -> let argTypes = zip args (constructorParameters constructor) (nonRecArg, recArgs) = partition (\(e,t) -> t == NonRecursive) argTypes in case recArgs of [] -> return Min [(arg, _)] -> do size <- sizeOf' cp arg; return $ C size args -> do sizes <- mapM (sizeOf' cp) (map fst recArgs) return (Multiple $ map C sizes) Nothing -> throwError $ SizeError "Called function does not exist. This is a type checking issue." sizeOf' f (TELet _ id _ p expr body) = do let params = paramsAsData p let localDef = Local id f params let localEnv = addControlPoint localDef . addData params exprSize <- local localEnv $ sizeOf' localDef expr local (addData [(id, DataPos exprSize)]) $ sizeOf' f body sizeOf' f (TECase ty expr cases) = do env <- ask exprSize <- sizeOf' f expr let exprType = getTypeAnno expr let isRecType = (== exprType) variant <- lift $ getVariantType exprType casesWSize <- forM cases $ \(id, (vars, caseExpr)) -> do caseTypes <- case lookup id variant of Just ts -> return ts Nothing -> throwError $ SizeError "Incompatible pattern" let annoVars = zip vars caseTypes let argEnv = map (\(v, t) -> if isRecType t then (v, DataPos $ D exprSize) else (v, DataPos $ Var v)) annoVars let isBaseCase = all (\(v,t) -> not $ isRecType t) annoVars if isBaseCase then do let newF = updateControlPoint f exprSize (const Min) let caseEnv = addData argEnv . addControlPoint newF . addData (map (\(name, DataPos size) -> (name, DataPos Min)) $ filter (\(_, DataPos size) -> size == exprSize) (dataPositions env)) baseCaseSize <- local caseEnv $ sizeOf' newF caseExpr return (id, baseCaseSize) else do let newF = updateControlPoint f exprSize NotMin let caseEnv = addData argEnv . addControlPoint newF . addData (map (\(name, DataPos size) -> (name, DataPos $ NotMin size)) $ filter (\(_, DataPos size) -> size == exprSize) (dataPositions env)) size <- local caseEnv $ sizeOf' newF caseExpr return (id, size) let caseSizes = map snd casesWSize let maxSize = if null caseSizes then Unknown else foldr1 max caseSizes -- Gør det mest konservative. case lookup expr (hints env) of Just hint -> case find (\c -> fst c == hint) casesWSize of Just (_, size) -> return size Nothing -> return maxSize Nothing -> return maxSize sizeOf' f (TETag tagty id args) = let hasTaggedType arg = case getTypeAnno arg of vari@(TVari _) -> vari == tagty TRecInd _ vari -> vari == tagty _ -> False sizeChangingArgs = filter hasTaggedType args in case sizeChangingArgs of [] -> return Min [arg] -> do size <- sizeOf' f arg; return $ C size args -> do sizes <- mapM (sizeOf' f) args return (Multiple $ map C sizes) sizeOf' _ _ = return Unknown -- | Builds a size-change graph for a call sizeChangeGraph :: Call DataEnv (Substitution Size) -> SizeChangeGraph DataEnv (Sym, Size) sizeChangeGraph (f, subs, g) = (f, mapMaybe toSCArc subs, g) where toSCArc :: (Sym, DataPosition Size) -> Maybe (SCArc (Sym, Size)) toSCArc (y, arg) = do let fData = controlPointData f let argSize = getData arg let roots = filter (\(x,_) -> x `elem` parameterRoots argSize) fData let comparisons = map (\(x, DataPos xSize) -> (x, DataPos xSize, compare argSize xSize)) $ roots --if null roots then fData else roots (x, DataPos initSize, ord) <- minOrder comparisons Nothing case ord of LT -> Just (DataPos (x, initSize), Descending, DataPos (y, argSize)) EQ -> Just (DataPos (x, initSize), NonIncreasing, DataPos (y, argSize)) GT -> Nothing parameterRoots :: Size -> [Sym] parameterRoots (Param x) = [x] parameterRoots (D s) = parameterRoots s parameterRoots (C s) = parameterRoots s parameterRoots (NotMin s) = parameterRoots s parameterRoots (Multiple ss) = concat $ map parameterRoots ss parameterRoots _ = [] minOrder :: Ord c => [(a, b, c)] -> Maybe (a, b, c) -> Maybe (a, b, c) minOrder [] acc = acc minOrder (el@(_, _, ord) : xs) Nothing = minOrder xs (Just el) minOrder (new@(_, _, ord) : xs) old@(Just (_, _, ord')) = if ord < ord' then minOrder xs (Just new) else minOrder xs old identityArcs :: SizeChangeGraph DataEnv (Sym, Size) -> [SCArc (Sym, Size)] identityArcs scg@(f, arcs, g) | isLoop scg = [ (DataPos (a, s), arc, DataPos (b, s')) | (DataPos (a, s), arc, DataPos (b, s')) <- arcs, a == b ] | otherwise = [] descendingArcs :: [SCArc a] -> [SCArc a] descendingArcs arcs = filter (\(f, arr, g) -> arr == Descending) arcs hasDescendingArcs :: SizeChangeGraph a b -> Bool hasDescendingArcs (f, arcs, g) = not (null $ descendingArcs arcs) showSizeChangeGraph :: SizeChangeGraph DataEnv (Sym, Size) -> Bool -> String showSizeChangeGraph (f, arcs, g) True = controlPointId f ++ " " ++ showArcs arcs ++ " " ++ controlPointId g where showArcs :: [SCArc (Sym, Size)] -> String showArcs arcs = "[" ++ intercalate "," (map show arcs) ++ "]" showSizeChangeGraph (f, arcs, g) False = controlPointId f ++ " --> " ++ controlPointId g showMultipath :: Multipath DataEnv (Sym, Size) -> Bool -> String showMultipath mp withArcs = intercalate " --> " $ map (\scg -> "(" ++ showSizeChangeGraph scg withArcs ++ ")") mp data Termination = Termination [SizeChangeGraph DataEnv (Sym, Size)] instance Show Termination where show (Termination scgs) = let showF (f,arcs,g) = controlPointId f ++ " terminates on input " ++ (show $ (map show (descendingArcs arcs))) in (intercalate "\n" $ map showF scgs) data NonTermination = UnsafeMultipathError (Multipath DataEnv (Sym, Size)) | InfiniteRecursion (Multipath DataEnv (Sym, Size)) | UnknownCause String | CallGraphError String | SizeError String instance Show NonTermination where show (UnsafeMultipathError mp) = "Could not determine termination due to unsafe multipath: " ++ showMultipath mp False show (InfiniteRecursion mp) = "Program is not size-change terminating due to possible infinite recursion in call chain: " ++ showMultipath mp True show (UnknownCause msg) = show msg show (CallGraphError msg) = "Error while building the call graph: " ++ msg show (SizeError msg) = "Error while determining size of expression: " ++ msg instance Error NonTermination -- Theorem 4! isSizeChangeTerminating :: Program -> Either NonTermination Termination isSizeChangeTerminating [] = return $ Termination [] isSizeChangeTerminating prog = do let (dataExprs, funExprs) = splitProgram prog -- Split program into function and data definitions let globalFuns = globalControlPoints funExprs let globalConstrs = globalDataConstructors dataExprs let initEnv cp = CallGraphEnv (map fst globalFuns) globalConstrs (controlPointData cp) [] -- Define initial environment for call graph callGraphs <- mapM (\(cp, e) -> runCallGraph cp e (initEnv cp)) globalFuns -- Create call graph let calls = concat callGraphs let sizeChangeGraphs = map sizeChangeGraph calls -- Build size-change graphs for each call in the call graph let multipaths = concat $ map allMultipaths (cyclicMultipaths sizeChangeGraphs) -- Find all the cyclic multipaths from the generated size-change graphs. let collapsedMultipaths = map (\mp -> (mp, collapse mp)) multipaths -- Collapse the cyclic multipaths to one size-change graph let unsafeMultipaths = map fst $ filter (\(mp, collapsed) -> isNothing collapsed) collapsedMultipaths -- Find those multipaths which are unsafe let safeCollapsedMultipaths = map (\(mp, c) -> (mp, fromJust c)) $ [ (m, c) | (m, c) <- collapsedMultipaths, isJust c ] -- .. And thos which are safe let possiblyNonTerminating = -- Find multipaths that possibly give rise to non-termination filter (\(mp, collapsed) -> isLoop collapsed && isSelfComposition collapsed) safeCollapsedMultipaths let descendingArcsWithGraph m = map (\(mp, collapsed) -> (mp, descendingArcs (identityArcs collapsed))) m -- Find descending size-change arcs in collapsed multipath let graphsWithNoDescendingArcs m = filter (\(mp, arcs) -> null arcs) (descendingArcsWithGraph m) -- Find the collapsed multipaths with no descending arcs case unsafeMultipaths of [] -> case graphsWithNoDescendingArcs possiblyNonTerminating of [] -> return $ Termination (map snd safeCollapsedMultipaths) nonDescending -> throwError $ InfiniteRecursion (head $ map fst nonDescending) unsafe -> throwError $ UnsafeMultipathError (head unsafe)
tdidriksen/copatterns
src/findus/TerminationChecker.hs
mit
30,030
148
26
9,367
10,186
5,286
4,900
491
18
-- | Tests some properties against Language.TaPL.TypedBoolean. module Language.TaPL.TypedBoolean.Tests where import Control.Applicative ((<$>)) import Test.QuickCheck (quickCheck) import Text.Printf (printf) import Language.TaPL.ShowPretty (showp) import Language.TaPL.TypedBoolean (Term, parseString, eval, eval', typeOf) -- | A test runner. main = mapM_ (\(s,a) -> printf "%-25s: " s >> a) tests -- | Both eval functions yield the same result. prop_evaluates_the_same :: Term -> Bool prop_evaluates_the_same t = eval t == eval' t -- | parse . showp is an identity function. prop_showp_parse_id :: Term -> Bool prop_showp_parse_id t = t == parseString (showp t) -- | eval . parse . showp evaluates the same as eval. prop_showp_parse_evaluates_the_same :: Term -> Bool prop_showp_parse_evaluates_the_same t = eval (parseString (showp t)) == eval t -- | eval' . parse . showp evaluates the same as eval'. prop_showp_parse_evaluates_the_same' :: Term -> Bool prop_showp_parse_evaluates_the_same' t = eval' (parseString (showp t)) == eval' t -- | typeOf before eval is the same after eval. prop_typeOf_eval :: Term -> Bool prop_typeOf_eval t = case eval t of Just t' -> typeOf t == typeOf t' Nothing -> True -- | typeOf before eval' is the same after eval'. prop_typeOf_eval' :: Term -> Bool prop_typeOf_eval' t = case eval' t of Just t' -> typeOf t == typeOf t' Nothing -> True -- | The resulting type of evaluating should be the same for both evaluators. prop_typeOf_eval_the_same :: Term -> Bool prop_typeOf_eval_the_same t = (typeOf <$> eval' t) == (typeOf <$> eval t) -- | List of tests and their names. tests = [("evaluates_the_same", quickCheck prop_evaluates_the_same) ,("showp_parse_id", quickCheck prop_showp_parse_id) ,("showp_parse_evaluates_the_same", quickCheck prop_showp_parse_evaluates_the_same) ,("showp_parse_evaluates_the_same'", quickCheck prop_showp_parse_evaluates_the_same') ,("prop_typeOf_eval", quickCheck prop_typeOf_eval) ,("prop_typeOf_eval'", quickCheck prop_typeOf_eval') ,("prop_typeOf_eval_the_same", quickCheck prop_typeOf_eval_the_same) ]
zeckalpha/TaPL
src/Language/TaPL/TypedBoolean/Tests.hs
mit
2,205
0
10
407
480
261
219
34
2
----------------------------------------------------------- ---- | ---- Module: SpaceAge ---- Description: Calculate age on a different planets of Solar system ---- Copyright: (c) 2015 Alex Dzyoba <[email protected]> ---- License: MIT ------------------------------------------------------------- module SpaceAge where data Planet = Mercury | Venus | Earth | Mars | Jupiter | Saturn | Uranus | Neptune ageOn :: Planet -> Double -> Double ageOn Earth seconds = seconds / 31557600 ageOn Mercury seconds = ageOn Earth seconds / 0.2408467 ageOn Venus seconds = ageOn Earth seconds / 0.61519726 ageOn Mars seconds = ageOn Earth seconds / 1.8808158 ageOn Jupiter seconds = ageOn Earth seconds / 11.862615 ageOn Saturn seconds = ageOn Earth seconds / 29.447498 ageOn Uranus seconds = ageOn Earth seconds / 84.016846 ageOn Neptune seconds = ageOn Earth seconds / 164.79132
dzeban/haskell-exercism
space-age/haskell/space-age/SpaceAge.hs
mit
880
0
6
137
199
105
94
11
1
{-| Module : Sivi.GCode.Base Description : GCode data structure Copyright : (c) Maxime ANDRE, 2015 License : GPL-2 Maintainer : [email protected] Stability : experimental Portability : POSIX -} module Sivi.GCode.Base ( GCode(..) , GCodeInstruction(..) , getGCode , g00 , g01 , g02 , g03 , gcomment , m00 , cline , g38d2 , g92 ) where import Data.Monoid() import Linear import Control.Monad.RWS import Sivi.Machine import Sivi.Backend import Sivi.Operation.Base import Sivi.Operation.Types import Sivi.Operation.Run import Sivi.Misc data GCodeInstruction = G00 { x :: Maybe Double, y :: Maybe Double, z :: Maybe Double } | G01 { x :: Maybe Double, y :: Maybe Double, z :: Maybe Double, f :: Maybe Double } | G02 { x :: Maybe Double, y :: Maybe Double, z :: Maybe Double, i :: Maybe Double, j :: Maybe Double, k :: Maybe Double, f :: Maybe Double } | G03 { x :: Maybe Double, y :: Maybe Double, z :: Maybe Double, i :: Maybe Double, j :: Maybe Double, k :: Maybe Double, f :: Maybe Double } | GComment { getComment :: String } | M00 | CLine { x :: Maybe Double, y :: Maybe Double, z :: Maybe Double, i :: Maybe Double, j :: Maybe Double, k :: Maybe Double, f :: Maybe Double } | G38d2 { x:: Maybe Double, y :: Maybe Double, z :: Maybe Double, f :: Maybe Double } | G92 { x:: Maybe Double, y :: Maybe Double, z :: Maybe Double } deriving Eq newtype GCode = GCode { getgCodeInstructions :: [GCodeInstruction] } deriving Eq -- | Shows a GCode word (with Maybe value) gword :: Char -> Maybe Double -> String gword w (Just v) = w : showDouble v gword _ Nothing = "" -- | Compiles parameters of a GCode command compileParams :: [Char] -- ^ List of parameter names -> [Maybe Double] -- ^ List of parameter values -> String -- ^ Compiled parameters compileParams pn pv = unwords . filter (/= "") $ zipWith gword pn pv instance Show GCodeInstruction where show (G00 mx my mz) = "G00 " ++ compileParams "XYZ" [mx, my, mz] show (G01 mx my mz mf) = "G01 " ++ compileParams "XYZF" [mx, my, mz, mf] show (G02 mx my mz mi mj mk mf) = "G02 " ++ compileParams "XYZIJKF" [mx, my, mz, mi, mj, mk, mf] show (G03 mx my mz mi mj mk mf) = "G03 " ++ compileParams "XYZIJKF" [mx, my, mz, mi, mj, mk, mf] show (GComment c) = "(" ++ c ++ ")" show M00 = "M00" show (CLine mx my mz mi mj mk mf) = compileParams "XYZIJKF" [mx, my, mz, mi, mj, mk, mf] show (G38d2 mx my mz mf) = "G38.2 " ++ compileParams "XYZF" [mx, my, mz, mf] show (G92 mx my mz) = "G92 " ++ compileParams "XYZ" [mx, my, mz] instance Show GCode where show (GCode l) = concatMap ((++"\n") . show) l instance Monoid GCode where mempty = GCode [] GCode xs `mappend` GCode ys = GCode $ xs ++ ys optim :: V3 Double -> V3 Double -> (Maybe Double, Maybe Double, Maybe Double) optim (V3 x y z) (V3 cx cy cz) = (f x cx, f y cy, f z cz) where f d c | d == c = Nothing | otherwise = Just d instance Backend GCode where bRapid dst = do cp <- getCurrentPosition let (mx, my, mz) = optim dst cp if cp == dst then noOp else tell $ GCode [G00 mx my mz] bSlow fr dst = do cp <- getCurrentPosition let (mx, my, mz) = optim dst cp if cp == dst then noOp else tell $ GCode [G01 mx my mz (Just fr)] -- fr is not optimized :( bFeed fr dst = do cp <- getCurrentPosition let (mx, my, mz) = optim dst cp if cp == dst then noOp else tell $ GCode [G01 mx my mz (Just fr)] -- fr is not optimized :( bArc fr dir center dst = do cp <- getCurrentPosition let (mx, my, mz) = optim dst cp let V3 i j k = center - cp let notZero v = if v /= 0 then Just v else Nothing case dir of CW -> tell $ GCode [G02 mx my mz (notZero i) (notZero j) (notZero k) (Just fr)] -- fr is not optimized :( CCW -> tell $ GCode [G03 mx my mz (notZero i) (notZero j) (notZero k) (Just fr)] -- fr is not optimized :( bPause = tell $ GCode [M00] bProbe pbr dst = do cp <- getCurrentPosition let (mx, my, mz) = optim dst cp if cp == dst then noOp else tell $ GCode [G38d2 mx my mz (Just pbr)] bDefCurPos p = do cp <- getCurrentPosition let (mx, my, mz) = optim p cp if cp == p then noOp else tell $ GCode [G92 mx my mz] bComment s = tell $ GCode [GComment s] -- | Returns the GCode generated from an operation. This is a GCode specific version of 'runOperation'. getGCode :: Machine m => CuttingParameters m -- Cutting parameters -> Operation m GCode () -- ^ op : Operation to tun -> GCode -- ^ Resulting GCode program getGCode = runOperation -- | Smart constructor for 'G00' g00 :: GCodeInstruction g00 = G00 Nothing Nothing Nothing -- | Smart constructor for 'G01' g01 :: GCodeInstruction g01 = G01 Nothing Nothing Nothing Nothing -- | Smart constructor for 'G02' g02 :: GCodeInstruction g02 = G02 Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- | Smart constructor for 'G03' g03 :: GCodeInstruction g03 = G03 Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- | Smart constructor for 'GComment' gcomment :: GCodeInstruction gcomment = GComment "" -- | Smart constructor for M00 m00 :: GCodeInstruction m00 = M00 -- | Smart constructor for 'CLine' cline :: GCodeInstruction cline = CLine Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- | Smart constructor for 'G38d2' g38d2 :: GCodeInstruction g38d2 = G38d2 Nothing Nothing Nothing Nothing -- | Smart constructor for 'G92' g92 :: GCodeInstruction g92 = G92 Nothing Nothing Nothing
iemxblog/sivi-haskell
src/Sivi/GCode/Base.hs
gpl-2.0
6,508
0
16
2,295
2,029
1,080
949
128
1
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="2.0"> <!-- title --> <title>Hilfe zum Modul zum EM-Algorithmus</title> <!-- maps --> <maps> <homeID>em</homeID> <mapref location="emMap.jhm"/> </maps> <!-- presentations --> <presentation default=true> <name>main window</name> <size width="920" height="450" /> <location x="150" y="150" /> <image>mainicon</image> <toolbar> <helpaction>javax.help.BackAction</helpaction> <helpaction>javax.help.ForwardAction</helpaction> <helpaction>javax.help.ReloadAction</helpaction> <helpaction>javax.help.SeparatorAction</helpaction> <helpaction image="Startseite">javax.help.HomeAction</helpaction> <helpaction>javax.help.SeparatorAction</helpaction> <helpaction>javax.help.PrintAction</helpaction> <helpaction>javax.help.PrintSetupAction</helpaction> </toolbar> </presentation> <!-- views --> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Inhaltsverzeichnis</label> <type>javax.help.TOCView</type> <data>emTOC.xml</data> </view> <view mergetype="javax.help.SortMerge"> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>emIndex.xml</data> </view> <view xml:lang="de"> <name>Search</name> <label>Suche</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> </helpset>
jurkov/j-algo-mod
res/module/em/help/jhelp/em_help.hs
gpl-2.0
1,628
124
90
216
651
325
326
-1
-1
module Main where data Term = Arg Integer | Abs Term | App Term Term instance Show Term where show (Arg n) = show n show (Abs t) = "λ. " ++ show t show (App t1 t2) = "(" ++ show t1 ++ " " ++ show t2 ++ ")" shift :: Integer -> Integer -> Term -> Term shift d c t = case t of arg@(Arg n) -> if n >= c then Arg (n + d) else arg Abs t -> Abs (shift d (c+1) t) App t1 t2 -> App (shift d c t1) (shift d c t2) subst :: Integer -> Term -> Term -> Term subst j s t = case t of arg@(Arg n) -> if n==j then s else arg Abs t -> subst (j+1) (shift 1 0 s) t App t1 t2 -> App (subst j s t1) (subst j s t2) eval :: Term -> Term -> Term eval t v = shift (-1) 0 (subst 0 (shift 1 0 v) t) isval :: Term -> Bool isval (Abs _) = True isval _ = False main = do let x = Arg 1 y = Arg 0 z = Arg 2 q = Abs (App x (App y z)) l = Abs q putStrLn . show $ l putStrLn . show $ shift 2 0 l
andbroby/444-untyped-lambda
src/Main.hs
gpl-2.0
961
2
15
329
553
277
276
31
4
-- Copyright 2017 Marcelo Garlet Millani -- This file is part of pictikz. -- pictikz is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- pictikz is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with pictikz. If not, see <http://www.gnu.org/licenses/>. module Pictikz.Parser where import Control.Monad.Trans.State import Control.Monad import Data.Char import Pictikz.Elements splitBy :: (Char -> Bool) -> String -> [String] splitBy _ [] = [] splitBy p xs = let (w, r) = span (not . p) (dropWhile p xs) in w : (splitBy p r) consumeWhile :: (Char -> Bool) -> State String String consumeWhile f = do str <- get let (x,r) = span f str put $ r return x whenNotEmpty e x = do s <- get if s == "" then return e else x readHexa xyz = let hexa = map digitToInt xyz in case hexa of (xh:xl:yh:yl:zh:zl:[]) -> ((xh*16 + xl), (yh*16 + yl), (zh*16 + zl)) (x:y:z:[]) -> ((x*17), (y*17), (z*17)) readColor ('#':color) = let (r,g,b) = readHexa color in RGB r g b
mgmillani/pictikz
src/Pictikz/Parser.hs
gpl-3.0
1,445
0
17
306
446
238
208
27
2
module FAunion ( unionTNFA ) where import Set import FiniteMap import Stuff import Options import TA import FAtypes import Ids import FAmap import FAcmpct import FAconv --------------------------------------------------------------------- unionTNFA :: Opts -> TNFA Int -> TNFA Int -> TNFA Int unionTNFA opts x1 x2 = let TNFA cons1 all1 starts1 moves1 = x1 n1 = maximum (0 : (setToList all1)) + 1 TNFA cons2 all2 starts2 moves2 = mapTNFA opts (n1 + ) x2 -- added 17-sep-98 -- this was sitting here for half a year at least. -- find out why it is wrong! -- top = maximum (0 : (setToList all2)) + 1 -- and why this is better: top = maximum (n1 : (setToList all2)) + 1 cons = cons1 `unionSet` cons2 y = ETNFA cons ((all1 `unionSet` all2) `unionSet` unitSet top) (unitSet top) (plusFM_C (error "unionTNFA") moves1 moves2) (unitFM top (starts1 `unionSet` starts2)) e = etnfa2tnfa opts y f = cmpctTNFA opts e in -- trace ("\nunionTNFA.x1 = " ++ show x1) $ -- trace ("\nunionTNFA.x2 = " ++ show x2) $ -- trace ("\nunionTNFA.n1 = " ++ show n1) $ -- trace ("\nunionTNFA.top = " ++ show top) $ -- trace ("\nunionTNFA.cons = " ++ show cons) $ -- trace ("\nunionTNFA.y = " ++ show y) $ -- trace ("\nunionTNFA.e = " ++ show e) $ trinfo opts "union" f $ f -------------------------------------------------------------------------
jwaldmann/rx
src/FAunion.hs
gpl-3.0
1,372
34
13
284
316
178
138
29
1
{-# OPTIONS_GHC -Wall #-} import Distribution.Simple import Distribution.Simple.LocalBuildInfo import Distribution.Simple.Setup import Distribution.PackageDescription import System.Process import System.Exit import Control.Exception import Data.List import Data.Either import Data.Char import Data.Time.Clock import qualified Data.Time.Format as DTF import Data.Time.LocalTime import System.Directory import System.FilePath import System.IO import qualified System.Locale as SL import qualified Data.ByteString.Lazy.Char8 as BS import qualified Codec.Compression.GZip as GZip main :: IO () main = defaultMainWithHooks (simpleUserHooks { buildHook = generateBuildInfoHook } ) -- Before each build, generate a BuildInfo_Generated module that exports the project version from cabal, -- the current revision number and the build time. -- -- Note that in order for this Setup.hs to be used by cabal, the build-type should be Custom. generateBuildInfoHook :: PackageDescription -> LocalBuildInfo -> UserHooks -> BuildFlags -> IO () generateBuildInfoHook pd lbi uh bf = do { let cabalVersionStr = intercalate "." (map show . versionBranch . pkgVersion . package $ pd) ; gitInfoStr <- getGitInfoStr ; clockTime <- getCurrentTime >>= utcToLocalZonedTime ; let buildTimeStr = DTF.formatTime SL.defaultTimeLocale "%d-%b-%y %H:%M:%S %Z" clockTime ; writeFile (pathFromModuleName buildInfoModuleName) $ buildInfoModule cabalVersionStr gitInfoStr buildTimeStr ; generateStaticFileModule ; putStrLn "" ; (buildHook simpleUserHooks) pd lbi uh bf -- start the build } buildInfoModuleName :: String buildInfoModuleName = "Database.Design.Ampersand.Basics.BuildInfo_Generated" buildInfoModule :: String -> String -> String -> String buildInfoModule cabalVersion gitInfo time = unlines [ "module "++buildInfoModuleName++"(cabalVersionStr, gitInfoStr, buildTimeStr) where" , "" , "-- This module is generated automatically by Setup.hs before building. Do not edit!" , "" -- Workaround: break pragma start { - #, since it upsets Eclipse :-( , "{-"++"# NOINLINE cabalVersionStr #-}" -- disable inlining to prevent recompilation of dependent modules on each build , "cabalVersionStr :: String" , "cabalVersionStr = \"" ++ cabalVersion ++ "\"" , "" , "{-"++"# NOINLINE gitInfoStr #-}" , "gitInfoStr :: String" , "gitInfoStr = \"" ++ gitInfo ++ "\"" , "" , "{-"++"# NOINLINE buildTimeStr #-}" , "buildTimeStr :: String" , "buildTimeStr = \"" ++ time ++ "\"" , "" ] getGitInfoStr :: IO String getGitInfoStr = do { eSHA <- readProcessEither "git" ["rev-parse", "--short", "HEAD"] "" ; eBranch <- readProcessEither "git" ["rev-parse", "--abbrev-ref", "HEAD"] "" ; (exitCode, _, _) <- readProcessWithExitCode "git" ["diff", "--quiet"] "" ; let isDirty = exitCode /= ExitSuccess -- exit code signals whether branch is dirty ; case (eSHA, eBranch) of (Right sha, Right branch) -> return $ strip branch ++ ":" ++ strip sha ++ (if isDirty then "*" else "") _ -> do { mapM_ print $ lefts [eSHA, eBranch] -- errors during git execution ; warnNoCommitInfo } } `catch` \err -> -- git failed to execute do { print (err :: IOException) ; warnNoCommitInfo } where strip str = reverse . dropWhile isSpace . reverse $ str readProcessEither :: String -> [String] -> String -> IO (Either String String) readProcessEither cmd args stdinStr = do { (exitCode,stdoutStr,stderrStr) <- readProcessWithExitCode cmd args stdinStr ; case exitCode of ExitSuccess -> return $ Right stdoutStr ExitFailure _ -> return $ Left stderrStr } warnNoCommitInfo :: IO String warnNoCommitInfo = do { putStrLn "\n\n\nWARNING: Execution of 'git' command failed." ; putStrLn $ "BuildInfo_Generated.hs will not contain revision information, and therefore\nneither will fatal error messages.\n"++ "Please check your installation\n" ; return "no git info" } {- For each file in the directory ampersand/static, we generate a StaticFile value, which contains the information necessary for Ampersand to create the file at run-time. To prevent compiling the generated module (which can get rather big) on each build, we compare the contents the file we are about to generate with the contents of the already generated file and only write if there is a difference. This complicates the build process, but seems the only way to handle large amounts of diverse static files, until Cabal's data-files mechanism is updated to allow fully recursive patterns. TODO: creating the entire file may be somewhat time-consuming, if this is a problem on slower machines, we may want to cache the timestamps+names in a file and only generate when there is a change. (using the timestamps from the previously generated module file is not an option, as a Haskell read on that file is extremely slow) -} staticFileModuleName :: String staticFileModuleName = "Database.Design.Ampersand.Prototype.StaticFiles_Generated" generateStaticFileModule :: IO () generateStaticFileModule = do { previousModuleContents <- getPreviousStaticFileModuleContents sfModulePath ; currentModuleContents <- readAllStaticFiles -- simply compare file contents to see if we need to write (to prevent re-compilation) ; if previousModuleContents == currentModuleContents then putStrLn $ "Static files unchanged, no need to update "++sfModulePath else do { putStrLn $ "Static files have changed, updating "++sfModulePath ; writeFile sfModulePath currentModuleContents } } where sfModulePath = pathFromModuleName staticFileModuleName getPreviousStaticFileModuleContents :: String -> IO String getPreviousStaticFileModuleContents sfModulePath = (withFile sfModulePath ReadMode $ \h -> do { str <- hGetContents h --; putStrLn $ "reading old file" ; length str `seq` return () -- lazy IO is :-( --; putStrLn $ "Done" ; return str }) `catch` \err -> -- old generated module exists, but we can't read the file or read the contents do { putStrLn $ "\n\n\nWarning: Cannot read previously generated " ++ sfModulePath ++ ":\n" ++ show (err :: SomeException) ++ "\nThis warning should disappear the next time you build Ampersand. If the error persists, please report this as a bug.\n" ; return [] } -- Collect all files required to be inside the ampersand.exe readAllStaticFiles :: IO String readAllStaticFiles = do { zwolleFrontEndFiles <- readStaticFiles ZwolleFrontEnd "static/zwolle" "." -- files that define the Zwolle Frontend ; pandocTemplatesFiles <- readStaticFiles PandocTemplates "outputTemplates" "." -- templates for several PANDOC output types ; formalAmpersandFiles <- readStaticFiles FormalAmpersand "AmpersandData/FormalAmpersand" "." --meta information about Ampersand ; return $ mkStaticFileModule $ zwolleFrontEndFiles ++ pandocTemplatesFiles ++ formalAmpersandFiles } readStaticFiles :: FileKind -> FilePath -> FilePath -> IO [String] readStaticFiles fkind base fileOrDirPth = do { let path = combine base fileOrDirPth ; isDir <- doesDirectoryExist path ; if isDir then do { fOrDs <- getProperDirectoryContents path ; fmap concat $ mapM (\fOrD -> readStaticFiles fkind base (combine fileOrDirPth fOrD)) fOrDs } else do { timeStamp <- getModificationTime path ; fileContents <- BS.readFile path ; return [ "SF "++show fkind++" "++show fileOrDirPth++" "++utcToEpochTime timeStamp ++ " {-"++show timeStamp++" -} (BS.unpack$ GZip.decompress "++show (GZip.compress fileContents)++")" ] } } where utcToEpochTime :: UTCTime -> String utcToEpochTime utcTime = DTF.formatTime SL.defaultTimeLocale "%s" utcTime data FileKind = ZwolleFrontEnd | PandocTemplates | FormalAmpersand deriving (Show, Eq) mkStaticFileModule :: [String] -> String mkStaticFileModule sfDeclStrs = unlines staticFileModuleHeader ++ " [ " ++ intercalate "\n , " sfDeclStrs ++ "\n" ++ " ]\n" staticFileModuleHeader :: [String] staticFileModuleHeader = [ "{-# LANGUAGE OverloadedStrings #-}" , "module "++staticFileModuleName++" where" , "import qualified Data.ByteString.Lazy.Char8 as BS" , "import qualified Codec.Compression.GZip as GZip" , "" , "data FileKind = ZwolleFrontEnd | PandocTemplates | FormalAmpersand deriving (Show, Eq)" , "data StaticFile = SF { fileKind :: FileKind" , " , filePath :: FilePath -- relative path, including extension" , " , timeStamp :: Integer -- unix epoch time" , " , contentString :: String" , " }" , "" , "getStaticFileContent :: FileKind -> FilePath -> Maybe String" , "getStaticFileContent fk fp =" , " case filter isRightFile allStaticFiles of" , " [x] -> Just (contentString x)" , " _ -> Nothing" , " where" , " isRightFile :: StaticFile -> Bool" , " isRightFile (SF fKind path _ _ ) = fKind == fk && path == \".\\\\\"++fp" , "" , "{-"++"# NOINLINE allStaticFiles #-}" -- Workaround: break pragma start { - #, since it upsets Eclipse :-( , "allStaticFiles :: [StaticFile]" , "allStaticFiles =" ] getProperDirectoryContents :: FilePath -> IO [String] getProperDirectoryContents pth = fmap (filter (`notElem` [".","..",".svn"])) $ getDirectoryContents pth pathFromModuleName :: String -> String pathFromModuleName m = "src/" ++ [if c == '.' then '/' else c | c <- m] ++ ".hs"
guoy34/ampersand
Setup.hs
gpl-3.0
9,915
6
22
2,228
1,703
921
782
157
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Vision.Images.Annotate -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Run image detection and annotation for a batch of images. -- -- /See:/ <https://cloud.google.com/vision/ Google Cloud Vision API Reference> for @vision.images.annotate@. module Network.Google.Resource.Vision.Images.Annotate ( -- * REST Resource ImagesAnnotateResource -- * Creating a Request , imagesAnnotate , ImagesAnnotate -- * Request Lenses , iaXgafv , iaUploadProtocol , iaPp , iaAccessToken , iaUploadType , iaPayload , iaBearerToken , iaCallback ) where import Network.Google.Prelude import Network.Google.Vision.Types -- | A resource alias for @vision.images.annotate@ method which the -- 'ImagesAnnotate' request conforms to. type ImagesAnnotateResource = "v1" :> "images:annotate" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "pp" Bool :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "bearer_token" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BatchAnnotateImagesRequest :> Post '[JSON] BatchAnnotateImagesResponse -- | Run image detection and annotation for a batch of images. -- -- /See:/ 'imagesAnnotate' smart constructor. data ImagesAnnotate = ImagesAnnotate' { _iaXgafv :: !(Maybe Xgafv) , _iaUploadProtocol :: !(Maybe Text) , _iaPp :: !Bool , _iaAccessToken :: !(Maybe Text) , _iaUploadType :: !(Maybe Text) , _iaPayload :: !BatchAnnotateImagesRequest , _iaBearerToken :: !(Maybe Text) , _iaCallback :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'ImagesAnnotate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'iaXgafv' -- -- * 'iaUploadProtocol' -- -- * 'iaPp' -- -- * 'iaAccessToken' -- -- * 'iaUploadType' -- -- * 'iaPayload' -- -- * 'iaBearerToken' -- -- * 'iaCallback' imagesAnnotate :: BatchAnnotateImagesRequest -- ^ 'iaPayload' -> ImagesAnnotate imagesAnnotate pIaPayload_ = ImagesAnnotate' { _iaXgafv = Nothing , _iaUploadProtocol = Nothing , _iaPp = True , _iaAccessToken = Nothing , _iaUploadType = Nothing , _iaPayload = pIaPayload_ , _iaBearerToken = Nothing , _iaCallback = Nothing } -- | V1 error format. iaXgafv :: Lens' ImagesAnnotate (Maybe Xgafv) iaXgafv = lens _iaXgafv (\ s a -> s{_iaXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). iaUploadProtocol :: Lens' ImagesAnnotate (Maybe Text) iaUploadProtocol = lens _iaUploadProtocol (\ s a -> s{_iaUploadProtocol = a}) -- | Pretty-print response. iaPp :: Lens' ImagesAnnotate Bool iaPp = lens _iaPp (\ s a -> s{_iaPp = a}) -- | OAuth access token. iaAccessToken :: Lens' ImagesAnnotate (Maybe Text) iaAccessToken = lens _iaAccessToken (\ s a -> s{_iaAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). iaUploadType :: Lens' ImagesAnnotate (Maybe Text) iaUploadType = lens _iaUploadType (\ s a -> s{_iaUploadType = a}) -- | Multipart request metadata. iaPayload :: Lens' ImagesAnnotate BatchAnnotateImagesRequest iaPayload = lens _iaPayload (\ s a -> s{_iaPayload = a}) -- | OAuth bearer token. iaBearerToken :: Lens' ImagesAnnotate (Maybe Text) iaBearerToken = lens _iaBearerToken (\ s a -> s{_iaBearerToken = a}) -- | JSONP iaCallback :: Lens' ImagesAnnotate (Maybe Text) iaCallback = lens _iaCallback (\ s a -> s{_iaCallback = a}) instance GoogleRequest ImagesAnnotate where type Rs ImagesAnnotate = BatchAnnotateImagesResponse type Scopes ImagesAnnotate = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ImagesAnnotate'{..} = go _iaXgafv _iaUploadProtocol (Just _iaPp) _iaAccessToken _iaUploadType _iaBearerToken _iaCallback (Just AltJSON) _iaPayload visionService where go = buildClient (Proxy :: Proxy ImagesAnnotateResource) mempty
rueshyna/gogol
gogol-vision/gen/Network/Google/Resource/Vision/Images/Annotate.hs
mpl-2.0
5,149
0
18
1,302
857
497
360
120
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Labels.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new label. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.labels.create@. module Network.Google.Resource.Gmail.Users.Labels.Create ( -- * REST Resource UsersLabelsCreateResource -- * Creating a Request , usersLabelsCreate , UsersLabelsCreate -- * Request Lenses , ulcPayload , ulcUserId ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.labels.create@ method which the -- 'UsersLabelsCreate' request conforms to. type UsersLabelsCreateResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "labels" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Label :> Post '[JSON] Label -- | Creates a new label. -- -- /See:/ 'usersLabelsCreate' smart constructor. data UsersLabelsCreate = UsersLabelsCreate' { _ulcPayload :: !Label , _ulcUserId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersLabelsCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ulcPayload' -- -- * 'ulcUserId' usersLabelsCreate :: Label -- ^ 'ulcPayload' -> UsersLabelsCreate usersLabelsCreate pUlcPayload_ = UsersLabelsCreate' { _ulcPayload = pUlcPayload_ , _ulcUserId = "me" } -- | Multipart request metadata. ulcPayload :: Lens' UsersLabelsCreate Label ulcPayload = lens _ulcPayload (\ s a -> s{_ulcPayload = a}) -- | The user\'s email address. The special value me can be used to indicate -- the authenticated user. ulcUserId :: Lens' UsersLabelsCreate Text ulcUserId = lens _ulcUserId (\ s a -> s{_ulcUserId = a}) instance GoogleRequest UsersLabelsCreate where type Rs UsersLabelsCreate = Label type Scopes UsersLabelsCreate = '["https://mail.google.com/", "https://www.googleapis.com/auth/gmail.labels", "https://www.googleapis.com/auth/gmail.modify"] requestClient UsersLabelsCreate'{..} = go _ulcUserId (Just AltJSON) _ulcPayload gmailService where go = buildClient (Proxy :: Proxy UsersLabelsCreateResource) mempty
rueshyna/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Labels/Create.hs
mpl-2.0
3,163
0
14
755
387
234
153
63
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.BinaryAuthorization.Projects.Policy.SetIAMPolicy -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ <https://cloud.google.com/binary-authorization/ Binary Authorization API Reference> for @binaryauthorization.projects.policy.setIamPolicy@. module Network.Google.Resource.BinaryAuthorization.Projects.Policy.SetIAMPolicy ( -- * REST Resource ProjectsPolicySetIAMPolicyResource -- * Creating a Request , projectsPolicySetIAMPolicy , ProjectsPolicySetIAMPolicy -- * Request Lenses , ppsipXgafv , ppsipUploadProtocol , ppsipAccessToken , ppsipUploadType , ppsipPayload , ppsipResource , ppsipCallback ) where import Network.Google.BinaryAuthorization.Types import Network.Google.Prelude -- | A resource alias for @binaryauthorization.projects.policy.setIamPolicy@ method which the -- 'ProjectsPolicySetIAMPolicy' request conforms to. type ProjectsPolicySetIAMPolicyResource = "v1" :> CaptureMode "resource" "setIamPolicy" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SetIAMPolicyRequest :> Post '[JSON] IAMPolicy -- | Sets the access control policy on the specified resource. Replaces any -- existing policy. Can return \`NOT_FOUND\`, \`INVALID_ARGUMENT\`, and -- \`PERMISSION_DENIED\` errors. -- -- /See:/ 'projectsPolicySetIAMPolicy' smart constructor. data ProjectsPolicySetIAMPolicy = ProjectsPolicySetIAMPolicy' { _ppsipXgafv :: !(Maybe Xgafv) , _ppsipUploadProtocol :: !(Maybe Text) , _ppsipAccessToken :: !(Maybe Text) , _ppsipUploadType :: !(Maybe Text) , _ppsipPayload :: !SetIAMPolicyRequest , _ppsipResource :: !Text , _ppsipCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsPolicySetIAMPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ppsipXgafv' -- -- * 'ppsipUploadProtocol' -- -- * 'ppsipAccessToken' -- -- * 'ppsipUploadType' -- -- * 'ppsipPayload' -- -- * 'ppsipResource' -- -- * 'ppsipCallback' projectsPolicySetIAMPolicy :: SetIAMPolicyRequest -- ^ 'ppsipPayload' -> Text -- ^ 'ppsipResource' -> ProjectsPolicySetIAMPolicy projectsPolicySetIAMPolicy pPpsipPayload_ pPpsipResource_ = ProjectsPolicySetIAMPolicy' { _ppsipXgafv = Nothing , _ppsipUploadProtocol = Nothing , _ppsipAccessToken = Nothing , _ppsipUploadType = Nothing , _ppsipPayload = pPpsipPayload_ , _ppsipResource = pPpsipResource_ , _ppsipCallback = Nothing } -- | V1 error format. ppsipXgafv :: Lens' ProjectsPolicySetIAMPolicy (Maybe Xgafv) ppsipXgafv = lens _ppsipXgafv (\ s a -> s{_ppsipXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ppsipUploadProtocol :: Lens' ProjectsPolicySetIAMPolicy (Maybe Text) ppsipUploadProtocol = lens _ppsipUploadProtocol (\ s a -> s{_ppsipUploadProtocol = a}) -- | OAuth access token. ppsipAccessToken :: Lens' ProjectsPolicySetIAMPolicy (Maybe Text) ppsipAccessToken = lens _ppsipAccessToken (\ s a -> s{_ppsipAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ppsipUploadType :: Lens' ProjectsPolicySetIAMPolicy (Maybe Text) ppsipUploadType = lens _ppsipUploadType (\ s a -> s{_ppsipUploadType = a}) -- | Multipart request metadata. ppsipPayload :: Lens' ProjectsPolicySetIAMPolicy SetIAMPolicyRequest ppsipPayload = lens _ppsipPayload (\ s a -> s{_ppsipPayload = a}) -- | REQUIRED: The resource for which the policy is being specified. See the -- operation documentation for the appropriate value for this field. ppsipResource :: Lens' ProjectsPolicySetIAMPolicy Text ppsipResource = lens _ppsipResource (\ s a -> s{_ppsipResource = a}) -- | JSONP ppsipCallback :: Lens' ProjectsPolicySetIAMPolicy (Maybe Text) ppsipCallback = lens _ppsipCallback (\ s a -> s{_ppsipCallback = a}) instance GoogleRequest ProjectsPolicySetIAMPolicy where type Rs ProjectsPolicySetIAMPolicy = IAMPolicy type Scopes ProjectsPolicySetIAMPolicy = '["https://www.googleapis.com/auth/cloud-platform"] requestClient ProjectsPolicySetIAMPolicy'{..} = go _ppsipResource _ppsipXgafv _ppsipUploadProtocol _ppsipAccessToken _ppsipUploadType _ppsipCallback (Just AltJSON) _ppsipPayload binaryAuthorizationService where go = buildClient (Proxy :: Proxy ProjectsPolicySetIAMPolicyResource) mempty
brendanhay/gogol
gogol-binaryauthorization/gen/Network/Google/Resource/BinaryAuthorization/Projects/Policy/SetIAMPolicy.hs
mpl-2.0
5,805
0
16
1,221
782
458
324
116
1
module Data.Map.Debug where import Data.Map (Map) import qualified Data.Map as Map (!) :: (Show k,Ord k) => Map k a -> k -> a (!) mp key = case Map.lookup key mp of Nothing -> error $ "Key "++show key++" not found in map "++show (Map.keys mp) Just r -> r
hguenther/nbis
Data/Map/Debug.hs
agpl-3.0
261
0
12
57
128
69
59
7
2
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-} {- Copyright 2018 The CodeWorld Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Blockly.Generator ( Workspace ) where import GHCJS.Types newtype Workspace = Workspace JSVal
tgdavies/codeworld
funblocks-client/src/Blockly/Generator.hs
apache-2.0
774
0
5
140
26
17
9
4
0
{- - Copyright (c) 2017 The Agile Monkeys S.L. <[email protected]> - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -} module HaskellDo.Toolbar.View where import Prelude hiding (div, id) import GHCJS.HPlay.View hiding (addHeader, atr, id, wlink) import AxiomUtils import qualified Ulmus import qualified HaskellDo.Toolbar.FileSystemTree as FileSystemTree import Control.Monad.IO.Class import HaskellDo.Toolbar.Types import Foreign.JQuery toolbar :: Widget () toolbar = rawHtml $ do div ! atr "class" "fixed-action-btn horizontal" $ do a ! atr "class" "btn-floating btn-large purple" $ i ! atr "class" "material-icons" $ ("menu" :: String) ul $ do li ! id "openProjectButton" $ noHtml li ! id "compileButton" $ noHtml li ! id "packageEditorButton" $ noHtml li ! id "toggleEditorButton" $ noHtml li ! id "toggleErrorButton" $ noHtml packageEditorModal -- Apparently, if we put this line openProjectModal -- under this one. The open project modal doesn't work modalPromptPlaceholder "newDirectoryModal" "New Directory" "Choose a name for the new directory" openProjectModal :: Perch openProjectModal = div ! id "openProjectModal" ! atr "class" "modal modal-fixed-footer" $ do div ! atr "class" "modal-content" $ do h4 ("Open project" :: String) div $ do b ("Path to Stack project" :: String) div ! id "pathInput" $ noHtml p ! atr "class" "grey-text lighten-4" $ ("Path must be absolute, without ~ or environment variables." :: String) div ! id "creationDisplay" $ noHtml ul ! atr "class" "fs-tree collection" $ do div ! atr "class" "collection-item row" $ li ! id "fsTree-tools" $ noHtml div ! id "fsTree" $ noHtml div ! atr "class" "modal-footer" $ div ! id "closeModalButton" $ noHtml modalPromptPlaceholder :: String -> String -> String -> Perch modalPromptPlaceholder id' htitle text = div ! id id' ! atr "class" "modal" $ do div ! atr "class" "modal-content" $ do if (not . null) htitle then h4 htitle else noHtml div $ do if (not . null) text then label text else noHtml div ! atr "class" "input-container" $ noHtml div ! atr "class" "modal-footer" $ div ! id (id' ++ "closeButton") $ noHtml modalPrompt :: String -> (String -> Action) -> Action -> State -> Widget Action modalPrompt id' inputAction buttonAction _ = inputWidget <|> closeButtonWidget where inputWidget = Ulmus.newWidget (id' ++ " .input-container") $ do _ <- getString Nothing `fire` OnKeyUp projPath <- liftIO $ getValueFromId ("#" ++ id' ++ " event input") return (inputAction projPath) closeButtonWidget = Ulmus.newWidget (id' ++ "closeButton") $ wlink buttonAction $ a ! atr "class" "modal-action modal-close waves-effect btn-flat waves-purple" $ i ! atr "class" "material-icons" $ ("input" :: String) packageEditorModal :: Perch packageEditorModal = div ! id "packageEditorModal" ! atr "class" "modal bottom-sheet" $ do div ! atr "class" "modal-content" $ do h4 ("Project settings" :: String) div $ div ! id "packageTextArea" $ noHtml div ! atr "class" "modal-footer" $ do p ! atr "class" "red-text" $ ("Dependencies will be downloaded after confirming" :: String) div ! id "cancelPackageEditorButton" $ noHtml div ! id "closePackageEditorButton" $ noHtml openProjectButton :: State -> Widget Action openProjectButton _ = Ulmus.newWidget "openProjectButton" $ wlink OpenProject $ a ! atr "class" "btn-floating purple darken-2 tooltipped" ! atr "data-position" "bottom" ! atr "data-tooltip" "New/Open" ! atr "data-delay" "50" $ i ! atr "class" "material-icons" $ ("folder_open" :: String) packageEditorButton :: State -> Widget Action packageEditorButton _ = Ulmus.newWidget "packageEditorButton" $ wlink LoadPackageYaml $ a ! atr "class" "btn-floating purple darken-2 tooltipped" ! atr "data-position" "bottom" ! atr "data-tooltip" "Project settings" ! atr "data-delay" "50"$ i ! atr "class" "material-icons" $ ("build" :: String) compileButton :: State -> Widget Action compileButton _ = Ulmus.newWidget "compileButton" $ wlink Compile $ a ! atr "class" "btn-floating purple darken-2 tooltipped" ! atr "data-position" "bottom" ! atr "data-tooltip" "Compile [Ctrl+Return]" ! atr "data-delay" "50"$ i ! atr "class" "material-icons" $ ("play_arrow" :: String) toggleEditorButton :: State -> Widget Action toggleEditorButton _ = Ulmus.newWidget "toggleEditorButton" $ wlink ToggleEditor $ a ! atr "class" "btn-floating purple darken-2 tooltipped" ! atr "data-position" "bottom" ! atr "data-tooltip" "Toggle editor" ! atr "data-delay" "50"$ i ! atr "class" "material-icons" $ ("remove_red_eye" :: String) toggleErrorButton :: State -> Widget Action toggleErrorButton _ = Ulmus.newWidget "toggleErrorButton" $ wlink ToggleError $ a ! atr "class" "btn-floating purple darken-2 tooltipped" ! atr "data-position" "bottom" ! atr "data-tooltip" "Toggle error" ! atr "data-delay" "50"$ i ! atr "class" "material-icons" $ ("error" :: String) closeModalButton :: State -> Widget Action closeModalButton _ = Ulmus.newWidget "closeModalButton" $ wlink LoadProject $ a ! atr "class" "modal-action modal-close waves-effect btn-flat waves-purple" $ i ! atr "class" "material-icons" $ ("input" :: String) closePackageEditorButton :: State -> Widget Action closePackageEditorButton _ = Ulmus.newWidget "closePackageEditorButton" $ wlink SavePackage $ a ! atr "class" "modal-action modal-close waves-effect btn-flat waves-purple" $ i ! atr "class" "material-icons" $ ("playlist_add_check" :: String) cancelPackageEditorButton :: State -> Widget Action cancelPackageEditorButton _ = Ulmus.newWidget "cancelPackageEditorButton" $ wlink ClosePackageModal $ a ! atr "class" "modal-action modal-close waves-effect btn-flat waves-purple" $ i ! atr "class" "material-icons" $ ("clear" :: String) pathInput :: State -> Widget Action pathInput state = Ulmus.newWidget "pathInput" $ do let pr = if lastProject state == "" then Nothing else Just $ lastProject state _ <- getString pr ! atr "placeholder" "/path/to/your/project" `fire` OnKeyUp projPath <- liftIO $ getValueFromId "#pathInput event input" return $ NewPath projPath packageTextArea :: State -> Widget Action packageTextArea _ = Ulmus.newWidget "packageTextArea" $ do _ <- getMultilineText "" ! atr "rows" "20" `fire` OnKeyUp newConfig <- liftIO $ getValueFromId "#packageTextArea event textarea" return $ NewPackage newConfig creationDisplay :: State -> Widget () creationDisplay _ = Ulmus.newWidget "creationDisplay" $ rawHtml $ p ! atr "class" "red-text" $ ("" :: String) updateDisplays :: State -> Widget Action updateDisplays = FileSystemTree.widget
theam/haskell-do
src/common/HaskellDo/Toolbar/View.hs
apache-2.0
7,716
0
21
1,770
1,887
911
976
123
3
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : Opengl.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:30 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.ClassTypes.Opengl ( QGL, TQGL, CQGL, qCast_QGL, QGLSc, TQGLSc, CQGLSc, qCastList_QGL, withQGLResult ,QGLFormat, TQGLFormat, CQGLFormat, qCast_QGLFormat, QGLFormatSc, TQGLFormatSc, CQGLFormatSc, qCastList_QGLFormat, withQGLFormatResult, qGLFormatAddFinalizer ,QGLColormap, TQGLColormap, CQGLColormap, qCast_QGLColormap, QGLColormapSc, TQGLColormapSc, CQGLColormapSc, qCastList_QGLColormap, withQGLColormapResult, qGLColormapAddFinalizer ,QGLContext, TQGLContext, CQGLContext, qCast_QGLContext, QGLContextSc, TQGLContextSc, CQGLContextSc, qCastList_QGLContext, withQGLContextResult, qGLContextAddFinalizer, qGLContextAddFinalizer1 ,QGLFramebufferObject, TQGLFramebufferObject, CQGLFramebufferObject, qCast_QGLFramebufferObject, QGLFramebufferObjectSc, TQGLFramebufferObjectSc, CQGLFramebufferObjectSc, qCastList_QGLFramebufferObject, withQGLFramebufferObjectResult, qGLFramebufferObjectAddFinalizer, qGLFramebufferObjectAddFinalizer1 ,QGLPixelBuffer, TQGLPixelBuffer, CQGLPixelBuffer, qCast_QGLPixelBuffer, QGLPixelBufferSc, TQGLPixelBufferSc, CQGLPixelBufferSc, qCastList_QGLPixelBuffer, withQGLPixelBufferResult, qGLPixelBufferAddFinalizer, qGLPixelBufferAddFinalizer1 ,QGLWidget, TQGLWidget, CQGLWidget, qCast_QGLWidget, QGLWidgetSc, TQGLWidgetSc, CQGLWidgetSc, qCastList_QGLWidget, withQGLWidgetResult, qGLWidgetFromPtr, withQListQGLWidgetResult, qGLWidgetListFromPtrList ) where import Foreign.C.Types import Qtc.Classes.Types import Qtc.ClassTypes.Core import Qtc.ClassTypes.Gui type QGL a = Object (CQGL a) type TQGL a = CQGL a data CQGL a = CQGL type QGLSc a = QGL (CQGLSc a) type TQGLSc a = TQGL (CQGLSc a) data CQGLSc a = CQGLSc qCast_QGL :: Object a -> IO (QGL ()) qCast_QGL _qobj = return (objectCast _qobj) withQGLResult :: IO (Ptr (TQGL a)) -> IO (QGL a) withQGLResult f = withObjectRefResult f class QqCastList_QGL a r where qcl_QGL :: [QGL ()] -> a -> r instance QqCastList_QGL (QGL ()) [QGL ()] where qcl_QGL l x = reverse $ x:l instance QqCastList_QGL a r => QqCastList_QGL (QGL ()) (a -> r) where qcl_QGL l x sx = qcl_QGL (x:l) sx qCastList_QGL x = qcl_QGL [] x type QGLFormat a = Object (CQGLFormat a) type TQGLFormat a = CQGLFormat a data CQGLFormat a = CQGLFormat type QGLFormatSc a = QGLFormat (CQGLFormatSc a) type TQGLFormatSc a = TQGLFormat (CQGLFormatSc a) data CQGLFormatSc a = CQGLFormatSc qCast_QGLFormat :: Object a -> IO (QGLFormat ()) qCast_QGLFormat _qobj = return (objectCast _qobj) withQGLFormatResult :: IO (Ptr (TQGLFormat a)) -> IO (QGLFormat a) withQGLFormatResult f = withObjectResult qtc_QGLFormat_getFinalizer f foreign import ccall qtc_QGLFormat_getFinalizer :: FunPtr (Ptr (TQGLFormat a) -> IO ()) qGLFormatAddFinalizer :: QGLFormat a -> IO () qGLFormatAddFinalizer (Object fp) = addForeignPtrFinalizer qtc_QGLFormat_getFinalizer fp class QqCastList_QGLFormat a r where qcl_QGLFormat :: [QGLFormat ()] -> a -> r instance QqCastList_QGLFormat (QGLFormat ()) [QGLFormat ()] where qcl_QGLFormat l x = reverse $ x:l instance QqCastList_QGLFormat a r => QqCastList_QGLFormat (QGLFormat ()) (a -> r) where qcl_QGLFormat l x sx = qcl_QGLFormat (x:l) sx qCastList_QGLFormat x = qcl_QGLFormat [] x type QGLColormap a = Object (CQGLColormap a) type TQGLColormap a = CQGLColormap a data CQGLColormap a = CQGLColormap type QGLColormapSc a = QGLColormap (CQGLColormapSc a) type TQGLColormapSc a = TQGLColormap (CQGLColormapSc a) data CQGLColormapSc a = CQGLColormapSc qCast_QGLColormap :: Object a -> IO (QGLColormap ()) qCast_QGLColormap _qobj = return (objectCast _qobj) withQGLColormapResult :: IO (Ptr (TQGLColormap a)) -> IO (QGLColormap a) withQGLColormapResult f = withObjectResult qtc_QGLColormap_getFinalizer f foreign import ccall qtc_QGLColormap_getFinalizer :: FunPtr (Ptr (TQGLColormap a) -> IO ()) qGLColormapAddFinalizer :: QGLColormap a -> IO () qGLColormapAddFinalizer (Object fp) = addForeignPtrFinalizer qtc_QGLColormap_getFinalizer fp class QqCastList_QGLColormap a r where qcl_QGLColormap :: [QGLColormap ()] -> a -> r instance QqCastList_QGLColormap (QGLColormap ()) [QGLColormap ()] where qcl_QGLColormap l x = reverse $ x:l instance QqCastList_QGLColormap a r => QqCastList_QGLColormap (QGLColormap ()) (a -> r) where qcl_QGLColormap l x sx = qcl_QGLColormap (x:l) sx qCastList_QGLColormap x = qcl_QGLColormap [] x type QGLContext a = Object (CQGLContext a) type TQGLContext a = CQGLContext a data CQGLContext a = CQGLContext type QGLContextSc a = QGLContext (CQGLContextSc a) type TQGLContextSc a = TQGLContext (CQGLContextSc a) data CQGLContextSc a = CQGLContextSc qCast_QGLContext :: Object a -> IO (QGLContext ()) qCast_QGLContext _qobj = return (objectCast _qobj) withQGLContextResult :: IO (Ptr (TQGLContext a)) -> IO (QGLContext a) withQGLContextResult f = withObjectResult qtc_QGLContext_getFinalizer f foreign import ccall qtc_QGLContext_getFinalizer :: FunPtr (Ptr (TQGLContext a) -> IO ()) qGLContextAddFinalizer :: QGLContext a -> IO () qGLContextAddFinalizer (Object fp) = addForeignPtrFinalizer qtc_QGLContext_getFinalizer fp foreign import ccall qtc_QGLContext_getFinalizer1 :: FunPtr (Ptr (TQGLContext a) -> IO ()) qGLContextAddFinalizer1 :: QGLContext a -> IO () qGLContextAddFinalizer1 (Object fp) = addForeignPtrFinalizer qtc_QGLContext_getFinalizer1 fp class QqCastList_QGLContext a r where qcl_QGLContext :: [QGLContext ()] -> a -> r instance QqCastList_QGLContext (QGLContext ()) [QGLContext ()] where qcl_QGLContext l x = reverse $ x:l instance QqCastList_QGLContext a r => QqCastList_QGLContext (QGLContext ()) (a -> r) where qcl_QGLContext l x sx = qcl_QGLContext (x:l) sx qCastList_QGLContext x = qcl_QGLContext [] x type QGLFramebufferObject a = QPaintDevice (CQGLFramebufferObject a) type TQGLFramebufferObject a = TQPaintDevice (CQGLFramebufferObject a) data CQGLFramebufferObject a = CQGLFramebufferObject type QGLFramebufferObjectSc a = QGLFramebufferObject (CQGLFramebufferObjectSc a) type TQGLFramebufferObjectSc a = TQGLFramebufferObject (CQGLFramebufferObjectSc a) data CQGLFramebufferObjectSc a = CQGLFramebufferObjectSc qCast_QGLFramebufferObject :: Object a -> IO (QGLFramebufferObject ()) qCast_QGLFramebufferObject _qobj = return (objectCast _qobj) withQGLFramebufferObjectResult :: IO (Ptr (TQGLFramebufferObject a)) -> IO (QGLFramebufferObject a) withQGLFramebufferObjectResult f = withObjectResult qtc_QGLFramebufferObject_getFinalizer f foreign import ccall qtc_QGLFramebufferObject_getFinalizer :: FunPtr (Ptr (TQGLFramebufferObject a) -> IO ()) qGLFramebufferObjectAddFinalizer :: QGLFramebufferObject a -> IO () qGLFramebufferObjectAddFinalizer (Object fp) = addForeignPtrFinalizer qtc_QGLFramebufferObject_getFinalizer fp foreign import ccall qtc_QGLFramebufferObject_getFinalizer1 :: FunPtr (Ptr (TQGLFramebufferObject a) -> IO ()) qGLFramebufferObjectAddFinalizer1 :: QGLFramebufferObject a -> IO () qGLFramebufferObjectAddFinalizer1 (Object fp) = addForeignPtrFinalizer qtc_QGLFramebufferObject_getFinalizer1 fp class QqCastList_QGLFramebufferObject a r where qcl_QGLFramebufferObject :: [QGLFramebufferObject ()] -> a -> r instance QqCastList_QGLFramebufferObject (QGLFramebufferObject ()) [QGLFramebufferObject ()] where qcl_QGLFramebufferObject l x = reverse $ x:l instance QqCastList_QGLFramebufferObject a r => QqCastList_QGLFramebufferObject (QGLFramebufferObject ()) (a -> r) where qcl_QGLFramebufferObject l x sx = qcl_QGLFramebufferObject (x:l) sx qCastList_QGLFramebufferObject x = qcl_QGLFramebufferObject [] x type QGLPixelBuffer a = QPaintDevice (CQGLPixelBuffer a) type TQGLPixelBuffer a = TQPaintDevice (CQGLPixelBuffer a) data CQGLPixelBuffer a = CQGLPixelBuffer type QGLPixelBufferSc a = QGLPixelBuffer (CQGLPixelBufferSc a) type TQGLPixelBufferSc a = TQGLPixelBuffer (CQGLPixelBufferSc a) data CQGLPixelBufferSc a = CQGLPixelBufferSc qCast_QGLPixelBuffer :: Object a -> IO (QGLPixelBuffer ()) qCast_QGLPixelBuffer _qobj = return (objectCast _qobj) withQGLPixelBufferResult :: IO (Ptr (TQGLPixelBuffer a)) -> IO (QGLPixelBuffer a) withQGLPixelBufferResult f = withObjectResult qtc_QGLPixelBuffer_getFinalizer f foreign import ccall qtc_QGLPixelBuffer_getFinalizer :: FunPtr (Ptr (TQGLPixelBuffer a) -> IO ()) qGLPixelBufferAddFinalizer :: QGLPixelBuffer a -> IO () qGLPixelBufferAddFinalizer (Object fp) = addForeignPtrFinalizer qtc_QGLPixelBuffer_getFinalizer fp foreign import ccall qtc_QGLPixelBuffer_getFinalizer1 :: FunPtr (Ptr (TQGLPixelBuffer a) -> IO ()) qGLPixelBufferAddFinalizer1 :: QGLPixelBuffer a -> IO () qGLPixelBufferAddFinalizer1 (Object fp) = addForeignPtrFinalizer qtc_QGLPixelBuffer_getFinalizer1 fp class QqCastList_QGLPixelBuffer a r where qcl_QGLPixelBuffer :: [QGLPixelBuffer ()] -> a -> r instance QqCastList_QGLPixelBuffer (QGLPixelBuffer ()) [QGLPixelBuffer ()] where qcl_QGLPixelBuffer l x = reverse $ x:l instance QqCastList_QGLPixelBuffer a r => QqCastList_QGLPixelBuffer (QGLPixelBuffer ()) (a -> r) where qcl_QGLPixelBuffer l x sx = qcl_QGLPixelBuffer (x:l) sx qCastList_QGLPixelBuffer x = qcl_QGLPixelBuffer [] x type QGLWidget a = QWidget (CQGLWidget a) type TQGLWidget a = TQWidget (CQGLWidget a) data CQGLWidget a = CQGLWidget type QGLWidgetSc a = QGLWidget (CQGLWidgetSc a) type TQGLWidgetSc a = TQGLWidget (CQGLWidgetSc a) data CQGLWidgetSc a = CQGLWidgetSc qCast_QGLWidget :: Object a -> IO (QGLWidget ()) qCast_QGLWidget _qobj = return (objectCast _qobj) withQGLWidgetResult :: IO (Ptr (TQGLWidget a)) -> IO (QGLWidget a) withQGLWidgetResult f = withObjectResult qtc_QGLWidget_getFinalizer f qGLWidgetFromPtr :: Ptr (TQGLWidget a) -> IO (QGLWidget a) qGLWidgetFromPtr p = objectFromPtr qtc_QGLWidget_getFinalizer p withQListQGLWidgetResult :: (Ptr (Ptr (TQGLWidget a)) -> IO CInt) -> IO [QGLWidget a] withQListQGLWidgetResult f = withQListObjectResult qtc_QGLWidget_getFinalizer f qGLWidgetListFromPtrList :: [Ptr (TQGLWidget a)] -> IO [QGLWidget a] qGLWidgetListFromPtrList p = objectListFromPtrList qtc_QGLWidget_getFinalizer p foreign import ccall qtc_QGLWidget_getFinalizer :: FunPtr (Ptr (TQGLWidget a) -> IO ()) class QqCastList_QGLWidget a r where qcl_QGLWidget :: [QGLWidget ()] -> a -> r instance QqCastList_QGLWidget (QGLWidget ()) [QGLWidget ()] where qcl_QGLWidget l x = reverse $ x:l instance QqCastList_QGLWidget a r => QqCastList_QGLWidget (QGLWidget ()) (a -> r) where qcl_QGLWidget l x sx = qcl_QGLWidget (x:l) sx qCastList_QGLWidget x = qcl_QGLWidget [] x
keera-studios/hsQt
Qtc/ClassTypes/Opengl.hs
bsd-2-clause
10,945
0
12
1,460
3,171
1,644
1,527
-1
-1
module Data.List.Statistics ( mean, median, standardDeviation ) where import qualified Data.List as DL mean :: Fractional a => [a] -> a mean xs = DL.sum xs / fromIntegral (length xs) median :: (Fractional a, Ord a) => [a] -> a median xs = if even len then avgMiddle else middleElem where len = length xs xs' = DL.sort xs halfLen = len `div` 2 middleElem = head $ drop halfLen xs' twoMiddle = take 2 $ drop (halfLen - 1) xs' avgMiddle = mean twoMiddle standardDeviation :: Floating a => [a] -> a standardDeviation xs = sqrt $ mean squareDiffs where meanValue = mean xs squareDiffs = map (\x -> x*x) $ map (meanValue -) xs
thomaschrstnsn/DaytumStats
src/Data/List/Statistics.hs
bsd-3-clause
722
0
11
217
271
145
126
20
2
{-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances #-} #if __GLASGOW_HASKELL__ > 702 {-# LANGUAGE DefaultSignatures, OverloadedStrings, ScopedTypeVariables, TypeOperators #-} #endif module Web.Routes.PathInfo ( stripOverlap , stripOverlapBS , stripOverlapText , URLParser , pToken , segment , anySegment , patternParse , parseSegments , PathInfo(..) , toPathInfo , toPathInfoParams , fromPathInfo , mkSitePI , showParseError #if __GLASGOW_HASKELL__ > 702 -- * Re-exported for convenience , Generic #endif ) where import Blaze.ByteString.Builder (Builder, toByteString) import Control.Applicative ((<$>), (<*)) import Control.Monad (msum) import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as B import Data.List as List (stripPrefix, tails) import Data.Text as Text (Text, pack, unpack, null, tails, stripPrefix) import Data.Text.Encoding (decodeUtf8) import Data.Text.Read (decimal, signed) import Data.Maybe (fromJust) import Network.HTTP.Types import Text.ParserCombinators.Parsec.Combinator (notFollowedBy) import Text.ParserCombinators.Parsec.Error (ParseError, errorPos, errorMessages, showErrorMessages) import Text.ParserCombinators.Parsec.Pos (incSourceLine, sourceName, sourceLine, sourceColumn) import Text.ParserCombinators.Parsec.Prim ((<?>), GenParser, getInput, setInput, getPosition, token, parse, many) import Web.Routes.Base (decodePathInfo, encodePathInfo) import Web.Routes.Site (Site(..)) #if __GLASGOW_HASKELL__ > 702 import Control.Applicative ((<$), (<*>), (<|>), pure) import Data.Char (toLower, isUpper) import Data.List (intercalate) import Data.List.Split (split, dropInitBlank, keepDelimsL, whenElt) import GHC.Generics #endif -- this is not very efficient. Among other things, we need only consider the last 'n' characters of x where n == length y. stripOverlap :: (Eq a) => [a] -> [a] -> [a] stripOverlap x y = fromJust $ msum $ [ List.stripPrefix p y | p <- List.tails x] stripOverlapText :: Text -> Text -> Text stripOverlapText x y = fromJust $ msum $ [ Text.stripPrefix p y | p <- Text.tails x ] stripOverlapBS :: B.ByteString -> B.ByteString -> B.ByteString stripOverlapBS x y = fromJust $ msum $ [ stripPrefix p y | p <- B.tails x ] -- fromJust will never fail where stripPrefix :: B.ByteString -> B.ByteString -> Maybe B.ByteString stripPrefix x y | x `B.isPrefixOf` y = Just $ B.drop (B.length x) y | otherwise = Nothing type URLParser a = GenParser Text () a pToken :: tok -> (Text -> Maybe a) -> URLParser a pToken msg f = do pos <- getPosition token unpack (const $ incSourceLine pos 1) f -- | match on a specific string segment :: Text -> URLParser Text segment x = (pToken (const x) (\y -> if x == y then Just x else Nothing)) <?> unpack x -- | match on any string anySegment :: URLParser Text anySegment = pToken (const "any string") Just -- | Only matches if all segments have been consumed eof :: URLParser () eof = notFollowedBy anySegment <?> "end of input" -- | apply a function to the remainder of the segments -- -- useful if you want to just do normal pattern matching: -- > -- > foo ["foo", "bar"] = Right (Foo Bar) -- > foo ["baz"] = Right Baz -- > foo _ = Left "parse error" -- -- > patternParse foo patternParse :: ([Text] -> Either String a) -> URLParser a patternParse p = do segs <- getInput case p segs of (Right r) -> do setInput [] return r (Left err) -> fail err -- | show Parsec 'ParseError' using terms that relevant to parsing a url showParseError :: ParseError -> String showParseError pErr = let pos = errorPos pErr posMsg = sourceName pos ++ " (segment " ++ show (sourceLine pos) ++ " character " ++ show (sourceColumn pos) ++ "): " msgs = errorMessages pErr in posMsg ++ showErrorMessages "or" "unknown parse error" "expecting" "unexpected" "end of input" msgs -- | run a 'URLParser' on a list of path segments -- -- returns @Left "parse error"@ on failure. -- -- returns @Right a@ on success parseSegments :: URLParser a -> [Text] -> Either String a parseSegments p segments = case parse (p <* eof) (show segments) segments of (Left e) -> Left (showParseError e) (Right r) -> Right r {- This requires parsec 3, can't figure out how to do it in parsec 2 yet. p2u :: Parser a -> URLParser a p2u p = mkPT $ \state@(State sInput sPos sUser) -> case sInput of (s:ss) -> do r <- runParsecT p (State s sPos sUser) return (fmap (fmap (fixReply ss)) r) where fixReply :: [String] -> (Reply String u a) -> (Reply [String] u a) fixReply _ (Error err) = (Error err) fixReply ss (Ok a (State "" sPos sUser) e) = (Ok a (State ss sPos sUser) e) fixReply ss (Ok a (State s sPos sUser) e) = (Ok a (State (s:ss) sPos sUser) e) -} {- p2u :: Parser a -> URLParser a p2u p = do (State sInput sPos sUser) <- getParserState case sInput of (s:ss) -> let r = runParser p () "" s in case r of (Left e) -> return e -} {- mkPT $ \state@(State sInput sPos sUser) -> case sInput of (s:ss) -> do r <- runParsecT p (State s sPos sUser) return (fmap (fmap (fixReply ss)) r) where fixReply :: [String] -> (Reply String u a) -> (Reply [String] u a) fixReply _ (Error err) = (Error err) fixReply ss (Ok a (State "" sPos sUser) e) = (Ok a (State ss sPos sUser) e) fixReply ss (Ok a (State s sPos sUser) e) = (Ok a (State (s:ss) sPos sUser) e) -} #if __GLASGOW_HASKELL__ > 702 hyphenate :: String -> Text hyphenate = pack . intercalate "-" . map (map toLower) . split splitter where splitter = dropInitBlank . keepDelimsL . whenElt $ isUpper class GPathInfo f where gtoPathSegments :: f url -> [Text] gfromPathSegments :: URLParser (f url) instance GPathInfo U1 where gtoPathSegments U1 = [] gfromPathSegments = pure U1 instance GPathInfo a => GPathInfo (D1 c a) where gtoPathSegments = gtoPathSegments . unM1 gfromPathSegments = M1 <$> gfromPathSegments instance GPathInfo a => GPathInfo (S1 c a) where gtoPathSegments = gtoPathSegments . unM1 gfromPathSegments = M1 <$> gfromPathSegments instance forall c a. (GPathInfo a, Constructor c) => GPathInfo (C1 c a) where gtoPathSegments m@(M1 x) = (hyphenate . conName) m : gtoPathSegments x gfromPathSegments = M1 <$ segment (hyphenate . conName $ (undefined :: C1 c a r)) <*> gfromPathSegments instance (GPathInfo a, GPathInfo b) => GPathInfo (a :*: b) where gtoPathSegments (a :*: b) = gtoPathSegments a ++ gtoPathSegments b gfromPathSegments = (:*:) <$> gfromPathSegments <*> gfromPathSegments instance (GPathInfo a, GPathInfo b) => GPathInfo (a :+: b) where gtoPathSegments (L1 x) = gtoPathSegments x gtoPathSegments (R1 x) = gtoPathSegments x gfromPathSegments = L1 <$> gfromPathSegments <|> R1 <$> gfromPathSegments instance PathInfo a => GPathInfo (K1 i a) where gtoPathSegments = toPathSegments . unK1 gfromPathSegments = K1 <$> fromPathSegments #endif -- | Simple parsing and rendering for a type to and from URL path segments. -- -- If you're using GHC 7.2 or later, you can use @DeriveGeneric@ to derive -- instances of this class: -- -- > {-# LANGUAGE DeriveGeneric #-} -- > data Sitemap = Home | BlogPost Int deriving Generic -- > instance PathInfo Sitemap -- -- This results in the following instance: -- -- > instance PathInfo Sitemap where -- > toPathSegments Home = ["home"] -- > toPathSegments (BlogPost x) = "blog-post" : toPathSegments x -- > fromPathSegments = Home <$ segment "home" -- > <|> BlogPost <$ segment "blog-post" <*> fromPathSegments -- -- And here it is in action: -- -- >>> toPathInfo (BlogPost 123) -- "/blog-post/123" -- >>> fromPathInfo "/blog-post/123" :: Either String Sitemap -- Right (BlogPost 123) -- -- To instead derive instances using @TemplateHaskell@, see -- <http://hackage.haskell.org/package/web-routes-th web-routes-th>. class PathInfo url where toPathSegments :: url -> [Text] fromPathSegments :: URLParser url #if __GLASGOW_HASKELL__ > 702 default toPathSegments :: (Generic url, GPathInfo (Rep url)) => url -> [Text] toPathSegments = gtoPathSegments . from default fromPathSegments :: (Generic url, GPathInfo (Rep url)) => URLParser url fromPathSegments = to <$> gfromPathSegments #endif -- |convert url into the path info portion of a URL toPathInfo :: (PathInfo url) => url -> Text toPathInfo = decodeUtf8 . toByteString . toPathInfoUtf8 -- |convert url into the path info portion of a URL toPathInfoUtf8 :: (PathInfo url) => url -> Builder toPathInfoUtf8 = flip encodePath [] . toPathSegments -- |convert url + params into the path info portion of a URL + a query string toPathInfoParams :: (PathInfo url) => url -- ^ url -> [(Text, Maybe Text)] -- ^ query string parameter -> Text toPathInfoParams url params = encodePathInfo (toPathSegments url) params -- should this fail if not all the input was consumed? -- -- in theory we -- require the pathInfo to have the initial '/', but this code will -- still work if it is missing. -- -- If there are multiple //// at the beginning, we only drop the first -- one, because we only added one in toPathInfo. Hence the others -- should be significant. -- -- However, if the pathInfo was prepend with http://example.org/ with -- a trailing slash, then things might not line up. -- | parse a 'String' into 'url' using 'PathInfo'. -- -- returns @Left "parse error"@ on failure -- -- returns @Right url@ on success fromPathInfo :: (PathInfo url) => ByteString -> Either String url fromPathInfo pi = parseSegments fromPathSegments (decodePathInfo $ dropSlash pi) where dropSlash s = if ((B.singleton '/') `B.isPrefixOf` s) then B.tail s else s -- | turn a routing function into a 'Site' value using the 'PathInfo' class mkSitePI :: (PathInfo url) => ((url -> [(Text, Maybe Text)] -> Text) -> url -> a) -- ^ a routing function -> Site url a mkSitePI handler = Site { handleSite = handler , formatPathSegments = (\x -> (x, [])) . toPathSegments , parsePathSegments = parseSegments fromPathSegments } -- it's instances all the way down instance PathInfo Text where toPathSegments = (:[]) fromPathSegments = anySegment instance PathInfo String where toPathSegments = (:[]) . pack fromPathSegments = unpack <$> anySegment instance PathInfo Int where toPathSegments i = [pack $ show i] fromPathSegments = pToken (const "Int") checkInt where checkInt txt = case signed decimal txt of (Left e) -> Nothing (Right (n, r)) | Text.null r -> Just n | otherwise -> Nothing instance PathInfo Integer where toPathSegments i = [pack $ show i] fromPathSegments = pToken (const "Integer") checkInt where checkInt txt = case signed decimal txt of (Left e) -> Nothing (Right (n, r)) | Text.null r -> Just n | otherwise -> Nothing instance PathInfo a => PathInfo [a] where toPathSegments = concat . fmap toPathSegments fromPathSegments = many fromPathSegments
shockkolate/web-routes
Web/Routes/PathInfo.hs
bsd-3-clause
11,425
0
15
2,591
2,482
1,367
1,115
126
2
{-# LANGUAGE GeneralizedNewtypeDeriving, CPP, QuasiQuotes, TypeFamilies, FlexibleInstances, MultiParamTypeClasses #-} -- | This module provides functions for using Markdown with Yesod. An example pipeline could be -- -- > (writePandoc defaultWriterOptions <$>) . localLinks . parseMarkdown defaultParserState module Yesod.Markdown ( Markdown (..) , parseMarkdown , localLinks , writePandoc -- * Option sets , yesodDefaultWriterOptions , yesodDefaultParserState , yesodDefaultParserStateTrusted ) where import Yesod import Data.Monoid import Data.String import Yesod.Form.Core import Text.Pandoc import Text.Pandoc.Shared import Control.Applicative import Data.Map ( Map ) import qualified Data.Map as Map import qualified Data.ByteString.Char8 as B newtype Markdown = Markdown String deriving (Eq, Ord, Show, Read, PersistField, IsString, Monoid) instance ToFormField Markdown y where toFormField = markdownField instance ToFormField (Maybe Markdown) y where toFormField = maybeMarkdownField lines' :: String -> [String] lines' = map go . lines where go [] = [] go ('\r':[]) = [] go (x:xs) = x : go xs markdownField :: (IsForm f, FormType f ~ Markdown) => FormFieldSettings -> Maybe Markdown -> f markdownField = requiredFieldHelper markdownFieldProfile maybeMarkdownField :: FormFieldSettings -> FormletField sub y (Maybe Markdown) maybeMarkdownField = optionalFieldHelper markdownFieldProfile markdownFieldProfile :: FieldProfile sub y Markdown markdownFieldProfile = FieldProfile { fpParse = Right . Markdown . unlines . lines' , fpRender = \(Markdown m) -> m , fpWidget = \theId name val _isReq -> addHamlet #if GHC7 [hamlet| #else [$hamlet| #endif %textarea.markdown#$theId$!name=$name$ $val$ |] } -- | Write 'Pandoc' to 'Html'. writePandoc :: WriterOptions -> Pandoc -> Html writePandoc wo = preEscapedString . writeHtmlString wo -- | Read in 'Markdown' to an intermediate 'Pandoc' type. parseMarkdown :: ParserState -> Markdown -> Pandoc parseMarkdown ro (Markdown m) = readMarkdown ro m -- | Convert local (in-site) links. This function works on all link URLs that start with the two-character -- prefix @~:@. It normalizes the links and replaces the @~:@ with the @approot@ value for the site. localLinks :: Yesod master => Pandoc -> GHandler sub master Pandoc localLinks p = (\y -> processWith (links y) p) <$> getYesod where links y (Link x ('~':':':l,n)) = Link x (joinPath y (approot y) (links' y (B.pack l)) [],n) links _ x = x links' y l = case splitPath y l of Left corrected -> links' y corrected Right xs -> xs -- | A set of default Pandoc writer options good for Yesod websites. Enables Javascript-based email obfuscation, -- eliminates div tags around sections, and disables text wrapping. yesodDefaultWriterOptions :: WriterOptions yesodDefaultWriterOptions = defaultWriterOptions { writerEmailObfuscation = JavascriptObfuscation , writerSectionDivs = False , writerWrapText = False } -- | A set of default Pandoc reader options good for Yesod websites /where the data input is trusted/. Disables -- HTML sanitization and enables smart parsing and raw HTML parsing. yesodDefaultParserStateTrusted :: ParserState yesodDefaultParserStateTrusted = yesodDefaultParserState { stateSanitizeHTML = False } -- | A set of default Pandoc reader options good for Yesod websites. Enables smart parsing, raw HTML parsing, and -- HTML sanitization. yesodDefaultParserState :: ParserState yesodDefaultParserState = defaultParserState { stateSmart = True, stateParseRaw = True, stateSanitizeHTML = True }
ajdunlap/yesod-markdown
Yesod/Markdown.hs
bsd-3-clause
3,646
0
14
631
741
413
328
62
3
{-# LANGUAGE TemplateHaskell #-} module Main where import IndexedSet import Criterion.Main import Criterion.Config import qualified Criterion.MultiMap as M import Data.Set (Set) import qualified Data.Set as S import Control.DeepSeq data Person = Person { name :: String , age :: Int , country :: String } deriving (Eq, Ord, Show) instance NFData Person where rnf (Person n a c) = rnf n `seq` rnf a `seq` rnf c data Database = Database { persons :: (Set Person) , ageindex :: (SetIndex Person Int) } instance Show Database where show a = show (persons a) instance NFData Database where rnf (Database s (SetIndex fn mp)) = rnf s `seq` rnf mp emptypersondb = Database S.empty (si age) personmap = $(deriveMap ''Database) personfilter = $(deriveFilter ''Database) persondelete = $(deriveDelete ''Database) personinsert = $(deriveInsert ''Database) personinsertmany = foldl (flip personinsert) personslist = map (\x -> Person (show x) (x`mod`100) (show x)) [1..50000] main = do let db = personinsertmany emptypersondb personslist rnf db `seq` defaultMain [ bench "index query" $ nf benchIndexQuery db , bench "filter query" $ nf benchFilterQuery db ] benchIndexQuery db = queryIndex (ageindex db) 20 benchFilterQuery db = S.filter (\x -> age x == 20) (persons db)
ArnoVanLumig/indexedset
Benchmark.hs
bsd-3-clause
1,441
0
11
379
500
265
235
35
1
{-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} module Graphics.UI.Threepenny.Widgets.DataTable where import Prelude hiding (id,(.)) import Control.Category import Graphics.UI.Threepenny.Attributes.Extra import Graphics.UI.Threepenny.Elements.ID import Graphics.UI.Threepenny.Extra hiding ((.=)) import qualified Graphics.UI.Threepenny as UI import Control.Monad import Foreign.JavaScript (JSObject) import qualified Foreign.JavaScript.Marshal as JS import qualified Foreign.RemotePtr as Foreign import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BS import qualified Data.ByteString as BSIO import Graphics.UI.Threepenny.Widgets.Plugins import Graphics.UI.Threepenny.Action data DataTable = DataTable { dtElement :: Element , dtUID :: UID , dtRef :: Ref JSObject , dtInitE :: E () , dtInitB :: B Bool } instance Widget DataTable where getElement = dtElement instance Identified DataTable where getUID = dtUID jsVarPrefix _ = "dt" dtObject :: DataTable -> UI JSObject dtObject = readRef . dtRef class (ToJSON a, FromJSON a) => JSONRow a where colNames :: p a -> [String] data Person = Person { firstName :: String , lastName :: String , age :: Int } instance ToJSON Person where toJSON p = object [ "first-name" .= firstName p , "last-name" .= lastName p , "age" .= age p ] instance FromJSON Person where parseJSON = withObject "Person" $ \o -> Person <$> o .: "first-name" <*> o .: "last-name" <*> o .: "age" instance JSONRow Person where colNames _ = ["first-name","last-name","age"] data LazyT a = LazyT { lazyB :: B (Maybe a) , readyE :: E () } data JSInit = JSInit { initB :: B (Maybe JSObject) , initReady :: E () } refB :: Ref a -> Event void -> UI (B a) refB r ev = do (e,h) <- newEvent onEvent ev $ \_ -> do a' <- readRef r h a' a <- readRef r stepper a e jsObjectT :: JSFunction JSObject -> UI JSInit jsObjectT f = do (r,e,h) <- onceRef runLater $ h =<< callFunction f b <- refB r e return $ JSInit b $ () <$ e jsDataTable :: JSONRow a => [a] -> UI (JSInit,Element) jsDataTable as = do t <- UI.table #. "display" i <- identify t lt <- jsObjectT $ ffi "$(%1).DataTable(%2)" (selUID i) $ object [ "data" .= as , "columns" .= [ object [ "data" .= c ] | c <- cs ] ] return (lt,t) where cs = colNames as testPeople :: [Person] testPeople = [ Person "Kyle" "Carter" 27 , Person "Toni" "Carter" 28 ] onInit :: JSInit -> (Element -> JSObject -> UI void) -> (Element -> UI (B (Maybe JSObject)),Element -> Maybe JSObject -> UI ()) onInit js f = ( pure $ return $ initB js , \e mo -> case mo of Just o -> void $ f e o _ -> return () ) -- Plugin {{{ data DataTables = DataTables instance Plugin DataTables where initPlugin _ = void $ do head_ #+ [ cssPath "static/css/jquery.dataTables.min.css" ] body_ #+ [ jsPath "static/js/jquery.dataTables.min.js" ] mkDataTable :: (hdr -> Element -> UI Element) -> (row -> Int -> Element -> UI Element) -> [hdr] -> [row] -> UI DataTable mkDataTable mkHdr mkEl hs rs = do t <- UI.table ## [ set class_ ["display"] ] #+ [ thead #+ [ UI.tr #+ [ UI.th >>= mkHdr h | h <- hs ] ] , tbody #+ [ UI.tr #+ [ UI.td >>= mkEl r i | i <- iota $ length hs ] | r <- rs ] ] (r,e,h) <- newRefE =<< emptyJSObject b <- stepper False (True <$ e) i <- identify t initDataTable i h return $ DataTable t i r (() <$ e) b initDataTable :: UID -> H UI JSObject -> UI () initDataTable i h = runLater $ h =<< callFunction (ffi "$(%1).DataTable()" $ selUID i) emptyJSObject :: UI JSObject emptyJSObject = callFunction $ ffi "{}" -- }}} -- Attributes {{{ dtAttr :: ToJSON a => String -> WriteAttr DataTable a dtAttr a = writeOnly (data_ a) # mapAttrSrc dtElement # mapWriteAttr toJSONStr dtBoolAttr :: String -> WriteAttr DataTable Bool dtBoolAttr = dtAttr autoWidth = dtBoolAttr "auto-width" info = dtBoolAttr "info" ordering = dtBoolAttr "ordering" paging = dtBoolAttr "paging" processing = dtBoolAttr "processing" lengthChange = dtBoolAttr "length-change" scrollX = dtBoolAttr "scroll-x" scrollY = dtBoolAttr "scroll-y" searching = dtBoolAttr "searching" {- tableData :: ReadAttr DataTable Value tableData = mkReadAttr $ \dt -> callFunction $ ffi "%1.rows().data()" $ uuidSelector $ dtUID dt -} -- }}} runDT :: IO () runDT = startGUI defaultConfig { jsPort = Just 10000 , jsCustomHTML = Just "index.html" , jsInclude = [] , jsStatic = Just "static" } $ pure dtSetup container :: UI Element container = UI.div #. "container" content_ :: UI Element content_ = UI.div #. "content" dtSetup :: UI () dtSetup = plugin DataTables $ withPlugins $ do addCSSFile "containers.css" e <- UI.div #+ [ UI.div #! "Element 1" , UI.div #! "Element 2" , UI.div #! "Element 3" , UI.div #! "Element 4" ] body_ #+ [ container #+ [ content_ #+ [ element e , UI.hr , UI.div #! "Children Test" , UI.hr , do es <- parseElements "<div>Div</div><span>Span</span>" es' <- filterElements es "div" UI.div #+> es' ] ] ]
kylcarte/threepenny-extra
src/Graphics/UI/Threepenny/Widgets/DataTable.hs
bsd-3-clause
5,567
0
17
1,469
1,822
955
867
168
2
-- | A demo to show that a tail-recursive function will not increase -- the JavaScript stack. -- -- More future work for TCO to be done here. module Demo.Tailrecursive where import Language.Fay.FFI import Language.Fay.Prelude main :: Fay () main = do benchmark benchmark benchmark benchmark benchmark :: Fay () benchmark = do start <- getSeconds printD (sum 1000000 0 :: Double) end <- getSeconds printS (show (end-start) ++ "ms") -- the tail recursive function sum :: Double -> Double -> Double sum 0 acc = acc sum n acc = sum (n - 1) (acc + n) getSeconds :: Fay Double getSeconds = ffi "new Date()" printD :: Double -> Fay () printD = ffi "console.log(%1)" printS :: String -> Fay () printS = ffi "console.log(%1)"
faylang/fay-server
modules/project/Demo/Tailrecursive.hs
bsd-3-clause
741
0
12
151
231
119
112
24
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Text.CSL.Data -- Copyright : (c) John MacFarlane -- License : BSD-style (see LICENSE) -- -- Maintainer : John MacFarlane <[email protected]> -- Stability : unstable -- Portability : unportable -- ----------------------------------------------------------------------------- module Text.CSL.Data ( getLocale , CSLLocaleException(..) , getDefaultCSL , langBase ) where import System.FilePath () import Data.Typeable import qualified Data.ByteString.Lazy as L import qualified Control.Exception as E #ifdef EMBED_DATA_FILES import Data.Maybe (fromMaybe) import Text.CSL.Data.Embedded (localeFiles, defaultCSL) import qualified Data.ByteString as S #else import Paths_pandoc_citeproc (getDataFileName) import System.Directory (doesFileExist) #endif data CSLLocaleException = CSLLocaleNotFound String | CSLLocaleReadError E.IOException deriving Typeable instance Show CSLLocaleException where show (CSLLocaleNotFound s) = "Could not find locale data for " ++ s show (CSLLocaleReadError e) = show e instance E.Exception CSLLocaleException -- | Raises 'CSLLocaleException' on error. getLocale :: String -> IO L.ByteString getLocale s = do #ifdef EMBED_DATA_FILES let toLazy x = L.fromChunks [x] case length s of 0 -> maybe (E.throwIO $ CSLLocaleNotFound "en-US") (return . toLazy) $ lookup "locales-en-US.xml" localeFiles 2 -> let fn = ("locales-" ++ fromMaybe s (lookup s langBase) ++ ".xml") in case lookup fn localeFiles of Just x' -> return $ toLazy x' _ -> E.throwIO $ CSLLocaleNotFound s _ -> case lookup ("locales-" ++ take 5 s ++ ".xml") localeFiles of Just x' -> return $ toLazy x' _ -> -- try again with 2-letter locale let s' = take 2 s in case lookup ("locales-" ++ fromMaybe s' (lookup s' langBase) ++ ".xml") localeFiles of Just x'' -> return $ toLazy x'' _ -> E.throwIO $ CSLLocaleNotFound s #else f <- case length s of 0 -> return "locales/locales-en-US.xml" 2 -> getDataFileName ("locales/locales-" ++ maybe s id (lookup s langBase) ++ ".xml") _ -> getDataFileName ("locales/locales-" ++ take 5 s ++ ".xml") exists <- doesFileExist f if not exists && length s > 2 then getLocale $ take 2 s -- try again with base locale else E.handle (\e -> E.throwIO (CSLLocaleReadError e)) $ L.readFile f #endif getDefaultCSL :: IO L.ByteString getDefaultCSL = #ifdef EMBED_DATA_FILES return $ L.fromChunks [defaultCSL] #else getDataFileName "chicago-author-date.csl" >>= L.readFile #endif langBase :: [(String, String)] langBase = [("af", "af-ZA") ,("bg", "bg-BG") ,("ca", "ca-AD") ,("cs", "cs-CZ") ,("da", "da-DK") ,("de", "de-DE") ,("el", "el-GR") ,("en", "en-US") ,("es", "es-ES") ,("et", "et-EE") ,("fa", "fa-IR") ,("fi", "fi-FI") ,("fr", "fr-FR") ,("he", "he-IL") ,("hr", "hr-HR") ,("hu", "hu-HU") ,("is", "is-IS") ,("it", "it-IT") ,("ja", "ja-JP") ,("km", "km-KH") ,("ko", "ko-KR") ,("lt", "lt-LT") ,("lv", "lv-LV") ,("mn", "mn-MN") ,("nb", "nb-NO") ,("nl", "nl-NL") ,("nn", "nn-NO") ,("pl", "pl-PL") ,("pt", "pt-PT") ,("ro", "ro-RO") ,("ru", "ru-RU") ,("sk", "sk-SK") ,("sl", "sl-SI") ,("sr", "sr-RS") ,("sv", "sv-SE") ,("th", "th-TH") ,("tr", "tr-TR") ,("uk", "uk-UA") ,("vi", "vi-VN") ,("zh", "zh-CN") ]
jkr/pandoc-citeproc
src/Text/CSL/Data.hs
bsd-3-clause
3,926
0
22
1,099
894
529
365
77
4
module Haseem.Analysis.Config where import Haseem.Types import Haseem.Monad
badi/haseem
Haseem/Analysis/Config.hs
bsd-3-clause
78
0
4
9
17
11
6
3
0
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE BangPatterns , CPP , ExistentialQuantification , NoImplicitPrelude , RecordWildCards , TypeSynonymInstances , FlexibleInstances #-} module GHC.Event.Manager ( -- * Types EventManager -- * Creation , new , newWith , newDefaultBackend -- * Running , finished , loop , step , shutdown , release , cleanup , wakeManager -- * State , callbackTableVar , emControl -- * Registering interest in I/O events , Event , evtRead , evtWrite , IOCallback , FdKey(keyFd) , FdData , registerFd_ , registerFd , unregisterFd_ , unregisterFd , closeFd , closeFd_ ) where #include "EventConfig.h" ------------------------------------------------------------------------ -- Imports import Control.Concurrent.MVar (MVar, newMVar, readMVar, putMVar, tryPutMVar, takeMVar, withMVar) import Control.Exception (onException) import Data.Bits ((.&.)) import Data.Foldable (forM_) import Data.Functor (void) import Data.IORef (IORef, atomicModifyIORef', mkWeakIORef, newIORef, readIORef, writeIORef) import Data.Maybe (maybe) import GHC.Arr (Array, (!), listArray) import GHC.Base import GHC.Conc.Signal (runHandlers) import GHC.Conc.Sync (yield) import GHC.List (filter, replicate) import GHC.Num (Num(..)) import GHC.Real (fromIntegral) import GHC.Show (Show(..)) import GHC.Event.Control import GHC.Event.IntTable (IntTable) import GHC.Event.Internal (Backend, Event, evtClose, evtRead, evtWrite, Timeout(..)) import GHC.Event.Unique (Unique, UniqueSource, newSource, newUnique) import System.Posix.Types (Fd) import qualified GHC.Event.IntTable as IT import qualified GHC.Event.Internal as I #if defined(HAVE_KQUEUE) import qualified GHC.Event.KQueue as KQueue #elif defined(HAVE_EPOLL) import qualified GHC.Event.EPoll as EPoll #elif defined(HAVE_POLL) import qualified GHC.Event.Poll as Poll #else # error not implemented for this operating system #endif ------------------------------------------------------------------------ -- Types data FdData = FdData { fdKey :: {-# UNPACK #-} !FdKey , fdEvents :: {-# UNPACK #-} !Event , _fdCallback :: !IOCallback } -- | A file descriptor registration cookie. data FdKey = FdKey { keyFd :: {-# UNPACK #-} !Fd , keyUnique :: {-# UNPACK #-} !Unique } deriving (Eq, Show) -- | Callback invoked on I/O events. type IOCallback = FdKey -> Event -> IO () data State = Created | Running | Dying | Releasing | Finished deriving (Eq, Show) -- | The event manager state. data EventManager = EventManager { emBackend :: !Backend , emFds :: {-# UNPACK #-} !(Array Int (MVar (IntTable [FdData]))) , emState :: {-# UNPACK #-} !(IORef State) , emUniqueSource :: {-# UNPACK #-} !UniqueSource , emControl :: {-# UNPACK #-} !Control , emOneShot :: !Bool , emLock :: {-# UNPACK #-} !(MVar ()) } -- must be power of 2 callbackArraySize :: Int callbackArraySize = 32 hashFd :: Fd -> Int hashFd fd = fromIntegral fd .&. (callbackArraySize - 1) {-# INLINE hashFd #-} callbackTableVar :: EventManager -> Fd -> MVar (IntTable [FdData]) callbackTableVar mgr fd = emFds mgr ! hashFd fd {-# INLINE callbackTableVar #-} haveOneShot :: Bool {-# INLINE haveOneShot #-} #if defined(darwin_HOST_OS) || defined(ios_HOST_OS) haveOneShot = False #elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE) haveOneShot = True #else haveOneShot = False #endif ------------------------------------------------------------------------ -- Creation handleControlEvent :: EventManager -> Fd -> Event -> IO () handleControlEvent mgr fd _evt = do msg <- readControlMessage (emControl mgr) fd case msg of CMsgWakeup -> return () CMsgDie -> writeIORef (emState mgr) Finished CMsgSignal fp s -> runHandlers fp s newDefaultBackend :: IO Backend #if defined(HAVE_KQUEUE) newDefaultBackend = KQueue.new #elif defined(HAVE_EPOLL) newDefaultBackend = EPoll.new #elif defined(HAVE_POLL) newDefaultBackend = Poll.new #else newDefaultBackend = error "no back end for this platform" #endif -- | Create a new event manager. new :: Bool -> IO EventManager new oneShot = newWith oneShot =<< newDefaultBackend newWith :: Bool -> Backend -> IO EventManager newWith oneShot be = do iofds <- fmap (listArray (0, callbackArraySize-1)) $ replicateM callbackArraySize (newMVar =<< IT.new 8) ctrl <- newControl False state <- newIORef Created us <- newSource _ <- mkWeakIORef state $ do st <- atomicModifyIORef' state $ \s -> (Finished, s) when (st /= Finished) $ do I.delete be closeControl ctrl lockVar <- newMVar () let mgr = EventManager { emBackend = be , emFds = iofds , emState = state , emUniqueSource = us , emControl = ctrl , emOneShot = oneShot , emLock = lockVar } registerControlFd mgr (controlReadFd ctrl) evtRead registerControlFd mgr (wakeupReadFd ctrl) evtRead return mgr where replicateM n x = sequence (replicate n x) failOnInvalidFile :: String -> Fd -> IO Bool -> IO () failOnInvalidFile loc fd m = do ok <- m when (not ok) $ let msg = "Failed while attempting to modify registration of file " ++ show fd ++ " at location " ++ loc in error msg registerControlFd :: EventManager -> Fd -> Event -> IO () registerControlFd mgr fd evs = failOnInvalidFile "registerControlFd" fd $ I.modifyFd (emBackend mgr) fd mempty evs -- | Asynchronously shuts down the event manager, if running. shutdown :: EventManager -> IO () shutdown mgr = do state <- atomicModifyIORef' (emState mgr) $ \s -> (Dying, s) when (state == Running) $ sendDie (emControl mgr) -- | Asynchronously tell the thread executing the event -- manager loop to exit. release :: EventManager -> IO () release EventManager{..} = do state <- atomicModifyIORef' emState $ \s -> (Releasing, s) when (state == Running) $ sendWakeup emControl finished :: EventManager -> IO Bool finished mgr = (== Finished) `liftM` readIORef (emState mgr) cleanup :: EventManager -> IO () cleanup EventManager{..} = do writeIORef emState Finished void $ tryPutMVar emLock () I.delete emBackend closeControl emControl ------------------------------------------------------------------------ -- Event loop -- | Start handling events. This function loops until told to stop, -- using 'shutdown'. -- -- /Note/: This loop can only be run once per 'EventManager', as it -- closes all of its control resources when it finishes. loop :: EventManager -> IO () loop mgr@EventManager{..} = do void $ takeMVar emLock state <- atomicModifyIORef' emState $ \s -> case s of Created -> (Running, s) Releasing -> (Running, s) _ -> (s, s) case state of Created -> go `onException` cleanup mgr Releasing -> go `onException` cleanup mgr Dying -> cleanup mgr -- While a poll loop is never forked when the event manager is in the -- 'Finished' state, its state could read 'Finished' once the new thread -- actually runs. This is not an error, just an unfortunate race condition -- in Thread.restartPollLoop. See #8235 Finished -> return () _ -> do cleanup mgr error $ "GHC.Event.Manager.loop: state is already " ++ show state where go = do state <- step mgr case state of Running -> yield >> go Releasing -> putMVar emLock () _ -> cleanup mgr -- | To make a step, we first do a non-blocking poll, in case -- there are already events ready to handle. This improves performance -- because we can make an unsafe foreign C call, thereby avoiding -- forcing the current Task to release the Capability and forcing a context switch. -- If the poll fails to find events, we yield, putting the poll loop thread at -- end of the Haskell run queue. When it comes back around, we do one more -- non-blocking poll, in case we get lucky and have ready events. -- If that also returns no events, then we do a blocking poll. step :: EventManager -> IO State step mgr@EventManager{..} = do waitForIO state <- readIORef emState state `seq` return state where waitForIO = do n1 <- I.poll emBackend Nothing (onFdEvent mgr) when (n1 <= 0) $ do yield n2 <- I.poll emBackend Nothing (onFdEvent mgr) when (n2 <= 0) $ do _ <- I.poll emBackend (Just Forever) (onFdEvent mgr) return () ------------------------------------------------------------------------ -- Registering interest in I/O events -- | Register interest in the given events, without waking the event -- manager thread. The 'Bool' return value indicates whether the -- event manager ought to be woken. registerFd_ :: EventManager -> IOCallback -> Fd -> Event -> IO (FdKey, Bool) registerFd_ mgr@(EventManager{..}) cb fd evs = do u <- newUnique emUniqueSource let fd' = fromIntegral fd reg = FdKey fd u !fdd = FdData reg evs cb (modify,ok) <- withMVar (callbackTableVar mgr fd) $ \tbl -> if haveOneShot && emOneShot then do oldFdd <- IT.insertWith (++) fd' [fdd] tbl let evs' = maybe evs (combineEvents evs) oldFdd ok <- I.modifyFdOnce emBackend fd evs' if ok then return (False, True) else IT.reset fd' oldFdd tbl >> return (False, False) else do oldFdd <- IT.insertWith (++) fd' [fdd] tbl let (oldEvs, newEvs) = case oldFdd of Nothing -> (mempty, evs) Just prev -> (eventsOf prev, combineEvents evs prev) modify = oldEvs /= newEvs ok <- if modify then I.modifyFd emBackend fd oldEvs newEvs else return True if ok then return (modify, True) else IT.reset fd' oldFdd tbl >> return (False, False) -- this simulates behavior of old IO manager: -- i.e. just call the callback if the registration fails. when (not ok) (cb reg evs) return (reg,modify) {-# INLINE registerFd_ #-} combineEvents :: Event -> [FdData] -> Event combineEvents ev [fdd] = mappend ev (fdEvents fdd) combineEvents ev fdds = mappend ev (eventsOf fdds) {-# INLINE combineEvents #-} -- | @registerFd mgr cb fd evs@ registers interest in the events @evs@ -- on the file descriptor @fd@. @cb@ is called for each event that -- occurs. Returns a cookie that can be handed to 'unregisterFd'. registerFd :: EventManager -> IOCallback -> Fd -> Event -> IO FdKey registerFd mgr cb fd evs = do (r, wake) <- registerFd_ mgr cb fd evs when wake $ wakeManager mgr return r {-# INLINE registerFd #-} {- Building GHC with parallel IO manager on Mac freezes when compiling the dph libraries in the phase 2. As workaround, we don't use oneshot and we wake up an IO manager on Mac every time when we register an event. For more information, please read: http://ghc.haskell.org/trac/ghc/ticket/7651 -} -- | Wake up the event manager. wakeManager :: EventManager -> IO () #if defined(darwin_HOST_OS) || defined(ios_HOST_OS) wakeManager mgr = sendWakeup (emControl mgr) #elif defined(HAVE_EPOLL) || defined(HAVE_KQUEUE) wakeManager _ = return () #else wakeManager mgr = sendWakeup (emControl mgr) #endif eventsOf :: [FdData] -> Event eventsOf = mconcat . map fdEvents -- | Drop a previous file descriptor registration, without waking the -- event manager thread. The return value indicates whether the event -- manager ought to be woken. unregisterFd_ :: EventManager -> FdKey -> IO Bool unregisterFd_ mgr@(EventManager{..}) (FdKey fd u) = withMVar (callbackTableVar mgr fd) $ \tbl -> do let dropReg = nullToNothing . filter ((/= u) . keyUnique . fdKey) fd' = fromIntegral fd pairEvents prev = do r <- maybe mempty eventsOf `fmap` IT.lookup fd' tbl return (eventsOf prev, r) (oldEvs, newEvs) <- IT.updateWith dropReg fd' tbl >>= maybe (return (mempty, mempty)) pairEvents let modify = oldEvs /= newEvs when modify $ failOnInvalidFile "unregisterFd_" fd $ if haveOneShot && emOneShot && newEvs /= mempty then I.modifyFdOnce emBackend fd newEvs else I.modifyFd emBackend fd oldEvs newEvs return modify -- | Drop a previous file descriptor registration. unregisterFd :: EventManager -> FdKey -> IO () unregisterFd mgr reg = do wake <- unregisterFd_ mgr reg when wake $ wakeManager mgr -- | Close a file descriptor in a race-safe way. closeFd :: EventManager -> (Fd -> IO ()) -> Fd -> IO () closeFd mgr close fd = do fds <- withMVar (callbackTableVar mgr fd) $ \tbl -> do prev <- IT.delete (fromIntegral fd) tbl case prev of Nothing -> close fd >> return [] Just fds -> do let oldEvs = eventsOf fds when (oldEvs /= mempty) $ do _ <- I.modifyFd (emBackend mgr) fd oldEvs mempty wakeManager mgr close fd return fds forM_ fds $ \(FdData reg ev cb) -> cb reg (ev `mappend` evtClose) -- | Close a file descriptor in a race-safe way. -- It assumes the caller will update the callback tables and that the caller -- holds the callback table lock for the fd. It must hold this lock because -- this command executes a backend command on the fd. closeFd_ :: EventManager -> IntTable [FdData] -> Fd -> IO (IO ()) closeFd_ mgr tbl fd = do prev <- IT.delete (fromIntegral fd) tbl case prev of Nothing -> return (return ()) Just fds -> do let oldEvs = eventsOf fds when (oldEvs /= mempty) $ do _ <- I.modifyFd (emBackend mgr) fd oldEvs mempty wakeManager mgr return $ forM_ fds $ \(FdData reg ev cb) -> cb reg (ev `mappend` evtClose) ------------------------------------------------------------------------ -- Utilities -- | Call the callbacks corresponding to the given file descriptor. onFdEvent :: EventManager -> Fd -> Event -> IO () onFdEvent mgr fd evs = if fd == controlReadFd (emControl mgr) || fd == wakeupReadFd (emControl mgr) then handleControlEvent mgr fd evs else if emOneShot mgr then do fdds <- withMVar (callbackTableVar mgr fd) $ \tbl -> IT.delete fd' tbl >>= maybe (return []) (selectCallbacks tbl) forM_ fdds $ \(FdData reg _ cb) -> cb reg evs else do found <- IT.lookup fd' =<< readMVar (callbackTableVar mgr fd) case found of Just cbs -> forM_ cbs $ \(FdData reg ev cb) -> do when (evs `I.eventIs` ev) $ cb reg evs Nothing -> return () where fd' :: Int fd' = fromIntegral fd selectCallbacks :: IntTable [FdData] -> [FdData] -> IO [FdData] selectCallbacks tbl cbs = aux cbs [] [] where -- nothing to rearm. aux [] _ [] = if haveOneShot then return cbs else do _ <- I.modifyFd (emBackend mgr) fd (eventsOf cbs) mempty return cbs -- reinsert and rearm; note that we already have the lock on the -- callback table for this fd, and we deleted above, so we know there -- is no entry in the table for this fd. aux [] fdds saved@(_:_) = do _ <- if haveOneShot then I.modifyFdOnce (emBackend mgr) fd $ eventsOf saved else I.modifyFd (emBackend mgr) fd (eventsOf cbs) $ eventsOf saved _ <- IT.insertWith (\_ _ -> saved) fd' saved tbl return fdds -- continue, saving those callbacks that don't match the event aux (fdd@(FdData _ evs' _) : cbs') fdds saved | evs `I.eventIs` evs' = aux cbs' (fdd:fdds) saved | otherwise = aux cbs' fdds (fdd:saved) nullToNothing :: [a] -> Maybe [a] nullToNothing [] = Nothing nullToNothing xs@(_:_) = Just xs
spacekitteh/smcghc
libraries/base/GHC/Event/Manager.hs
bsd-3-clause
16,308
0
23
4,278
4,121
2,136
1,985
-1
-1
{-# LANGUAGE CPP #-} module Distribution.Client.Dependency.Modular.Preference ( avoidReinstalls , deferSetupChoices , deferWeakFlagChoices , enforceManualFlags , enforcePackageConstraints , enforceSingleInstanceRestriction , firstGoal , lpreferEasyGoalChoices , preferBaseGoalChoice , preferLinked , preferPackagePreferences , requireInstalled ) where -- Reordering or pruning the tree in order to prefer or make certain choices. import qualified Data.List as L import qualified Data.Map as M #if !MIN_VERSION_base(4,8,0) import Data.Monoid import Control.Applicative #endif import qualified Data.Set as S import Prelude hiding (sequence) import Control.Monad.Reader hiding (sequence) import Data.Ord import Data.Map (Map) import Data.Traversable (sequence) import Distribution.Client.Dependency.Types ( PackageConstraint(..), LabeledPackageConstraint(..), ConstraintSource(..) , PackagePreferences(..), InstalledPreference(..) ) import Distribution.Client.Types ( OptionalStanza(..) ) import Distribution.Client.Dependency.Modular.Dependency import Distribution.Client.Dependency.Modular.Flag import Distribution.Client.Dependency.Modular.Package import qualified Distribution.Client.Dependency.Modular.PSQ as P import Distribution.Client.Dependency.Modular.Tree import Distribution.Client.Dependency.Modular.Version -- | Generic abstraction for strategies that just rearrange the package order. -- Only packages that match the given predicate are reordered. packageOrderFor :: (PN -> Bool) -> (PN -> I -> I -> Ordering) -> Tree a -> Tree a packageOrderFor p cmp' = trav go where go (PChoiceF v@(Q _ pn) r cs) | p pn = PChoiceF v r (P.sortByKeys (flip (cmp pn)) cs) | otherwise = PChoiceF v r cs go x = x cmp :: PN -> POption -> POption -> Ordering cmp pn (POption i _) (POption i' _) = cmp' pn i i' -- | Prefer to link packages whenever possible preferLinked :: Tree a -> Tree a preferLinked = trav go where go (PChoiceF qn a cs) = PChoiceF qn a (P.sortByKeys cmp cs) go x = x cmp (POption _ linkedTo) (POption _ linkedTo') = cmpL linkedTo linkedTo' cmpL Nothing Nothing = EQ cmpL Nothing (Just _) = GT cmpL (Just _) Nothing = LT cmpL (Just _) (Just _) = EQ -- | Ordering that treats versions satisfying more preferred ranges as greater -- than versions satisfying less preferred ranges. preferredVersionsOrdering :: [VR] -> Ver -> Ver -> Ordering preferredVersionsOrdering vrs v1 v2 = compare (check v1) (check v2) where check v = Prelude.length . Prelude.filter (==True) . Prelude.map (flip checkVR v) $ vrs -- | Traversal that tries to establish package preferences (not constraints). -- Works by reordering choice nodes. preferPackagePreferences :: (PN -> PackagePreferences) -> Tree a -> Tree a preferPackagePreferences pcs = packageOrderFor (const True) preference where preference pn i1@(I v1 _) i2@(I v2 _) = let PackagePreferences vrs ipref = pcs pn in preferredVersionsOrdering vrs v1 v2 `mappend` -- combines lexically locationsOrdering ipref i1 i2 -- Note that we always rank installed before uninstalled, and later -- versions before earlier, but we can change the priority of the -- two orderings. locationsOrdering PreferInstalled v1 v2 = preferInstalledOrdering v1 v2 `mappend` preferLatestOrdering v1 v2 locationsOrdering PreferLatest v1 v2 = preferLatestOrdering v1 v2 `mappend` preferInstalledOrdering v1 v2 -- | Ordering that treats installed instances as greater than uninstalled ones. preferInstalledOrdering :: I -> I -> Ordering preferInstalledOrdering (I _ (Inst _)) (I _ (Inst _)) = EQ preferInstalledOrdering (I _ (Inst _)) _ = GT preferInstalledOrdering _ (I _ (Inst _)) = LT preferInstalledOrdering _ _ = EQ -- | Compare instances by their version numbers. preferLatestOrdering :: I -> I -> Ordering preferLatestOrdering (I v1 _) (I v2 _) = compare v1 v2 -- | Helper function that tries to enforce a single package constraint on a -- given instance for a P-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintP :: PP -> ConflictSet QPN -> I -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintP pp _ _ (LabeledPackageConstraint _ src) r | src == ConstraintSourceUserTarget && not (primaryPP pp) = r -- the constraints arising from targets, like "foo-1.0" only apply to -- the main packages in the solution, they don't constrain setup deps processPackageConstraintP _ c i (LabeledPackageConstraint pc src) r = go i pc where go (I v _) (PackageConstraintVersion _ vr) | checkVR vr v = r | otherwise = Fail c (GlobalConstraintVersion vr src) go _ (PackageConstraintInstalled _) | instI i = r | otherwise = Fail c (GlobalConstraintInstalled src) go _ (PackageConstraintSource _) | not (instI i) = r | otherwise = Fail c (GlobalConstraintSource src) go _ _ = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintF :: Flag -> ConflictSet QPN -> Bool -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintF f c b' (LabeledPackageConstraint pc src) r = go pc where go (PackageConstraintFlags _ fa) = case L.lookup f fa of Nothing -> r Just b | b == b' -> r | otherwise -> Fail c (GlobalConstraintFlag src) go _ = r -- | Helper function that tries to enforce a single package constraint on a -- given flag setting for an F-node. Translates the constraint into a -- tree-transformer that either leaves the subtree untouched, or replaces it -- with an appropriate failure node. processPackageConstraintS :: OptionalStanza -> ConflictSet QPN -> Bool -> LabeledPackageConstraint -> Tree a -> Tree a processPackageConstraintS s c b' (LabeledPackageConstraint pc src) r = go pc where go (PackageConstraintStanzas _ ss) = if not b' && s `elem` ss then Fail c (GlobalConstraintFlag src) else r go _ = r -- | Traversal that tries to establish various kinds of user constraints. Works -- by selectively disabling choices that have been ruled out by global user -- constraints. enforcePackageConstraints :: M.Map PN [LabeledPackageConstraint] -> Tree QGoalReasonChain -> Tree QGoalReasonChain enforcePackageConstraints pcs = trav go where go (PChoiceF qpn@(Q pp pn) gr ts) = let c = toConflictSet (Goal (P qpn) gr) -- compose the transformation functions for each of the relevant constraint g = \ (POption i _) -> foldl (\ h pc -> h . processPackageConstraintP pp c i pc) id (M.findWithDefault [] pn pcs) in PChoiceF qpn gr (P.mapWithKey g ts) go (FChoiceF qfn@(FN (PI (Q _ pn) _) f) gr tr m ts) = let c = toConflictSet (Goal (F qfn) gr) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintF f c b pc) id (M.findWithDefault [] pn pcs) in FChoiceF qfn gr tr m (P.mapWithKey g ts) go (SChoiceF qsn@(SN (PI (Q _ pn) _) f) gr tr ts) = let c = toConflictSet (Goal (S qsn) gr) -- compose the transformation functions for each of the relevant constraint g = \ b -> foldl (\ h pc -> h . processPackageConstraintS f c b pc) id (M.findWithDefault [] pn pcs) in SChoiceF qsn gr tr (P.mapWithKey g ts) go x = x -- | Transformation that tries to enforce manual flags. Manual flags -- can only be re-set explicitly by the user. This transformation should -- be run after user preferences have been enforced. For manual flags, -- it checks if a user choice has been made. If not, it disables all but -- the first choice. enforceManualFlags :: Tree QGoalReasonChain -> Tree QGoalReasonChain enforceManualFlags = trav go where go (FChoiceF qfn gr tr True ts) = FChoiceF qfn gr tr True $ let c = toConflictSet (Goal (F qfn) gr) in case span isDisabled (P.toList ts) of ([], y : ys) -> P.fromList (y : L.map (\ (b, _) -> (b, Fail c ManualFlag)) ys) _ -> ts -- something has been manually selected, leave things alone where isDisabled (_, Fail _ (GlobalConstraintFlag _)) = True isDisabled _ = False go x = x -- | Require installed packages. requireInstalled :: (PN -> Bool) -> Tree QGoalReasonChain -> Tree QGoalReasonChain requireInstalled p = trav go where go (PChoiceF v@(Q _ pn) gr cs) | p pn = PChoiceF v gr (P.mapWithKey installed cs) | otherwise = PChoiceF v gr cs where installed (POption (I _ (Inst _)) _) x = x installed _ _ = Fail (toConflictSet (Goal (P v) gr)) CannotInstall go x = x -- | Avoid reinstalls. -- -- This is a tricky strategy. If a package version is installed already and the -- same version is available from a repo, the repo version will never be chosen. -- This would result in a reinstall (either destructively, or potentially, -- shadowing). The old instance won't be visible or even present anymore, but -- other packages might have depended on it. -- -- TODO: It would be better to actually check the reverse dependencies of installed -- packages. If they're not depended on, then reinstalling should be fine. Even if -- they are, perhaps this should just result in trying to reinstall those other -- packages as well. However, doing this all neatly in one pass would require to -- change the builder, or at least to change the goal set after building. avoidReinstalls :: (PN -> Bool) -> Tree QGoalReasonChain -> Tree QGoalReasonChain avoidReinstalls p = trav go where go (PChoiceF qpn@(Q _ pn) gr cs) | p pn = PChoiceF qpn gr disableReinstalls | otherwise = PChoiceF qpn gr cs where disableReinstalls = let installed = [ v | (POption (I v (Inst _)) _, _) <- P.toList cs ] in P.mapWithKey (notReinstall installed) cs notReinstall vs (POption (I v InRepo) _) _ | v `elem` vs = Fail (toConflictSet (Goal (P qpn) gr)) CannotReinstall notReinstall _ _ x = x go x = x -- | Always choose the first goal in the list next, abandoning all -- other choices. -- -- This is unnecessary for the default search strategy, because -- it descends only into the first goal choice anyway, -- but may still make sense to just reduce the tree size a bit. firstGoal :: Tree a -> Tree a firstGoal = trav go where go (GoalChoiceF xs) = -- P.casePSQ xs (GoalChoiceF xs) (\ _ t _ -> out t) -- more space efficient, but removes valuable debug info P.casePSQ xs (GoalChoiceF (P.fromList [])) (\ g t _ -> GoalChoiceF (P.fromList [(g, t)])) go x = x -- Note that we keep empty choice nodes, because they mean success. -- | Transformation that tries to make a decision on base as early as -- possible. In nearly all cases, there's a single choice for the base -- package. Also, fixing base early should lead to better error messages. preferBaseGoalChoice :: Tree a -> Tree a preferBaseGoalChoice = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortByKeys preferBase xs) go x = x preferBase :: OpenGoal comp -> OpenGoal comp -> Ordering preferBase (OpenGoal (Simple (Dep (Q _pp pn) _) _) _) _ | unPN pn == "base" = LT preferBase _ (OpenGoal (Simple (Dep (Q _pp pn) _) _) _) | unPN pn == "base" = GT preferBase _ _ = EQ -- | Deal with setup dependencies after regular dependencies, so that we can -- will link setup depencencies against package dependencies when possible deferSetupChoices :: Tree a -> Tree a deferSetupChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortByKeys deferSetup xs) go x = x deferSetup :: OpenGoal comp -> OpenGoal comp -> Ordering deferSetup (OpenGoal (Simple (Dep (Q (Setup _ _) _) _) _) _) _ = GT deferSetup _ (OpenGoal (Simple (Dep (Q (Setup _ _) _) _) _) _) = LT deferSetup _ _ = EQ -- | Transformation that tries to avoid making weak flag choices early. -- Weak flags are trivial flags (not influencing dependencies) or such -- flags that are explicitly declared to be weak in the index. deferWeakFlagChoices :: Tree a -> Tree a deferWeakFlagChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortBy defer xs) go x = x defer :: Tree a -> Tree a -> Ordering defer (FChoice _ _ True _ _) _ = GT defer _ (FChoice _ _ True _ _) = LT defer _ _ = EQ -- Transformation that sorts choice nodes so that -- child nodes with a small branching degree are preferred. As a -- special case, choices with 0 branches will be preferred (as they -- are immediately considered inconsistent), and choices with 1 -- branch will also be preferred (as they don't involve choice). -- -- Only approximates the number of choices in the branches. lpreferEasyGoalChoices :: Tree a -> Tree a lpreferEasyGoalChoices = trav go where go (GoalChoiceF xs) = GoalChoiceF (P.sortBy (comparing lchoices) xs) go x = x -- | Monad used internally in enforceSingleInstanceRestriction type EnforceSIR = Reader (Map (PI PN) QPN) -- | Enforce ghc's single instance restriction -- -- From the solver's perspective, this means that for any package instance -- (that is, package name + package version) there can be at most one qualified -- goal resolving to that instance (there may be other goals _linking_ to that -- instance however). enforceSingleInstanceRestriction :: Tree QGoalReasonChain -> Tree QGoalReasonChain enforceSingleInstanceRestriction = (`runReader` M.empty) . cata go where go :: TreeF QGoalReasonChain (EnforceSIR (Tree QGoalReasonChain)) -> EnforceSIR (Tree QGoalReasonChain) -- We just verify package choices. go (PChoiceF qpn gr cs) = PChoice qpn gr <$> sequence (P.mapWithKey (goP qpn) cs) go _otherwise = innM _otherwise -- The check proper goP :: QPN -> POption -> EnforceSIR (Tree QGoalReasonChain) -> EnforceSIR (Tree QGoalReasonChain) goP qpn@(Q _ pn) (POption i linkedTo) r = do let inst = PI pn i env <- ask case (linkedTo, M.lookup inst env) of (Just _, _) -> -- For linked nodes we don't check anything r (Nothing, Nothing) -> -- Not linked, not already used local (M.insert inst qpn) r (Nothing, Just qpn') -> do -- Not linked, already used. This is an error return $ Fail (S.fromList [P qpn, P qpn']) MultipleInstances
edsko/cabal
cabal-install/Distribution/Client/Dependency/Modular/Preference.hs
bsd-3-clause
16,047
0
21
4,501
3,848
1,981
1,867
219
5
{-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} ----------------------------------------------------------------------------- -- | -- Module : Diagrams.TwoD.Layout.Tree -- Copyright : (c) 2011 Brent Yorgey -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- A collection of methods for laying out various kinds of trees. -- This module is still experimental, and more layout methods will -- probably be added over time. -- -- Laying out a rose tree using a symmetric layout: -- -- > import Data.Tree -- > import Diagrams.TwoD.Layout.Tree -- > -- > t1 = Node 'A' [Node 'B' (map lf "CDE"), Node 'F' [Node 'G' (map lf "HIJ")]] -- > where lf x = Node x [] -- > -- > exampleSymmTree = -- > renderTree ((<> circle 1 # fc white) . text . (:[])) -- > (~~) -- > (symmLayout' (with & slHSep .~ 4 & slVSep .~ 4) t1) -- > # centerXY # pad 1.1 -- -- <<diagrams/src_Diagrams_TwoD_Layout_Tree_exampleSymmTree.svg#diagram=exampleSymmTree&width=300>> -- -- Laying out a rose tree of diagrams, with spacing automatically -- adjusted for the size of the diagrams: -- -- > import Data.Tree -- > import Data.Maybe (fromMaybe) -- > import Diagrams.TwoD.Layout.Tree -- > -- > tD = Node (rect 1 3) -- > [ Node (circle 0.2) [] -- > , Node (hcat . replicate 3 $ circle 1) [] -- > , Node (eqTriangle 5) [] -- > ] -- > -- > exampleSymmTreeWithDs = -- > renderTree id (~~) -- > (symmLayout' (with & slWidth .~ fromMaybe (0,0) . extentX -- > & slHeight .~ fromMaybe (0,0) . extentY) -- > tD) -- > # centerXY # pad 1.1 -- -- <<diagrams/src_Diagrams_TwoD_Layout_Tree_exampleSymmTreeWithDs.svg#diagram=exampleSymmTreeWithDs&width=300>> -- -- Using a variant symmetric layout algorithm specifically for binary trees: -- -- > import Diagrams.TwoD.Layout.Tree -- > -- > drawT = maybe mempty (renderTree (const (circle 0.05 # fc black)) (~~)) -- > . symmLayoutBin' (with & slVSep .~ 0.5) -- > -- > tree500 = drawT t # centerXY # pad 1.1 -- > where t = genTree 500 0.05 -- > -- genTree 500 0.05 randomly generates trees of size 500 +/- 5%, -- > -- definition not shown -- -- <<diagrams/src_Diagrams_TwoD_Layout_Tree_tree500.svg#diagram=tree500&width=400>> -- -- Using force-based layout on a binary tree: -- -- > {-# LANGUAGE NoMonomorphismRestriction #-} -- > import Diagrams.Prelude -- > import Diagrams.TwoD.Layout.Tree -- > -- > t 0 = Empty -- > t n = BNode n (t (n-1)) (t (n-1)) -- > -- > Just t' = uniqueXLayout 1 1 (t 4) -- > -- > fblEx = renderTree (\n -> (text (show n) # fontSizeL 0.5 -- > <> circle 0.3 # fc white)) -- > (~~) -- > (forceLayoutTree t') -- > # centerXY # pad 1.1 -- -- <<diagrams/src_Diagrams_TwoD_Layout_Tree_fblEx.svg#diagram=fblEx&width=300>> -- -- > import Diagrams.Prelude -- > import Diagrams.TwoD.Layout.Tree -- > import Data.Tree -- > -- > t = Node 'A' [Node 'B' [], Node 'C'[], Node 'D'[], Node 'E'[], Node 'F'[], Node 'G'[], Node 'H'[], Node 'I'[] ] -- > -- > example = -- > renderTree (\n -> (text (show n) # fontSizeG 0.5 -- > <> circle 0.5 # fc white)) -- > (~~) (radialLayout t) -- > # centerXY # pad 1.1 -- -- module Diagrams.TwoD.Layout.Tree ( -- * Binary trees -- $BTree BTree(..) , leaf -- * Layout algorithms -- ** Unique-x layout , uniqueXLayout -- ** Radial-Layout , radialLayout -- ** Symmetric layout -- $symmetric , symmLayout , symmLayout' , symmLayoutBin , symmLayoutBin' , SymmLayoutOpts(..), slHSep, slVSep, slWidth, slHeight -- ** Force-directed layout -- $forcedirected , forceLayoutTree , forceLayoutTree' , ForceLayoutTreeOpts(..), forceLayoutOpts, edgeLen, springK, staticK , treeToEnsemble , label , reconstruct -- * Rendering , renderTree , renderTree' ) where import Physics.ForceLayout import Control.Arrow (first, second, (&&&), (***)) import Control.Monad.State import Data.Default import qualified Data.Foldable as F import Data.Function (on) import Data.List (mapAccumL) import qualified Data.Map as M import Data.Maybe import qualified Data.Traversable as T import Data.Tree import Diagrams.Prelude hiding (Empty) import Diagrams.TwoD.Vector() import Diagrams.TwoD.Transform() import Diagrams.TwoD.Types() ------------------------------------------------------------ -- Binary trees ------------------------------------------------------------ -- $BTree -- There is a standard type of rose trees ('Tree') defined in the -- @containers@ package, but there is no standard type for binary -- trees, so we define one here. Note, if you want to draw binary -- trees with data of type @a@ at the leaves, you can use something -- like @BTree (Maybe a)@ with @Nothing@ at internal nodes; -- 'renderTree' lets you specify how to draw each node. -- | Binary trees with data at internal nodes. data BTree a = Empty | BNode a (BTree a) (BTree a) deriving (Eq, Ord, Read, Show, Functor, F.Foldable, T.Traversable) -- | Convenient constructor for leaves. leaf :: a -> BTree a leaf a = BNode a Empty Empty ------------------------------------------------------------ -- Layout algorithms ------------------------------------------------------------ -------------------------------------------------- -- Unique X layout for binary trees. No -- two nodes share the same X coordinate. data Pos = Pos { _level :: Int , _horiz :: Int } deriving (Eq, Show) makeLenses ''Pos pos2Point :: Num n => n -> n -> Pos -> P2 n pos2Point cSep lSep (Pos l h) = p2 (fromIntegral h * cSep, -fromIntegral l * lSep) -- | @uniqueXLayout xSep ySep t@ lays out the binary tree @t@ using a -- simple recursive algorithm with the following properties: -- -- * Every left subtree is completely to the left of its parent, and -- similarly for right subtrees. -- -- * All the nodes at a given depth in the tree have the same -- y-coordinate. The separation distance between levels is given by -- @ySep@. -- -- * Every node has a unique x-coordinate. The separation between -- successive nodes from left to right is given by @xSep@. uniqueXLayout :: Num n => n -> n -> BTree a -> Maybe (Tree (a, P2 n)) uniqueXLayout cSep lSep t = (fmap . fmap . second) (pos2Point cSep lSep) $ evalState (uniqueXLayout' t) (Pos 0 0) where uniqueXLayout' Empty = return Nothing uniqueXLayout' (BNode a l r) = do down l' <- uniqueXLayout' l up p <- mkNode down r' <- uniqueXLayout' r up return $ Just (Node (a,p) (catMaybes [l', r'])) mkNode = get <* (horiz += 1) down = level += 1 up = level -= 1 -------------------------------------------------- -- "Symmetric" layout of rose trees. -- $symmetric -- \"Symmetric\" layout of rose trees, based on the algorithm described in: -- -- Andrew J. Kennedy. /Drawing Trees/, J Func. Prog. 6 (3): 527-534, -- May 1996. -- -- Trees laid out using this algorithm satisfy: -- -- 1. Nodes at a given level are always separated by at least a -- given minimum distance. -- -- 2. Parent nodes are centered with respect to their immediate -- offspring (though /not/ necessarily with respect to the entire -- subtrees under them). -- -- 3. Layout commutes with mirroring: that is, the layout of a given -- tree is the mirror image of the layout of the tree's mirror -- image. Put another way, there is no inherent left or right bias. -- -- 4. Identical subtrees are always rendered identically. Put -- another way, the layout of any subtree is independent of the rest -- of the tree. -- -- 5. The layouts are as narrow as possible while satisfying all the -- above constraints. -- | A tree with /relative/ positioning information. The @n@ -- at each node is the horizontal /offset/ from its parent. type Rel t n a = t (a, n) -- | Shift a RelTree horizontally. moveTree :: Num n => n -> Rel Tree n a -> Rel Tree n a moveTree x' (Node (a, x) ts) = Node (a, x+x') ts -- | An /extent/ is a list of pairs, recording the leftmost and -- rightmost (absolute) horizontal positions of a tree at each -- depth. newtype Extent n = Extent { getExtent :: [(n, n)] } extent :: ([(n, n)] -> [(n, n)]) -> Extent n -> Extent n extent f = Extent . f . getExtent consExtent :: (n, n) -> Extent n -> Extent n consExtent = extent . (:) -- | Shift an extent horizontally. moveExtent :: Num n => n -> Extent n -> Extent n moveExtent x = (extent . map) ((+x) *** (+x)) -- | Reflect an extent about the vertical axis. flipExtent :: Num n => Extent n -> Extent n flipExtent = (extent . map) (\(p,q) -> (-q, -p)) -- | Merge two non-overlapping extents. mergeExtents :: Extent n -> Extent n -> Extent n mergeExtents (Extent e1) (Extent e2) = Extent $ mergeExtents' e1 e2 where mergeExtents' [] qs = qs mergeExtents' ps [] = ps mergeExtents' ((p,_) : ps) ((_,q) : qs) = (p,q) : mergeExtents' ps qs instance Semigroup (Extent n) where (<>) = mergeExtents instance Monoid (Extent n) where mempty = Extent [] mappend = (<>) -- | Determine the amount to shift in order to \"fit\" two extents -- next to one another. The first argument is the separation to -- leave between them. fit :: (Num n, Ord n) => n -> Extent n -> Extent n -> n fit hSep (Extent ps) (Extent qs) = maximum (0 : zipWith (\(_,p) (q,_) -> p - q + hSep) ps qs) -- | Fit a list of subtree extents together using a left-biased -- algorithm. Compute a list of positions (relative to the leftmost -- subtree which is considered to have position 0). fitListL :: (Num n, Ord n) => n -> [Extent n] -> [n] fitListL hSep = snd . mapAccumL fitOne mempty where fitOne acc e = let x = fit hSep acc e in (acc <> moveExtent x e, x) -- | Fit a list of subtree extents together with a right bias. fitListR :: (Num n, Ord n) => n -> [Extent n] -> [n] fitListR hSep = reverse . map negate . fitListL hSep . map flipExtent . reverse -- | Compute a symmetric fitting by averaging the results of left- and -- right-biased fitting. fitList :: (Fractional n, Ord n) => n -> [Extent n] -> [n] fitList hSep = uncurry (zipWith mean) . (fitListL hSep &&& fitListR hSep) where mean x y = (x+y)/2 -- | Options for controlling the symmetric tree layout algorithm. data SymmLayoutOpts n a = SLOpts { _slHSep :: n -- ^ Minimum horizontal -- separation between sibling -- nodes. The default is 1. , _slVSep :: n -- ^ Vertical separation -- between adjacent levels of -- the tree. The default is 1. , _slWidth :: a -> (n, n) -- ^ A function for measuring the horizontal extent (a pair -- of x-coordinates) of an item in the tree. The default -- is @const (0,0)@, that is, the nodes are considered as -- taking up no space, so the centers of the nodes will -- be separated according to the @slHSep@ and @slVSep@. -- However, this can be useful, /e.g./ if you have a tree -- of diagrams of irregular size and want to make sure no -- diagrams overlap. In that case you could use -- @fromMaybe (0,0) . extentX@. , _slHeight :: a -> (n, n) -- ^ A function for measuring the vertical extent of an -- item in the tree. The default is @const (0,0)@. See -- the documentation for 'slWidth' for more information. } makeLenses ''SymmLayoutOpts instance Num n => Default (SymmLayoutOpts n a) where def = SLOpts { _slHSep = 1 , _slVSep = 1 , _slWidth = const (0,0) , _slHeight = const (0,0) } -- | Actual recursive tree layout algorithm, which returns a tree -- layout as well as an extent. symmLayoutR :: (Fractional n, Ord n) => SymmLayoutOpts n a -> Tree a -> (Rel Tree n a, Extent n) symmLayoutR opts (Node a ts) = (rt, ext) where (trees, extents) = unzip (map (symmLayoutR opts) ts) positions = fitList (opts ^. slHSep) extents pTrees = zipWith moveTree positions trees pExtents = zipWith moveExtent positions extents ext = (opts^.slWidth) a `consExtent` mconcat pExtents rt = Node (a, 0) pTrees -- | Symmetric tree layout algorithm specialized to binary trees. -- Returns a tree layout as well as an extent. symmLayoutBinR :: (Fractional n, Ord n) => SymmLayoutOpts n a -> BTree a -> (Maybe (Rel Tree n a), Extent n) symmLayoutBinR _ Empty = (Nothing, mempty) symmLayoutBinR opts (BNode a l r) = (Just rt, ext) where (l', extL) = symmLayoutBinR opts l (r', extR) = symmLayoutBinR opts r positions = case (l', r') of (Nothing, _) -> [0, opts ^. slHSep / 2] (_, Nothing) -> [-(opts ^. slHSep) / 2, 0] _ -> fitList (opts ^. slHSep) [extL, extR] pTrees = catMaybes $ zipWith (fmap . moveTree) positions [l',r'] pExtents = zipWith moveExtent positions [extL, extR] ext = (opts^.slWidth) a `consExtent` mconcat pExtents rt = Node (a, 0) pTrees -- | Run the symmetric rose tree layout algorithm on a given tree, -- resulting in the same tree annotated with node positions. symmLayout' :: (Fractional n, Ord n) => SymmLayoutOpts n a -> Tree a -> Tree (a, P2 n) symmLayout' opts = unRelativize opts origin . fst . symmLayoutR opts -- | Run the symmetric rose tree layout algorithm on a given tree -- using default options, resulting in the same tree annotated with -- node positions. symmLayout :: (Fractional n, Ord n) => Tree a -> Tree (a, P2 n) symmLayout = symmLayout' def -- | Lay out a binary tree using a slight variant of the symmetric -- layout algorithm. In particular, if a node has only a left child -- but no right child (or vice versa), the child will be offset from -- the parent horizontally by half the horizontal separation -- parameter. Note that the result will be @Nothing@ if and only if -- the input tree is @Empty@. symmLayoutBin' :: (Fractional n, Ord n) => SymmLayoutOpts n a -> BTree a -> Maybe (Tree (a,P2 n)) symmLayoutBin' opts = fmap (unRelativize opts origin) . fst . symmLayoutBinR opts -- | Lay out a binary tree using a slight variant of the symmetric -- layout algorithm, using default options. In particular, if a -- node has only a left child but no right child (or vice versa), -- the child will be offset from the parent horizontally by half the -- horizontal separation parameter. Note that the result will be -- @Nothing@ if and only if the input tree is @Empty@. symmLayoutBin :: (Fractional n, Ord n) => BTree a -> Maybe (Tree (a,P2 n)) symmLayoutBin = symmLayoutBin' def -- | Given a fixed location for the root, turn a tree with -- \"relative\" positioning into one with absolute locations -- associated to all the nodes. unRelativize :: (Num n, Ord n) => SymmLayoutOpts n a -> P2 n -> Rel Tree n a -> Tree (a, P2 n) unRelativize opts curPt (Node (a,hOffs) ts) = Node (a, rootPt) (map (unRelativize opts (rootPt .+^ (vOffs *^ unit_Y))) ts) where rootPt = curPt .+^ (hOffs *^ unitX) vOffs = - fst ((opts^.slHeight) a) + (maximum . map (snd . (opts^.slHeight) . fst . rootLabel) $ ts) + (opts ^. slVSep) -------------------------------------------------- -- Force-directed layout of rose trees -- $forcedirected -- Force-directed layout of rose trees. data ForceLayoutTreeOpts n = FLTOpts { _forceLayoutOpts :: ForceLayoutOpts n -- ^ Options to the force layout simulator, including damping. , _edgeLen :: n -- ^ How long edges should be, ideally. -- This will be the resting length for -- the springs. , _springK :: n -- ^ Spring constant. The -- bigger the constant, -- the more the edges -- push/pull towards their -- resting length. , _staticK :: n -- ^ Coulomb constant. The -- bigger the constant, the -- more sibling nodes repel -- each other. } makeLenses ''ForceLayoutTreeOpts instance Floating n => Default (ForceLayoutTreeOpts n) where def = FLTOpts { _forceLayoutOpts = def , _edgeLen = sqrt 2 , _springK = 0.05 , _staticK = 0.1 } -- | Assign unique ID numbers to the nodes of a tree, and generate an -- 'Ensemble' suitable for simulating in order to do force-directed -- layout of the tree. In particular, -- -- * edges are modeled as springs -- -- * nodes are modeled as point charges -- -- * nodes are constrained to keep the same y-coordinate. -- -- The input to @treeToEnsemble@ could be a tree already laid out by -- some other method, such as 'uniqueXLayout'. treeToEnsemble :: forall a n. Floating n => ForceLayoutTreeOpts n -> Tree (a, P2 n) -> (Tree (a, PID), Ensemble V2 n) treeToEnsemble opts t = ( fmap (first fst) lt , Ensemble [ (edges, \pt1 pt2 -> project unitX (hookeForce (opts ^. springK) (opts ^. edgeLen) pt1 pt2)) , (sibs, \pt1 pt2 -> project unitX (coulombForce (opts ^. staticK) pt1 pt2)) ] particleMap ) where lt :: Tree ((a,P2 n), PID) lt = label t particleMap :: M.Map PID (Particle V2 n) particleMap = M.fromList . map (second initParticle) . F.toList . fmap (swap . first snd) $ lt swap (x,y) = (y,x) edges, sibs :: [Edge] edges = extractEdges (fmap snd lt) sibs = extractSibs [fmap snd lt] extractEdges :: Tree PID -> [Edge] extractEdges (Node i cs) = map (((,) i) . rootLabel) cs ++ concatMap extractEdges cs extractSibs :: Forest PID -> [Edge] extractSibs [] = [] extractSibs ts = (\is -> zip is (tail is)) (map rootLabel ts) ++ extractSibs (concatMap subForest ts) -- sz = ala Sum foldMap . fmap (const 1) $ t -- sibs = [(x,y) | x <- [0..sz-2], y <- [x+1 .. sz-1]] -- | Assign unique IDs to every node in a tree (or other traversable structure). label :: (T.Traversable t) => t a -> t (a, PID) label = flip evalState 0 . T.mapM (\a -> get >>= \i -> modify (+1) >> return (a,i)) -- | Reconstruct a tree (or any traversable structure) from an -- 'Ensemble', given unique identifier annotations matching the -- identifiers used in the 'Ensemble'. reconstruct :: (Functor t, Num n) => Ensemble V2 n -> t (a, PID) -> t (a, P2 n) reconstruct e = (fmap . second) (fromMaybe origin . fmap (view pos) . flip M.lookup (e^.particles)) -- | Force-directed layout of rose trees, with default parameters (for -- more options, see 'forceLayoutTree''). In particular, -- -- * edges are modeled as springs -- -- * nodes are modeled as point charges -- -- * nodes are constrained to keep the same y-coordinate. -- -- The input could be a tree already laid out by some other method, -- such as 'uniqueXLayout'. forceLayoutTree :: (Floating n, Ord n) => Tree (a, P2 n) -> Tree (a, P2 n) forceLayoutTree = forceLayoutTree' def -- | Force-directed layout of rose trees, with configurable parameters. forceLayoutTree' :: (Floating n, Ord n) => ForceLayoutTreeOpts n -> Tree (a, P2 n) -> Tree (a, P2 n) forceLayoutTree' opts t = reconstruct (forceLayout (opts^.forceLayoutOpts) e) ti where (ti, e) = treeToEnsemble opts t -------------------------------------------------------------------- -- Radial Layout Implementation -- -- alpha beta defines annulus wedge of a vertex -- d is the depth of any vertex from root -- k is #leaves of root and lambda is #leaves of vertex -- weight assigns the length of radius wrt the number of -- number of children to avoid node overlapping -- Extension of Algotihm 1, Page 18 http://www.cs.cmu.edu/~pavlo/static/papers/APavloThesis032006.pdf -- Example: https://drive.google.com/file/d/0B3el1oMKFsOIVGVRYzJzWGwzWDA/view ------------------------------------------------------------------- radialLayout :: Tree a -> Tree (a, P2 Double) radialLayout t = finalTree $ radialLayout' 0 pi 0 (countLeaves $ decorateDepth 0 t) (weight t) (decorateDepth 0 t) radialLayout' :: Double -> Double -> Double -> Int -> Double -> Tree (a, P2 Double, Int) -> Tree (a, P2 Double, Int) radialLayout' alpha beta theta k w (Node (a, pt, d) ts) = Node (a, pt, d) (assignPos alpha beta theta k w ts) assignPos :: Double -> Double -> Double -> Int -> Double -> [Tree (a, P2 Double, Int)] -> [Tree (a, P2 Double, Int)] assignPos _ _ _ _ _ [] = [] assignPos alpha beta theta k w (Node (a, pt, d) ts1:ts2) = Node (a, pt2, d) (assignPos theta u theta lambda w ts1) : assignPos alpha beta u k w ts2 where lambda = countLeaves (Node (a, pt, d) ts1) u = theta + (beta - alpha) * fromIntegral lambda / fromIntegral k pt2 = mkP2 (w * fromIntegral d * cos (theta + u)/2) (w * fromIntegral d * sin (theta + u)/2) decorateDepth:: Int -> Tree a -> Tree (a, P2 Double, Int) decorateDepth d (Node a ts) = Node (a, mkP2 0 0, d) $ map (decorateDepth (d+1)) ts countLeaves :: Tree (a, P2 Double, Int) -> Int countLeaves (Node _ []) = 1 countLeaves (Node _ ts) = sum (map countLeaves ts) weight :: Tree a -> Double weight t = maximum $ map (((\ x -> fromIntegral x / 2) . length) . map rootLabel) (takeWhile (not . null) $ iterate (concatMap subForest) [t]) finalTree :: Tree (a, P2 Double, Int) -> Tree (a, P2 Double) finalTree (Node (a, pt, _) ts) = Node (a, pt) $ map finalTree ts ------------------------------------------------------------ -- Rendering ------------------------------------------------------------ -- | Draw a tree annotated with node positions, given functions -- specifying how to draw nodes and edges. renderTree :: (Monoid' m, Floating n, Ord n) => (a -> QDiagram b V2 n m) -> (P2 n -> P2 n -> QDiagram b V2 n m) -> Tree (a, P2 n) -> QDiagram b V2 n m renderTree n e = renderTree' n (e `on` snd) -- | Draw a tree annotated with node positions, given functions -- specifying how to draw nodes and edges. Unlike 'renderTree', -- this version gives the edge-drawing function access to the actual -- values stored at the nodes rather than just their positions. renderTree' :: (Monoid' m, Floating n, Ord n) => (a -> QDiagram b V2 n m) -> ((a,P2 n) -> (a,P2 n) -> QDiagram b V2 n m) -> Tree (a, P2 n) -> QDiagram b V2 n m renderTree' renderNode renderEdge = alignT . centerX . renderTreeR where renderTreeR (Node (a,p) cs) = renderNode a # moveTo p <> mconcat (map renderTreeR cs) <> mconcat (map (renderEdge (a,p) . rootLabel) cs) -- > -- Critical size-limited Boltzmann generator for binary trees (used in example) -- > -- > import Control.Applicative -- > import Control.Lens hiding (( # )) -- > import Control.Monad.Random -- > import Control.Monad.Reader -- > import Control.Monad.State -- > import Control.Monad.Trans.Maybe -- > -- > genTreeCrit :: ReaderT Int (StateT Int (MaybeT (Rand StdGen))) (BTree ()) -- > genTreeCrit = do -- > r <- getRandom -- > if r <= (1/2 :: Double) -- > then return Empty -- > else atom >> (BNode () <$> genTreeCrit <*> genTreeCrit) -- > -- > atom :: ReaderT Int (StateT Int (MaybeT (Rand StdGen))) () -- > atom = do -- > targetSize <- ask -- > curSize <- get -- > when (curSize >= targetSize) mzero -- > put (curSize + 1) -- > -- > genOneTree :: Int -> Int -> Double -> Maybe (BTree ()) -- > genOneTree seed size eps = -- > case mt of -- > Nothing -> Nothing -- > Just (t,sz) -> if sz >= minSz then Just t else Nothing -- > -- > where -- > g = mkStdGen seed -- > sizeWiggle = floor $ fromIntegral size * eps -- > maxSz = size + sizeWiggle -- > minSz = size - sizeWiggle -- > mt = (evalRand ?? g) . runMaybeT . (runStateT ?? 0) . (runReaderT ?? maxSz) -- > $ genTreeCrit -- > -- > genTree' :: Int -> Int -> Double -> BTree () -- > genTree' seed size eps = -- > case (genOneTree seed size eps) of -- > Nothing -> genTree' (seed+1) size eps -- > Just t -> t -- > -- > genTree :: Int -> Double -> BTree () -- > genTree = genTree' 0
tejon/diagrams-contrib
src/Diagrams/TwoD/Layout/Tree.hs
bsd-3-clause
25,728
6
18
7,108
5,114
2,865
2,249
237
3
-- | A term index to accelerate matching. -- An index is a multimap from terms to arbitrary values. -- -- The type of query supported is: given a search term, find all keys such that -- the search term is an instance of the key, and return the corresponding -- values. {-# LANGUAGE BangPatterns, RecordWildCards, OverloadedStrings, FlexibleContexts, CPP #-} -- We get some bogus warnings because of pattern synonyms. {-# OPTIONS_GHC -fno-warn-overlapping-patterns #-} {-# OPTIONS_GHC -O2 -fmax-worker-args=100 #-} #ifdef USE_LLVM {-# OPTIONS_GHC -fllvm #-} #endif module Twee.Index( Index, empty, null, singleton, insert, delete, lookup, matches, approxMatches, elems, fromListWith) where import Prelude hiding (null, lookup) import Data.Maybe import Twee.Base hiding (var, fun, empty, singleton, prefix, funs, lookupList, lookup) import qualified Twee.Term as Term import Data.DynamicArray import qualified Data.List as List -- The term index in this module is an _imperfect discrimination tree_. -- This is a trie whose keys are terms, represented as flat lists of symbols, -- but where all variables have been replaced by a single don't-care variable '_'. -- That is, the edges of the trie can be either function symbols or '_'. -- To insert a key-value pair into the discrimination tree, we first replace all -- variables in the key with '_', and then do ordinary trie insertion. -- -- Lookup maintains a term list, which is initially the search term. -- It proceeds down the trie, consuming bits of the term list as it goes. -- -- If the current trie node has an edge for a function symbol f, and the term at -- the head of the term list is f(t1..tn), we can follow the f edge. We then -- delete f from the term list, but keep t1..tn at the front of the term list. -- (In other words we delete only the symbol f and not its arguments.) -- -- If the current trie node has an edge for '_', we can always follow that edge. -- We then remove the head term from the term list, as the '_' represents a -- variable that should match that whole term. -- -- If the term list ever becomes empty, we have a possible match. We then -- do matching on the values stored at the current node to see if they are -- genuine matches. -- -- Often there are two edges we can follow (function symbol and '_'), and in -- that case the algorithm uses backtracking. -- | A term index: a multimap from @'Term' f@ to @a@. data Index f a = -- A non-empty index. Index { -- Size of smallest term in index. size :: {-# UNPACK #-} !Int, -- When all keys in the index start with the same sequence of symbols, we -- compress them into this prefix; the "fun" and "var" fields below refer to -- the first symbol _after_ the prefix, and the "here" field contains values -- whose remaining key is exactly this prefix. prefix :: {-# UNPACK #-} !(TermList f), -- The values that are found at this node. here :: [a], -- Function symbol edges. -- The array is indexed by function number. fun :: {-# UNPACK #-} !(Array (Index f a)), -- Variable edge. var :: !(Index f a) } | -- An empty index. Nil deriving Show instance Default (Index f a) where def = Nil -- To get predictable performance, the lookup function uses an explicit stack -- instead of a lazy list to control backtracking. data Stack f a = -- A normal stack frame: records the current index node and term. Frame { frame_term :: {-# UNPACK #-} !(TermList f), frame_index :: !(Index f a), frame_rest :: !(Stack f a) } -- A stack frame which is used when we have found a match. | Yield { yield_found :: [a], yield_rest :: !(Stack f a) } -- End of stack. | Stop -- Turn a stack into a list of results. {-# SCC run #-} run :: Stack f a -> [a] run Stop = [] run Frame{..} = run (step frame_term frame_index frame_rest) run Yield{..} = yield_found ++ run yield_rest -- Execute a single stack frame. {-# INLINE step #-} {-# SCC step #-} step :: TermList f -> Index f a -> Stack f a -> Stack f a step !_ _ _ | False = undefined step t idx rest = case idx of Nil -> rest Index{..} | lenList t < size -> rest -- the search term is smaller than any in this index | otherwise -> pref t prefix here fun var rest -- The main work of 'step' goes on here. -- It is carefully tweaked to generate nice code, -- in particular casing on each term list exactly once. pref :: TermList f -> TermList f -> [a] -> Array (Index f a) -> Index f a -> Stack f a -> Stack f a pref !_ !_ _ !_ !_ _ | False = undefined pref search prefix here fun var rest = case search of ConsSym{hd = t, tl = ts, rest = ts1} -> case prefix of ConsSym{hd = u, tl = us, rest = us1} -> -- Check the search term against the prefix. case (t, u) of (_, Var _) -> -- Prefix contains a variable - if there is a match, the -- variable will be bound to t. pref ts us here fun var rest (App f _, App g _) | f == g -> -- Term and prefix start with same symbol, chop them off. pref ts1 us1 here fun var rest _ -> -- Term and prefix don't match. rest _ -> -- We've exhausted the prefix, so let's descend into the tree. -- Seems to work better to explore the function node first. case t of App f _ -> case (fun ! fun_id f, var) of (Nil, Nil) -> rest (Nil, Index{}) -> step ts var rest (idx, Nil) -> step ts1 idx rest (idx, Index{}) -> step ts1 idx (Frame ts var rest) _ -> case var of Nil -> rest _ -> step ts var rest Empty -> case prefix of Empty -> -- The search term matches this node. case here of [] -> rest _ -> Yield here rest _ -> -- We've run out of search term - it doesn't match this node. rest -- | An empty index. empty :: Index f a empty = Nil -- | Is the index empty? null :: Index f a -> Bool null Nil = True null _ = False -- | An index with one entry. singleton :: Term f -> a -> Index f a singleton !t x = singletonList (Term.singleton t) x -- An index with one entry, giving a termlist instead of a term. {-# INLINE singletonList #-} singletonList :: TermList f -> a -> Index f a singletonList t x = Index 0 t [x] newArray Nil -- | Insert an entry into the index. {-# SCC insert #-} insert :: Term f -> a -> Index f a -> Index f a insert !t x !idx = aux (Term.singleton t) idx where aux t Nil = singletonList t x aux (Cons t ts) idx@Index{prefix = Cons u us} | skeleton t == skeleton u = withPrefix t (aux ts idx{prefix = us}) aux (ConsSym{hd = t, rest = ts}) idx@Index{prefix = ConsSym{hd = u, rest = us}} | t `sameSymbolAs` u = withPrefix (build (atom t)) (aux ts idx{prefix = us}) aux t idx@Index{prefix = Cons{}} = aux t (expand idx) aux Empty idx = idx { size = 0, here = x:here idx } aux t@ConsSym{hd = App f _, rest = u} idx = idx { size = lenList t `min` size idx, fun = update (fun_id f) idx' (fun idx) } where idx' = aux u (fun idx ! fun_id f) aux t@ConsSym{hd = Var _, rest = u} idx = idx { size = lenList t `min` size idx, var = aux u (var idx) } Var _ `sameSymbolAs` Var _ = True App f _ `sameSymbolAs` App g _ = f == g _ `sameSymbolAs` _ = False skeleton t = build (subst (const (Term.var (V 0))) t) atom (Var x) = Term.var x atom (App f _) = con f -- Add a prefix to an index. -- Does not update the size field. withPrefix :: Term f -> Index f a -> Index f a withPrefix _ Nil = Nil withPrefix t idx@Index{..} = idx{prefix = buildList (builder t `mappend` builder prefix)} -- Take an index with a prefix and pull out the first symbol of the prefix, -- giving an index which doesn't start with a prefix. {-# INLINE expand #-} expand :: Index f a -> Index f a expand idx@Index{size = size, prefix = ConsSym{hd = t, rest = ts}} = case t of Var _ -> Index { size = size, prefix = Term.empty, here = [], fun = newArray, var = idx { prefix = ts, size = size - 1 } } App f _ -> Index { size = size, prefix = Term.empty, here = [], fun = update (fun_id f) idx { prefix = ts, size = size - 1 } newArray, var = Nil } -- | Delete an entry from the index. {-# INLINEABLE delete #-} {-# SCC delete #-} delete :: Eq a => Term f -> a -> Index f a -> Index f a delete !t x !idx = aux (Term.singleton t) idx where aux _ Nil = Nil aux (ConsSym{rest = ts}) idx@Index{prefix = u@ConsSym{rest = us}} = -- The prefix must match, since the term ought to be in the index -- (which is checked in the Empty case below). case aux ts idx{prefix = us} of Nil -> Nil idx -> idx{prefix = u} aux _ idx@Index{prefix = Cons{}} = idx aux Empty idx | x `List.elem` here idx = idx { here = List.delete x (here idx) } | otherwise = error "deleted term not found in index" aux ConsSym{hd = App f _, rest = t} idx = idx { fun = update (fun_id f) (aux t (fun idx ! fun_id f)) (fun idx) } aux ConsSym{hd = Var _, rest = t} idx = idx { var = aux t (var idx) } -- | Look up a term in the index. Finds all key-value such that the search term -- is an instance of the key, and returns an instance of the the value which -- makes the search term exactly equal to the key. {-# INLINE lookup #-} lookup :: (Has a b, Symbolic b, Has b (TermOf b)) => TermOf b -> Index (ConstantOf b) a -> [b] lookup t idx = lookupList (Term.singleton t) idx {-# INLINEABLE lookupList #-} lookupList :: (Has a b, Symbolic b, Has b (TermOf b)) => TermListOf b -> Index (ConstantOf b) a -> [b] lookupList t idx = [ subst sub x | x <- List.map the (approxMatchesList t idx), sub <- maybeToList (matchList (Term.singleton (the x)) t)] -- | Look up a term in the index. Like 'lookup', but returns the exact value -- that was inserted into the index, not an instance. Also returns a substitution -- which when applied to the value gives you the matching instance. {-# INLINE matches #-} matches :: Has a (Term f) => Term f -> Index f a -> [(Subst f, a)] matches t idx = matchesList (Term.singleton t) idx {-# INLINEABLE matchesList #-} matchesList :: Has a (Term f) => TermList f -> Index f a -> [(Subst f, a)] matchesList t idx = [ (sub, x) | x <- approxMatchesList t idx, sub <- maybeToList (matchList (Term.singleton (the x)) t)] -- | Look up a term in the index, possibly returning spurious extra results. {-# INLINE approxMatches #-} approxMatches :: Term f -> Index f a -> [a] approxMatches t idx = approxMatchesList (Term.singleton t) idx {-# SCC approxMatchesList #-} approxMatchesList :: TermList f -> Index f a -> [a] approxMatchesList t idx = run (Frame t idx Stop) -- | Return all elements of the index. elems :: Index f a -> [a] elems Nil = [] elems idx = here idx ++ concatMap elems (map snd (toList (fun idx))) ++ elems (var idx) -- | Create an index from a list of items fromListWith :: (a -> Term f) -> [a] -> Index f a fromListWith f xs = foldr (\x -> insert (f x) x) empty xs
nick8325/kbc
src/Twee/Index.hs
bsd-3-clause
11,519
0
19
3,203
3,123
1,665
1,458
-1
-1
module Prime ( primes, factorize ) where primes = 2 : oddPrimes oddPrimes = 3 : primeGen 5 primeGen q = if (q ==) . fst . head $ factorize' q oddPrimes then q : primeGen (q + 2) else primeGen (q + 2) factorize n = factorize' n primes factorize' 1 _ = [] factorize' n [] = [(n, 1)] factorize' n (p:ps) = let (q, k, done) = divideOut n p 0 rest = if done then [] else ps in if k > 0 then (p, k) : factorize' q rest else factorize' q rest divideOut n p k = let (q, r) = quotRem n p in if r == 0 then divideOut q p (k + 1) else (n, k, p > q)
cullina/Extractor
src/Prime.hs
bsd-3-clause
659
0
10
249
306
163
143
24
3
module Main where import Graphics.ChalkBoard as CB import Control.Applicative (pure) main = startChalkBoard [BoardSize (400) (400)] animMain animMain cb = do --Set up the animations let triangle345 = pure $ choose (alpha black) transparent <$> triangle (0,0) (0,-0.3) (0.4,-0.3) :: Active (Board (RGBA->RGBA)) moveSq3s = [ taking 0.5 (moveSq3 curSq i) | (curSq,i) <- Prelude.zip square3s [0..] ] square3s = [ scale 0.3 $ scale (1/3) $ choose (withAlpha 0.6 red) transparent <$> square | (x,y) <- combinations [0..2] [0..2] ] moveSq4s = [ taking 0.3 (moveSq4 curSq i) | (curSq,i) <- Prelude.zip square4s [0..] ] square4s = [ scale 0.4 $ scale (1/4) $ choose (withAlpha 0.6 blue) transparent <$> square | (x,y) <- combinations [0..3] [0..3] ] moveRec4s = [ taking 1 (moveRec4 curSq i) | (curSq,i) <- Prelude.zip rectangle4s [0..] ] rectangle4s = [ scale 0.4 $ scaleXY (1/4,1) $ choose (withAlpha 0.6 blue) transparent <$> square | (x,y) <- combinations [0..1] [0..1] ] -- could use something instead of combinations or actually do something with them? -- could start square moves from their start locations and then move from 0,0 to final location? -- could potentially use UI instead as an example, not that it would be more helpful --Determine the ordering/timing to create different animations let normalAnim = for 6 $ (flicker moveSq4s) `over` (flicker moveSq3s) `over` triangle345 allAtOnce = for 6 $ (taking 1 $ overList moveSq4s) `over` (taking 1 $ overList moveSq3s) `over` triangle345 redThenBlue = for 8 $ flicker $ [taking 0 triangle345] ++ (map (taking 0.3) moveSq3s) ++ moveSq4s blueThenRed = for 8 $ flicker $ [taking 0 triangle345] ++ moveSq4s ++ (map (taking 0.3) moveSq3s) rectangles = for 6 $ (flicker moveRec4s) `over` (flicker moveSq3s) `over` triangle345 rectsAtOnce = for 6 $ (taking 1 $ overList moveRec4s) `over` (taking 1 $ overList moveSq3s) `over` triangle345 combineSome = for 6 $ (flicker [(overList (take 2 (drop i moveSq4s))) | i <- [0,2..14] ]) `over` (flicker moveSq3s) `over` triangle345 moveSq4sSep = [ mvActive (0.15*i) moveSq4 | (moveSq4,i) <- Prelude.zip moveSq4s [0..] ] moveSq3sSep = [ mvActive (0.25*i) moveSq3 | (moveSq3,i) <- Prelude.zip moveSq3s [0..] ] allWithDelays = for 4 $ (overList moveSq4sSep) `over` (overList moveSq3sSep) `over` triangle345 --Pick the animation you would like to see and turn it into a play object playObj <- byFrame 29.97 allWithDelays --playObj <- realTime active --Run the animation let loop = do mbScene <- play playObj case mbScene of Just scene -> do let scaledScene = scale 0.8 $ move (-0.2,0.15) $ scene drawChalkBoard cb $ unAlphaBoard (boardOf white) scaledScene loop Nothing -> return () loop exitChalkBoard cb overList (b:[]) = b overList (b:bs) = b `over` (overList bs) combinations (a:as) (b:bs) = (a,b):((combinations as (b:bs)) ++ (combinationsR (a:as) bs)) combinations _ _ = [] combinationsR (a:as) (b:bs) = (a,b):(combinationsR (a:as) bs) combinationsR _ _ = [] moveSq3 :: Board a -> Int -> Active (Board a) moveSq3 sq i = moveBrd sq (pi/2-atan(4/3)) (x*0.1-0.25,y*0.1-0.25) (x*0.1+0.15,y*0.1+0.15) where x = fromIntegral (i `mod` 3) y = fromIntegral (i `div` 3) moveSq4 :: Board a -> Int -> Active (Board a) moveSq4 sq i = moveBrd sq (pi/2-atan(4/3)) (x*0.1+0.05,-y*0.1-0.35) ((fx i)*0.1+0.05,(fy i)*0.1+0.05) where x = fromIntegral (i `mod` 4) y = fromIntegral (i `div` 4) fx index | index < 5 = fromIntegral index | index > 10 = fromIntegral (index-11) | odd index = 0 | even index = 4 fy index | index < 5 = 0 | index < 7 = 1 | index < 9 = 2 | index < 11 = 3 | index >= 11 = 4 moveRec4 :: Board a -> Int -> Active (Board a) moveRec4 rec i = case num of 0 -> moveBrd rec angle (num*0.1+0.05,0.1-0.6) (0.05,0.2) 1 -> moveBrd rec (angle+pi/2) (num*0.1+0.05,0.1-0.6) (-0.05,0.2+0.1) 2 -> moveBrd rec angle (num*0.1+0.05,0.1-0.6) (0.05+0.4,0.2+0.1) 3 -> moveBrd rec (angle+pi/2) (num*0.1+0.05,0.1-0.6) (-0.05-0.4,0.2) where angle = (pi/2-atan(4/3)) num = fromIntegral i moveBrd :: Board a -> Radian -> Point -> Point -> Active (Board a) moveBrd brd rot (sx,sy) (ex,ey) = mkActive brd activeBoth where activeMove ui = move (ui*(ex-sx)+sx,ui*(ey-sy)+sy) activeRot ui = rotate (ui * rot) activeBoth ui board = (activeRot ui) $ (activeMove ui) board mkActive :: (Board a) -> (UI -> Board a -> Board a) -> Active (Board a) mkActive brd fn = fmap (\ ui -> (fn ui) $ brd) age {- mkActive, color, overList, unfilledPolygon?, moveBrd/rotBrd/scaleBrd/etc? moveToOrigin? or a localRotate? or a moveToPosition? compiler optimizations would be great since we are often manipulating the same board over and over color :: O RGB -> Active (Board UI) -> Active (Board (RGBA -> RGBA)) color rgb = fmap ((\ ui -> withAlpha ui rgb) .$) --}
andygill/chalkboard2
tests/triAnim/Main.hs
bsd-3-clause
5,591
8
23
1,663
2,233
1,167
1,066
71
4
module B.Shake.Timing(resetTimings, addTiming, printTimings) where import Control.Arrow import Data.IORef import Data.Time import System.IO.Unsafe import Numeric {-# NOINLINE timings #-} timings :: IORef [(UTCTime, String)] -- number of times called, newest first timings = unsafePerformIO $ newIORef [] resetTimings :: IO () resetTimings = do now <- getCurrentTime writeIORef timings [(now, "Start")] -- | Print all withTiming information and clear the information. printTimings :: IO () printTimings = do now <- getCurrentTime old <- atomicModifyIORef timings $ \ts -> ([(now, "Start")], ts) putStr $ unlines $ showTimings now $ reverse old addTiming :: String -> IO () addTiming msg = do now <- getCurrentTime atomicModifyIORef timings $ \ts -> ((now,msg):ts, ()) showTimings :: UTCTime -> [(UTCTime, String)] -> [String] showTimings _ [] = [] showTimings stop times = showGap $ [(a ++ " ", showDP 3 b ++ "s " ++ showPerc b ++ " " ++ progress b) | (a,b) <- xs] ++ [("Total", showDP 3 sm ++ "s " ++ showPerc sm ++ " " ++ replicate 25 ' ')] where a // b = if b == 0 then 0 else a / b showPerc x = let s = show $ floor $ x * 100 // sm in replicate (3 - length s) ' ' ++ s ++ "%" progress x = let i = floor $ x * 25 // mx in replicate i '=' ++ replicate (25-i) ' ' mx = maximum $ map snd xs sm = sum $ map snd xs xs = [ (name, fromRational $ toRational $ stop `diffUTCTime` start) | ((start, name), stop) <- zip times $ map fst (drop 1 times) ++ [stop]] showGap :: [(String,String)] -> [String] showGap xs = [a ++ replicate (n - length a - length b) ' ' ++ b | (a,b) <- xs] where n = maximum [length a + length b | (a,b) <- xs] showDP :: Int -> Double -> String showDP n x = a ++ "." ++ b ++ replicate (n - length b) '0' where (a,b) = second (drop 1) $ break (== '.') $ showFFloat (Just n) x ""
strager/b-shake
B/Shake/Timing.hs
bsd-3-clause
1,924
0
14
483
859
451
408
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} -- | Features list. module HL.V.Home.Features where import HL.V hiding (list) -- | Features section explains what's notable about Haskell as a -- language. features :: Html features = div ! class_ "features" $ (container (do h1 "Features" row (do span6 purefunc span6 statically) row (do span6 concurrent span6 inference) row (do span6 lazy span6 packages))) -- TODO: Features: tart up the wording. -- -- Note: these below are me writing out the facts, for myself, rather -- than putting in a way that newbies will understand. The intention -- is to put *something* here and then rewrite the bits below to be -- more "salesy" aand friendly to people who have no idea what's so -- special about "IO" from any other form of programming, or what a -- parallel GC is or unification. purefunc :: Html purefunc = do h2 "Purely functional" p "Every function in Haskell is pure. They are functions in the mathematical sense. \ \Even side-effecting IO operations are but a description of what to do, produced \ \by pure code. There are no statements or instructions, only expressions. Which \ \cannot mutate variables, local or global, or access state like time or random \ \numbers." p (a "View examples") statically :: Html statically = do h2 "Statically typed" p "Every expression in Haskell has a type which is determined at compile time. \ \All the types composed together by function application have to match up. If \ \they don't, the program will be rejected by the compiler. Types become not \ \only a form of guarantee, but a language for expressing the construction \ \of programs." p (a "View examples") concurrent :: Html concurrent = do h2 "Concurrent" p "Haskell lends itself well to concurrent programming due to its explicit \ \handling of effects. Its flagship compiler, GHC, comes with a high-\ \performance parallel garbage collector and light-weight concurrency \ \library containing a number of useful concurrency primitives and \ \abstractions." p (a "View examples") inference :: Html inference = do h2 "Type inference" p "You don't have to explicitly write out every type in a Haskell program. \ \Types will be inferred by unifying every type bidirectionally. But you \ \can write out types, or ask the compiler to write them for you, for \ \handy documentation." p (a "View examples") lazy :: Html lazy = do h2 "Lazy" p "Functions don't evaluate their arguments. This means that programs \ \can compose together very well, with the ability to write control \ \constructs with normal functions, and, thanks also to the purity \ \of Haskell, to fuse chains of functions together for high \ \performance." p (a "View examples") packages :: Html packages = do h2 "Packages" p "Open source contribution to Haskell is very active with a wide range \ \of packages available on the public package servers." p (a "View examples")
chrisdone/hl
src/HL/V/Home/Features.hs
bsd-3-clause
3,250
0
15
830
335
158
177
45
1
module Compiler.Util where import Data.Char import LLVM.AST import LLVM.AST.AddrSpace import qualified Language.MiniStg as STG int :: Type int = IntegerType 64 intptr :: Type intptr = PointerType int (AddrSpace 0) intintfunc :: Type intintfunc = FunctionType int [int] False intintfptr :: Type intintfptr = PointerType intintfunc (AddrSpace 0) -- | referer tag, refer to an evaled value -- either a direct literal or an indirect construction evalLitTag :: Integer evalLitTag = 0 -- | referer tag, refer to an evaled construction (directly) evalConTag :: Integer evalConTag = 2 -- | referer tag, refer to an unevaled primitive expression unevalPrimTag :: Integer unevalPrimTag = 1 -- | referer tag, refer to an unevaled function application unevalFuncTag :: Integer unevalFuncTag = 3 -- | referee tag, it's unvaluated, either -- a function application or a primitive operation. funcTag :: Integer funcTag = 1 -- | referee tag, it's an evaluated literal litTag :: Integer litTag = 0 -- | referee tag, it's an indirect construction pointer indTag :: Integer indTag = 2 -- | encode characters into numbers encChar :: Char -> Integer encChar c | '0' <= c && c <= '9' = fromIntegral $ ord c - ord '0' encChar c | 'A' <= c && c <= 'Z' = fromIntegral $ ord c - ord 'A' + 10 encChar c | 'a' <= c && c <= 'z' = fromIntegral $ ord c - ord 'a' + 36 encChar '_' = 62 encChar '#' = 63 encChar _ = error "Syntax Error: Invalid character" -- | encode operations into numbers encOp :: STG.PrimOp -> Integer encOp p = case p of STG.Add -> 0 STG.Sub -> 1 STG.Mul -> 2 STG.Div -> 3 STG.Mod -> 4 _ -> error "Error: primitive function not supported" -- | decode operations from numbers decOp :: Integer -> STG.PrimOp decOp n = case n of 0 -> STG.Add 1 -> STG.Sub 2 -> STG.Mul 3 -> STG.Div 4 -> STG.Mod _ -> error "Error: primitive function not supported" -- | encode a constructor into a number encConstr :: String -> Integer -> Integer encConstr s l = foldr (\ch i -> encChar ch + i * 64) 0 s * 8 + (fromIntegral l * 2)
Neuromancer42/ministgwasm
src/Compiler/Util.hs
bsd-3-clause
2,073
0
12
447
565
298
267
57
6
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Cheapskate.Terminal ( -- * Rendering markdown to the terminal prettyPrint , renderTerminal , renderIO -- * Options , PrettyPrintOptions(..) , def , renderIOWith -- * Pure rendering , renderPureWith -- * Internal functions and implementation comments , renderBlock , renderBlockPure , renderInline ) where import Cheapskate import Control.Monad (foldM) import Data.Default import Data.Foldable (toList) import Data.Maybe (isJust) import Data.Monoid import Data.String (IsString) import qualified Data.Text as Text (Text, lines, pack, unpack) import qualified Data.Text.Lazy as Text.Lazy import Data.Text.Lazy.Builder import qualified Data.Text.Lazy.IO as Text.Lazy import GHC.Int import Language.Haskell.HsColour import Language.Haskell.HsColour.Colourise (defaultColourPrefs, readColourPrefs) import System.Console.ANSI import System.Console.Terminal.Size (Window (..), size) import System.Directory import Text.Highlighting.Pygments -- | -- An alias for 'renderTerminal' data PrettyPrintOptions = PrettyPrintOptions { prettyPrintWidth :: Int64 , prettyPrintColourPrefs :: ColourPrefs , prettyPrintHasPygments :: Bool } instance Default PrettyPrintOptions where def = PrettyPrintOptions { prettyPrintColourPrefs = defaultColourPrefs , prettyPrintWidth = 80 , prettyPrintHasPygments = False } -- | -- An alias for 'renderTerminal' prettyPrint :: Doc -> IO () prettyPrint = renderTerminal -- | -- Prints a markdown document to the terminal renderTerminal :: Doc -> IO () renderTerminal doc = do b <- renderIO doc mapM_ Text.Lazy.putStrLn (Text.Lazy.lines b) -- | -- Renders a 'Doc' doing 'IO' reading options from the environment renderIO :: Doc -> IO Text.Lazy.Text renderIO doc = do wid <- size >>= \s -> case s of Just (Window _ w) -> return w Nothing -> return 80 prefs <- readColourPrefs hasPygments <- isJust <$> findExecutable "pygments" let opts = PrettyPrintOptions { prettyPrintWidth = wid , prettyPrintHasPygments = hasPygments , prettyPrintColourPrefs = prefs } renderIOWith opts doc -- | -- Renders a 'Doc' doing 'IO' with some set of options renderIOWith :: PrettyPrintOptions -> Doc -> IO Text.Lazy.Text renderIOWith opts (Doc _ blocks) = toLazyText <$> foldM helper "\n" blocks where helper m block = do t <- renderBlock opts block return (m <> fromLazyText t <> "\n") -- | -- Renders a 'Doc' without doing 'IO' renderPureWith :: PrettyPrintOptions -> Doc -> Text.Lazy.Text renderPureWith opts (Doc _ blocks) = toLazyText (foldl helper "" blocks) where helper m block = let t = renderBlockPure opts block in m <> fromLazyText t <> "\n" -- | -- Renders a 'Block' doing 'IO'; this is necessary for @pygments@ usage. renderBlock :: PrettyPrintOptions -> Block -> IO Text.Lazy.Text renderBlock opts@PrettyPrintOptions{..} b@(CodeBlock (CodeAttr lang _) t) | lang /= "haskell" && prettyPrintHasPygments = do mlexer <- getLexerByName (Text.unpack lang) case mlexer of Nothing -> return (renderBlockPure opts b) Just lexer -> do let st = Text.unpack t highlighted <- highlight lexer terminalFormatter [] st return $ mconcatMapF ((<> "\n") . (" " <>) . Text.Lazy.pack) (lines highlighted) renderBlock opts block = return (renderBlockPure opts block) -- | -- Renders a 'Block' without doing 'IO'. Uses a 'Text.Lazy.Text' so wrapping is -- easier to implement. The absolute majority of the time is spent going from -- 'Text.Lazy.Text' to 'Builder' and back. If we strip out 'Builder' we gain -- complexity like crazy. Suggestions welcome. renderBlockPure :: PrettyPrintOptions -> Block -> Text.Lazy.Text renderBlockPure opts@PrettyPrintOptions{..} block = case block of (Header level els) -> setSGRCodeText [ SetColor Foreground Vivid Black , SetConsoleIntensity BoldIntensity ] <> Text.Lazy.replicate (fromIntegral level) "#" <> " " <> setSGRCodeText [ Reset ] <> setSGRCodeText [ SetColor Foreground Vivid Cyan , SetConsoleIntensity BoldIntensity ] <> toLazyText (mconcatMapF renderInline els) <> setSGRCodeText [ Reset ] <> "\n" (Para els) -> wordwrap prettyPrintWidth (toLazyText (mconcatMapF renderInline els)) (List _ (Bullet c) bss) -> flip mconcatMapF bss $ \bs -> setSGRCodeText [ SetColor Foreground Vivid Black ] <> Text.Lazy.pack (" " ++ (c:" ")) <> setSGRCodeText [ Reset ] <> mconcatMapF (renderBlockPure opts) bs (List _ (Numbered w i) bss) -> let ibss = zip bss [0..] in flip mconcatMapF ibss $ \(bs, j) -> setSGRCodeText [ SetColor Foreground Vivid Black ] <> let wc = case w of PeriodFollowing -> '.' ParenFollowing -> ')' in Text.Lazy.pack (" " ++ show (i + j) ++ (wc : " ")) <> setSGRCodeText [ Reset ] <> mconcatMapF (renderBlockPure opts) bs (Blockquote bs) -> flip mconcatMapF bs $ \b -> setSGRCodeText [ SetColor Foreground Vivid Black ] <> " > " <> setSGRCodeText [ SetColor Foreground Vivid Blue ] <> renderBlockPure opts b (CodeBlock (CodeAttr "haskell" _) t) -> let code = hscolour TTY prettyPrintColourPrefs False True "" False (Text.unpack t) in toLazyText (mconcatMapF ((<> "\n") . (" " <>) . fromString) (lines code)) (CodeBlock (CodeAttr _ _) t) -> setSGRCodeText [ SetColor Foreground Dull Yellow ] <> mconcat (map (Text.Lazy.fromStrict . (<> "\n") . (" " <>) ) (Text.lines t)) <> setSGRCodeText [ Reset ] HRule -> setSGRCodeText [ SetColor Foreground Vivid Black ] <> Text.Lazy.replicate (fromIntegral prettyPrintWidth) "-" <> setSGRCodeText [ Reset ] (HtmlBlock html) -> Text.Lazy.fromStrict html <> "\n" -- | -- Renders an inline to a 'Text' 'Builder' renderInline :: Inline -> Builder renderInline el = case el of LineBreak -> "\n" Space -> " " SoftBreak -> " " Entity t -> fromText t RawHtml t -> fromText t (Str s) -> fromText s (Link els url _) -> "[" <> renderInlinesWith [ SetConsoleIntensity BoldIntensity ] els <> setSGRCodeBuilder [ Reset ] <> "](" <> setSGRCodeBuilder [ SetColor Foreground Vivid Blue ] <> fromText url <> setSGRCodeBuilder [ Reset ] <> ")" (Emph els) -> renderInlinesWith [ SetItalicized True , SetUnderlining SingleUnderline ] els <> setSGRCodeBuilder [ Reset ] (Strong els) -> renderInlinesWith [ SetConsoleIntensity BoldIntensity ] els <> setSGRCodeBuilder [ Reset ] (Code s) -> setSGRCodeBuilder [ SetColor Foreground Dull Yellow ] <> fromText s <> setSGRCodeBuilder [ Reset ] (Image _ url tit) -> "![" <> setSGRCodeBuilder [ SetConsoleIntensity BoldIntensity ] <> fromText tit <> setSGRCodeBuilder [ Reset ] <> "](" <> setSGRCodeBuilder [ SetColor Foreground Vivid Blue ] <> fromText url <> setSGRCodeBuilder [ Reset ] <> ")" where renderInlinesWith sgr = mconcatMapF helper where helper e = setSGRCodeBuilder sgr <> renderInline e concats :: (IsString a, Monoid a) => [a] -> [a] concats = scanl1 (\s v -> s <> " " <> v) wordwrap :: Int64 -> Text.Lazy.Text -> Text.Lazy.Text wordwrap maxwidth = Text.Lazy.unlines . wordwrap' . Text.Lazy.words where wordwrap' [] = [] wordwrap' ws = sentence : wordwrap' restwords where zipped = zip (concats ws) ws (sentences, rest) = span (\(s, _) -> Text.Lazy.length s <= maxwidth) zipped sentence = last (map fst sentences) restwords = map snd rest setSGRCodeText :: [SGR] -> Text.Lazy.Text setSGRCodeText = Text.Lazy.pack . setSGRCode setSGRCodeTextS :: [SGR] -> Text.Text setSGRCodeTextS = Text.pack . setSGRCode setSGRCodeBuilder :: [SGR] -> Builder setSGRCodeBuilder = fromText . setSGRCodeTextS -- Probably there's a function in prelude that we don't know that does this mconcatMapF :: (Foldable f, Monoid m) => (a -> m) -> f a -> m mconcatMapF f = mconcat . map f . toList
yamadapc/cheapskate-terminal
src/Cheapskate/Terminal.hs
bsd-3-clause
9,433
0
23
3,064
2,400
1,253
1,147
188
11
module Sgf.XMonad.Util.Run ( spawnPipe' , spawnPID' , spawn' , executeFileWithPATH , spawnPipeWithPATH' , spawnPIDWithPATH' , spawnWithPATH' ) where import XMonad.Core import System.IO import System.Posix.IO import System.Posix.Process (executeFile) import System.Posix.Types (ProcessID) import Control.Monad (void) import Control.Monad.Trans import Sgf.System.Process -- Variants of spawnPipe and spawnPID running process directly (not through -- shell). spawnPipe' :: MonadIO m => FilePath -> [String] -> m (Handle, ProcessID) spawnPipe' x xs = io $ do (rd, wr) <- createPipe setFdOption wr CloseOnExec True h <- fdToHandle wr hSetBuffering h LineBuffering p <- xfork $ do _ <- dupTo rd stdInput executeFile x True xs Nothing closeFd rd return (h, p) spawnPID' :: MonadIO m => FilePath -> [String] -> m ProcessID spawnPID' x xs = xfork $ executeFile x True xs Nothing spawn' :: MonadIO m => FilePath -> [String] -> m () spawn' x xs = void (spawnPID' x xs) -- Modify PATH using supplied function and use resulting path list when -- searching for command (if command name does not contain slashes). Search -- behavior conforms to execve() behavior, but PATH search itself is performed -- here with modified path list. executeFileWithPATH :: FilePath -> Maybe ([FilePath] -> [FilePath]) -> [String] -> Maybe [(String, String)] -> IO a executeFileWithPATH cmd mf args env = do c <- searchPATH cmd mf -- Path c executeFile c True args env -- Versions of spawnX', which allow to modify PATH. spawnPipeWithPATH' :: MonadIO m => Maybe ([FilePath] -> [FilePath]) -> FilePath -> [String] -> m (Handle, ProcessID) spawnPipeWithPATH' mf x xs = io $ do (rd, wr) <- createPipe setFdOption wr CloseOnExec True h <- fdToHandle wr hSetBuffering h LineBuffering p <- xfork $ do _ <- dupTo rd stdInput executeFileWithPATH x mf xs Nothing closeFd rd return (h, p) spawnPIDWithPATH' :: MonadIO m => Maybe ([FilePath] -> [FilePath]) -> FilePath -> [String] -> m ProcessID spawnPIDWithPATH' mf x xs = xfork $ executeFileWithPATH x mf xs Nothing spawnWithPATH' :: MonadIO m => Maybe ([FilePath] -> [FilePath]) -> FilePath -> [String] -> m () spawnWithPATH' mf x xs = void (spawnPIDWithPATH' mf x xs)
sgf-dma/sgf-xmonad-modules
src/Sgf/XMonad/Util/Run.hs
bsd-3-clause
2,795
0
13
964
736
377
359
54
1
{-# LANGUAGE MultiWayIf #-} {-# LANGUAGE PackageImports #-} module Draw (draw) where import Brick import Draw.DeleteChannelConfirm import Draw.JoinChannel import Draw.LeaveChannelConfirm import Draw.Main import Draw.PostListOverlay import Draw.ShowHelp import Draw.UserListOverlay import Draw.ViewMessage import Types draw :: ChatState -> [Widget Name] draw st = case appMode st of Main -> drawMain st ChannelScroll -> drawMain st UrlSelect -> drawMain st ShowHelp topic -> drawShowHelp topic st ChannelSelect -> drawMain st LeaveChannelConfirm -> drawLeaveChannelConfirm st JoinChannel -> drawJoinChannel st MessageSelect -> drawMain st MessageSelectDeleteConfirm -> drawMain st DeleteChannelConfirm -> drawDeleteChannelConfirm st PostListOverlay contents -> drawPostListOverlay contents st UserListOverlay -> drawUserListOverlay st ViewMessage -> drawViewMessage st
aisamanra/matterhorn
src/Draw.hs
bsd-3-clause
1,126
0
8
359
214
107
107
29
13
{-# LANGUAGE Rank2Types #-} -- Create Ramses build script. -- -- (c) 2015 Galois, Inc. -- module Tower.AADL.Build.Common where import Data.Char import Data.Maybe (maybeToList, fromMaybe) import System.FilePath import Text.PrettyPrint.Leijen hiding ((</>)) import Ivory.Artifact import Ivory.Tower import qualified Ivory.Compile.C.CmdlineFrontend as O import Tower.AADL.Config (AADLConfig(..)) import Tower.AADL.Compile data Required = Req | Opt deriving (Read, Show, Eq) data Assign = Equals | ColonEq | QuestionEq | PlusEq deriving (Read, Show, Eq) data Export = NoExport | Export deriving (Read, Show, Eq) data MkStmt = Include Required FilePath | Var Export String Assign String | Target String [String] [String] | IfNDef String [MkStmt] [MkStmt] | Comment String deriving (Read, Show, Eq) -- Combinators to make building make statements easier ------------------------ include :: FilePath -> MkStmt include fname = Include Req fname includeOpt :: FilePath -> MkStmt includeOpt fname = Include Opt fname infixr 4 ?=, =:, +=, === (?=) :: String -> String -> MkStmt var ?= val = Var NoExport var QuestionEq val (=:) :: String -> String -> MkStmt var =: val = Var NoExport var ColonEq val (+=) :: String -> String -> MkStmt var += val = Var NoExport var PlusEq val (===) :: String -> String -> MkStmt var === val = Var NoExport var Equals val export :: MkStmt -> MkStmt export (Var _ var assign val) = Var Export var assign val export s = s ------------------------------------------------------------------------------- -- Makefile pretty printer ---------------------------------------------------- renderExport :: Export -> Doc renderExport NoExport = empty renderExport Export = text "export " renderAssign :: Assign -> Doc renderAssign Equals = char '=' renderAssign ColonEq = text " := " renderAssign QuestionEq = text " ?= " renderAssign PlusEq = text " += " renderMkStmt :: MkStmt -> Doc renderMkStmt (Include Req fp) = text "include" <+> text fp renderMkStmt (Include Opt fp) = text "-include" <+> text fp renderMkStmt (Var expt var assign val) = renderExport expt <> text var <> renderAssign assign <> text val renderMkStmt (Target name deps actions) = text name <> text ":" <+> hsep (map text deps) <> foldr (\str acc -> linebreak <> char '\t' <> text str <> acc) empty actions <> linebreak renderMkStmt (IfNDef var t e) = text "ifndef" <+> text var <$$> vsep (map renderMkStmt t) <$$> text "else" <$$> vsep (map renderMkStmt e) <$$> text "endif" renderMkStmt (Comment msg) = char '#' <+> text msg renderMkStmts :: [MkStmt] -> String renderMkStmts stmts = show $ foldr (\mkstmt acc -> renderMkStmt mkstmt <> linebreak <> linebreak <> acc) empty (autogenComment : stmts) where autogenComment = Comment "This makefile is autogenerated. DO NOT EDIT." ------------------------------------------------------------------------------- ramsesMakefileName :: String ramsesMakefileName = "ramses.mk" aadlFilesMk :: String aadlFilesMk = "AADL_FILES.mk" componentLibsName :: String componentLibsName = "componentlibs.mk" mkLib :: AADLConfig -> [String] -> String mkLib c aadlFileNames = unlines (map go aadlFileNames) ++ [] where go m = m ++ "_LIBS += " ++ configLibDir c makefileName :: String makefileName = "Makefile" aadlDocNames :: CompiledDocs -> [String] aadlDocNames docs = map docName $ maybeToList (tyDoc docs) ++ thdDocs docs -------------------------------------------------------------------------------- -- Helpers shellVar :: String -> String shellVar = map toUpper -------------------------------------------------------------------------------- -- Support for OS Specific Code generation -------------------------------------------------------------------------------- data OSSpecific a = OSSpecific { osSpecificName :: String , osSpecificConfig :: a , osSpecificArtifacts :: String -> AADLConfig -> [String] -> [Located Artifact] , osSpecificSrcDir :: AADLConfig -> Located Artifact -> Located Artifact , osSpecificTower :: forall e. Tower e () , osSpecificOptsApps :: AADLConfig -> O.Opts -> O.Opts , osSpecificOptsLibs :: AADLConfig -> O.Opts -> O.Opts } defaultOptsUpdate :: AADLConfig -> O.Opts -> O.Opts defaultOptsUpdate c copts = copts { O.outDir = Just (dir </> configSrcsDir c) , O.outHdrDir = Just (dir </> configHdrDir c) , O.outArtDir = Just dir } where dir = fromMaybe "." (O.outDir copts)
GaloisInc/tower
tower-aadl/src/Tower/AADL/Build/Common.hs
bsd-3-clause
4,545
0
13
849
1,327
704
623
109
1
{-# LANGUAGE Trustworthy #-} -- | -- Module : Codec.Dvorak -- Description : Dvorak encoding for Haskell. -- Copyright : (c) Kyle Van Berendonck, 2014 -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- This module exposes all the API for this package. module Codec.Dvorak ( toDvorakChar , toDvorak , fromDvorakChar , fromDvorak ) where import Data.Tuple import qualified Data.Map.Strict as Map toTable :: Map.Map Char Char toTable = Map.fromList $ zip "-=qwertyuiop[]asdfghjkl;'zxcvbnm,./_+QWERTYUIOP{}ASDFGHJKL:\"ZXCVBNM<>?" "[]',.pyfgcrl/=aoeuidhtns-;qjkxbmwvz{}\"<>PYFGCRL?+AOEUIDHTNS_:QJKXBMWVZ" fromTable :: Map.Map Char Char fromTable = Map.fromList . map swap . Map.assocs $ toTable -- | Encodes a single given 'Char' to its dvorak encoded equivalent. toDvorakChar :: Char -> Char toDvorakChar c = case Map.lookup c toTable of Just x -> x Nothing -> c {-# INLINABLE toDvorakChar #-} -- | Encodes a string to its dvorak encoded equivalent using 'toDvorakChar'. Analagous to: -- -- @ -- toDvorak = map toDvorakChar -- @ toDvorak :: String -> String toDvorak = map toDvorakChar {-# INLINE toDvorak #-} -- | Decodes a single given 'Char' from its dvorak encoded equivalent. fromDvorakChar :: Char -> Char fromDvorakChar c = case Map.lookup c fromTable of Just x -> x Nothing -> c {-# INLINABLE fromDvorakChar #-} -- | Decodes a string from its dvorak encoded equivalent using 'fromDvorakChar'. Analagous to: -- -- @ -- fromDvorak = map fromDvorakChar -- @ fromDvorak :: String -> String fromDvorak = map fromDvorakChar {-# INLINE fromDvorak #-}
kvanberendonck/codec-dvorak
src/Codec/Dvorak.hs
bsd-3-clause
1,690
0
8
319
245
142
103
28
2
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Author ( AuthorId(..) , Author(..) , AuthorQueryCondition(..) , AuthorList(..) ) where import Data.Aeson import Data.Text (Text, unpack) import Data.Time (UTCTime) import Data.Time.Calendar import Data.Typeable import Data.Word import GHC.Generics import Servant.API (FromHttpApiData(..)) import Data.Scientific (scientific, coefficient) import Types import Address newtype AuthorId = AuthorId { getAuthorId :: Word64 } deriving (Show, Generic, Typeable) instance FromJSON AuthorId where parseJSON (Number v) = AuthorId <$> pure (fromIntegral $ coefficient v) parseJSON _ = mempty instance ToJSON AuthorId where toJSON = Number . flip scientific 0 . toInteger . getAuthorId instance FromHttpApiData AuthorId where parseQueryParam = Right . AuthorId . read . unpack data Author = Author { authorId :: Maybe AuthorId , name :: Text , gender :: Gender , birth :: Day , age :: Word8 , address :: Address , createdAt :: UTCTime , updatedAt :: UTCTime } deriving (Show, FromJSON, ToJSON, Generic, Typeable) data AuthorQueryCondition = AuthorQueryCondition { authorNameLike :: Maybe Text , genderEq :: Maybe Gender , ageFrom :: Maybe Word8 , ageTo :: Maybe Word8 , prefectureIn :: Maybe [Prefecture] } deriving (Show, FromJSON, ToJSON, Generic, Typeable) data AuthorList = AuthorList { hits :: Word64 , page :: Word64 , per_page :: Word16 , result :: [Author] } deriving (Show, FromJSON, ToJSON, Generic, Typeable)
cutsea110/servant-sample-book
src/Author.hs
bsd-3-clause
1,940
0
10
677
470
274
196
47
0
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} ------------------------------------------------------------------------------- -- | This module lets you get API docs for free. It lets generate -- an 'API' from the type that represents your API using 'docs': -- -- @docs :: 'HasDocs' api => 'Proxy' api -> 'API'@ -- -- You can then call 'markdown' on it: -- -- @markdown :: 'API' -> String@ -- -- or define a custom pretty printer: -- -- @yourPrettyDocs :: 'API' -> String -- or blaze-html's HTML, or ...@ -- -- The only thing you'll need to do will be to implement some classes -- for your captures, get parameters and request or response bodies. -- -- Here's a little (but complete) example that you can run to see the -- markdown pretty printer in action: -- -- > {-# LANGUAGE DataKinds #-} -- > {-# LANGUAGE PolyKinds #-} -- > {-# LANGUAGE TypeFamilies #-} -- > {-# LANGUAGE DeriveGeneric #-} -- > {-# LANGUAGE TypeOperators #-} -- > {-# LANGUAGE FlexibleInstances #-} -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Data.Proxy -- > import Data.Text -- > import Servant -- > -- > -- our type for a Greeting message -- > data Greet = Greet { _msg :: Text } -- > deriving (Generic, Show) -- > -- > -- we get our JSON serialization for free -- > instance FromJSON Greet -- > instance ToJSON Greet -- > -- > -- we provide a sample value for the 'Greet' type -- > instance ToSample Greet where -- > toSample = Just g -- > -- > where g = Greet "Hello, haskeller!" -- > -- > instance ToParam (QueryParam "capital" Bool) where -- > toParam _ = -- > DocQueryParam "capital" -- > ["true", "false"] -- > "Get the greeting message in uppercase (true) or not (false). Default is false." -- > -- > instance ToCapture (Capture "name" Text) where -- > toCapture _ = DocCapture "name" "name of the person to greet" -- > -- > instance ToCapture (Capture "greetid" Text) where -- > toCapture _ = DocCapture "greetid" "identifier of the greet msg to remove" -- > -- > -- API specification -- > type TestApi = -- > "hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get Greet -- > :<|> "greet" :> RQBody Greet :> Post Greet -- > :<|> "delete" :> Capture "greetid" Text :> Delete -- > -- > testApi :: Proxy TestApi -- > testApi = Proxy -- > -- > -- Generate the Documentation's ADT -- > greetDocs :: API -- > greetDocs = docs testApi -- > -- > main :: IO () -- > main = putStrLn $ markdown greetDocs module Servant.Docs ( -- * 'HasDocs' class and key functions HasDocs(..), docs, markdown {- , -- * Serving the documentation serveDocumentation -} , -- * Classes you need to implement for your types ToSample(..) , sampleByteString , ToParam(..) , ToCapture(..) , -- * ADTs to represent an 'API' Method(..) , Endpoint, path, method, defEndpoint , API, emptyAPI , DocCapture(..), capSymbol, capDesc , DocQueryParam(..), ParamKind(..), paramName, paramValues, paramDesc, paramKind , Response, respStatus, respBody, defResponse , Action, captures, params, rqbody, response, defAction , single , -- * Useful modules when defining your doc printers module Control.Lens , module Data.Monoid ) where import Control.Lens hiding (Action) import Data.Aeson import Data.Aeson.Encode.Pretty (encodePretty) import Data.ByteString.Lazy.Char8 (ByteString) import Data.Hashable import Data.HashMap.Strict (HashMap) import Data.List import Data.Monoid import Data.Proxy import Data.Text (Text, pack, unpack) import Data.String.Conversions import GHC.Generics import GHC.TypeLits import Servant.API import qualified Data.HashMap.Strict as HM -- | Supported HTTP request methods data Method = DocDELETE -- ^ the DELETE method | DocGET -- ^ the GET method | DocPOST -- ^ the POST method | DocPUT -- ^ the PUT method deriving (Eq, Generic) instance Show Method where show DocGET = "GET" show DocPOST = "POST" show DocDELETE = "DELETE" show DocPUT = "PUT" instance Hashable Method -- | An 'Endpoint' type that holds the 'path' and the 'method'. -- -- Gets used as the key in the 'API' hashmap. Modify 'defEndpoint' -- or any 'Endpoint' value you want using the 'path' and 'method' -- lenses to tweak. -- -- @ -- λ> 'defEndpoint' -- GET / -- λ> 'defEndpoint' & 'path' '<>~' "foo" -- GET /foo -- λ> 'defEndpoint' & 'path' '<>~' "foo" & 'method' '.~' 'DocPOST' -- POST /foo -- @ data Endpoint = Endpoint { _path :: String -- type collected , _method :: Method -- type collected } deriving (Eq, Generic) instance Show Endpoint where show (Endpoint p m) = show m ++ " " ++ p -- | An 'Endpoint' whose path is `"/"` and whose method is 'DocGET' -- -- Here's how you can modify it: -- -- @ -- λ> 'defEndpoint' -- GET / -- λ> 'defEndpoint' & 'path' '<>~' "foo" -- GET /foo -- λ> 'defEndpoint' & 'path' '<>~' "foo" & 'method' '.~' 'DocPOST' -- POST /foo -- @ defEndpoint :: Endpoint defEndpoint = Endpoint "/" DocGET instance Hashable Endpoint -- | Our API type, a good old hashmap from 'Endpoint' to 'Action' type API = HashMap Endpoint Action -- | An empty 'API' emptyAPI :: API emptyAPI = HM.empty -- | A type to represent captures. Holds the name of the capture -- and a description. -- -- Write a 'ToCapture' instance for your captured types. data DocCapture = DocCapture { _capSymbol :: String -- type supplied , _capDesc :: String -- user supplied } deriving (Eq, Show) -- | A type to represent a /GET/ parameter from the Query String. Holds its name, -- the possible values (leave empty if there isn't a finite number of them), -- and a description of how it influences the output or behavior. -- -- Write a 'ToParam' instance for your GET parameter types data DocQueryParam = DocQueryParam { _paramName :: String -- type supplied , _paramValues :: [String] -- user supplied , _paramDesc :: String -- user supplied , _paramKind :: ParamKind } deriving (Eq, Show) -- | Type of GET parameter: -- -- - Normal corresponds to @QueryParam@, i.e your usual GET parameter -- - List corresponds to @QueryParams@, i.e GET parameters with multiple values -- - Flag corresponds to @QueryFlag@, i.e a value-less GET parameter data ParamKind = Normal | List | Flag deriving (Eq, Show) -- | A type to represent an HTTP response. Has an 'Int' status and -- a 'Maybe ByteString' response body. Tweak 'defResponse' using -- the 'respStatus' and 'respBody' lenses if you want. -- -- If you want to respond with a non-empty response body, you'll most likely -- want to write a 'ToSample' instance for the type that'll be represented -- as some JSON in the response. -- -- Can be tweaked with two lenses. -- -- > λ> defResponse -- > Response {_respStatus = 200, _respBody = Nothing} -- > λ> defResponse & respStatus .~ 204 & respBody .~ Just "[]" -- > Response {_respStatus = 204, _respBody = Just "[]"} data Response = Response { _respStatus :: Int , _respBody :: Maybe ByteString } deriving (Eq, Show) -- | Default response: status code 200, no response body. -- -- Can be tweaked with two lenses. -- -- > λ> defResponse -- > Response {_respStatus = 200, _respBody = Nothing} -- > λ> defResponse & respStatus .~ 204 & respBody .~ Just "[]" -- > Response {_respStatus = 204, _respBody = Just "[]"} defResponse :: Response defResponse = Response 200 Nothing -- | A datatype that represents everything that can happen -- at an endpoint, with its lenses: -- -- - List of captures ('captures') -- - List of GET parameters ('params') -- - What the request body should look like, if any is requested ('rqbody') -- - What the response should be if everything goes well ('response') -- -- You can tweak an 'Action' (like the default 'defAction') with these lenses -- to transform an action and add some information to it. data Action = Action { _captures :: [DocCapture] -- type collected + user supplied info , _headers :: [Text] -- type collected , _params :: [DocQueryParam] -- type collected + user supplied info , _rqbody :: Maybe ByteString -- user supplied , _response :: Response -- user supplied } deriving (Eq, Show) -- Default 'Action'. Has no 'captures', no GET 'params', expects -- no request body ('rqbody') and the typical response is 'defResponse'. -- -- Tweakable with lenses. -- -- > λ> defAction -- > Action {_captures = [], _params = [], _rqbody = Nothing, _response = Response {_respStatus = 200, _respBody = Nothing}} -- > λ> defAction & response.respStatus .~ 201 -- > Action {_captures = [], _params = [], _rqbody = Nothing, _response = Response {_respStatus = 201, _respBody = Nothing}} defAction :: Action defAction = Action [] [] [] Nothing defResponse -- | Create an API that's comprised of a single endpoint. -- 'API' is a 'Monoid', so combine multiple endpoints with -- 'mappend' or '<>'. single :: Endpoint -> Action -> API single = HM.singleton -- gimme some lenses makeLenses ''Endpoint makeLenses ''DocCapture makeLenses ''DocQueryParam makeLenses ''Response makeLenses ''Action -- | Generate the docs for a given API that implements 'HasDocs'. docs :: HasDocs layout => Proxy layout -> API docs p = docsFor p (defEndpoint, defAction) -- | The class that abstracts away the impact of API combinators -- on documentation generation. class HasDocs layout where docsFor :: Proxy layout -> (Endpoint, Action) -> API -- | The class that lets us display a sample JSON input or output -- when generating documentation for endpoints that either: -- -- - expect a request body, or -- - return a non empty response body -- -- Example of an instance: -- -- > {-# LANGUAGE DeriveGeneric #-} -- > {-# LANGUAGE OverloadedStrings #-} -- > -- > import Data.Aeson -- > import Data.Text -- > import GHC.Generics -- > -- > data Greet = Greet { _msg :: Text } -- > deriving (Generic, Show) -- > -- > instance FromJSON Greet -- > instance ToJSON Greet -- > -- > instance ToSample Greet where -- > toSample = Just g -- > -- > where g = Greet "Hello, haskeller!" class ToJSON a => ToSample a where toSample :: Maybe a instance ToSample () where toSample = Just () sampleByteString :: forall a . ToSample a => Proxy a -> Maybe ByteString sampleByteString Proxy = fmap encodePretty (toSample :: Maybe a) -- | The class that helps us automatically get documentation -- for GET parameters. -- -- Example of an instance: -- -- > instance ToParam (QueryParam "capital" Bool) where -- > toParam _ = -- > DocQueryParam "capital" -- > ["true", "false"] -- > "Get the greeting message in uppercase (true) or not (false). Default is false." class ToParam t where toParam :: Proxy t -> DocQueryParam -- | The class that helps us automatically get documentation -- for URL captures. -- -- Example of an instance: -- -- > instance ToCapture (Capture "name" Text) where -- > toCapture _ = DocCapture "name" "name of the person to greet" class ToCapture c where toCapture :: Proxy c -> DocCapture -- | Generate documentation in Markdown format for -- the given 'API'. markdown :: API -> String markdown = unlines . concat . map (uncurry printEndpoint) . HM.toList where printEndpoint :: Endpoint -> Action -> [String] printEndpoint endpoint action = str : replicate len '-' : "" : capturesStr (action ^. captures) ++ headersStr (action ^. headers) ++ paramsStr (action ^. params) ++ rqbodyStr (action ^. rqbody) ++ responseStr (action ^. response) ++ [] where str = show (endpoint^.method) ++ " " ++ endpoint^.path len = length str capturesStr :: [DocCapture] -> [String] capturesStr [] = [] capturesStr l = "**Captures**: " : "" : map captureStr l ++ "" : [] captureStr cap = "- *" ++ (cap ^. capSymbol) ++ "*: " ++ (cap ^. capDesc) headersStr :: [Text] -> [String] headersStr [] = [] headersStr l = [""] ++ map headerStr l ++ [""] where headerStr hname = "- This endpoint is sensitive to the value of the **" ++ unpack hname ++ "** HTTP header." paramsStr :: [DocQueryParam] -> [String] paramsStr [] = [] paramsStr l = "**GET Parameters**: " : "" : map paramStr l ++ "" : [] paramStr param = unlines $ (" - " ++ param ^. paramName) : (if (not (null values) || param ^. paramKind /= Flag) then [" - **Values**: *" ++ intercalate ", " values ++ "*"] else []) ++ (" - **Description**: " ++ param ^. paramDesc) : (if (param ^. paramKind == List) then [" - This parameter is a **list**. All GET parameters with the name " ++ param ^. paramName ++ "[] will forward their values in a list to the handler."] else []) ++ (if (param ^. paramKind == Flag) then [" - This parameter is a **flag**. This means no value is expected to be associated to this parameter."] else []) ++ [] where values = param ^. paramValues rqbodyStr :: Maybe ByteString -> [String] rqbodyStr Nothing = [] rqbodyStr (Just b) = "**Request Body**: " : jsonStr b jsonStr b = "" : "``` javascript" : cs b : "```" : "" : [] responseStr :: Response -> [String] responseStr resp = "**Response**: " : "" : (" - Status code " ++ show (resp ^. respStatus)) : (resp ^. respBody & maybe [" - No response body\n"] (\b -> " - Response body as below." : jsonStr b)) -- * Instances -- | The generated docs for @a ':<|>' b@ just appends the docs -- for @a@ with the docs for @b@. instance (HasDocs layout1, HasDocs layout2) => HasDocs (layout1 :<|> layout2) where docsFor Proxy (ep, action) = docsFor p1 (ep, action) <> docsFor p2 (ep, action) where p1 :: Proxy layout1 p1 = Proxy p2 :: Proxy layout2 p2 = Proxy -- | @"books" :> 'Capture' "isbn" Text@ will appear as -- @/books/:isbn@ in the docs. instance (KnownSymbol sym, ToCapture (Capture sym a), HasDocs sublayout) => HasDocs (Capture sym a :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint', action') where sublayoutP = Proxy :: Proxy sublayout captureP = Proxy :: Proxy (Capture sym a) action' = over captures (|> toCapture captureP) action endpoint' = over path (\p -> p++"/:"++symbolVal symP) endpoint symP = Proxy :: Proxy sym instance HasDocs Delete where docsFor Proxy (endpoint, action) = single endpoint' action' where endpoint' = endpoint & method .~ DocDELETE action' = action & response.respBody .~ Nothing & response.respStatus .~ 204 instance ToSample a => HasDocs (Get a) where docsFor Proxy (endpoint, action) = single endpoint' action' where endpoint' = endpoint & method .~ DocGET action' = action & response.respBody .~ sampleByteString p p = Proxy :: Proxy a instance (KnownSymbol sym, HasDocs sublayout) => HasDocs (Header sym a :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint, action') where sublayoutP = Proxy :: Proxy sublayout action' = over headers (|> headername) action headername = pack $ symbolVal (Proxy :: Proxy sym) instance ToSample a => HasDocs (Post a) where docsFor Proxy (endpoint, action) = single endpoint' action' where endpoint' = endpoint & method .~ DocPOST action' = action & response.respBody .~ sampleByteString p & response.respStatus .~ 201 p = Proxy :: Proxy a instance ToSample a => HasDocs (Put a) where docsFor Proxy (endpoint, action) = single endpoint' action' where endpoint' = endpoint & method .~ DocPUT action' = action & response.respBody .~ sampleByteString p & response.respStatus .~ 200 p = Proxy :: Proxy a instance (KnownSymbol sym, ToParam (QueryParam sym a), HasDocs sublayout) => HasDocs (QueryParam sym a :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint, action') where sublayoutP = Proxy :: Proxy sublayout paramP = Proxy :: Proxy (QueryParam sym a) action' = over params (|> toParam paramP) action instance (KnownSymbol sym, ToParam (QueryParams sym a), HasDocs sublayout) => HasDocs (QueryParams sym a :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint, action') where sublayoutP = Proxy :: Proxy sublayout paramP = Proxy :: Proxy (QueryParams sym a) action' = over params (|> toParam paramP) action instance (KnownSymbol sym, ToParam (QueryFlag sym), HasDocs sublayout) => HasDocs (QueryFlag sym :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint, action') where sublayoutP = Proxy :: Proxy sublayout paramP = Proxy :: Proxy (QueryFlag sym) action' = over params (|> toParam paramP) action instance HasDocs Raw where docsFor _proxy (endpoint, action) = single endpoint action instance (ToSample a, HasDocs sublayout) => HasDocs (ReqBody a :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint, action') where sublayoutP = Proxy :: Proxy sublayout action' = action & rqbody .~ sampleByteString p p = Proxy :: Proxy a instance (KnownSymbol path, HasDocs sublayout) => HasDocs (path :> sublayout) where docsFor Proxy (endpoint, action) = docsFor sublayoutP (endpoint', action) where sublayoutP = Proxy :: Proxy sublayout endpoint' = endpoint & path <>~ symbolVal pa pa = Proxy :: Proxy path {- -- | Serve your API's docs as markdown embedded in an html \<pre> tag. -- -- > type MyApi = "users" :> Get [User] -- > :<|> "docs :> Raw -- > -- > apiProxy :: Proxy MyApi -- > apiProxy = Proxy -- > -- > server :: Server MyApi -- > server = listUsers -- > :<|> serveDocumentation apiProxy serveDocumentation :: HasDocs api => Proxy api -> Server Raw serveDocumentation proxy _request respond = respond $ responseLBS ok200 [] $ cs $ toHtml $ markdown $ docs proxy toHtml :: String -> String toHtml md = "<html>" ++ "<body>" ++ "<pre>" ++ md ++ "</pre>" ++ "</body>" ++ "</html>" -}
derekelkins/servant-docs
src/Servant/Docs.hs
bsd-3-clause
19,057
0
20
4,738
3,298
1,886
1,412
-1
-1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RecordWildCards #-} module IOCP.Manager ( -- * Manager Manager, new, getSystemManager, -- * Overlapped I/O associateHandle, withOverlapped, StartCallback, CompletionCallback, Overlapped(..), -- * Timeouts TimeoutCallback, TimeoutKey, Seconds, registerTimeout, updateTimeout, unregisterTimeout, ) where import IOCP.Clock (Clock, Seconds, getClock, getTime) import IOCP.FFI (Overlapped(..)) import IOCP.Worker (Worker, forkOSUnmasked) import qualified IOCP.FFI as FFI import qualified IOCP.PSQ as Q import qualified IOCP.Worker as Worker import Control.Concurrent import Control.Exception as E import Control.Monad import Data.IORef import Data.Word import Data.Unique import Debug.Trace (traceIO) import Foreign.Ptr import System.IO.Unsafe (unsafeInterleaveIO, unsafePerformIO) import System.Win32.Types import qualified Data.IntMap as IM ------------------------------------------------------------------------ -- Manager data Manager = Manager { mgrIOCP :: !(FFI.IOCP ManagerCallback) , mgrClock :: !Clock , mgrWorkers :: WorkerList , mgrWorkerMap :: !(IORef WorkerMap) } type ManagerCallback = ErrCode -> DWORD -> Mgr () new :: IO Manager new = do mgrIOCP <- FFI.newIOCP mgrClock <- getClock mgrWorkers <- newWorkerList mgrWorkerMap <- newIORef IM.empty let mgr = Manager{..} _tid <- forkOSUnmasked $ loop mgr return mgr getSystemManager :: IO (Maybe Manager) getSystemManager = readIORef managerRef managerRef :: IORef (Maybe Manager) managerRef = unsafePerformIO $ if rtsSupportsBoundThreads then new >>= newIORef . Just else newIORef Nothing {-# NOINLINE managerRef #-} newOverlapped :: Word64 -> ManagerCallback -> IO Overlapped newOverlapped = FFI.newOverlapped -- | Queue an action to be performed by the I/O manager thread. postIO :: Manager -> IO () -> IO () postIO mgr = postMgr mgr . liftIO -- | Variant of 'postIO' that allows the callback to modify the -- timeout queue. postMgr :: Manager -> Mgr () -> IO () postMgr mgr cb = newOverlapped 0 (\_errCode _numBytes -> cb) >>= FFI.postCompletion (mgrIOCP mgr) 0 ------------------------------------------------------------------------ -- Overlapped I/O -- | Callback that starts the overlapped I/O operation. -- It must return successfully if and only if an I/O completion has been -- queued. Otherwise, it must throw an exception, which 'withOverlapped' -- will rethrow. type StartCallback = Overlapped -> IO () -- | Called when the completion is delivered. type CompletionCallback a = ErrCode -- ^ 0 indicates success -> DWORD -- ^ Number of bytes transferred -> IO a -- | Associate a 'HANDLE' with the I/O manager's completion port. This must be -- done before using the handle with 'withOverlapped'. associateHandle :: Manager -> HANDLE -> IO () associateHandle Manager{..} h = FFI.associateHandleWithIOCP mgrIOCP h -- | Start an overlapped I/O operation, and wait for its completion. If -- 'withOverlapped' is interrupted by an asynchronous exception, the operation -- will be canceled using @CancelIo@. -- -- 'withOverlapped' waits for a completion to arrive before returning or -- throwing an exception. This means you can use functions like -- 'Foreign.Marshal.Alloc.alloca' to allocate buffers for the operation. withOverlapped :: Manager -> HANDLE -> Word64 -- ^ Value to use for the @OVERLAPPED@ -- structure's Offset/OffsetHigh members. -> StartCallback -> CompletionCallback a -> IO a withOverlapped mgr h offset startCB completionCB = do signal <- newEmptyMVar let signalReturn a = void $ tryPutMVar signal $ return a signalThrow ex = void $ tryPutMVar signal $ throwIO (ex :: SomeException) mask_ $ withWorker mgr h $ \enqueue -> do enqueue $ do let completionCB' e b = liftIO $ (completionCB e b >>= signalReturn) `E.catch` signalThrow e <- try $ newOverlapped offset completionCB' case e of Left ex -> signalThrow ex Right ol -> startCB ol `E.catch` \ex -> do FFI.discardOverlapped ol signalThrow ex let cancel = uninterruptibleMask_ $ do cancelDone <- newEmptyMVar enqueue $ do FFI.cancelIo h `E.catch` \ex -> do traceIO $ "CancelIo failed: " ++ show (ex :: SomeException) signalThrow ex putMVar cancelDone () _ <- takeMVar signal takeMVar cancelDone join (takeMVar signal `onException` cancel) ------------------------------------------------------------------------ -- Timeouts type TimeoutQueue = Q.PSQ TimeoutCallback -- | -- Warning: since the 'TimeoutCallback' is called from the I/O manager, it must -- not throw an exception or block for a long period of time. In particular, -- be wary of 'Control.Exception.throwTo' and 'Control.Concurrent.killThread': -- if the target thread is making a foreign call, these functions will block -- until the call completes. type TimeoutCallback = IO () newtype TimeoutKey = TK Unique deriving (Eq, Ord) -- | Register an action to be performed in the given number of seconds. The -- returned 'TimeoutKey' can be used to later unregister or update the timeout. -- The timeout is automatically unregistered when it fires. -- -- The 'TimeoutCallback' will not be called more than once. registerTimeout :: Manager -> Seconds -> TimeoutCallback -> IO TimeoutKey registerTimeout mgr relTime cb = do key <- newUnique now <- getTime (mgrClock mgr) let !expTime = now + relTime postMgr mgr $ modifyTQ $ Q.insert key expTime cb return $ TK key -- | Update an active timeout to fire in the given number of seconds (from the -- time 'updateTimeout' is called), instead of when it was going to fire. -- This has no effect if the timeout has already fired. updateTimeout :: Manager -> TimeoutKey -> Seconds -> IO () updateTimeout mgr (TK key) relTime = do now <- getTime (mgrClock mgr) let !expTime = now + relTime postMgr mgr $ modifyTQ $ Q.adjust (const expTime) key -- | Unregister an active timeout. This is a harmless no-op if the timeout is -- already unregistered or has already fired. -- -- Warning: the timeout callback may fire even after -- 'unregisterTimeout' completes. unregisterTimeout :: Manager -> TimeoutKey -> IO () unregisterTimeout mgr (TK key) = postMgr mgr $ modifyTQ $ Q.delete key ------------------------------------------------------------------------ -- The Mgr state monad newtype Mgr a = Mgr { runMgr :: TimeoutQueue -> IO (a, TimeoutQueue) } instance Monad Mgr where return a = Mgr $ \s -> return (a, s) m >>= k = Mgr $ \s -> do (a, s') <- runMgr m s runMgr (k a) s' liftIO :: IO a -> Mgr a liftIO io = Mgr $ \s -> do a <- io return (a, s) getsTQ :: (TimeoutQueue -> a) -> Mgr a getsTQ f = Mgr $ \s -> return (f s, s) modifyTQ :: (TimeoutQueue -> TimeoutQueue) -> Mgr () modifyTQ f = Mgr $ \s -> do let !s' = f s return ((), s') stateTQ :: (TimeoutQueue -> (a, TimeoutQueue)) -> Mgr a stateTQ f = Mgr $ \s -> do let (a, !s') = f s return (a, s') ------------------------------------------------------------------------ -- I/O manager loop -- | Call all expired timeouts, and return how much time until the next expiration. runExpiredTimeouts :: Manager -> Mgr (Maybe Seconds) runExpiredTimeouts Manager{..} = do empty <- getsTQ Q.null if empty then return Nothing else do now <- liftIO $ getTime mgrClock stateTQ (Q.atMost now) >>= mapM_ (liftIO . Q.value) next <- getsTQ $ fmap Q.prio . Q.findMin case next of Nothing -> return Nothing Just t -> do -- This value will always be positive since the call -- to 'atMost' above removed any timeouts <= 'now' let !t' = t - now return $ Just t' -- | Return the delay argument to pass to GetQueuedCompletionStatus. fromTimeout :: Maybe Seconds -> Word32 fromTimeout Nothing = 120000 fromTimeout (Just sec) | sec > 120 = 120000 | sec > 0 = ceiling (sec * 1000) | otherwise = 0 step :: Manager -> Mgr () step mgr@Manager{..} = do delay <- runExpiredTimeouts mgr m <- liftIO $ FFI.getNextCompletion mgrIOCP (fromTimeout delay) case m of Nothing -> return () Just (cb, numBytes, errCode) -> cb errCode numBytes loop :: Manager -> IO loop loop mgr = go Q.empty where go s = runMgr (step mgr) s >>= go . snd ------------------------------------------------------------------------ -- Worker allocation type WorkerMap = IM.IntMap Pool -- | Used to allocate worker threads for I/O requests. The rule is: a handle -- may not use the same worker for two simultaneous operations (however, -- multiple handles may share the same worker). This is because CancelIo -- cancels all pending I/O for a given handle in the current thread. -- CancelIoEx would let us specify an individual operation to cancel, -- but it was introduced in Windows Vista. -- -- Whenever we can, we queue jobs to the completion handler using -- 'postIO'. This is about 30% faster than using a separate -- worker thread, as it avoids a context switch. data Pool = Pool { pCompletionPort :: !Bool , pWorkers :: WorkerList , pRefCount :: !Int -- ^ Number of in-progress 'withWorker' calls. When this drops to -- zero, we can remove this entry from the 'WorkerMap'. } data WorkerList = WL !Worker WorkerList -- | Nifty trick to allow each 'Pool' to allocate workers per concurrent -- operation, while allowing 'Pool's to share workers. newWorkerList :: IO WorkerList newWorkerList = unsafeInterleaveIO $ do w <- Worker.new ws <- newWorkerList return (WL w ws) {-# NOINLINE newWorkerList #-} type Enqueue = IO () -> IO () type ReleaseF = WorkerMap -> (WorkerMap, ()) withWorker :: Manager -> HANDLE -> (Enqueue -> IO a) -> IO a withWorker mgr@Manager{..} h cb = mask $ \restore -> do (enqueue, releaseF) <- atomicModifyIORef mgrWorkerMap grabF let release = atomicModifyIORef mgrWorkerMap releaseF >>= evaluate a <- restore (cb enqueue) `onException` release release return a where key = (fromIntegral . ptrToIntPtr) h :: Int grabF :: WorkerMap -> (WorkerMap, (Enqueue, ReleaseF)) grabF m = case IM.lookup key m of Nothing -> let !pool = Pool False mgrWorkers 1 !m' = IM.insert key pool m in (m', (postIO mgr, releaseCP)) Just Pool{..} | pCompletionPort -> let !pool = Pool False pWorkers (pRefCount + 1) !m' = IM.insert key pool m in (m', (postIO mgr, releaseCP)) | WL w ws <- pWorkers -> let !pool = Pool pCompletionPort ws (pRefCount + 1) !m' = IM.insert key pool m in (m', (Worker.enqueue w, releaseWorker w)) releaseCP :: ReleaseF releaseCP = releaseWith $ \Pool{..} -> Pool True pWorkers (pRefCount - 1) releaseWorker :: Worker -> ReleaseF releaseWorker w = releaseWith $ \Pool{..} -> Pool pCompletionPort (WL w pWorkers) (pRefCount - 1) releaseWith :: (Pool -> Pool) -> ReleaseF releaseWith f m = case IM.lookup key m of Nothing -> (m, ()) -- should never happen Just pool | pRefCount pool <= 1 -> let !m' = IM.delete key m in (m', ()) | otherwise -> let !pool' = f pool !m' = IM.insert key pool' m in (m', ())
joeyadams/haskell-iocp
IOCP/Manager.hs
bsd-3-clause
12,352
4
27
3,405
2,795
1,453
1,342
243
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE OverloadedStrings #-} module Yesod.Core.Content ( -- * Content Content (..) , emptyContent , ToContent (..) , ToFlushBuilder (..) -- * Mime types -- ** Data type , ContentType , typeHtml , typePlain , typeJson , typeXml , typeAtom , typeRss , typeJpeg , typePng , typeGif , typeSvg , typeJavascript , typeCss , typeFlv , typeOgv , typeOctet -- * Utilities , simpleContentType , contentTypeTypes -- * Evaluation strategy , DontFullyEvaluate (..) -- * Representations , TypedContent (..) , ToTypedContent (..) , HasContentType (..) -- ** Specific content types , RepHtml , RepJson (..) , RepPlain (..) , RepXml (..) -- ** Smart constructors , repJson , repPlain , repXml ) where import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import Data.Text.Lazy (Text, pack) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8Builder) import qualified Data.Text.Lazy as TL import Data.ByteString.Builder (Builder, byteString, lazyByteString, stringUtf8) import Text.Hamlet (Html) import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder) import Data.Conduit (Flush (Chunk), SealedConduitT, mapOutput) import Control.Monad (liftM) import Control.Monad.Trans.Resource (ResourceT) import qualified Data.Conduit.Internal as CI import qualified Data.Aeson as J import Data.Text.Lazy.Builder (toLazyText) import Yesod.Core.Types import Text.Lucius (Css, renderCss) import Text.Julius (Javascript, unJavascript) import Data.Word8 (_semicolon, _slash) import Control.Arrow (second) -- | Zero-length enumerator. emptyContent :: Content emptyContent = ContentBuilder mempty $ Just 0 -- | Anything which can be converted into 'Content'. Most of the time, you will -- want to use the 'ContentBuilder' constructor. An easier approach will be to use -- a pre-defined 'toContent' function, such as converting your data into a lazy -- bytestring and then calling 'toContent' on that. -- -- Please note that the built-in instances for lazy data structures ('String', -- lazy 'L.ByteString', lazy 'Text' and 'Html') will not automatically include -- the content length for the 'ContentBuilder' constructor. class ToContent a where toContent :: a -> Content instance ToContent Content where toContent = id instance ToContent Builder where toContent = flip ContentBuilder Nothing instance ToContent B.ByteString where toContent bs = ContentBuilder (byteString bs) $ Just $ B.length bs instance ToContent L.ByteString where toContent = flip ContentBuilder Nothing . lazyByteString instance ToContent T.Text where toContent = toContent . encodeUtf8Builder instance ToContent Text where toContent = toContent . foldMap encodeUtf8Builder . TL.toChunks instance ToContent String where toContent = toContent . stringUtf8 instance ToContent Html where toContent bs = ContentBuilder (renderHtmlBuilder bs) Nothing instance ToContent () where toContent () = toContent B.empty instance ToContent (ContentType, Content) where toContent = snd instance ToContent TypedContent where toContent (TypedContent _ c) = c instance ToContent Css where toContent = toContent . renderCss instance ToContent Javascript where toContent = toContent . toLazyText . unJavascript instance ToFlushBuilder builder => ToContent (CI.Pipe () () builder () (ResourceT IO) ()) where toContent src = ContentSource $ CI.ConduitT (CI.mapOutput toFlushBuilder src >>=) instance ToFlushBuilder builder => ToContent (CI.ConduitT () builder (ResourceT IO) ()) where toContent src = ContentSource $ mapOutput toFlushBuilder src instance ToFlushBuilder builder => ToContent (SealedConduitT () builder (ResourceT IO) ()) where toContent (CI.SealedConduitT src) = toContent src -- | A class for all data which can be sent in a streaming response. Note that -- for textual data, instances must use UTF-8 encoding. -- -- Since 1.2.0 class ToFlushBuilder a where toFlushBuilder :: a -> Flush Builder instance ToFlushBuilder (Flush Builder) where toFlushBuilder = id instance ToFlushBuilder Builder where toFlushBuilder = Chunk instance ToFlushBuilder (Flush B.ByteString) where toFlushBuilder = fmap byteString instance ToFlushBuilder B.ByteString where toFlushBuilder = Chunk . byteString instance ToFlushBuilder (Flush L.ByteString) where toFlushBuilder = fmap lazyByteString instance ToFlushBuilder L.ByteString where toFlushBuilder = Chunk . lazyByteString instance ToFlushBuilder (Flush Text) where toFlushBuilder = fmap (foldMap encodeUtf8Builder . TL.toChunks) instance ToFlushBuilder Text where toFlushBuilder = Chunk . foldMap encodeUtf8Builder . TL.toChunks instance ToFlushBuilder (Flush T.Text) where toFlushBuilder = fmap encodeUtf8Builder instance ToFlushBuilder T.Text where toFlushBuilder = Chunk . encodeUtf8Builder instance ToFlushBuilder (Flush String) where toFlushBuilder = fmap stringUtf8 instance ToFlushBuilder String where toFlushBuilder = Chunk . stringUtf8 instance ToFlushBuilder (Flush Html) where toFlushBuilder = fmap renderHtmlBuilder instance ToFlushBuilder Html where toFlushBuilder = Chunk . renderHtmlBuilder repJson :: ToContent a => a -> RepJson repJson = RepJson . toContent repPlain :: ToContent a => a -> RepPlain repPlain = RepPlain . toContent repXml :: ToContent a => a -> RepXml repXml = RepXml . toContent class ToTypedContent a => HasContentType a where getContentType :: Monad m => m a -> ContentType instance HasContentType RepJson where getContentType _ = typeJson deriving instance ToContent RepJson instance HasContentType RepPlain where getContentType _ = typePlain deriving instance ToContent RepPlain instance HasContentType RepXml where getContentType _ = typeXml deriving instance ToContent RepXml typeHtml :: ContentType typeHtml = "text/html; charset=utf-8" typePlain :: ContentType typePlain = "text/plain; charset=utf-8" typeJson :: ContentType typeJson = "application/json; charset=utf-8" typeXml :: ContentType typeXml = "text/xml" typeAtom :: ContentType typeAtom = "application/atom+xml" typeRss :: ContentType typeRss = "application/rss+xml" typeJpeg :: ContentType typeJpeg = "image/jpeg" typePng :: ContentType typePng = "image/png" typeGif :: ContentType typeGif = "image/gif" typeSvg :: ContentType typeSvg = "image/svg+xml" typeJavascript :: ContentType typeJavascript = "text/javascript; charset=utf-8" typeCss :: ContentType typeCss = "text/css; charset=utf-8" typeFlv :: ContentType typeFlv = "video/x-flv" typeOgv :: ContentType typeOgv = "video/ogg" typeOctet :: ContentType typeOctet = "application/octet-stream" -- | Removes \"extra\" information at the end of a content type string. In -- particular, removes everything after the semicolon, if present. -- -- For example, \"text/html; charset=utf-8\" is commonly used to specify the -- character encoding for HTML data. This function would return \"text/html\". simpleContentType :: ContentType -> ContentType simpleContentType = fst . B.break (== _semicolon) -- | Give just the media types as a pair. -- -- For example, \"text/html; charset=utf-8\" returns ("text", "html") contentTypeTypes :: ContentType -> (B.ByteString, B.ByteString) contentTypeTypes = second tailEmpty . B.break (== _slash) . simpleContentType where tailEmpty x = if B.null x then "" else B.tail x instance HasContentType a => HasContentType (DontFullyEvaluate a) where getContentType = getContentType . liftM unDontFullyEvaluate instance ToContent a => ToContent (DontFullyEvaluate a) where toContent (DontFullyEvaluate a) = ContentDontEvaluate $ toContent a instance ToContent J.Value where toContent = flip ContentBuilder Nothing . J.fromEncoding . J.toEncoding instance ToContent J.Encoding where toContent = flip ContentBuilder Nothing . J.fromEncoding instance HasContentType J.Value where getContentType _ = typeJson instance HasContentType J.Encoding where getContentType _ = typeJson instance HasContentType Html where getContentType _ = typeHtml instance HasContentType Text where getContentType _ = typePlain instance HasContentType T.Text where getContentType _ = typePlain instance HasContentType Css where getContentType _ = typeCss instance HasContentType Javascript where getContentType _ = typeJavascript -- | Any type which can be converted to 'TypedContent'. -- -- Since 1.2.0 class ToContent a => ToTypedContent a where toTypedContent :: a -> TypedContent instance ToTypedContent TypedContent where toTypedContent = id instance ToTypedContent () where toTypedContent () = TypedContent typePlain (toContent ()) instance ToTypedContent (ContentType, Content) where toTypedContent (ct, content) = TypedContent ct content instance ToTypedContent RepJson where toTypedContent (RepJson c) = TypedContent typeJson c instance ToTypedContent RepPlain where toTypedContent (RepPlain c) = TypedContent typePlain c instance ToTypedContent RepXml where toTypedContent (RepXml c) = TypedContent typeXml c instance ToTypedContent J.Value where toTypedContent v = TypedContent typeJson (toContent v) instance ToTypedContent J.Encoding where toTypedContent e = TypedContent typeJson (toContent e) instance ToTypedContent Html where toTypedContent h = TypedContent typeHtml (toContent h) instance ToTypedContent T.Text where toTypedContent t = TypedContent typePlain (toContent t) instance ToTypedContent [Char] where toTypedContent = toTypedContent . pack instance ToTypedContent Text where toTypedContent t = TypedContent typePlain (toContent t) instance ToTypedContent a => ToTypedContent (DontFullyEvaluate a) where toTypedContent (DontFullyEvaluate a) = let TypedContent ct c = toTypedContent a in TypedContent ct (ContentDontEvaluate c) instance ToTypedContent Css where toTypedContent = TypedContent typeCss . toContent instance ToTypedContent Javascript where toTypedContent = TypedContent typeJavascript . toContent
s9gf4ult/yesod
yesod-core/Yesod/Core/Content.hs
mit
10,363
0
10
1,754
2,383
1,291
1,092
222
2
{-| Module : Veca.Operations Description : Functions for VECA Copyright : (c) 2017 Pascal Poizat License : Apache-2.0 (see the file LICENSE) Maintainer : [email protected] Stability : experimental Portability : unknown -} module Veca.Operations ( -- * model transformation cToCTree , cToTA , cTreeToTAList , fLift , indexBy -- * other , operations ) where import Relude.Extra.Tuple import Data.Maybe import Control.Monad ( when ) import Control.Monad.State as MS import Data.Bifunctor ( second ) import Data.Hashable ( Hashable , hash , hashWithSalt ) import Data.Map as M ( Map , empty , keysSet , member , (!) ) import Data.Monoid ( All(..) , Any(..) , (<>) ) import Data.Set as S ( fromList ) import GHC.Generics ( Generic ) import Models.Events ( CTIOEvent(..) , liftToCTIOEvent ) import Models.Communication import Models.LabelledTransitionSystem ( LabelledTransitionSystem(..) , Path(..) , State(..) , Transition ( Transition , label , source , target ) , end , outgoing , hasLoop , isValidLTS , paths' , start ) import Models.Name ( Name(..) , isValidName ) import Models.Named ( Named(..) , suffixBy ) import Models.TimedAutomaton as TA ( Clock(..) , ClockConstraint(..) , ClockOperator(GE, LE) , ClockReset(..) , Edge(Edge) , Location(..) , TimedAutomaton(..) , ToXta , asXta , addObservers , relabel ) import Numeric.Natural import Transformations.Substitution ( Substitution(..) , apply , freevariables , isBound ) import Trees.Tree ( Tree(..) ) import Trees.Trifunctor ( first ) import Veca.Model {-| Get the operations of a component. There may be duplicates in the returned list if the signature is not valid. -} operations :: Component -> [Operation] operations c = pos <> ros where pos = providedOperations sig ros = requiredOperations sig sig = signature c -- |Transform an architecture (given as a component instance) into a component tree cToCTree :: ComponentInstance -> VCTree cToCTree c@(ComponentInstance _ BasicComponent{} ) = Leaf c cToCTree c@(ComponentInstance _ (CompositeComponent _ _ cs _ _)) = Node c cs' where cs' = indexInstance <$> cs indexInstance ci = (instanceId ci, cToCTree ci) data TABuildState = TABS {nextId:: Integer, ta:: VTA, beh:: VLTS} cToTAAddFinals' :: [VState] -> MS.State TABuildState () cToTAAddFinals' [] = return () cToTAAddFinals' (f : fs) = do TABS n ta beh <- get let newLoc = Location ("_" ++ show n) let edge1 = Edge (toLocation f) CTTau [] [] [] newLoc let edge2 = Edge newLoc CTTau [] [] [] (toLocation f) put $ TABS (n + 1) (update ta [newLoc] [edge1, edge2]) beh cToTAAddFinals' fs return () where update (TimedAutomaton i ls l0 cls uls cs vs as es is) newL newE = TimedAutomaton i (newL ++ ls) l0 cls uls cs vs as (newE ++ es) is cToTAAddFinals :: MS.State TABuildState () cToTAAddFinals = do currentState <- get let fs = finalStates . beh $ currentState cToTAAddFinals' fs return () cToTAAddTimeouts''' :: VLocation -> [VTransition] -> MS.State TABuildState () cToTAAddTimeouts''' _ [] = return () cToTAAddTimeouts''' l (t : ts) = do let ll = label t when (isEventLabel ll) $ do TABS n ta beh <- get let (EventLabel e) = label t let newEdge = Edge l (liftToCTIOEvent e) [] [] [] (toLocation $ target t) put $ TABS n (update ta [] [newEdge] []) beh cToTAAddTimeouts''' l ts return () cToTAAddTimeouts'' :: VState -> VTransition -> MS.State TABuildState () cToTAAddTimeouts'' s t = do TABS n ta beh <- get let ts = transitions beh let s' = target t let c = Clock "0" let l = label t when (isTimeoutLabel l) $ do let (TimeoutLabel x) = label t -- add new location and its invariant let newLoc = Location ("_" ++ show n) let newInv = (newLoc, [ClockConstraint c LE x]) -- add edges let newEdge1 = Edge (toLocation s) CTTau [] [ClockReset c] [] newLoc let newEdge2 = Edge newLoc CTTau [ClockConstraint c GE x] [] [] (toLocation s') -- update state put $ TABS (n + 1) (update ta [newLoc] [newEdge1, newEdge2] [newInv]) beh -- deal with other transitions outgoing from s cToTAAddTimeouts''' newLoc $ outgoing ts s return () update :: VTA -> [VLocation] -> [VTEdge] -> [(VLocation, [ClockConstraint])] -> VTA update (TimedAutomaton i ls l0 cls uls cs vs as es is) newL newE newI = TimedAutomaton i (newL ++ ls) l0 cls uls cs vs as (newE ++ es) (newI ++ is) cToTAAddTimeouts' :: [(VState, VTransition)] -> MS.State TABuildState () cToTAAddTimeouts' [] = return () cToTAAddTimeouts' ((s, tt) : ss) = do cToTAAddTimeouts'' s tt cToTAAddTimeouts' ss return () cToTAAddTimeouts :: MS.State TABuildState () cToTAAddTimeouts = do currentState <- get let ts = transitions . beh $ currentState let ss = states . beh $ currentState let ss' = catMaybes $ traverseToSnd (getTimeoutTransition ts) <$> ss cToTAAddTimeouts' ss' return () cToTAAddRegular'' :: [VTransition] -> MS.State TABuildState () cToTAAddRegular'' [] = return () cToTAAddRegular'' (t : ts) = do TABS n ta beh <- get let s = source t let s' = target t let l = label t case label t of InternalLabel (TimeValue 0) InfiniteValue -> do let newEdge = Edge (toLocation s) CTTau [] [] [] (toLocation s') put $ TABS n (update ta [] [newEdge] []) beh return () EventLabel e -> if isInput e then do let newLoc = Location ("_" ++ show n) let newEdge1 = Edge (toLocation s) CTTau [] [] [] newLoc let newEdge2 = Edge newLoc (liftToCTIOEvent e) [] [] [] (toLocation s') put $ TABS (n + 1) (update ta [newLoc] [newEdge1, newEdge2] []) beh return () else do let newEdge = Edge (toLocation s) (liftToCTIOEvent e) [] [] [] (toLocation s') put $ TABS n (update ta [] [newEdge] []) beh return () _ -> return () cToTAAddRegular' :: [[VTransition]] -> MS.State TABuildState () cToTAAddRegular' [] = return () cToTAAddRegular' (ts : tss) = do cToTAAddRegular'' ts cToTAAddRegular' tss return () cToTAAddRegular :: MS.State TABuildState () cToTAAddRegular = do currentState <- get let ts = transitions . beh $ currentState let ss = states . beh $ currentState let st = outgoing ts <$> filter (not . hasTimeoutTransition ts) ss cToTAAddRegular' st return () cToTAAddInternals' :: [VTransition] -> MS.State TABuildState () cToTAAddInternals' [] = return () cToTAAddInternals' (t:ts) = do TABS n ta beh <- get let c = Clock "0" let s = source t let s' = target t let l = label t case label t of (InternalLabel (TimeValue x) (TimeValue y)) -> do -- add new location and its invariant let newLoc = Location ("_" ++ show n) let newInv = (newLoc, [ClockConstraint c LE y]) -- add edges let newEdge1 = Edge (toLocation s) CTTau [] [ClockReset c] [] newLoc let newEdge2 = Edge newLoc CTTau [ClockConstraint c GE x] [] [] (toLocation s') put $ TABS (n+1) (update ta [newLoc] [newEdge1, newEdge2] [newInv]) beh return () _ -> return () cToTAAddInternals' ts return () cToTAAddInternals :: MS.State TABuildState () cToTAAddInternals = do currentState <- get let ts = transitions . beh $ currentState let tss = filter (isRegularInternalLabel . label) ts cToTAAddInternals' tss return () hasTimeoutTransition :: [VTransition] -> VState -> Bool hasTimeoutTransition ts s = isJust $ getTimeoutTransition ts s getTimeoutTransition :: [VTransition] -> VState -> Maybe VTransition getTimeoutTransition ts s = listToMaybe $ filter timeoutT $ outgoing ts s where timeoutT = isTimeoutLabel . label -- |Transform a component into a timed automaton (state monadic helper) cToTA' :: MS.State TABuildState () cToTA' = do -- treatment of final states cToTAAddFinals -- treatment of timeouts cToTAAddTimeouts -- treatment of events and infinite internal events cToTAAddRegular -- treatment of regular (non infinite) internal events cToTAAddInternals -- end return () -- |Transform a component into a timed automaton (calls the state monadic helper) cToTA :: ComponentInstance -> VTA cToTA (ComponentInstance i (BasicComponent _ _ b)) = let ta0 = TimedAutomaton i ls l0 cls uls cs vs as es is in -- initialize with steps 1 to 3. addObservers . ta . snd $ runState cToTA' (TABS 0 ta0 b) where ls = lsorig l0 = toLocation (initialState b) cls = [] uls = lsorig cs = [Clock "0"] vs = empty as = events (alphabet b) ++ [CTTau] es = [] is = [] lsorig = toLocation <$> states b events [] = [] events (EventLabel e : ees) = liftToCTIOEvent e : events ees events (_ : ees) = events ees cToTA (ComponentInstance _ CompositeComponent{}) = undefined -- TODO: define using cToTA and flatten -- |Transform a state into a location toLocation :: VState -> VLocation toLocation (State s) = Location s -- |Generates a new location from a state toLocationNew :: [Int] -> VState -> ([Int], VLocation) toLocationNew (id : ids) (State s) = (ids, Location $ s ++ show id) -- |Generate a looping tau edge for a state genFinalLoop :: [Int] -> VState -> ([Int], [VTEdge]) genFinalLoop ids s = (ids', [Edge l CTTau [] [] [] lnew, Edge lnew CTTau [] [] [] l]) where l = toLocation s (ids', lnew) = toLocationNew ids s {-| Flatten a VecaTATree into a list of TimedAutomata. -} cTreeToTAList :: VCTree -> [VTA] cTreeToTAList = cTreeToTAList' (mempty :: VName) (mempty :: VOSubstitution) {-| Helper to flatten a VecaTATree into a list of TimedAutomata. -} cTreeToTAList' :: VName -> VOSubstitution -> VCTree -> [VTA] -- for a leaf (contains a component instance of a basic component type): -- - transform the component instance c in l into a timed automaton ta -- - lift the substitution sub on operations to one on events, sub' -- - apply sub' to ta -- - prefix the name of ta by p cTreeToTAList' p sub (Leaf c) = [prefixBy p . relabel sub' $ ta] where ta = cToTA c sub' = liftOSubToESub sub -- for a node (contains a component instance x of a composite component type ct):, -- - define p' as p.x -- - for each component instance c_i in ct (it requires using snd and value to get them): -- (=iterate) -- build a substitution sub'_i and recurse with cTreeToTAList p' sub'_i c_i where -- for each op_i_j of c_i: -- (=buildSub) -- - if c_i.op_i_j is in an external binding k of c, -- then if op_i_j is in sub, then (op_i_j, sub(op_i_j)) in sub_'i -- else (op_i_j, p'.k.op_i_j) in sub'_i -- - if c_i.op_i_j is in an internal binding k of c, then (op_i_j, p'.k.op_i_j) in sub'_i -- - else (op_i_j is unbound), (op_i_j, p'.c_i.op_i_j) in sub'_i -- note: an operation cannot be in more than on binding (this is checked using the VECA IDE). cTreeToTAList' p sub (Node c xs) = foldMap iterate (snd <$> xs) where x = instanceId c ct = componentType c p' = p <> x iterate sti = cTreeToTAList' p' (sub' . value $ sti) sti where sub' ci = foldMap (buildSub ci) (operations . componentType $ ci) buildSub ci' opij = case findEB ct ci' opij of Just k -> if isBound sub opij then opij |-> apply sub opij else opij |-> indexBy (p' <> k) opij _ -> case findIB ct ci' opij of Just k -> opij |-> indexBy (p' <> k) opij _ -> opij |-> indexBy (p' <> instanceId ci') opij infix 3 |-> -- (|->) :: Operation -> Operation -> VOSubstitution o |-> o' = [(o, o')] findB :: [Binding] -> ComponentInstance -> Operation -> Maybe VName findB bs ci o = let candidates = filter cond bs cond b = ok ci o (from b) || ok ci o (to b) ok ci o' jp = (jpname jp == instanceId ci) && (jpoperation jp == o') in case candidates of [] -> Nothing _ -> Just . bindingId . head $ candidates findEB :: Component -> ComponentInstance -> Operation -> Maybe VName findEB (CompositeComponent _ _ _ _ ebs) ci o = findB ebs ci o findEB BasicComponent{} _ _ = Nothing findIB :: Component -> ComponentInstance -> Operation -> Maybe VName findIB (CompositeComponent _ _ _ ibs _) ci o = findB ibs ci o findIB BasicComponent{} _ _ = Nothing {-| Helper to get the root value in a tree (provided leaves and nodes have the same kind of value). -} value :: Tree a a c -> a value (Leaf x ) = x value (Node x _) = x {-| Get the component instance at the root of a tree. -} rootInstance :: VCTree -> ComponentInstance rootInstance (Leaf c ) = c rootInstance (Node c _) = c {-| Get the instance id at the root of a tree. -} rootId :: VCTree -> VName rootId = instanceId . rootInstance {-| Index an operation by a name. -} indexBy :: VName -> Operation -> Operation indexBy i (Operation n) = Operation (i <> n) {-| Map a function on the leaves of a tree. Just a renaming for first in Trifunctor. -} mapleaves :: (a -> a') -> Tree a b c -> Tree a' b c mapleaves = first {-| Lift a substitution over operations to a substitution over events. -} liftOSubToESub :: VOSubstitution -> VTESubstitution liftOSubToESub = foldMap (fLift [CTReceive, CTReply, CTInvoke, CTResult]) {-| Lift a couple wrt. a collection of functions. -} fLift :: Functor f => f (a -> b) -> (a, a) -> f (b, b) fLift cs (a1, a2) = f a1 a2 <$> cs where f x y c = (c x, c y)
pascalpoizat/vecahaskell
src/Veca/Operations.hs
apache-2.0
16,330
22
23
6,046
4,532
2,309
2,223
305
4
module Futhark.CodeGen.ImpGen.OpenCL ( compileProg ) where import Control.Applicative import Prelude import Futhark.Representation.ExplicitMemory (Prog) import qualified Futhark.CodeGen.ImpCode.OpenCL as OpenCL import qualified Futhark.CodeGen.ImpGen.Kernels as ImpGenKernels import Futhark.CodeGen.ImpGen.Kernels.ToOpenCL import Futhark.MonadFreshNames compileProg :: MonadFreshNames m => Prog -> m (Either String OpenCL.Program) compileProg prog = either Left kernelsToOpenCL <$> ImpGenKernels.compileProg prog
CulpaBS/wbBach
src/Futhark/CodeGen/ImpGen/OpenCL.hs
bsd-3-clause
521
0
10
55
116
70
46
11
1
module AST.Module ( Interfaces , Types, Aliases, ADTs , AdtInfo, CanonicalAdt , SourceModule, ValidModule, CanonicalModule, Optimized , Module(..), Body(..) , Header(..) , Interface(..), toInterface , UserImport, DefaultImport, ImportMethod(..) ) where import Control.Applicative ((<$>),(<*>)) import Data.Binary import qualified Data.Map as Map import qualified AST.Declaration as Decl import qualified AST.Expression.Canonical as Canonical import qualified AST.Expression.Optimized as Optimized import qualified AST.Module.Name as Name import qualified AST.Type as Type import qualified AST.Variable as Var import qualified Docs.AST as Docs import qualified Elm.Package as Package import qualified Elm.Compiler.Version as Compiler import qualified Reporting.Annotation as A -- HELPFUL TYPE ALIASES type Interfaces = Map.Map Name.Canonical Interface type Types = Map.Map String Type.Canonical type Aliases = Map.Map String ([String], Type.Canonical) type ADTs = Map.Map String (AdtInfo String) type AdtInfo v = ( [String], [(v, [Type.Canonical])] ) type CanonicalAdt = (Var.Canonical, AdtInfo Var.Canonical) -- MODULES type SourceModule = Module String [UserImport] (Var.Listing (A.Located Var.Value)) [Decl.SourceDecl] type ValidModule = Module String ([DefaultImport], [UserImport]) (Var.Listing (A.Located Var.Value)) [Decl.ValidDecl] type CanonicalModule = Module Docs.Centralized [Name.Raw] [Var.Value] (Body Canonical.Expr) type Optimized = Module Docs.Centralized [Name.Raw] [Var.Value] (Body [Optimized.Def]) data Module docs imports exports body = Module { name :: Name.Canonical , path :: FilePath , docs :: A.Located (Maybe docs) , exports :: exports , imports :: imports , body :: body } data Body expr = Body { program :: expr , types :: Types , fixities :: [(Decl.Assoc, Int, String)] , aliases :: Aliases , datatypes :: ADTs , ports :: [String] } -- HEADERS {-| Basic info needed to identify modules and determine dependencies. -} data Header imports = Header { _name :: Name.Raw , _docs :: A.Located (Maybe String) , _exports :: Var.Listing (A.Located Var.Value) , _imports :: imports } -- IMPORTs type UserImport = A.Located (Name.Raw, ImportMethod) type DefaultImport = (Name.Raw, ImportMethod) data ImportMethod = ImportMethod { alias :: Maybe String , exposedVars :: !(Var.Listing Var.Value) } -- INTERFACES {-| Key facts about a module, used when reading info from .elmi files. -} data Interface = Interface { iVersion :: Package.Version , iPackage :: Package.Name , iExports :: [Var.Value] , iTypes :: Types , iImports :: [Name.Raw] , iAdts :: ADTs , iAliases :: Aliases , iFixities :: [(Decl.Assoc, Int, String)] , iPorts :: [String] } toInterface :: Package.Name -> Optimized -> Interface toInterface pkgName modul = let body' = body modul in Interface { iVersion = Compiler.version , iPackage = pkgName , iExports = exports modul , iTypes = types body' , iImports = imports modul , iAdts = datatypes body' , iAliases = aliases body' , iFixities = fixities body' , iPorts = ports body' } instance Binary Interface where get = Interface <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get put modul = do put (iVersion modul) put (iPackage modul) put (iExports modul) put (iTypes modul) put (iImports modul) put (iAdts modul) put (iAliases modul) put (iFixities modul) put (iPorts modul)
Axure/elm-compiler
src/AST/Module.hs
bsd-3-clause
3,762
0
14
918
1,121
661
460
105
1
{-# LANGUAGE QuasiQuotes, OverloadedStrings #-} {- virtual-dom bindings demo, rendering a large pixel grid with a bouncing red square. the step and patch are calculated asynchronously, the update is batched in an animation frame -} module Main where import Prelude hiding (div) import Control.Concurrent import Data.IntMap (IntMap) import qualified Data.IntMap as IM import System.IO import GHCJS.VDOM import GHCJS.VDOM.QQ import GHCJS.Foreign import GHCJS.Foreign.QQ import GHCJS.Types import Control.Arrow red :: JSString red = "pixel-red" white :: JSString white = "pixel-white" type Pixels = IntMap (IntMap JSString) setPixel :: Int -> Int -> JSString -> Pixels -> Pixels setPixel x y c p = let r = p IM.! y r' = IM.insert x c r in r' `seq` IM.insert y r' p data State = State { x :: !Int, y :: !Int , dx :: !Int, dy :: !Int , w :: !Int, h :: !Int , pixels :: !Pixels } mkState :: Int -> Int -> Int -> Int -> State mkState w h x y = State x y 1 1 w h pix where pix = IM.fromList $ map row [0..h-1] row n = (n, IM.fromList (map (col n) [0..w-1])) col n m = (m, if (m,n)==(x,y) then red else white) step :: State -> State step (State x y dx dy w h p) = let dx' = if x==0 then 1 else if x==(w-1) then -1 else dx dy' = if y==0 then 1 else if y==(h-1) then -1 else dy x' = x+dx' y' = y+dy' p' = setPixel x' y' red (setPixel x y white p) in State x' y' dx' dy' w h p' cls :: JSString -> Properties cls name = [pr| className: name |] render :: State -> VNode render s = div (cls "state") [ch|pixelDiv,numDiv|] where xd = textDiv (y s) yd = textDiv (x s) numDiv = div (cls "numeric") [ch|xd,yd|] pixelDiv = div (cls "pixels") . mkChildren $ map (renderRowM (w s) . (pixels s IM.!)) [0..h s-1] textDiv :: Show a => a -> VNode textDiv x = div noProps [ch|c|] where c = text . toJSString . show $ x renderRowM = memo renderRow renderRow :: Int -> IntMap JSString -> VNode renderRow w r = div [pr|className: 'row' |] . mkChildren $ map (renderPixelM r) [0..w-1] renderPixelM = memo renderPixel renderPixel :: IntMap JSString -> Int -> VNode renderPixel r c = div (cls (r IM.! c)) noChildren animate :: DOMNode -> VNode -> State -> IO () animate n r s = let s' = step s r' = render s' p = diff r r' -- in s' `seq` redraw n p >> threadDelay 20000 >> animate n r' s' -- for async calculation, sync repaint in atAnimationFrame (patch n p >> animate n r' s') -- sync all redraw :: DOMNode -> Patch -> IO () redraw node p = p `seq` atAnimationFrame (patch node p) atAnimationFrame :: IO () -> IO () atAnimationFrame m = do cb <- fixIO $ \cb -> syncCallback AlwaysRetain False (release cb >> m) [js_| window.requestAnimationFrame(`cb); |] main :: IO () main = do root <- [js| document.createElement('div') |] [js_| document.body.appendChild(`root); |] let s = mkState 167 101 10 20 animate root emptyDiv s
wavewave/ghcjs-vdom
example/Example.hs
mit
3,159
0
13
906
1,189
636
553
93
5
{-# LANGUAGE OverloadedStrings #-} import Control.Monad (filterM, when) import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L8 import Data.List (isInfixOf, isPrefixOf, sort) import Network.HTTP.Client import Network.HTTP.Client.MultipartFormData import System.Directory (doesDirectoryExist, getDirectoryContents) import System.Environment (getArgs, getEnv, getProgName) import System.Exit (exitFailure) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (takeDirectory, (</>)) import System.Process (createProcess, cwd, proc, waitForProcess) main :: IO () main = withManager defaultManagerSettings $ \m -> do args <- getArgs token <- readFile "/auth-token" (filepath, alias) <- case args of [x, y] -> return (x, y) _ -> do pn <- getProgName putStrLn $ concat [ "Usage: " , pn , " <filepath> <alias name>" ] exitFailure let uploadDocs = "exclusive" `isInfixOf` alias uploadHackageDistro = alias == "unstable-ghc78-exclusive" putStrLn $ concat [ "Uploading " , filepath , " as " , alias ] req1 <- parseUrl "http://www.stackage.org/upload" let formData = [ partBS "alias" $ S8.pack alias , partFileSource "stackage" filepath ] req2 <- formDataBody formData req1 let req3 = req2 { method = "PUT" , requestHeaders = [ ("Authorization", S8.pack token) , ("Accept", "application/json") ] ++ requestHeaders req2 , redirectCount = 0 , checkStatus = \_ _ _ -> Nothing } res <- httpLbs req3 m snapid <- case lookup "x-stackage-ident" $ responseHeaders res of Just snapid -> do putStrLn $ "New ident: " ++ S8.unpack snapid return snapid Nothing -> error $ "An error occurred: " ++ show res when uploadDocs $ do putStrLn "Generating index file" let root = takeDirectory filepath </> "haddock" contents <- getDirectoryContents root dirs <- filterM (\n -> doesDirectoryExist $ root </> n) $ filter (not . ("." `isPrefixOf`)) $ sort contents writeFile (root </> "index.html") $ mkIndex (S8.unpack snapid) dirs writeFile (root </> "style.css") styleCss putStrLn "Creating tarball" (Nothing, Nothing, Nothing, ph) <- createProcess (proc "tar" $ "cJf" : "haddock.tar.xz" : "index.html" : "style.css" : dirs) { cwd = Just root } ec <- waitForProcess ph if ec == ExitSuccess then putStrLn "Haddock tarball generated" else error "Error generating Haddock tarball" putStrLn "Uploading Haddocks" req1 <- parseUrl $ "http://www.stackage.org/upload-haddock/" ++ S8.unpack snapid let formData = [ partFileSource "tarball" $ root </> "haddock.tar.xz" ] req2 <- formDataBody formData req1 let req3 = req2 { method = "PUT" , requestHeaders = [ ("Authorization", S8.pack token) , ("Accept", "application/json") ] ++ requestHeaders req2 , redirectCount = 0 , checkStatus = \_ _ _ -> Nothing } httpLbs req3 m >>= print when uploadHackageDistro $ do lbs <- L.readFile $ takeDirectory filepath </> "build-plan.csv" let req = "http://hackage.haskell.org/distro/Stackage/packages.csv" { requestHeaders = [("Content-Type", "text/csv")] , requestBody = RequestBodyLBS $ L.intercalate "\n" $ L8.lines lbs , checkStatus = \_ _ _ -> Nothing , method = "PUT" } httpLbs req m >>= print mkIndex :: String -> [String] -> String mkIndex snapid dirs = concat [ "<!DOCTYPE html>\n<html lang='en'><head><title>Haddocks index</title>" , "<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>" , "<link rel='stylesheet' href='style.css'>" , "<link rel='shortcut icon' href='http://www.stackage.org/static/img/favicon.ico' />" , "</head>" , "<body><div class='container'>" , "<div class='row'><div class='span12 col-md-12'>" , "<h1>Haddock documentation index</h1>" , "<p class='return'><a href=\"http://www.stackage.org/stackage/" , snapid , "\">Return to snapshot</a></p><ul>" , concatMap toLI dirs , "</ul></div></div></div></body></html>" ] where toLI name = concat [ "<li><a href='" , name , "/index.html'>" , name , "</a></li>" ] styleCss :: String styleCss = concat [ "@media (min-width: 530px) {" , "ul { -webkit-column-count: 2; -moz-column-count: 2; column-count: 2 }" , "}" , "@media (min-width: 760px) {" , "ul { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3 }" , "}" , "ul {" , " margin-left: 0;" , " padding-left: 0;" , " list-style-type: none;" , "}" , "body {" , " background: #f0f0f0;" , " font-family: 'Lato', sans-serif;" , " text-shadow: 1px 1px 1px #ffffff;" , " font-size: 20px;" , " line-height: 30px;" , " padding-bottom: 5em;" , "}" , "h1 {" , " font-weight: normal;" , " color: #06537d;" , " font-size: 45px;" , "}" , ".return a {" , " color: #06537d;" , " font-style: italic;" , "}" , ".return {" , " margin-bottom: 1em;" , "}"]
feuerbach/stackage
stackage-upload.hs
mit
6,476
0
21
2,466
1,234
665
569
153
4
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 HsTypes: Abstract syntax: user-defined types -} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE CPP #-} module ETA.HsSyn.HsTypes ( HsType(..), LHsType, HsKind, LHsKind, HsTyOp,LHsTyOp, HsTyVarBndr(..), LHsTyVarBndr, LHsTyVarBndrs(..), HsWithBndrs(..), HsTupleSort(..), HsExplicitFlag(..), HsContext, LHsContext, HsQuasiQuote(..), HsTyWrapper(..), HsTyLit(..), HsIPName(..), hsIPNameFS, LBangType, BangType, HsBang(..), HsSrcBang, HsImplBang, getBangType, getBangStrictness, ConDeclField(..), LConDeclField, pprConDeclFields, mkHsQTvs, hsQTvBndrs, isHsKindedTyVar, hsTvbAllKinded, mkExplicitHsForAllTy, mkImplicitHsForAllTy, mkQualifiedHsForAllTy, mkHsForAllTy, flattenTopLevelLHsForAllTy,flattenTopLevelHsForAllTy, flattenHsForAllTyKeepAnns, hsExplicitTvs, hsTyVarName, mkHsWithBndrs, hsLKiTyVarNames, hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsLTyVarLocNames, splitLHsInstDeclTy_maybe, splitHsClassTy_maybe, splitLHsClassTy_maybe, splitHsFunType, splitHsAppTys, hsTyGetAppHead_maybe, mkHsAppTys, mkHsOpTy, isWildcardTy, isNamedWildcardTy, -- Printing pprParendHsType, pprHsForAll, pprHsForAllExtra, pprHsContext, pprHsContextNoArrow, pprHsContextMaybe ) where import {-# SOURCE #-} ETA.HsSyn.HsExpr ( HsSplice, pprUntypedSplice ) import ETA.HsSyn.PlaceHolder ( PostTc,PostRn,DataId,PlaceHolder(..) ) import ETA.BasicTypes.Name( Name ) import ETA.BasicTypes.RdrName( RdrName ) import ETA.BasicTypes.DataCon( HsBang(..), HsSrcBang, HsImplBang ) import ETA.Prelude.TysPrim( funTyConName ) import ETA.Types.Type import ETA.HsSyn.HsDoc import ETA.BasicTypes.BasicTypes import ETA.BasicTypes.SrcLoc import ETA.Main.StaticFlags import ETA.Utils.Outputable import ETA.Utils.FastString import ETA.Parser.Lexer ( AddAnn, mkParensApiAnn ) import ETA.Utils.Maybes( isJust ) import Data.Data hiding ( Fixity ) import Data.Maybe ( fromMaybe ) #if __GLASGOW_HASKELL__ < 709 import Data.Monoid hiding ((<>)) #endif {- ************************************************************************ * * Quasi quotes; used in types and elsewhere * * ************************************************************************ -} data HsQuasiQuote id = HsQuasiQuote id -- The quasi-quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string deriving (Data, Typeable) instance OutputableBndr id => Outputable (HsQuasiQuote id) where ppr = ppr_qq ppr_qq :: OutputableBndr id => HsQuasiQuote id -> SDoc ppr_qq (HsQuasiQuote quoter _ quote) = char '[' <> ppr quoter <> ptext (sLit "|") <> ppr quote <> ptext (sLit "|]") {- ************************************************************************ * * \subsection{Bang annotations} * * ************************************************************************ -} type LBangType name = Located (BangType name) type BangType name = HsType name -- Bangs are in the HsType data type getBangType :: LHsType a -> LHsType a getBangType (L _ (HsBangTy _ ty)) = ty getBangType ty = ty getBangStrictness :: LHsType a -> HsSrcBang getBangStrictness (L _ (HsBangTy s _)) = s getBangStrictness _ = HsNoBang {- ************************************************************************ * * \subsection{Data types} * * ************************************************************************ This is the syntax for types as seen in type signatures. Note [HsBSig binder lists] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider a binder (or pattern) decoarated with a type or kind, \ (x :: a -> a). blah forall (a :: k -> *) (b :: k). blah Then we use a LHsBndrSig on the binder, so that the renamer can decorate it with the variables bound by the pattern ('a' in the first example, 'k' in the second), assuming that neither of them is in scope already See also Note [Kind and type-variable binders] in RnTypes -} type LHsContext name = Located (HsContext name) -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit' -- For details on above see note [Api annotations] in ApiAnnotation type HsContext name = [LHsType name] type LHsType name = Located (HsType name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation type HsKind name = HsType name type LHsKind name = Located (HsKind name) -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation type LHsTyVarBndr name = Located (HsTyVarBndr name) data LHsTyVarBndrs name = HsQTvs { hsq_kvs :: [Name] -- Kind variables , hsq_tvs :: [LHsTyVarBndr name] -- Type variables -- See Note [HsForAllTy tyvar binders] } deriving( Typeable ) deriving instance (DataId name) => Data (LHsTyVarBndrs name) mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsTyVarBndrs RdrName -- Just at RdrName because in the Name variant we should know just -- what the kind-variable binders are; and we don't -- We put an empty list (rather than a panic) for the kind vars so -- that the pretty printer works ok on them. mkHsQTvs tvs = HsQTvs { hsq_kvs = [], hsq_tvs = tvs } emptyHsQTvs :: LHsTyVarBndrs name -- Use only when you know there are no kind binders emptyHsQTvs = HsQTvs { hsq_kvs = [], hsq_tvs = [] } hsQTvBndrs :: LHsTyVarBndrs name -> [LHsTyVarBndr name] hsQTvBndrs = hsq_tvs instance Monoid (LHsTyVarBndrs name) where mempty = emptyHsQTvs mappend (HsQTvs kvs1 tvs1) (HsQTvs kvs2 tvs2) = HsQTvs (kvs1 ++ kvs2) (tvs1 ++ tvs2) ------------------------------------------------ -- HsWithBndrs -- Used to quantify the binders of a type in cases -- when a HsForAll isn't appropriate: -- * Patterns in a type/data family instance (HsTyPats) -- * Type of a rule binder (RuleBndr) -- * Pattern type signatures (SigPatIn) -- In the last of these, wildcards can happen, so we must accommodate them data HsWithBndrs name thing = HsWB { hswb_cts :: thing -- Main payload (type or list of types) , hswb_kvs :: PostRn name [Name] -- Kind vars , hswb_tvs :: PostRn name [Name] -- Type vars , hswb_wcs :: PostRn name [Name] -- Wildcards } deriving (Typeable) deriving instance (Data name, Data thing, Data (PostRn name [Name])) => Data (HsWithBndrs name thing) mkHsWithBndrs :: thing -> HsWithBndrs RdrName thing mkHsWithBndrs x = HsWB { hswb_cts = x, hswb_kvs = PlaceHolder , hswb_tvs = PlaceHolder , hswb_wcs = PlaceHolder } -- | These names are used early on to store the names of implicit -- parameters. They completely disappear after type-checking. newtype HsIPName = HsIPName FastString-- ?x deriving( Eq, Data, Typeable ) hsIPNameFS :: HsIPName -> FastString hsIPNameFS (HsIPName n) = n instance Outputable HsIPName where ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters instance OutputableBndr HsIPName where pprBndr _ n = ppr n -- Simple for now pprInfixOcc n = ppr n pprPrefixOcc n = ppr n data HsTyVarBndr name = UserTyVar -- no explicit kinding name | KindedTyVar (Located name) (LHsKind name) -- The user-supplied kind signature -- ^ -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (HsTyVarBndr name) -- | Does this 'HsTyVarBndr' come with an explicit kind annotation? isHsKindedTyVar :: HsTyVarBndr name -> Bool isHsKindedTyVar (UserTyVar {}) = False isHsKindedTyVar (KindedTyVar {}) = True -- | Do all type variables in this 'LHsTyVarBndr' come with kind annotations? hsTvbAllKinded :: LHsTyVarBndrs name -> Bool hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvBndrs data HsType name = HsForAllTy HsExplicitFlag -- Renamer leaves this flag unchanged, to record the way -- the user wrote it originally, so that the printer can -- print it as the user wrote it (Maybe SrcSpan) -- Indicates whether extra constraints may be inferred. -- When Nothing, no, otherwise the location of the extra- -- constraints wildcard is stored. For instance, for the -- signature (Eq a, _) => a -> a -> Bool, this field would -- be something like (Just 1:8), with 1:8 being line 1, -- column 8. (LHsTyVarBndrs name) (LHsContext name) (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall', -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsTyVar name -- Type variable, type constructor, or data constructor -- see Note [Promotions (HsTyVar)] -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsAppTy (LHsType name) (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsFunTy (LHsType name) -- function type (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsListTy (LHsType name) -- Element type -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPArrTy (LHsType name) -- Elem. type of parallel array: [:t:] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTupleTy HsTupleSort [LHsType name] -- Element types (length gives arity) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@, -- 'ApiAnnotation.AnnClose' @')' or '#)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsOpTy (LHsType name) (LHsTyOp name) (LHsType name) -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsParTy (LHsType name) -- See Note [Parens in HsSyn] in HsExpr -- Parenthesis preserved for the precedence re-arrangement in RnTypes -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c! -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsIParamTy HsIPName -- (?x :: ty) (LHsType name) -- Implicit parameters as they occur in contexts -- ^ -- > (?x :: ty) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | HsEqTy (LHsType name) -- ty1 ~ ty2 (LHsType name) -- Always allowed even without TypeOperators, and has special kinding rule -- ^ -- > ty1 ~ ty2 -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | HsKindSig (LHsType name) -- (ty :: kind) (LHsKind name) -- A type with a kind signature -- ^ -- > (ty :: kind) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsQuasiQuoteTy (HsQuasiQuote name) -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceTy (HsSplice name) (PostTc name Kind) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsDocTy (LHsType name) LHsDocString -- A documented type -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsBangTy HsSrcBang (LHsType name) -- Bang-style type annotations -- ^ - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@, -- 'ApiAnnotation.AnnClose' @'#-}'@ -- 'ApiAnnotation.AnnBang' @\'!\'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsRecTy [LConDeclField name] -- Only in data type declarations -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreTy Type -- An escape hatch for tunnelling a *closed* -- Core Type through HsSyn. -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsExplicitListTy -- A promoted explicit list (PostTc name Kind) -- See Note [Promoted lists and tuples] [LHsType name] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsExplicitTupleTy -- A promoted explicit tuple [PostTc name Kind] -- See Note [Promoted lists and tuples] [LHsType name] -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTyLit HsTyLit -- A promoted numeric literal. -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsWrapTy HsTyWrapper (HsType name) -- only in typechecker output -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsWildcardTy -- A type wildcard -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation | HsNamedWildcardTy name -- A named wildcard -- ^ - 'ApiAnnotation.AnnKeywordId' : None -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (HsType name) -- Note [Literal source text] in BasicTypes for SourceText fields in -- the following data HsTyLit = HsNumTy SourceText Integer | HsStrTy SourceText FastString deriving (Data, Typeable) data HsTyWrapper = WpKiApps [Kind] -- kind instantiation: [] k1 k2 .. kn deriving (Data, Typeable) type LHsTyOp name = HsTyOp (Located name) type HsTyOp name = (HsTyWrapper, name) mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name mkHsOpTy ty1 op ty2 = HsOpTy ty1 (WpKiApps [], op) ty2 {- Note [HsForAllTy tyvar binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ After parsing: * Implicit => empty Explicit => the variables the user wrote After renaming * Implicit => the *type* variables free in the type Explicit => the variables the user wrote (renamed) Qualified currently behaves exactly as Implicit, but it is deprecated to use it for implicit quantification. In this case, GHC 7.10 gives a warning; see Note [Context quantification] and Trac #4426. In GHC 7.12, Qualified will no longer bind variables and this will become an error. The kind variables bound in the hsq_kvs field come both a) from the kind signatures on the kind vars (eg k1) b) from the scope of the forall (eg k2) Example: f :: forall (a::k1) b. T a (b::k2) Note [Unit tuples] ~~~~~~~~~~~~~~~~~~ Consider the type type instance F Int = () We want to parse that "()" as HsTupleTy HsBoxedOrConstraintTuple [], NOT as HsTyVar unitTyCon Why? Because F might have kind (* -> Constraint), so we when parsing we don't know if that tuple is going to be a constraint tuple or an ordinary unit tuple. The HsTupleSort flag is specifically designed to deal with that, but it has to work for unit tuples too. Note [Promotions (HsTyVar)] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ HsTyVar: A name in a type or kind. Here are the allowed namespaces for the name. In a type: Var: not allowed Data: promoted data constructor Tv: type variable TcCls before renamer: type constructor, class constructor, or promoted data constructor TcCls after renamer: type constructor or class constructor In a kind: Var, Data: not allowed Tv: kind variable TcCls: kind constructor or promoted type constructor Note [Promoted lists and tuples] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Notice the difference between HsListTy HsExplicitListTy HsTupleTy HsExplicitListTupleTy E.g. f :: [Int] HsListTy g3 :: T '[] All these use g2 :: T '[True] HsExplicitListTy g1 :: T '[True,False] g1a :: T [True,False] (can omit ' where unambiguous) kind of T :: [Bool] -> * This kind uses HsListTy! E.g. h :: (Int,Bool) HsTupleTy; f is a pair k :: S '(True,False) HsExplicitTypleTy; S is indexed by a type-level pair of booleans kind of S :: (Bool,Bool) -> * This kind uses HsExplicitTupleTy Note [Distinguishing tuple kinds] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Apart from promotion, tuples can have one of three different kinds: x :: (Int, Bool) -- Regular boxed tuples f :: Int# -> (# Int#, Int# #) -- Unboxed tuples g :: (Eq a, Ord a) => a -- Constraint tuples For convenience, internally we use a single constructor for all of these, namely HsTupleTy, but keep track of the tuple kind (in the first argument to HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing, because of the #. However, with -XConstraintKinds we can only distinguish between constraint and boxed tuples during type checking, in general. Hence the four constructors of HsTupleSort: HsUnboxedTuple -> Produced by the parser HsBoxedTuple -> Certainly a boxed tuple HsConstraintTuple -> Certainly a constraint tuple HsBoxedOrConstraintTuple -> Could be a boxed or a constraint tuple. Produced by the parser only, disappears after type checking -} data HsTupleSort = HsUnboxedTuple | HsBoxedTuple | HsConstraintTuple | HsBoxedOrConstraintTuple deriving (Data, Typeable) data HsExplicitFlag = Qualified | Implicit | Explicit deriving (Data, Typeable) type LConDeclField name = Located (ConDeclField name) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation data ConDeclField name -- Record fields have Haddoc docs on them = ConDeclField { cd_fld_names :: [Located name], cd_fld_type :: LBangType name, cd_fld_doc :: Maybe LHsDocString } -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation deriving (Typeable) deriving instance (DataId name) => Data (ConDeclField name) ----------------------- -- A valid type must have a for-all at the top of the type, or of the fn arg -- types mkImplicitHsForAllTy :: LHsType RdrName -> HsType RdrName mkExplicitHsForAllTy :: [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName mkQualifiedHsForAllTy :: LHsContext RdrName -> LHsType RdrName -> HsType RdrName -- | mkImplicitHsForAllTy is called when we encounter -- f :: type -- Wrap around a HsForallTy if one is not there already. mkImplicitHsForAllTy (L _ (HsForAllTy exp extra tvs cxt ty)) = HsForAllTy exp' extra tvs cxt ty where exp' = case exp of Qualified -> Implicit -- Qualified is used only for a nested forall, -- this is now top level _ -> exp mkImplicitHsForAllTy ty = mkHsForAllTy Implicit [] (noLoc []) ty mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty mkQualifiedHsForAllTy ctxt ty = mkHsForAllTy Qualified [] ctxt ty -- |Smart constructor for HsForAllTy, which populates the extra-constraints -- field if a wildcard is present in the context. mkHsForAllTy :: HsExplicitFlag -> [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName mkHsForAllTy exp tvs (L l []) ty = HsForAllTy exp Nothing (mkHsQTvs tvs) (L l []) ty mkHsForAllTy exp tvs ctxt ty = HsForAllTy exp extra (mkHsQTvs tvs) cleanCtxt ty where -- Separate the extra-constraints wildcard when present (cleanCtxt, extra) | (L l HsWildcardTy) <- ignoreParens (last (unLoc ctxt)) = (init `fmap` ctxt, Just l) | otherwise = (ctxt, Nothing) ignoreParens (L _ (HsParTy ty)) = ty ignoreParens ty = ty -- |When a sigtype is parsed, the type found is wrapped in an Implicit -- HsForAllTy via mkImplicitHsForAllTy, to ensure that a signature always has a -- forall at the outer level. For Api Annotations this nested structure is -- important to ensure that all `forall` and `.` locations are retained. From -- the renamer onwards this structure is flattened, to ease the renaming and -- type checking process. flattenTopLevelLHsForAllTy :: LHsType name -> LHsType name flattenTopLevelLHsForAllTy (L l ty) = L l (flattenTopLevelHsForAllTy ty) flattenTopLevelHsForAllTy :: HsType name -> HsType name flattenTopLevelHsForAllTy (HsForAllTy exp extra tvs (L l []) ty) = snd $ mk_forall_ty [] l exp extra tvs ty flattenTopLevelHsForAllTy ty = ty flattenHsForAllTyKeepAnns :: HsType name -> ([AddAnn],HsType name) flattenHsForAllTyKeepAnns (HsForAllTy exp extra tvs (L l []) ty) = mk_forall_ty [] l exp extra tvs ty flattenHsForAllTyKeepAnns ty = ([],ty) -- mk_forall_ty makes a pure for-all type (no context) mk_forall_ty :: [AddAnn] -> SrcSpan -> HsExplicitFlag -> Maybe SrcSpan -> LHsTyVarBndrs name -> LHsType name -> ([AddAnn],HsType name) mk_forall_ty ann _ exp1 extra1 tvs1 (L _ (HsForAllTy exp2 extra qtvs2 ctxt ty)) = (ann,HsForAllTy (exp1 `plus` exp2) (mergeExtra extra1 extra) (tvs1 `mappend` qtvs2) ctxt ty) where -- Bias the merging of extra's to the top level, so that a single -- wildcard context will prevail mergeExtra (Just s) _ = Just s mergeExtra _ e = e mk_forall_ty ann l exp extra tvs (L lp (HsParTy ty)) = mk_forall_ty (ann ++ mkParensApiAnn lp) l exp extra tvs ty mk_forall_ty ann l exp extra tvs ty = (ann,HsForAllTy exp extra tvs (L l []) ty) -- Even if tvs is empty, we still make a HsForAll! -- In the Implicit case, this signals the place to do implicit quantification -- In the Explicit case, it prevents implicit quantification -- (see the sigtype production in Parser.y) -- so that (forall. ty) isn't implicitly quantified plus :: HsExplicitFlag -> HsExplicitFlag -> HsExplicitFlag Qualified `plus` Qualified = Qualified Explicit `plus` _ = Explicit _ `plus` Explicit = Explicit _ `plus` _ = Implicit --------------------- hsExplicitTvs :: LHsType Name -> [Name] -- The explicitly-given forall'd type variables of a HsType hsExplicitTvs (L _ (HsForAllTy Explicit _ tvs _ _)) = hsLKiTyVarNames tvs hsExplicitTvs _ = [] --------------------- hsTyVarName :: HsTyVarBndr name -> name hsTyVarName (UserTyVar n) = n hsTyVarName (KindedTyVar (L _ n) _) = n hsLTyVarName :: LHsTyVarBndr name -> name hsLTyVarName = hsTyVarName . unLoc hsLTyVarNames :: LHsTyVarBndrs name -> [name] -- Type variables only hsLTyVarNames qtvs = map hsLTyVarName (hsQTvBndrs qtvs) hsLKiTyVarNames :: LHsTyVarBndrs Name -> [Name] -- Kind and type variables hsLKiTyVarNames (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) = kvs ++ map hsLTyVarName tvs hsLTyVarLocName :: LHsTyVarBndr name -> Located name hsLTyVarLocName = fmap hsTyVarName hsLTyVarLocNames :: LHsTyVarBndrs name -> [Located name] hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvBndrs qtvs) --------------------- isWildcardTy :: HsType a -> Bool isWildcardTy HsWildcardTy = True isWildcardTy _ = False isNamedWildcardTy :: HsType a -> Bool isNamedWildcardTy (HsNamedWildcardTy _) = True isNamedWildcardTy _ = False splitHsAppTys :: LHsType n -> [LHsType n] -> (LHsType n, [LHsType n]) splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as) splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as splitHsAppTys f as = (f,as) -- retrieve the name of the "head" of a nested type application -- somewhat like splitHsAppTys, but a little more thorough -- used to examine the result of a GADT-like datacon, so it doesn't handle -- *all* cases (like lists, tuples, (~), etc.) hsTyGetAppHead_maybe :: LHsType n -> Maybe (n, [LHsType n]) hsTyGetAppHead_maybe = go [] where go tys (L _ (HsTyVar n)) = Just (n, tys) go tys (L _ (HsAppTy l r)) = go (r : tys) l go tys (L _ (HsOpTy l (_, L _ n) r)) = Just (n, l : r : tys) go tys (L _ (HsParTy t)) = go tys t go tys (L _ (HsKindSig t _)) = go tys t go _ _ = Nothing mkHsAppTys :: OutputableBndr n => LHsType n -> [LHsType n] -> HsType n mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty) mkHsAppTys fun_ty (arg_ty:arg_tys) = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys where mk_app fun arg = HsAppTy (noLoc fun) arg -- Add noLocs for inner nodes of the application; -- they are never used splitLHsInstDeclTy_maybe :: LHsType name -> Maybe (LHsTyVarBndrs name, HsContext name, Located name, [LHsType name]) -- Split up an instance decl type, returning the pieces splitLHsInstDeclTy_maybe inst_ty = do let (tvs, cxt, ty) = splitLHsForAllTy inst_ty (cls, tys) <- splitLHsClassTy_maybe ty return (tvs, cxt, cls, tys) splitLHsForAllTy :: LHsType name -> (LHsTyVarBndrs name, HsContext name, LHsType name) splitLHsForAllTy poly_ty = case unLoc poly_ty of HsParTy ty -> splitLHsForAllTy ty HsForAllTy _ _ tvs cxt ty -> (tvs, unLoc cxt, ty) _ -> (emptyHsQTvs, [], poly_ty) -- The type vars should have been computed by now, even if they were implicit splitHsClassTy_maybe :: HsType name -> Maybe (name, [LHsType name]) splitHsClassTy_maybe ty = fmap (\(L _ n, tys) -> (n, tys)) $ splitLHsClassTy_maybe (noLoc ty) splitLHsClassTy_maybe :: LHsType name -> Maybe (Located name, [LHsType name]) --- Watch out.. in ...deriving( Show )... we use this on --- the list of partially applied predicates in the deriving, --- so there can be zero args. -- In TcDeriv we also use this to figure out what data type is being -- mentioned in a deriving (Generic (Foo bar baz)) declaration (i.e. "Foo"). splitLHsClassTy_maybe ty = checkl ty [] where checkl (L l ty) args = case ty of HsTyVar t -> Just (L l t, args) HsAppTy l r -> checkl l (r:args) HsOpTy l (_, tc) r -> checkl (fmap HsTyVar tc) (l:r:args) HsParTy t -> checkl t args HsKindSig ty _ -> checkl ty args _ -> Nothing -- splitHsFunType decomposes a type (t1 -> t2 ... -> tn) -- Breaks up any parens in the result type: -- splitHsFunType (a -> (b -> c)) = ([a,b], c) -- Also deals with (->) t1 t2; that is why it only works on LHsType Name -- (see Trac #9096) splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name) splitHsFunType (L _ (HsParTy ty)) = splitHsFunType ty splitHsFunType (L _ (HsFunTy x y)) | (args, res) <- splitHsFunType y = (x:args, res) splitHsFunType orig_ty@(L _ (HsAppTy t1 t2)) = go t1 [t2] where -- Look for (->) t1 t2, possibly with parenthesisation go (L _ (HsTyVar fn)) tys | fn == funTyConName , [t1,t2] <- tys , (args, res) <- splitHsFunType t2 = (t1:args, res) go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys) go (L _ (HsParTy ty)) tys = go ty tys go _ _ = ([], orig_ty) -- Failure to match splitHsFunType other = ([], other) {- ************************************************************************ * * \subsection{Pretty printing} * * ************************************************************************ -} instance (OutputableBndr name) => Outputable (HsType name) where ppr ty = pprHsType ty instance Outputable HsTyLit where ppr = ppr_tylit instance (OutputableBndr name) => Outputable (LHsTyVarBndrs name) where ppr (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs }) = sep [ ifPprDebug $ braces (interppSP kvs), interppSP tvs ] instance (OutputableBndr name) => Outputable (HsTyVarBndr name) where ppr (UserTyVar n) = ppr n ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k] instance (Outputable thing) => Outputable (HsWithBndrs name thing) where ppr (HsWB { hswb_cts = ty }) = ppr ty pprHsForAll :: OutputableBndr name => HsExplicitFlag -> LHsTyVarBndrs name -> LHsContext name -> SDoc pprHsForAll exp = pprHsForAllExtra exp Nothing -- | Version of 'pprHsForAll' that can also print an extra-constraints -- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This -- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just' -- containing the location of the extra-constraints wildcard. A special -- function for this is needed, as the extra-constraints wildcard is removed -- from the actual context and type, and stored in a separate field, thus just -- printing the type will not print the extra-constraints wildcard. pprHsForAllExtra :: OutputableBndr name => HsExplicitFlag -> Maybe SrcSpan -> LHsTyVarBndrs name -> LHsContext name -> SDoc pprHsForAllExtra exp extra qtvs cxt | show_forall = forall_part <+> pprHsContextExtra show_extra (unLoc cxt) | otherwise = pprHsContextExtra show_extra (unLoc cxt) where show_extra = isJust extra show_forall = opt_PprStyle_Debug || (not (null (hsQTvBndrs qtvs)) && is_explicit) is_explicit = case exp of {Explicit -> True; Implicit -> False; Qualified -> False} forall_part = forAllLit <+> ppr qtvs <> dot pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe pprHsContextNoArrow :: (OutputableBndr name) => HsContext name -> SDoc pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe pprHsContextMaybe :: (OutputableBndr name) => HsContext name -> Maybe SDoc pprHsContextMaybe [] = Nothing pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty FunPrec pred pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt) -- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@ pprHsContextExtra :: (OutputableBndr name) => Bool -> HsContext name -> SDoc pprHsContextExtra False = pprHsContext pprHsContextExtra True = \ctxt -> case ctxt of [] -> char '_' <+> darrow _ -> parens (sep (punctuate comma ctxt')) <+> darrow where ctxt' = map ppr ctxt ++ [char '_'] pprConDeclFields :: OutputableBndr name => [LConDeclField name] -> SDoc pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields))) where ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty, cd_fld_doc = doc })) = ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc ppr_names [n] = ppr n ppr_names ns = sep (punctuate comma (map ppr ns)) {- Note [Printing KindedTyVars] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Trac #3830 reminded me that we should really only print the kind signature on a KindedTyVar if the kind signature was put there by the programmer. During kind inference GHC now adds a PostTcKind to UserTyVars, rather than converting to KindedTyVars as before. (As it happens, the message in #3830 comes out a different way now, and the problem doesn't show up; but having the flag on a KindedTyVar seems like the Right Thing anyway.) -} -- Printing works more-or-less as for Types pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc pprHsType ty = getPprStyle $ \sty -> ppr_mono_ty TopPrec (prepare sty ty) pprParendHsType ty = ppr_mono_ty TyConPrec ty -- Before printing a type -- (a) Remove outermost HsParTy parens -- (b) Drop top-level for-all type variables in user style -- since they are implicit in Haskell prepare :: PprStyle -> HsType name -> HsType name prepare sty (HsParTy ty) = prepare sty (unLoc ty) prepare _ ty = ty ppr_mono_lty :: (OutputableBndr name) => TyPrec -> LHsType name -> SDoc ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty) ppr_mono_ty :: (OutputableBndr name) => TyPrec -> HsType name -> SDoc ppr_mono_ty ctxt_prec (HsForAllTy exp extra tvs ctxt ty) = maybeParen ctxt_prec FunPrec $ sep [pprHsForAllExtra exp extra tvs ctxt, ppr_mono_lty TopPrec ty] ppr_mono_ty _ (HsBangTy b ty) = ppr b <> ppr_mono_lty TyConPrec ty ppr_mono_ty _ (HsQuasiQuoteTy qq) = ppr qq ppr_mono_ty _ (HsRecTy flds) = pprConDeclFields flds ppr_mono_ty _ (HsTyVar name) = pprPrefixOcc name ppr_mono_ty prec (HsFunTy ty1 ty2) = ppr_fun_ty prec ty1 ty2 ppr_mono_ty _ (HsTupleTy con tys) = tupleParens std_con (interpp'SP tys) where std_con = case con of HsUnboxedTuple -> UnboxedTuple _ -> BoxedTuple ppr_mono_ty _ (HsKindSig ty kind) = parens (ppr_mono_lty TopPrec ty <+> dcolon <+> ppr kind) ppr_mono_ty _ (HsListTy ty) = brackets (ppr_mono_lty TopPrec ty) ppr_mono_ty _ (HsPArrTy ty) = paBrackets (ppr_mono_lty TopPrec ty) ppr_mono_ty prec (HsIParamTy n ty) = maybeParen prec FunPrec (ppr n <+> dcolon <+> ppr_mono_lty TopPrec ty) ppr_mono_ty _ (HsSpliceTy s _) = pprUntypedSplice s ppr_mono_ty _ (HsCoreTy ty) = ppr ty ppr_mono_ty _ (HsExplicitListTy _ tys) = quote $ brackets (interpp'SP tys) ppr_mono_ty _ (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys) ppr_mono_ty _ (HsTyLit t) = ppr_tylit t ppr_mono_ty _ HsWildcardTy = char '_' ppr_mono_ty _ (HsNamedWildcardTy name) = ppr name ppr_mono_ty ctxt_prec (HsWrapTy (WpKiApps _kis) ty) = ppr_mono_ty ctxt_prec ty -- We are not printing kind applications. If we wanted to do so, we should do -- something like this: {- = go ctxt_prec kis ty where go ctxt_prec [] ty = ppr_mono_ty ctxt_prec ty go ctxt_prec (ki:kis) ty = maybeParen ctxt_prec TyConPrec $ hsep [ go FunPrec kis ty , ptext (sLit "@") <> pprParendKind ki ] -} ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2) = maybeParen ctxt_prec TyOpPrec $ ppr_mono_lty TyOpPrec ty1 <+> char '~' <+> ppr_mono_lty TyOpPrec ty2 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty) = maybeParen ctxt_prec TyConPrec $ hsep [ppr_mono_lty FunPrec fun_ty, ppr_mono_lty TyConPrec arg_ty] ppr_mono_ty ctxt_prec (HsOpTy ty1 (_wrapper, L _ op) ty2) = maybeParen ctxt_prec TyOpPrec $ sep [ ppr_mono_lty TyOpPrec ty1 , sep [pprInfixOcc op, ppr_mono_lty TyOpPrec ty2 ] ] -- Don't print the wrapper (= kind applications) -- c.f. HsWrapTy ppr_mono_ty _ (HsParTy ty) = parens (ppr_mono_lty TopPrec ty) -- Put the parens in where the user did -- But we still use the precedence stuff to add parens because -- toHsType doesn't put in any HsParTys, so we may still need them ppr_mono_ty ctxt_prec (HsDocTy ty doc) = maybeParen ctxt_prec TyOpPrec $ ppr_mono_lty TyOpPrec ty <+> ppr (unLoc doc) -- we pretty print Haddock comments on types as if they were -- postfix operators -------------------------- ppr_fun_ty :: (OutputableBndr name) => TyPrec -> LHsType name -> LHsType name -> SDoc ppr_fun_ty ctxt_prec ty1 ty2 = let p1 = ppr_mono_lty FunPrec ty1 p2 = ppr_mono_lty TopPrec ty2 in maybeParen ctxt_prec FunPrec $ sep [p1, ptext (sLit "->") <+> p2] -------------------------- ppr_tylit :: HsTyLit -> SDoc ppr_tylit (HsNumTy _ i) = integer i ppr_tylit (HsStrTy _ s) = text (show s)
alexander-at-github/eta
compiler/ETA/HsSyn/HsTypes.hs
bsd-3-clause
39,207
0
15
10,353
6,907
3,708
3,199
431
6
{-# LANGUAGE TypeInType, RankNTypes, TypeFamilies #-} module T12742 where import Data.Kind type family F :: forall k2. (k1, k2) data T :: (forall k2. (Bool, k2)) -> Type type S = T F
ezyang/ghc
testsuite/tests/dependent/should_compile/T12742.hs
bsd-3-clause
188
0
8
38
62
39
23
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>График вызовов </title> <maps> <homeID>callgraph</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>СОДЕРЖАНИЕ </label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/callgraph/src/main/javahelp/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,012
77
66
158
485
243
242
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- | Clean a project. module Stack.Clean (clean ,CleanOpts(..) ,StackCleanException(..) ) where import Stack.Prelude import Data.List ((\\),intercalate) import qualified Data.Map.Strict as Map import qualified Data.Text as T import Path.IO (ignoringAbsence, removeDirRecur) import Stack.Config (getLocalPackages) import Stack.Constants.Config (distDirFromDir, workDirFromDir) import Stack.Types.PackageName import Stack.Types.Config import System.Exit (exitFailure) -- | Deletes build artifacts in the current project. -- -- Throws 'StackCleanException'. clean :: HasEnvConfig env => CleanOpts -> RIO env () clean cleanOpts = do failures <- mapM cleanDir =<< dirsToDelete cleanOpts when (or failures) $ liftIO exitFailure where cleanDir dir = liftIO (ignoringAbsence (removeDirRecur dir) >> return False) `catchAny` \ex -> do logError $ "Exception while recursively deleting " <> T.pack (toFilePath dir) <> "\n" <> T.pack (show ex) logError "Perhaps you do not have permission to delete these files or they are in use?" return True dirsToDelete :: HasEnvConfig env => CleanOpts -> RIO env [Path Abs Dir] dirsToDelete cleanOpts = do packages <- getLocalPackages case cleanOpts of CleanShallow [] -> -- Filter out packages listed as extra-deps mapM (distDirFromDir . lpvRoot) $ Map.elems $ lpProject packages CleanShallow targets -> do let localPkgViews = lpProject packages localPkgNames = Map.keys localPkgViews getPkgDir pkgName = fmap lpvRoot (Map.lookup pkgName localPkgViews) case targets \\ localPkgNames of [] -> mapM distDirFromDir (mapMaybe getPkgDir targets) xs -> throwM (NonLocalPackages xs) CleanFull -> do pkgWorkDirs <- mapM (workDirFromDir . lpvRoot) $ Map.elems $ lpProject packages projectWorkDir <- getProjectWorkDir return (projectWorkDir : pkgWorkDirs) -- | Options for @stack clean@. data CleanOpts = CleanShallow [PackageName] -- ^ Delete the "dist directories" as defined in 'Stack.Constants.distRelativeDir' -- for the given local packages. If no packages are given, all project packages -- should be cleaned. | CleanFull -- ^ Delete all work directories in the project. -- | Exceptions during cleanup. newtype StackCleanException = NonLocalPackages [PackageName] deriving (Typeable) instance Show StackCleanException where show (NonLocalPackages pkgs) = "The following packages are not part of this project: " ++ intercalate ", " (map show pkgs) instance Exception StackCleanException
MichielDerhaeg/stack
src/Stack/Clean.hs
bsd-3-clause
2,963
0
18
725
621
326
295
56
4
{-# LANGUAGE PatternGuards #-} {-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-overlapping-patterns #-} module T3078 where data T = A Int | B Int funny :: T -> Int funny t = n where n | A x <- t = x | B x <- t = x
ezyang/ghc
testsuite/tests/pmcheck/should_compile/T3078.hs
bsd-3-clause
237
0
11
66
73
38
35
8
1
{-# OPTIONS -fno-warn-redundant-constraints #-} {-# LANGUAGE TypeFamilies, GeneralizedNewtypeDeriving, StandaloneDeriving, FlexibleInstances #-} -- Test Trac #2856 module T2856 where import Data.Ratio ---------------------- class C a where data D a instance C Bool where newtype D Bool = DInt Int deriving (Eq, Show, Num) instance C a => C [a] where newtype D [a] = DList (Ratio a) deriving (Eq, Show, Num) ---------------------- data family W a newtype instance W Bool = WInt Int deriving( Eq, Show ) newtype instance W [a] = WList (Ratio a) deriving( Eq, Show ) deriving instance Num (W Bool) deriving instance (Integral a, Num a) => Num (W [a]) -- Integral needed because superclass Eq needs it, -- because of the stupid context on Ratio
urbanslug/ghc
testsuite/tests/deriving/should_compile/T2856.hs
bsd-3-clause
766
0
8
144
226
125
101
15
0
module TidyClash where -- Type variables originating from wildcards are normally given the name w_, -- but in this case there is already a type variable called w_. Tidying the -- types should result in w_1 and w_2 for the two new type variables -- originating from the wildcards. bar :: w_ -> (w_, _ -> _) bar x = (x, \y -> undefined)
siddhanathan/ghc
testsuite/tests/partial-sigs/should_fail/TidyClash.hs
bsd-3-clause
337
0
7
66
46
29
17
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Models.LegacyJson ( Period(..) , PlayoffSeed(..) , Game(..) , Event(..) , PlayoffsResponse(..) ) where import Data.Char as Char import Data.List as List import Hockey.Database import Hockey.Formatting (formattedGame, formattedSeason, formattedYear, intToInteger, fromStrength, fromEventType, boolToInt) import Hockey.Types (Season(..)) import Yesod -- Period instance ToJSON Period where toJSON Period {..} = object [ "teamID" .= periodTeamId , "gameID" .= show periodGameId , "period" .= periodPeriod , "goals" .= periodGoals , "shots" .= periodShots ] -- Seeds instance ToJSON PlayoffSeed where toJSON PlayoffSeed {..} = object [ "seasonID" .= (formattedYear (intToInteger playoffSeedYear) ++ formattedSeason Playoffs) , "conference" .= playoffSeedConference , "seed" .= playoffSeedSeries , "homeID" .= playoffSeedHomeId , "awayID" .= playoffSeedAwayId , "round" .= playoffSeedRound ] -- Team instance ToJSON Game where toJSON Game {..} = object [ "seasonID" .= (formattedYear (intToInteger gameYear) ++ formattedSeason gameSeason) , "awayID" .= gameAwayId , "homeID" .= gameHomeId , "awayScore" .= gameAwayScore , "homeScore" .= gameHomeScore , "gameID" .= show gameGameId , "date" .= show gameDate , "time" .= show gameTime , "tv" .= gameTv , "period" .= gamePeriod , "periodTime" .= List.map Char.toUpper gamePeriodTime , "homeStatus" .= gameHomeStatus , "awayStatus" .= gameAwayStatus , "homeHighlight" .= gameHomeHighlight , "awayHighlight" .= gameAwayHighlight , "homeCondense" .= gameHomeCondense , "awayCondense" .= gameAwayCondense , "active" .= gameActive ] -- Event instance ToJSON Event where toJSON Event {..} = object [ "eventID" .= eventEventId , "gameID" .= show eventGameId , "teamID" .= eventTeamId , "period" .= eventPeriod , "time" .= eventTime , "type" .= fromEventType eventEventType , "description" .= eventDescription , "videoLink" .= eventVideoLink , "formalID" .= eventFormalId , "strength" .= fromStrength eventStrength ] data PlayoffsResponse = PlayoffsResponse { periods :: [Period] , seeds :: [PlayoffSeed] , games :: [Game] , events :: [Event] } deriving (Show) instance ToJSON PlayoffsResponse where toJSON PlayoffsResponse {..} = object [ "periods" .= periods , "teams" .= seeds , "games" .= games , "events" .= events ]
petester42/haskell-hockey
web/Models/LegacyJson.hs
mit
2,719
0
13
706
659
372
287
83
0
{-# OPTIONS_HADDOCK show-extensions #-} {-# LANGUAGE ExistentialQuantification, FlexibleContexts #-} -- | -- -- Module : EventProbability -- Description : Events and probabilities. -- License : MIT -- -- Definitions for events and probabilities. -- module EventProbability ( -- * Events Event(..) , EventName(..) , mkEvent , emptyEvent , compositeEvent -- * Atomic Events , AtomicEvent(..) , EvAtom(..) , EventIntersection(..) -- * Probability , Prob, mkProb, getProb , ProbabilityEstimation(..) ) where import qualified Data.Set as Set import qualified Data.Map as Map import Data.Set (Set) import Data.Map (Map) import Data.List (intercalate) import Data.Typeable import Control.Arrow ( (&&&) ) ----------------------------------------------------------------------------- -- | A name of an event. newtype EventName = EventName String deriving (Eq, Ord) -- | An event: intersection of underlying 'EvAtom's. newtype Event = Event (Map EventName EvAtom) deriving (Eq, Ord) evPair = eventName &&& id -- | Creates a singleton 'Event'. mkEvent :: EvAtom -> Event mkEvent = Event . uncurry Map.singleton . evPair -- | Creates an empty 'Event'. emptyEvent :: Event emptyEvent = Event Map.empty -- | Creates an /intersection/ 'Event'. compositeEvent :: (AtomicEvent e, Typeable e, Show e, Ord e) => Set e -> Event compositeEvent set | Set.null set = emptyEvent | otherwise = Set.foldr ((&) . EvAtom) emptyEvent set instance Show EventName where show (EventName name) = name instance Show Event where show (Event set) = intercalate " & " . map (show . snd) $ Map.toAscList set ----------------------------------------------------------------------------- -- | An existential container for 'AtomicEvent'. data EvAtom = forall e . (AtomicEvent e, Show e, Ord e, Typeable e) => EvAtom e instance Show EvAtom where show (EvAtom a) = show a instance Eq EvAtom where (EvAtom a) == (EvAtom b) = case cast b of Just b -> a == b _ -> False instance Ord EvAtom where (EvAtom a) `compare` (EvAtom b) = case cast b of Just b' -> a `compare` b' _ -> eventName a `compare` eventName b instance AtomicEvent EvAtom where eventName (EvAtom e) = eventName e eventDomain (EvAtom e) = Set.map EvAtom $ eventDomain e ----------------------------------------------------------------------------- -- | Atomic (not composite) event. class AtomicEvent e where -- | Event's name. eventName :: e -> EventName -- | Event's values domain. eventDomain :: e -> Set e ----------------------------------------------------------------------------- -- | Events intersection builder. class EventIntersection e1 e2 where -- | Events intersection. intersect :: e1 -> e2 -> Event -- | Alias for 'intersect'. (&) :: e1 -> e2 -> Event (&) = intersect instance EventIntersection EvAtom EvAtom where intersect a b = Event . Map.fromList $ map evPair [a,b] instance EventIntersection EvAtom Event where intersect e (Event es) = Event $ Map.insert (eventName e) e es instance EventIntersection Event EvAtom where intersect = flip intersect instance EventIntersection Event Event where intersect (Event es1) (Event es2) = Event $ Map.union es1 es2 ----------------------------------------------------------------------------- -- | Probability value container. newtype Prob = Prob Double deriving (Eq, Ord) instance Show Prob where show (Prob p) = show p -- | Create a 'Prob'. mkProb :: Double -> Prob -- | Get 'Double' value from 'Prob'. getProb :: Prob -> Double mkProb d | d >=0 && d <= 1 = Prob d | otherwise = error $ probErrStr ++ show d getProb (Prob d) = d probErrStr = "probability must be within [0,1], but got " probf f (Prob mx) = mkProb $ f mx probf2 f (Prob mx) (Prob my) = mkProb $ f mx my instance Num Prob where (+) = probf2 (+) (-) = probf2 (-) (*) = probf2 (*) abs = probf abs signum = probf signum fromInteger 0 = Prob 0 fromInteger 1 = Prob 1 fromInteger p = error $ npErrStr ++ show p npErrStr = "probability must be in [0,1], got " ----------------------------------------------------------------------------- -- | Interface for 'Event's probability estimation. class (Monad m) => ProbabilityEstimation context m where -- | Estimate the probability of an event, given a context. estimateProb :: context -> Event -> m Prob -- | Estimate the the conditional probability of an event, given a context. estimateCondProb :: context -> Event -- ^ the event -> EvAtom -- ^ condition -> m Prob
fehu/min-dat--naive-bayes
src/EventProbability.hs
mit
5,037
0
10
1,366
1,238
669
569
-1
-1
{-# LANGUAGE BangPatterns #-} module Control.Coroutine.FRP where import qualified Control.Category as C import Control.Arrow import Control.Applicative (liftA2) import Data.Monoid import Data.List (foldl') import Control.Coroutine import qualified Data.IntMap as IntMap type Event a = [a] edge :: Eq a => Coroutine a (Event a) edge = Coroutine $ \i -> ([i], Just $ step i) where step old = Coroutine $ \i -> if old == i then ([], Just $ step i) else ([i], Just $ step i) watch :: (a -> Bool) -> Coroutine a (Event a) watch f = Coroutine $ \i -> if f i then ([i], Just $ watch f) else ([], Just $ watch f) withPrevious :: a -> Coroutine a (a,a) withPrevious first = Coroutine $ \i -> ((i, first), Just $ step i) where step old = Coroutine $ \i -> ((i, old), Just $ step i) withPrevious' :: Coroutine a (a,a) withPrevious' = Coroutine $ \i -> ((i,i), Just $ step i) where step old = Coroutine $ \i -> ((i, old), Just $ step i) delay :: a -> Coroutine a a delay a = withPrevious a >>> arr snd integrate :: Num a => a -> Coroutine a a integrate = scan (+) derivate :: Num a => Coroutine a a derivate = withPrevious 0 >>> zipWithC (-) scanE :: (a -> e -> a) -> a -> Coroutine (Event e) a scanE f i = Coroutine $ step i where step a e = let a' = foldl' f a e in (a', Just $ scanE f a') mapE :: (e -> e') -> Coroutine (Event e) (Event e') mapE = arr . map concatMapE :: (e -> Event e') -> Coroutine (Event e) (Event e') concatMapE = arr . concatMap filterE :: (e -> Bool) -> Coroutine (Event e) (Event e) filterE = arr . filter zipE :: Coroutine (Event e, Event e) (Event e) zipE = zipWithC (++) mergeE :: Coroutine i (Event e) -> Coroutine i (Event e) -> Coroutine i (Event e) mergeE = (<++>) (<++>) :: Monoid o => Coroutine i o -> Coroutine i o -> Coroutine i o (<++>) = liftA2 mappend constE :: e -> Coroutine (Event e') (Event e) constE = mapE . const stepE :: a -> Coroutine (Event a) a stepE a = Coroutine $ \ev -> let a' = last (a:ev) in (a', Just $ stepE a') restartWhen :: Coroutine a b -> Coroutine (a, Event e) b restartWhen co = Coroutine $ step co where step c (i, ev) = (o, fmap Coroutine cont) where (o, c') = runC c i cont | null ev = fmap step c' | otherwise = Just $ step co delayE :: Int -> Coroutine (Event e) (Event e) delayE delay = arr (const delay) &&& C.id >>> delayEn delayEn :: Coroutine (Int, Event e) (Event e) delayEn = Coroutine $ step 0 IntMap.empty where step !cur !buffer (delay, ev) = (ev', Just $ Coroutine $ step (cur+1) buffer') where ev' = IntMap.findWithDefault [] cur buffer' buffer' | null ev = buffer | otherwise = IntMap.insertWith (++) (cur+delay) ev buffer
shangaslammi/frp-pong
Control/Coroutine/FRP.hs
mit
2,788
0
15
712
1,347
707
640
70
2
import Data.List (permutations, sort) import Data.Char (intToDigit) main :: IO () main = do putStr $ map intToDigit list where list = (sort . permutations $ [0..9]) !! 999999
DestructHub/ProjectEuler
Problem024/Haskell/solution_1.hs
mit
186
0
10
40
78
42
36
6
1
module TestDemoNeuron where import Test.Hspec import AI.DemoNeuron import TestNeuron testDemoNeuron :: IO () testDemoNeuron = hspec $ do describe "Reduced Neuron" $ do it "should pass tests" $ do True `shouldBe` True describe "L2 Neuron" $ do it "should pass tests" $ do True `shouldBe` True
qzchenwl/LambdaNet
test/TestDemoNeuron.hs
mit
320
0
14
74
94
47
47
12
1
{-# LANGUAGE OverloadedStrings #-} {- | Module : <File name or $Header$ to be replaced automatically> Description : <optional short text displayed on contents page> Copyright : (c) <Authors or Affiliations> License : <license> Maintainer : <email> Stability : unstable | experimental | provisional | stable | frozen Portability : portable | non-portable (<reason>) <module description starting at first column> -} module App (app) where -- Third Party import Web.Scotty hiding (body) -- Application import Controllers.Home app :: ScottyM () app = do get "/" $ Controllers.Home.home
slogsdon/url
src/App.hs
mit
633
0
8
138
57
34
23
7
1
module GUBS.Solver.ZThree (zthree) where import GUBS.Algebra import qualified GUBS.Expression as E import qualified GUBS.MaxPolynomial as MP import GUBS.Solver.Class import qualified GUBS.Solver.Formula as F import Control.Monad.State.Strict import Data.Maybe (fromJust) import qualified Text.PrettyPrint.ANSI.Leijen as PP import qualified Z3.Monad as Z zthree :: SolverM ZThree a -> IO a zthree (Z3 z3) = Z.evalZ3With (Just Z.QF_NIA) Z.stdOpts z3 data ZThree = ZThree deriving (Eq, Ord, Show) instance SMTSolver ZThree where newtype SolverM ZThree a = Z3 { _runZ3 :: Z.Z3 a } deriving (Functor, Applicative, Monad, MonadIO, Z.MonadZ3) newtype NLiteral ZThree = NLit Z.AST deriving (Eq, Ord) newtype BLiteral ZThree = BLit Z.AST freshBool = BLit <$> Z.mkFreshBoolVar "b" freshNat = do n <- Z.mkFreshIntVar "n" z <- Z.mkInteger 0 Z.assert =<< n `Z.mkGe` z return $ NLit n push = Z.push pop = Z.pop 1 assertFormula = aFormula checkSat = (==) Z.Sat <$> Z.check getValue (NLit n) = do m <- Z.solverGetModel fromJust <$> Z.evalInt m n aFormula :: SMTFormula ZThree -> SolverM ZThree () aFormula f = Z.assert =<< toFormula f toFormula :: SMTFormula ZThree -> SolverM ZThree Z.AST toFormula Top = Z.mkBool True toFormula Bot = Z.mkBool False toFormula (Lit (BoolLit (BLit l))) = return l toFormula (Atom (Geq l r)) = join $ Z.mkGe <$> toExpression l <*> toExpression r toFormula (Atom (Eq l r)) = join $ Z.mkEq <$> toExpression l <*> toExpression r toFormula (Or a b) = Z.mkOr =<< sequence [toFormula a, toFormula b] toFormula (And a b) = Z.mkAnd =<< sequence [toFormula a, toFormula b] toFormula (Iff a b) = join $ Z.mkIff <$> toFormula a <*> toFormula b toExpression :: SMTExpression ZThree -> SolverM ZThree Z.AST toExpression = fromMP . E.fromPolynomial MP.variable MP.constant where -- to exploit simplification fromMP (MP.Var (NLit v)) = return v fromMP (MP.Const i) = Z.mkInteger i fromMP (MP.Plus a b) = Z.mkAdd =<< sequence [fromMP a, fromMP b] fromMP (MP.Mult a b) = Z.mkMul =<< sequence [fromMP a, fromMP b] fromMP MP.Max{} = error "max encountered"
mzini/gubs
src/GUBS/Solver/ZThree.hs
mit
2,394
0
11
667
885
451
434
-1
-1
{-# LANGUAGE TypeFamilies, FlexibleContexts #-} -------------------------------------------------------------------------------- -- | -- Module : System.Socket.Internal.Socket -- Copyright : (c) Lars Petersen 2015 -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -------------------------------------------------------------------------------- module System.Socket.Internal.Socket ( Socket (..) , Family (..) , Type (..) , Protocol (..) ) where import Control.Concurrent.MVar import Foreign.C.Types import Foreign.Storable import System.Posix.Types -- | A generic socket type. Use `System.Socket.socket` to create a new socket. -- -- The socket is just an `Control.Concurrent.MVar.MVar`-wrapped file descriptor. -- The `System.Socket.Unsafe.Socket` constructor is exported trough the unsafe -- module in order to make this library easily extensible, but it is usually -- not necessary nor advised to work directly on the file descriptor. -- If you do, the following rules must be obeyed: -- -- - Make sure not to deadlock. Use `Control.Concurrent.MVar.withMVar` or similar. -- - The lock __must not__ be held during a blocking call. This would make it impossible -- to send and receive simultaneously or to close the socket. -- - The lock __must__ be held when calling operations that use the file descriptor. -- Otherwise the socket might get closed or even reused by another -- thread/capability which might result in reading from or writing on a -- totally different socket. This is a security nightmare! -- - The socket is non-blocking and all the code relies on that assumption. -- You need to use GHC's eventing mechanism primitives to block until -- something happens. The former rules forbid to use `GHC.Conc.threadWaitRead` as it -- does not separate between registering the file descriptor (for which -- the lock __must__ be held) and the actual waiting (for which you must -- __not__ hold the lock). -- Also see [this](https://mail.haskell.org/pipermail/haskell-cafe/2014-September/115823.html) -- thread and read the library code to see how the problem is currently circumvented. newtype Socket f t p = Socket (MVar Fd) -- | The address `Family` determines the network protocol to use. -- -- The most common address families are `System.Socket.Family.Inet.Inet` (IPv4) -- and `System.Socket.Family.Inet6.Inet6` (IPv6). class Storable (SocketAddress f) => Family f where -- | The number designating this `Family` on the specific platform. This -- method is only exported for implementing extension libraries. -- -- This function shall yield the values of constants like `AF_INET`, `AF_INET6` etc. familyNumber :: f -> CInt -- | The `SocketAddress` type is a [data family](https://wiki.haskell.org/GHC/Type_families#Detailed_definition_of_data_families). -- This allows to provide different data constructors depending on the socket -- family without knowing all of them in advance or the need to extend this -- core library. -- -- > SocketAddressInet inetLoopback 8080 :: SocketAddress Inet -- > SocketAddressInet6 inet6Loopback 8080 0 0 :: SocketAddress Inet6 data SocketAddress f -- | The `Type` determines properties of the transport layer and the semantics -- of basic socket operations. -- -- The instances supplied by this library are `System.Socket.Type.Raw` -- (no transport layer), `System.Socket.Type.Stream` -- (for unframed binary streams, e.g. `System.Socket.Protocol.TCP`), -- `System.Socket.Type.Datagram` (for datagrams -- of limited length, e.g. `System.Socket.Protocol.UDP`) and -- `System.Socket.Type.SequentialPacket` (for framed messages of arbitrary -- length, e.g. `System.Socket.Protocol.SCTP`). class Type t where -- | This number designates this `Type` on the specific platform. This -- method is only exported for implementing extension libraries. -- -- The function shall yield the values of constants like `SOCK_STREAM`, -- `SOCK_DGRAM` etc. typeNumber :: t -> CInt -- | The `Protocol` determines the transport protocol to use. -- -- Use `System.Socket.Protocol.Default` to let the operating system choose -- a transport protocol compatible with the socket's `Type`. class Protocol p where -- | This number designates this `Protocol` on the specific platform. This -- method is only exported for implementing extension libraries. -- -- The function shall yield the values of constants like `IPPROTO_TCP`, -- `IPPROTO_UDP` etc. protocolNumber :: p -> CInt
lpeterse/haskell-socket
src/System/Socket/Internal/Socket.hs
mit
4,681
0
8
872
221
161
60
19
0
module Faorien.Pathfinding ( BoardMap , HeroBoardMap , buildBoardMap , buildSafeBoardMap , buildEmptyBoardMap , distance , walk ) where import Data.List (unfoldr, foldl') import Data.Maybe (fromMaybe) import Data.PSQueue (PSQ, Binding(..)) import Control.Applicative ((<$>)) import Control.Monad (unless, forM_) import Control.Monad.State (execState, get, modify) import Control.Lens ((^.)) import Control.Parallel.Strategies (rpar, parMap) import qualified Data.Map as M import qualified Data.Set as S import qualified Data.PSQueue as PSQ import Faorien.Types import Faorien.Utils buildBoardMap :: Activity -> BoardMap buildBoardMap activity = let heroes = activity^.activityGame.gameHeroes buildHeroBoardMap hero = pathDijkstra (dijkstra (adjacent activity start) manhattan start) where start = hero^.heroPos makeHeroBoardMap hero@(Hero {_heroId = hId}) = (hId, buildHeroBoardMap hero) in M.fromList $ parMap rpar makeHeroBoardMap heroes buildSafeBoardMap :: Activity -> BoardMap buildSafeBoardMap activity = let heroes = activity^.activityGame.gameHeroes buildSafeHeroBoardMap hero = pathDijkstra (dijkstra (adjacentSafe activity start) manhattan start) where start = hero^.heroPos makeSafeHeroBoardMap hero@(Hero {_heroId = hId}) = (hId, buildSafeHeroBoardMap hero) in M.fromList $ parMap rpar makeSafeHeroBoardMap heroes buildEmptyBoardMap :: Activity -> BoardMap buildEmptyBoardMap activity = let heroes = activity^.activityGame.gameHeroes buildEmptyHeroBoardMap hero = pathDijkstra (dijkstra (adjacentEmpty activity start) manhattan start) where start = hero^.heroPos makeEmptyHeroBoardMap hero@(Hero {_heroId = hId}) = (hId, buildEmptyHeroBoardMap hero) in M.fromList $ parMap rpar makeEmptyHeroBoardMap heroes distance :: Path -> Int distance (Path path) = length path walk :: Hero -> Path -> Dir walk _ (Path []) = Stay walk hero (Path (nextPos : _)) = dirFromPos (hero^.heroPos) nextPos ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Based on https://gist.github.com/kazu-yamamoto/5218431 -- http://mew.org/~kazu/material/2012-psq.pdf type Graph = Pos -> [Pos] -- Given a position on a board return all neighbours type Cost = Int -- Connected tiles on a board all have cost 1 type Vertex = Pos -- Nodes in the graph are represented by position on a board type Queue = PSQ Vertex Priority -- Priority search queue to be used in constructing shortest paths from starting position type Mapping = (Vertex, Priority) -- Every node is going to be assigned a priority -- keeps information from which node we got to the node we are interested in newtype Dijkstra = Dijkstra (M.Map Vertex Vertex) data Priority = Priority Cost Vertex deriving (Eq) instance Ord Priority where Priority cost1 _ `compare` Priority cost2 _ = cost1 `compare` cost2 -- select neighbour positions which we can actually move to -- taking into account the position from which we are asking those -- neighbouring tiles (if it is not a FreeTile or tile at Hero position -- then we cannot possibly reach that tile and there is no way to go to any -- of its neighbours) -- -- Example: given a 1x3 board [Hero, WoodTile, MineTile] -- if we ask to give neighbours of position (1,2) then we would return an -- empty set because we cannot actually make our hero go to (1,2) in the -- first place. If we didn't restrict it then it would return the -- neighbouring tiles and our pathing would think that it can reach MineTile adjacent :: Activity -> Vertex -> Graph adjacent activity start pos = let board = activity^.activityGame.gameBoard tiles = S.toList $ adjacentTiles board pos canEnter tile = let targetTile = fromMaybe WoodTile (tileAt board tile) in targetTile /= WoodTile in if pos == start || fromMaybe WoodTile (tileAt board pos) == FreeTile then filter canEnter tiles else [] -- extra precaution, we avoid enemies during our path construction adjacentSafe :: Activity -> Vertex -> Graph adjacentSafe activity start pos = let board = activity^.activityGame.gameBoard tiles = S.toList $ adjacentTiles board pos heroHasEnoughHealth = activity^.activityHero.heroLife > 30 worthEntering tile = let targetTile = fromMaybe WoodTile (tileAt board tile) in if heroHasEnoughHealth then targetTile /= WoodTile else targetTile /= WoodTile && not (isEnemyNearby activity pos) in if pos == start || fromMaybe WoodTile (tileAt board pos) == FreeTile then filter worthEntering tiles else [] -- imagine that there are no enemies on the map, how fast can we get to the -- desired goal? adjacentEmpty :: Activity -> Vertex -> Graph adjacentEmpty = undefined -- given a start position construct shortest paths to all other positions dijkstra :: Graph -> Distance -> Vertex -> Dijkstra dijkstra graph dist start = buildDijkstra $ unfoldr (step graph dist) $ relax (start, Priority 0 start) queue where queue = PSQ.fromList $ map (\v -> v :-> Priority maxBound start) (S.toList $ vertices graph start) buildDijkstra = foldl' insertEdge (Dijkstra M.empty) insertEdge dij@(Dijkstra p) (destination, _, source) = if source /= destination then Dijkstra (M.insert destination source p) else dij -- construct next edge in the graph taking the vertex with minimal cost step :: Graph -> Distance -> Queue -> Maybe ((Vertex, Cost, Vertex), Queue) step graph dist queue = extractMin graph dist <$> PSQ.minView queue -- grab an item from PSQueue with minimal priority -- and update priority of its neighbours extractMin :: Graph -> Distance -> (Binding Vertex Priority, Queue) -> ((Vertex, Cost, Vertex), Queue) extractMin graph dist (destination :-> Priority cost source, queue) = ((destination, cost, source), relaxList queue adj) where adj = [(neighbour, Priority (cost + dist destination neighbour) destination) | neighbour <- graph destination] -- update priority of a given key in PSQueue relax :: Mapping -> Queue -> Queue relax (key, priority@(Priority cost _)) = PSQ.adjust update key where update otherPriority@(Priority otherCost _) | cost < otherCost = priority | otherwise = otherPriority -- update priorities of given keys in PSQueue relaxList :: Queue -> [Mapping] -> Queue relaxList = foldr relax -- collect all unique vertices from graph vertices :: Graph -> Vertex -> S.Set Vertex vertices graph start = execState (visitFrom start) S.empty where visitFrom start' = forM_ (graph start') $ \neighbour -> get >>= \v -> unless (neighbour `S.member` v) $ modify (S.insert neighbour) >> visitFrom neighbour -- path to a goal position pathDijkstra :: Dijkstra -> Vertex -> Maybe Path pathDijkstra (Dijkstra prev) goal = case searchBackwards goal of [_] -> Nothing path -> Just (Path $ (tail . reverse) path) where searchBackwards goal' = goal' : maybe [] searchBackwards (M.lookup goal' prev)
ksaveljev/vindinium-bot
Faorien/Pathfinding.hs
mit
7,486
0
16
1,710
1,812
975
837
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE DoAndIfThenElse #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module CommandLoop ( setupCommandLoop , CommandObj ) where import Control.Applicative import Control.Concurrent import qualified Control.Concurrent.Event as Event import Control.Exception import Control.Lens import Control.Monad import Control.Monad.Loops import Control.Monad.Reader.Class import Control.Monad.State.Class import Control.Proxy import Control.Proxy.Concurrent import qualified Control.Proxy.Trans.Reader as ReaderP import Control.Proxy.Trans.Reader hiding (ask, asks, local) import qualified Control.Proxy.Trans.State as StateP import Control.Proxy.Trans.State hiding (get, gets, modify, put, state, stateT) import Data.Foldable (traverse_) import Data.IORef import Data.List import qualified Data.Sequence as S import Distribution.PackageDescription (allBuildInfo, hsSourceDirs) import Distribution.ParseUtils import qualified DynFlags as GHC import qualified ErrUtils import qualified Exception import qualified FastString as GHC import qualified GHC import qualified GHC.Paths import qualified MonadUtils as GHC import qualified Outputable import qualified SrcLoc as GHC import System.Directory (canonicalizePath) import System.Exit (ExitCode (ExitFailure, ExitSuccess)) import System.FilePath (makeRelative, takeDirectory) import System.Posix.Files import System.Posix.Signals import System.Posix.Types import Cabal import Info (getIdentifierInfo, getType) import Types -- Orphan instance (Proxy p, Monad m) => MonadState s (StateP s p a' a b' b m) where get = StateP.get put = StateP.put instance (Proxy p, Monad m) => MonadReader s (ReaderP s p a' a b' b m) where ask = ReaderP.ask local = ReaderP.local type CommandObj = (Command, [String]) data ErrorInfo = ErrorInfo { _severity :: GHC.Severity , _location :: GHC.SrcSpan , _style :: Outputable.PprStyle , _messageChanges :: Outputable.SDoc -> Outputable.SDoc , _message :: (Outputable.SDoc -> Outputable.SDoc) -> GHC.Severity -> GHC.SrcSpan -> Outputable.PprStyle -> String } makeLenses ''ErrorInfo data Settings = Settings { _cabalFile :: Maybe FilePath , _refWarningsEnabled :: IORef Bool , _refFileName :: IORef GHC.FastString , _refFilePath :: IORef GHC.FastString , _refErrors :: IORef (S.Seq ErrorInfo) , _extraOptions :: [String] } makeLenses ''Settings data Options = Options { _cabalMod :: EpochTime , _ghcOpts :: [String] , _needReconfig :: Bool } makeLenses ''Options defaultOptions :: Options defaultOptions = Options { _cabalMod = 0 , _ghcOpts = [] , _needReconfig = True } readRef :: (GHC.MonadIO m, MonadTrans t, MonadReader s (t m)) => Lens' s (IORef a) -> t m a readRef l = view l >>= lift . GHC.liftIO . readIORef writeRef :: (GHC.MonadIO m, MonadTrans t, MonadReader s (t m)) => Lens' s (IORef a) -> a -> t m () writeRef l v = view l >>= lift . GHC.liftIO . flip writeIORef v commandLoop :: (Proxy p) => () -> Pipe (StateP Options (ReaderP Settings p)) CommandObj ClientDirective GHC.Ghc () commandLoop () = do let status = respond . ClientLog "CommandLoop" forever $ do unitD ->> reconfigure status "Process commands" (request () >>= (unitD ->>) . processCommandObj) `untilM` use needReconfig reconfigure :: (Proxy p) => Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc () reconfigure = do let status = respond . ClientLog "Reconfigure" status "Updating GHC options" opts <- use ghcOpts settings <- liftP ask status $ "New options: " ++ unwords (settings ^. extraOptions ++ opts) configOk <- newSession (settings ^. refErrors) (settings ^. extraOptions ++ opts) status "Processing configure result" needReconfig .= not configOk processCommandObj :: (Proxy p) => CommandObj -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc () processCommandObj (command,opts') = do let logmsg = respond . ClientLog "processCommandObj" logmsg $ "Processing command: " ++ show command opts <- use ghcOpts when (opts /= opts') $ do logmsg "Reconfigure needed" ghcOpts .= opts' needReconfig .= True reconfigure liftP $ writeRef refErrors S.empty result <- runCommand command logmsg "Finished executing command. Start collecting errors" errors <- liftP $ readRef refErrors logmsg "Responding with errors" traverse_ processError errors logmsg "Done. Returning ClientExit status" respond $ ClientExit result return () renderError :: ErrorInfo -> String renderError err = view message err (err ^. messageChanges) (err ^. severity) (err ^. location) (err ^. style) isWarning :: GHC.Severity -> Bool isWarning GHC.SevWarning = True isWarning _ = False processError :: (Proxy p) => ErrorInfo -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc () processError err = liftP $ hoist GHC.liftIO $ do warningsEnabled <- readRef refWarningsEnabled fname <- readRef refFileName fpath <- readRef refFilePath msg <- lift $ GHC.liftIO $ fmap renderError $ adjustFileName fname fpath err when (warningsEnabled || not (isWarning $ err ^. severity)) $ respond $ ClientStdout msg setupCommandLoop :: Maybe FilePath -> [String] -> IO (Input CommandObj, Output ClientDirective, Input ClientDirective) setupCommandLoop cabal initialGhcOpts = do (serverInput,serverOutput) <- spawn Unbounded (clientInput,clientOutput) <- spawn Unbounded warnings <- newIORef True fileName <- newIORef $ GHC.fsLit "" filePath <- newIORef $ GHC.fsLit "" errors <- newIORef S.empty cabalOptions <- cabalMiscOptions let settings = Settings cabal warnings fileName filePath errors cabalOptions finishGHCstartup <- Event.new t <- myThreadId let exception (SomeException e) = GHC.liftIO $ atomically $ do void $ send serverInput $ ClientStderr $ "[setupCommandLoop] Unhandled GHC Exception: " ++ show e void $ send serverInput $ ClientExit $ ExitFailure 2 _ <- forkIO $ GHC.runGhc (Just GHC.Paths.libdir) $ do GHC.liftIO $ Event.signal finishGHCstartup forever $ Exception.ghandle exception $ runProxy $ runReaderK settings $ evalStateK (defaultOptions & ghcOpts .~ initialGhcOpts) $ hoist GHC.liftIO . recvS clientOutput >-> commandLoop >-> hoist GHC.liftIO . sendD serverInput -- for some reason GHC changes the default ^C handlers. They don't work when used in a thread, so we reset -- them here, after GHC started to make sure we override GHC's handler. Event.wait finishGHCstartup _ <- installHandler sigINT (Catch $ throwTo t UserInterrupt) Nothing _ <- installHandler sigTERM (Catch $ throwTo t UserInterrupt) Nothing return (clientInput,serverOutput,serverInput) newSession :: (Proxy p) => IORef (S.Seq ErrorInfo) -> [String] -> Producer p ClientDirective GHC.Ghc Bool newSession errorIn opts = handleGHCException $ do initialDynFlags <- GHC.getSessionDynFlags let updatedDynFlags = GHC.dopt_unset ?? GHC.Opt_WarnIsError $ initialDynFlags { GHC.log_action = logAction' errorIn , GHC.ghcLink = GHC.NoLink , GHC.hscTarget = GHC.HscInterpreted } (finalDynFlags, _, _) <- GHC.parseDynamicFlags updatedDynFlags (map GHC.noLoc $ ["-Wall", "-O0"] ++ opts) void $ GHC.setSessionDynFlags finalDynFlags handleGHCException :: (Proxy p) => GHC.Ghc () -> Producer p ClientDirective GHC.Ghc Bool handleGHCException action = runIdentityP $ do errM <- lift $ GHC.gcatch (Nothing <$ action) (return . Just . flip GHC.showGhcException "") case errM of Nothing -> return True (Just err) -> do respond $ ClientStderr err respond $ ClientExit $ ExitFailure 1 return False cabalCached :: (MonadTrans t, MonadState Options (t m), GHC.GhcMonad m) => FilePath -> t m () -> t m () cabalCached file action = do s <- lift $ GHC.liftIO $ getSymbolicLinkStatus file let tnew = modificationTime s told <- use cabalMod when (told < tnew) $ do cabalMod .= tnew action setCabalPerFileOpts :: (Proxy p) => FilePath -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc () setCabalPerFileOpts configPath = cabalCached configPath $ do file <- fmap GHC.unpackFS $ liftP $ readRef refFileName cabalDir <- lift $ GHC.liftIO $ canonicalizePath $ takeDirectory configPath fileRel <- lift $ GHC.liftIO $ makeRelative cabalDir <$> canonicalizePath file respond $ ClientLog "CabalFileOpts" $ "Loading cabal (looking for file: " ++ fileRel ++ ")" config <- lift $ GHC.liftIO $ readFile configPath case parseCabalConfig config of (ParseFailed err) -> do respond $ ClientLog "CabalFileOpts" $ "Cabal error:" ++ show err respond $ ClientStderr "Warning: Parsing of the cabal config failed. Please correct it, or use --no-cabal." (ParseOk _ pkgDesc) -> do let srcInclude = "-i" ++ takeDirectory file respond $ ClientLog "CabalFileOpts" $ "build infos: " ++ show (reallyAllBuildInfo pkgDesc) flags <- case findBuildInfoFile pkgDesc fileRel of Left err -> do respond $ ClientLog "CabalFileOpts" $ "Couldn't find file: " ++ err return [] Right buildInfo -> do let opts = getBuildInfoOptions buildInfo respond $ ClientLog "CabalFileOpts" $ "Cabal: Adding options " ++ show opts return opts dynFlags <- lift GHC.getSessionDynFlags (finalDynFlags, _, _) <- lift $ GHC.parseDynamicFlags dynFlags (map GHC.noLoc $ srcInclude : flags) void $ handleGHCException $ void $ GHC.setSessionDynFlags $ finalDynFlags `GHC.dopt_unset` GHC.Opt_WarnIsError setAllCabalImportDirs :: (Proxy p) => FilePath -> Producer p ClientDirective GHC.Ghc () setAllCabalImportDirs cabal = runIdentityP $ do config <- lift $ GHC.liftIO $ readFile cabal case parseCabalConfig config of (ParseFailed err) -> do respond $ ClientLog "setAllCabalImportDirs" $ "Parsing failed: " ++ show err return () (ParseOk _ r) -> do let dirs = allBuildInfo r >>= hsSourceDirs respond $ ClientLog "setAllCabalImportDirs" $ "Added directories: " ++ show dirs dynFlags <- lift GHC.getSessionDynFlags (finalDynFlags,_,_) <- lift $ GHC.parseDynamicFlags dynFlags (map (GHC.noLoc . ("-i" ++)) dirs) void $ handleGHCException $ void $ GHC.setSessionDynFlags finalDynFlags setCurrentFile :: (Proxy p) => FilePath -> FilePath -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc () setCurrentFile path name = do respond $ ClientLog "Cabal" "Initialize cabal and state" liftP $ writeRef refFileName $ GHC.fsLit name liftP $ writeRef refFilePath $ GHC.fsLit path liftP (view cabalFile) >>= traverse_ setCabalPerFileOpts withWarnings :: (Proxy p) => Bool -> GHC.Ghc a -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc a withWarnings v action = do beforeValue <- liftP $ readRef refWarningsEnabled ref <- liftP $ view refWarningsEnabled liftP $ writeRef refWarningsEnabled v lift (action `GHC.gfinally` GHC.liftIO (writeIORef ref beforeValue)) runCommand :: (Proxy p) => Command -> Producer (StateP Options (ReaderP Settings p)) ClientDirective GHC.Ghc ExitCode runCommand (CmdCheck real file) = do let status = respond . ClientLog "Check" setCurrentFile real file let noPhase = Nothing status "Unload previous target" lift $ GHC.setTargets [] void $ lift $ GHC.load GHC.LoadAllTargets status "Load target" target <- lift $ GHC.guessTarget file noPhase lift $ GHC.setTargets [target] let handler err = GHC.printException err >> return GHC.Failed status "Compile target" flag <- lift $ GHC.handleSourceError handler (GHC.load GHC.LoadAllTargets) status "Check result" case flag of GHC.Succeeded -> return ExitSuccess GHC.Failed -> return $ ExitFailure 1 runCommand (CmdModuleFile moduleName) = do let status = respond . ClientLog "ModuleFile" status "Initialize cabal" liftP (view cabalFile) >>= traverse_ setAllCabalImportDirs status "Load target" target <- lift $ GHC.guessTarget moduleName Nothing lift $ GHC.setTargets [target] -- TODO: This currently fails, need to figure out why (when cabal support enabled) status "Build module graph" moduleGraph <- lift $ GHC.depanal [] False `GHC.gcatch` \(SomeException _) -> return [] status "Find module" case find (moduleSummaryMatchesModuleName moduleName) moduleGraph of Nothing -> do respond $ ClientStderr "Module not found" return $ ExitFailure 1 Just modSummary -> case GHC.ml_hs_file (GHC.ms_location modSummary) of Nothing -> do respond $ ClientStderr "Module does not have a source file" return $ ExitFailure 1 Just file -> do respond $ ClientStdout file return ExitSuccess where moduleSummaryMatchesModuleName modName modSummary = modName == (GHC.moduleNameString . GHC.moduleName . GHC.ms_mod) modSummary runCommand (CmdInfo real file identifier) = do let status = respond . ClientLog "Info" setCurrentFile real file status "Get info" result <- withWarnings False $ getIdentifierInfo file identifier status "Check result" case result of Left err -> do respond $ ClientStderr err return $ ExitFailure 1 Right info -> do respond $ ClientStdout info return ExitSuccess runCommand (CmdType real file (line, col)) = do let status = respond . ClientLog "Type" setCurrentFile real file status "Get type" result <- withWarnings False $ getType file (line, col) status "Check result" case result of Left err -> do respond $ ClientStderr err return $ ExitFailure 1 Right types -> do mapM_ (respond . ClientStdout . formatType) types return ExitSuccess where formatType :: ((Int, Int, Int, Int), String) -> String formatType ((startLine, startCol, endLine, endCol), t) = concat [ show startLine , " " , show startCol , " " , show endLine , " " , show endCol , " " , "\"", t, "\"" ] adjustFileName :: GHC.FastString -> GHC.FastString -> ErrorInfo -> IO ErrorInfo adjustFileName fname fpath info = case info ^. location of (GHC.UnhelpfulSpan _) -> return $ inOtherFile id (GHC.RealSrcSpan span') -> if GHC.srcSpanFile span' == fname then return $ info & location .~ fileSrcSpan span' else do otherFile <- canonicalizePath $ GHC.unpackFS $ GHC.srcSpanFile span' return $ inOtherFile $ (Outputable.$$) $ Outputable.text $ otherFile ++ ": " where inOtherFile f = info & messageChanges . mapped %~ f & location .~ firstLineSpan firstLineSpan = GHC.RealSrcSpan $ GHC.mkRealSrcSpan (GHC.mkRealSrcLoc fpath 1 1) (GHC.mkRealSrcLoc fpath 1 1) fileSrcSpan span' = GHC.RealSrcSpan $ GHC.mkRealSrcSpan (GHC.mkRealSrcLoc fpath lineStart colStart) (GHC.mkRealSrcLoc fpath lineEnd colEnd) where colStart = GHC.srcSpanStartCol span' colEnd = GHC.srcSpanEndCol span' lineStart = GHC.srcSpanStartLine span' lineEnd = GHC.srcSpanEndLine span' #if __GLASGOW_HASKELL__ >= 706 logAction' :: IORef (S.Seq ErrorInfo) -> GHC.DynFlags -> GHC.Severity -> GHC.SrcSpan -> Outputable.PprStyle -> ErrUtils.MsgDoc -> IO () logAction' errorIn dflags sev sspan mstyle doc = modifyIORef errorIn (S.|> ErrorInfo sev sspan mstyle id f) where f g sev' span' = Outputable.renderWithStyle dflags (ErrUtils.mkLocMessage sev' span' $ g doc) #else logAction' :: IORef (S.Seq ErrorInfo) -> GHC.Severity -> GHC.SrcSpan -> Outputable.PprStyle -> ErrUtils.Message -> IO () logAction' errorIn sev sspan mstyle doc = modifyIORef errorIn (S.|> ErrorInfo sev sspan mstyle id f) where f g sev' span' = Outputable.renderWithStyle (ErrUtils.mkLocMessage span' $ g doc) #endif
bennofs/hdevtools
src/CommandLoop.hs
mit
16,938
0
22
3,983
4,968
2,444
2,524
-1
-1
module Quark.Colors where import Quark.Types -- Color IDs defaultBg = (-1) :: Int defaultColor = (-1) :: Int black = 0 :: Int red = 1 :: Int green = 2 :: Int orange = 3 :: Int blue = 4 :: Int purple = 5 :: Int teal = 6 :: Int lightGray = 7 :: Int darkGray = 8 :: Int lightRed = 9 :: Int lightGreen = 10 :: Int yellow = 11 :: Int lightBlue = 12 :: Int lightPurple = 13 :: Int cyan = 14 :: Int white = 15 :: Int lineNumberInt = 51 :: Int titleBarInt = 52 :: Int treeDefaultInt = 53 :: Int treeActiveInt = 54 :: Int errorColorInt = 55 :: Int selectionColor = darkGray hintColor = darkGray highlightColor = blue backupColor = lightGray -- different from selectionColor and highlightColor -- Color pairs titleBarPair = (black, lightGray) lineNumberPair = (lightGray, defaultBg) rulerPair = (darkGray, defaultBg) treeDefaultPair = (defaultColor, defaultBg) treeActivePair = (defaultColor, selectionColor) errorPair = (lightRed, red) -- Variations for 8-color terminals selectionColor' = lightGray highlightColor' = teal backupColor' = defaultColor treeDefaultPair' = (defaultColor, defaultBg) treeActivePair' = (black, selectionColor') lineNumberPair' = (lightGray, defaultBg) titleBarPair' = (black, lightGray) errorPair' = (black, red) colorTriples :: Int -> [(Int, Int, Int)] colorTriples k = baseColors ++ selectedColors ++ highlightColors ++ extraColors where baseColors -- 0..16 | k >= 17 = map (\n -> (n, n, (-1))) [1..16] | k >= 16 = (16, 15, (-1)):(map (\n -> (n, n, (-1))) [1..15]) | k >= 8 = (16, 0, (-1)):(map (\n -> (n, mod n 8, (-1))) [1..15]) | otherwise = map (\n -> (n, (-1), (-1))) [1..16] selectedColors = bgColors 1 $ if k >= 16 -- 17..33 then (selectionColor, backupColor) else (selectionColor', backupColor') highlightColors = bgColors 2 $ if k >= 16 -- 34..50 then (highlightColor, backupColor) else (highlightColor', backupColor') extraColors | k >= 16 = [ cons lineNumberInt lineNumberPair , cons titleBarInt titleBarPair , cons treeDefaultInt treeDefaultPair , cons treeActiveInt treeActivePair , cons errorColorInt errorPair ] | k >= 8 = [ cons lineNumberInt lineNumberPair' , cons titleBarInt titleBarPair' , cons treeDefaultInt treeDefaultPair' , cons treeActiveInt treeActivePair' , cons errorColorInt errorPair' ] | otherwise = [ (lineNumberInt, 0, (-1)) , (titleBarInt, (-1), 0) , (treeDefaultInt, 0, (-1)) , (treeActiveInt, (-1), 0) , (errorColorInt, 0, (-1)) ] where cons x (y, z) = (x, y, z) bgColors q (col, backupCol) | k >= 17 = let p0 = (q*17, (-1), col) f = \n -> if n == col then (n + q*17, backupCol, col) else (n + q*17, n, col) in p0:(map f [1..16]) | k >= 16 = let p0 = (q*17, (-1), col) p1 = (q*17 + 16, 15, col) f = \n -> if n == col then (n + q*17, backupCol, col) else (n + q*17, n, col) in p0:p1:(map f [1..16]) | k >= 8 = let p0 = (q*17, (-1), col) p1 = (q*17 + 16, (-1), col) f = \n -> if n == col then (n + q*17, backupCol, col ) else (n + q*17, n, col ) in p0:p1:(map (f . (\n -> mod n 8)) [1..16]) | otherwise = map (\n -> (n, (-1), 0)) $ map (+(q*17)) [0..16]
sjpet/quark
src/Quark/Colors.hs
mit
4,296
0
17
1,825
1,436
833
603
92
6
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Types.Checklist where import Types.Imports data Checklist = Checklist { checklistId :: Maybe Int, listOwner :: Int, checklistItems :: [ChecklistItem]} deriving (Show, Generic) instance FromRow Checklist where fromRow = Checklist <$> field <*> field <*> pure [] instance HasId Checklist where getId a = checklistId a setId a id = a { checklistId = id } instance HasArray Checklist where setArray conn a = do xs <- getChecklistsItems conn $ listOwner a return a { checklistItems = xs } getChecklistsItems :: Connection -> Int -> IO [ChecklistItem] getChecklistsItems conn checkId = query conn getChecklistItemsQueryByTeamId (Only checkId) getChecklistItemsQueryByTeamId = "select id, name, finished, checklist from checklistitems where checklist = (?)" :: Query instance ToRow Checklist where toRow c = [toField $ listOwner c] instance ToJSON Checklist instance FromJSON Checklist where parseJSON (Object v) = Checklist <$> v .:? "checklistId" <*> v .: "listOwner" <*> v .: "checklistItems" data ChecklistItem = ChecklistItem { checklistItemId :: Maybe Int, itemText :: String, finished :: Bool, checklist :: Int } deriving (Show, Generic) instance HasId ChecklistItem where getId a = checklistItemId a setId a id = a { checklistItemId = id } instance FromRow ChecklistItem where fromRow = ChecklistItem <$> field <*> field <*> field <*> field instance ToRow ChecklistItem where toRow i = [toField $ itemText i, toField $ finished i, toField $ checklist i] instance ToJSON ChecklistItem instance FromJSON ChecklistItem where parseJSON (Object v) = ChecklistItem <$> v .:? "checklistItemId" <*> v .: "itemText" <*> v .: "finished" <*> v .: "checklist"
maciejspychala/haskell-server
src/Types/Checklist.hs
mit
1,882
0
13
417
522
272
250
46
1
-- Function with one argument doubleMe x = x + x -- Function with two arguments doubleUs x y = x*2 + y*2 -- Function with if doubleSmallNumber x = if x > 100 then x else x*2 -- if is an expression! doubleSmallNumberAndAddOne x = (if x > 100 then x else x*2) + 1 -- in the ghci, you would need to do: -- let aListOfNumbers = [1,2,3,4,5] aListOfNumbers = [1,2,3,4,5] -- Adding lists anotherListOfNumbers = [1,2,3] ++ [4,5,6] -- Strings are lists aString = "hello" ++ " " ++ "world" -- Cons'ing consingTakeOne = 'A':' ':"SMALL CAT" consingTakeTwo= 1:[2,3,4] -- Indexing indexTakeOne = "Steve Buscemi" !! 6 indexTakeTwo = [1,2,3,4,5] !! 0 -- Usefull functions: -- head, tail, last, init -- length, null -- reverse, take, drop -- maximum, minimum -- sum, product -- elem -- Ranges oneToTwenty = [1..20] letters = ['a'..'z'] -- Range with step evens = [2,4..20] -- Possible funky range funky = [0.1, 0.3 .. 1] -- Infinite list -- see also repeat infiniteTaked = take 12 (cycle "LOL") -- List comprehension doublesOneToTen = [x*2 | x <- [1 .. 10]] doublesOneToTenThenGreaterThanTwelve = [x*2 | x <- [1 .. 10], x*2 >= 12] fiftenToHundredRemainOfDivBySevenIsThree = [x | x <- [50 .. 100], x `mod` 7 == 3 ] boomBangs xs = [if x < 10 then "BOOM!" else "BANG!" | x <- xs, odd x] severalLists = [x*y | x <- [1..5], y <- [6..10], x * y > 20] -- Length using list comprehension length' xs = sum [1 | _ <- xs] -- String manipulation using list comprehension removeNonUpper st = [x | x <- st, x `elem` ['A'..'Z'] ] -- List comprehensions on nested lists theNestedList = [[2,4,7,5], [2,3,6,1], [5,8,2,4]] theNestedListEvens = [[x | x <- xs, even x] | xs <- theNestedList] -- Tuples -- For pairs: fst, snd -- zip zipped = zip [1,2,3,4,5] [6,7,8,9,10] triangles = [(a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a + b + c == 24, a^2 + b^2 == c^2 ]
fabriceleal/learn-you-a-haskell
02/startingout.hs
mit
1,877
4
11
389
774
452
322
29
2
{-# LANGUAGE OverloadedStrings #-} -- sass sassCompiler :: Compiler (Item String) sassCompiler = getResourceString >>= withItemBody (unixFilter "sass" ["-s", "-scss"]) -- "--sitemap" >>= return . fmap compressCss
dled/inre
src/Inre/Compilers.hs
mit
232
2
11
46
57
30
27
6
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} module Functionality.Explicit.Configuration where import Control.Applicative ((<$>)) import Data.Aeson (Value (String)) import Data.Function (($)) import qualified Database.Couch.Explicit.Configuration as Configuration (delValue, getValue, section, server, setValue) import Database.Couch.Types (Context, Result) import Functionality.Util (runTests, serverContext, testAgainstSchema) import Network.HTTP.Client (Manager) import System.IO (IO) import Test.Tasty (TestTree, testGroup) _main :: IO () _main = runTests tests -- We specifically don't use makeTests here because we want no-databas-selected context tests :: IO Manager -> TestTree tests manager = testGroup "Tests of the config interface" $ ($ serverContext manager) <$> [server, section, getValue, setValue, delValue] -- Server-oriented functions server :: IO Context -> TestTree server = testAgainstSchema "Get server config" Configuration.server "get--_config.json" section :: IO Context -> TestTree section = testAgainstSchema "Get section config" (Configuration.section "couchdb") "get--_config-section.json" getValue :: IO Context -> TestTree getValue = testAgainstSchema "Get config item" (Configuration.getValue "couchdb" "max_document_size") "get--_config-section-key.json" setValue :: IO Context -> TestTree setValue = testAgainstSchema "Set config item" (Configuration.setValue "testsection" "testkey" $ String "foo") "put--_config-section-key.json" delValue :: IO Context -> TestTree delValue = testAgainstSchema "Delete config item" (\c -> do _ :: Result Value <- Configuration.setValue "testsection" "testkey" (String "foo") c Configuration.delValue "testsection" "testkey" c) "delete--_config-section-key.json"
mdorman/couch-simple
test/Functionality/Explicit/Configuration.hs
mit
2,307
0
13
711
420
234
186
33
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} module Firestone.GameBuilder ( buildGame , baseGame , setMaxHealth , setStartingMana , setActiveMinions , setDeck ) where import Firestone.Types import Firestone.IdGenerator import Firestone.Database import Firestone.Game import Control.Monad.State import Control.Lens data GameBuilder = GameBuilder { gameBuilderP1 :: Player , gameBuilderP2 :: Player , gameBuilderIdGen :: IdGenerator } makeFields ''GameBuilder buildGame :: State GameBuilder a -> Game buildGame buildActions = flip evalState makeGameBuilder $ do buildActions gb <- get return $ makeGame (gb^.p1) (gb^.p2) 0 (gb^.idGen) baseGame :: Game baseGame = buildGame $ return () makeGameBuilder :: GameBuilder makeGameBuilder = GameBuilder player1 player2 makeIdGenerator where idGen1 = makeIdGenerator (player1, idGen2) = createPlayer idGen1 (player2, idGen3) = createPlayer idGen2 createPlayer :: IdGenerator -> (Player, IdGenerator) createPlayer idGen1 = (makePlayer pId hero, idGen3) where (hId, _, idGen2) = create idGen1 "hero" hero = makeHero hId "hero" 30 0 (pId, _, idGen3) = create idGen2 "player" playerAt :: Int -> Lens' GameBuilder Player playerAt i f gb = case i of 1 -> p1 f gb 2 -> p2 f gb heroAt :: Int -> Lens' GameBuilder Hero heroAt i = playerAt i.hero setMaxHealth :: Int -> Int -> State GameBuilder () setMaxHealth i newHealth = do zoom (heroAt i) $ do health .= newHealth maxHealth .= newHealth setStartingMana :: Int -> Int -> State GameBuilder () setStartingMana i newMana = do zoom (heroAt i) $ do mana .= newMana maxMana .= newMana setActiveMinions :: Int -> [String] -> State GameBuilder () setActiveMinions i names = do gb <- get let (newMinions, newGen) = lookupMinions (gb^.idGen) names playerAt i.activeMinions .= newMinions idGen .= newGen setDeck :: Int -> [String] -> State GameBuilder () setDeck i names = do gb <- get let (newCards, newGen) = lookupCards (gb^.idGen) names playerAt i.deck.cards .= newCards idGen .= newGen
Jinxit/firestone
src/Firestone/GameBuilder.hs
mit
2,581
0
12
762
714
367
347
-1
-1
-- Intermission: Exercises -- 1. It is probably clear to you why you wouldn’t put an otherwise in your -- top-most guard, but try it with avgGrade anyway and see what happens. It’ll -- be more clear if you rewrite it as an actual otherwise match: | otherwise = -- 'F'. What happens now if you pass a 90 as an argument? 75? 60? -- 2. What happens if you take avgGrade as it is written and reorder the guards? -- Does it still typecheck and work the same? Try mov- ing | y >= 0.7 = 'C' and -- passing it the argument 90, which should be an ‘A.’ Does it return an ‘A’? -- 3. The following function returns pal xs | xs == reverse xs = True | otherwise = False -- a) xs written backwards when it’s True -- b) True when xs is a palindrome -- c) False when xs is a palindrome -- d) False when xs is reversed -- b -- 4. What types of arguments can pal take? -- any EQ in a list. -- 5. What is the type of the function pal? pal :: Eq a => [a] -> Bool -- 6. The following function returns numbers x | x < 0 = -1 | x == 0 = 0 | x > 0 = 1 -- a) the value of its argument plus or minus 1 -- b) the negation of its argument -- c) an indication of whether its argument is a positive or nega- tive number -- or zero -- d) binary machine language -- c -- 7. What types of arguments can numbers take? -- numbers that are comparable -- 8. What is the type of the function numbers? numbers :: (Num a, Num a1, Ord a1) => a1 -> a
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/07_07.hs
mit
1,444
0
9
327
153
87
66
9
1
{-# LANGUAGE OverloadedStrings #-} module Network.Danibot.Slack.API ( AuthToken , startRTM ) where import Control.Lens import Data.Aeson (Value(..),fromJSON,toJSON,Result(Error,Success)) import Data.Aeson.Lens import Data.Text (Text) import qualified Data.Monoid.Textual as Textual import qualified Network.Wreq as Wreq import Network.Danibot.Slack.Types (Wire(..),Intro(..)) type AuthToken = Text {-| Start a connection with the Slack RTM and return the initial state of the chat. -} startRTM :: AuthToken -> IO (Either String Intro) startRTM authToken = do resp <- Wreq.postWith (withToken authToken) "https://slack.com/api/rtm.start" (toJSON ()) respJSON <- view Wreq.responseBody <$> Wreq.asJSON resp pure (checkResp respJSON) withToken :: AuthToken -> Wreq.Options withToken token = Wreq.defaults & set (Wreq.param "token") [token] checkResp :: Value -> Either String Intro checkResp v = let parsedOk = v^?key "ok"._Bool parsedIntro = fromJSON v parsedError = v^?key "error"._String in case (parsedOk,parsedIntro,parsedError) of (Just True ,Success (Wire info),_ ) -> Right info (Just False,_ ,Just err) -> Left (Textual.fromText err) (_ ,Error err ,_ ) -> Left err _ -> Left "malformed response"
danidiaz/danibot
lib/Network/Danibot/Slack/API.hs
mit
1,423
0
13
378
415
227
188
-1
-1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.WishHandler where import Import import Handler.WishList postWishHandlerR :: Text -> AccessLevel -> WishId -> Handler Html postWishHandlerR listUrl Admin wishId = do (listId, _) <- getWishlist listUrl Admin wish <- runDB $ get wishId render <- getMessageRender ((updateResult, _), _) <- runFormPost $ wishOwnerForm listId wish wasUpdated <- updateIfSuccess updateResult wishId if wasUpdated then return $ () else do ((deleteResult, _), _) <- runFormPost $ deleteWishForm wishId wasDeleted <- deleteIfSuccess deleteResult wishId if wasDeleted then return $ () else setMessage $ toHtml $ render MsgRegisterWishErrorChangingWish redirect $ (WishListR listUrl Admin) postWishHandlerR listUrl Guest wishId = do render <- getMessageRender ((result, _), _) <- runFormPost $ wishGuestForm case result of FormSuccess (numPurchased) -> do runDB $ update wishId [WishBought +=. numPurchased] _ -> setMessage $ toHtml $ render MsgRegisterPurchasedError redirect $ WishListR listUrl Guest updateIfSuccess :: FormResult Wish -> WishId -> Handler (Bool) updateIfSuccess result wishId = do render <- getMessageRender case result of FormSuccess (wish) -> do runDB $ replace wishId wish setMessage $ toHtml $ render MsgRegisterWishWishUpdated return $ True _ -> return $ False deleteIfSuccess :: FormResult WishId -> WishId -> Handler (Bool) deleteIfSuccess result wishId = do render <- getMessageRender case result of FormSuccess (_) -> do runDB $ delete wishId setMessage $ toHtml $ render MsgRegisterWishWishDeleted return $ True _ -> return $ False
lulf/wishsys
Handler/WishHandler.hs
mit
1,853
0
15
478
533
259
274
46
4
{-# LANGUAGE TemplateHaskell #-} module CounterBot where import qualified Data.Text as T (pack) import Web.Slack import Web.Slack.Message import System.Environment (lookupEnv) import Data.Maybe (fromMaybe) import Control.Applicative import Control.Lens myConfig :: String -> SlackConfig myConfig apiToken = SlackConfig { _slackApiToken = apiToken } data CounterState = CounterState { _messageCount :: Int } makeLenses ''CounterState -- Count how many messages the bot recieves counterBot :: SlackBot CounterState counterBot (Message cid _ _ _ _ _) = do num <- userState . messageCount <%= (+1) sendMessage cid (T.pack . show $ num) counterBot _ = return () main :: IO () main = do apiToken <- fromMaybe (error "SLACK_API_TOKEN not set") <$> lookupEnv "SLACK_API_TOKEN" runBot (myConfig apiToken) counterBot startState where startState = CounterState 0
madjar/slack-api
example/CounterBot.hs
mit
944
0
11
212
257
137
120
-1
-1
module TestImport ( module TestImport , module X ) where import Application (makeFoundation, makeLogWare) #if MIN_VERSION_classy_prelude(1, 0, 0) import ClassyPrelude as X hiding (delete, deleteBy, Handler) #else import ClassyPrelude as X hiding (delete, deleteBy) #endif import Database.Persist as X hiding (get) import Database.Persist.Sql ( SqlPersistM , SqlBackend , runSqlPersistMPool , rawSql , rawExecute , unSingle , connEscapeName ) import Foundation as X import Model as X import Test.Hspec as X import Text.Shakespeare.Text (st) import Yesod.Default.Config2 (useEnv, loadYamlSettings) import Yesod.Auth as X import Yesod.Test as X runDB :: SqlPersistM a -> YesodExample App a runDB query = do pool <- fmap appConnPool getTestYesod liftIO $ runSqlPersistMPool query pool runDBWithApp :: App -> SqlPersistM a -> IO a runDBWithApp app query = runSqlPersistMPool query (appConnPool app) withApp :: SpecWith (TestApp App) -> Spec withApp = before $ do settings <- loadYamlSettings ["config/test-settings.yml", "config/settings.yml"] [] useEnv foundation <- makeFoundation settings wipeDB foundation logWare <- liftIO $ makeLogWare foundation return (foundation, logWare) -- This function will truncate all of the tables in your database. -- 'withApp' calls it before each test, creating a clean environment for each -- spec to run in. wipeDB :: App -> IO () wipeDB app = runDBWithApp app $ do tables <- getTables sqlBackend <- ask let escapedTables = map (connEscapeName sqlBackend . DBName) tables query = "TRUNCATE TABLE " ++ intercalate ", " escapedTables rawExecute query [] getTables :: MonadIO m => ReaderT SqlBackend m [Text] getTables = do tables <- rawSql [st| SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'; |] [] return $ map unSingle tables -- | Authenticate as a user. This relies on the `auth-dummy-login: true` flag -- being set in test-settings.yaml, which enables dummy authentication in -- Foundation.hs authenticateAs :: Entity User -> YesodExample App () authenticateAs (Entity _ u) = do request $ do setMethod "POST" addPostParam "ident" $ userIdent u setUrl $ AuthR $ PluginR "dummy" [] -- | Create a user. createUser :: Text -> YesodExample App (Entity User) createUser ident = do runDB $ insertEntity User { userIdent = ident , userPassword = Nothing } getWithAuthenticatedUser :: Route App -> Text -> YesodExample App () getWithAuthenticatedUser route user = do userEntity <- createUser user authenticateAs userEntity get route statusIs 200
frt/happyscheduler
test/TestImport.hs
mit
2,979
0
14
846
670
349
321
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Pane.Modules -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : Juergen Nicklisch-Franken <[email protected]> -- Stability : provisional -- Portability : portable -- -- | The pane of ide where modules are presented in tree form with their -- packages and exports -- ------------------------------------------------------------------------------- module IDE.Pane.Modules ( IDEModules(..) , ModulesState(..) , ExpanderState(..) , showModules , selectIdentifier , reloadKeepSelection , replaySelHistory , replayScopeHistory , addModule ) where import Graphics.UI.Gtk hiding (get) import Graphics.UI.Gtk.Gdk.Events import Data.Maybe import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Data.Tree import Data.List import Distribution.Package import Distribution.Version import Data.Char (toLower) import Prelude hiding (catch) import Data.IORef import IDE.Core.State import IDE.Pane.Info import IDE.Pane.SourceBuffer import Distribution.ModuleName import Distribution.Text (simpleParse,display) import Data.Typeable (Typeable(..)) import Control.Exception (SomeException(..),catch) import Control.Applicative ((<$>)) import IDE.Package (packageConfig,addModuleToPackageDescr,delModuleFromPackageDescr,getEmptyModuleTemplate,getPackageDescriptionAndPath, ModuleLocation(..)) import Distribution.PackageDescription (PackageDescription, BuildInfo, hsSourceDirs, hasLibs, executables, testSuites, exeName, testName, benchmarks, benchmarkName, libBuildInfo, library, buildInfo, testBuildInfo, benchmarkBuildInfo) import System.FilePath (takeBaseName, (</>),dropFileName,makeRelative,takeDirectory) import System.Directory (doesFileExist,createDirectoryIfMissing, removeFile) import Graphics.UI.Editor.MakeEditor (buildEditor,FieldDescription(..),mkField) import Graphics.UI.Editor.Parameters (paraMinSize, paraMultiSel, Parameter(..), emptyParams, (<<<-), paraName) import Graphics.UI.Editor.Simple (textEditor, boolEditor, staticListEditor) import Graphics.UI.Editor.Composite (maybeEditor) import IDE.Utils.GUIUtils (stockIdFromType, __, treeViewContextMenu) import IDE.Metainfo.Provider (getSystemInfo, getWorkspaceInfo, getPackageInfo) import System.Log.Logger (debugM) import Default (Default(..)) import IDE.Workspaces (packageTry) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad (when, void) import Control.Monad.Trans.Class (MonadTrans(..)) import Control.Monad.Trans.Reader (ask) import System.Glib.Properties (newAttrFromMaybeStringProperty) import Data.Text (Text, toCaseFold) import qualified Data.Text as T (unpack, isInfixOf, toLower, pack) import Data.Monoid ((<>)) import qualified Text.Printf as S (printf) import Text.Printf (PrintfType) import qualified Data.Text.IO as T (writeFile) printf :: PrintfType r => Text -> r printf = S.printf . T.unpack -- | A modules pane description -- type ModuleRecord = (Text, Maybe (ModuleDescr,PackageDescr)) data IDEModules = IDEModules { outer :: VBox , paned :: HPaned , treeView :: TreeView , treeStore :: TreeStore ModuleRecord , descrView :: TreeView , descrStore :: TreeStore Descr , descrSortedStore :: TypedTreeModelSort Descr -- ^ The sorted model for descrs , packageScopeB :: RadioButton , workspaceScopeB :: RadioButton , systemScopeB :: RadioButton , dependsB :: CheckButton , blacklistB :: CheckButton , oldSelection :: IORef SelectionState , expanderState :: IORef ExpanderState } deriving Typeable data ModulesState = ModulesState Int (Scope,Bool) (Maybe ModuleName, Maybe Text) ExpanderState deriving(Eq,Ord,Read,Show,Typeable) data ExpanderState = ExpanderState { packageExp :: ExpanderFacet , packageExpNoBlack :: ExpanderFacet , packageDExp :: ExpanderFacet , packageDExpNoBlack :: ExpanderFacet , workspaceExp :: ExpanderFacet , workspaceExpNoBlack :: ExpanderFacet , workspaceDExp :: ExpanderFacet , workspaceDExpNoBlack :: ExpanderFacet , systemExp :: ExpanderFacet , systemExpNoBlack :: ExpanderFacet } deriving (Eq,Ord,Show,Read) type ExpanderFacet = ([TreePath], [TreePath]) data SelectionState = SelectionState { moduleS' :: Maybe ModuleName , facetS' :: Maybe Text , scope' :: Scope , blacklist' :: Bool} deriving (Eq,Ord,Show) instance Pane IDEModules IDEM where primPaneName _ = __ "Modules" getAddedIndex _ = 0 getTopWidget = castToWidget . outer paneId b = "*Modules" --liftIO $ widgetGrabFocus (descrView p) getModules :: Maybe PanePath -> IDEM IDEModules getModules Nothing = forceGetPane (Right "*Modules") getModules (Just pp) = forceGetPane (Left pp) showModules :: IDEAction showModules = do pane <- getModules Nothing displayPane pane False instance RecoverablePane IDEModules ModulesState IDEM where saveState p = do m <- getModules Nothing sc <- getScope mbModules <- getPane recordExpanderState expander <- liftIO $ readIORef (expanderState p) case mbModules of Nothing -> return Nothing Just p -> liftIO $ do i <- panedGetPosition (paned p) mbTreeSelection <- getSelectionTree (treeView m) (treeStore m) mbFacetSelection <- getSelectionDescr (descrView m) (descrStore m) (descrSortedStore m) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbFacetSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) return (Just (ModulesState i sc mbs expander)) recoverState pp (ModulesState i sc@(scope,useBlacklist) se exp) = do nb <- getNotebook pp p <- buildPane pp nb builder mod <- getModules Nothing liftIO $ writeIORef (expanderState mod) exp liftIO $ writeIORef (oldSelection mod) (uncurry SelectionState se scope useBlacklist) liftIO $ panedSetPosition (paned mod) i return p builder pp nb windows = do packageInfo' <- getPackageInfo reifyIDE $ \ ideR -> do let forest = case packageInfo' of Nothing -> [] Just (GenScopeC fst,GenScopeC snd) -> subForest (buildModulesTree (fst,snd)) treeStore <- treeStoreNew forest treeView <- treeViewNew treeViewSetModel treeView treeStore --treeViewSetRulesHint treeView True renderer0 <- cellRendererPixbufNew set renderer0 [ newAttrFromMaybeStringProperty "stock-id" := (Nothing :: Maybe Text) ] renderer <- cellRendererTextNew col <- treeViewColumnNew treeViewColumnSetTitle col (__ "Module") treeViewColumnSetSizing col TreeViewColumnAutosize treeViewColumnSetResizable col True treeViewColumnSetReorderable col True treeViewAppendColumn treeView col cellLayoutPackStart col renderer0 False cellLayoutPackStart col renderer True cellLayoutSetAttributes col renderer treeStore $ \row -> [ cellText := fst row] cellLayoutSetAttributes col renderer0 treeStore $ \row -> [ newAttrFromMaybeStringProperty "stock-id" := case snd row of Nothing -> Nothing Just pair -> if isJust (mdMbSourcePath (fst pair)) then Just ("ide_source" :: Text) else Nothing] renderer2 <- cellRendererTextNew col2 <- treeViewColumnNew treeViewColumnSetTitle col2 (__ "Package") treeViewColumnSetSizing col2 TreeViewColumnAutosize treeViewColumnSetResizable col2 True treeViewColumnSetReorderable col2 True treeViewAppendColumn treeView col2 cellLayoutPackStart col2 renderer2 True cellLayoutSetAttributes col2 renderer2 treeStore $ \row -> [ cellText := case snd row of Nothing -> "" Just pair -> (T.pack . display . pdPackage . snd) pair] treeViewSetHeadersVisible treeView True treeViewSetEnableSearch treeView True treeViewSetSearchEqualFunc treeView (Just (treeViewSearch treeView treeStore)) -- Facet view descrView <- treeViewNew descrStore <- treeStoreNew [] -- sorted model descrSortedStore <- treeModelSortNewWithModel descrStore treeViewSetModel descrView descrSortedStore renderer30 <- cellRendererPixbufNew renderer31 <- cellRendererPixbufNew renderer3 <- cellRendererTextNew col <- treeViewColumnNew treeViewColumnSetTitle col (__ "Interface") --treeViewColumnSetSizing col TreeViewColumnAutosize treeViewAppendColumn descrView col cellLayoutPackStart col renderer30 False cellLayoutPackStart col renderer31 False cellLayoutPackStart col renderer3 True cellLayoutSetAttributes col renderer3 descrStore $ \row -> [ cellText := descrTreeText row] cellLayoutSetAttributes col renderer30 descrStore $ \row -> [ cellPixbufStockId := stockIdFromType (descrIdType row)] cellLayoutSetAttributes col renderer31 descrStore $ \row -> [ cellPixbufStockId := if isReexported row then "ide_reexported" else if isJust (dscMbLocation row) then if dscExported row then ("ide_source" :: Text) else "ide_source_local" else "ide_empty"] -- sort definitions on name, ignoring case treeSortableSetSortFunc descrSortedStore 2 $ \iter1 iter2 -> do d1 <- treeModelGetRow descrStore iter1 d2 <- treeModelGetRow descrStore iter2 let cafName = toCaseFold . descrTreeText return (compare (cafName d1) (cafName d2)) treeViewColumnSetSortColumnId col 2 treeSortableSetSortColumnId descrSortedStore 2 SortAscending treeViewSetHeadersVisible descrView True treeViewSetEnableSearch descrView True treeViewSetSearchEqualFunc descrView (Just (descrViewSearch descrView descrStore)) pane' <- hPanedNew sw <- scrolledWindowNew Nothing Nothing scrolledWindowSetShadowType sw ShadowIn containerAdd sw treeView scrolledWindowSetPolicy sw PolicyAutomatic PolicyAutomatic sw2 <- scrolledWindowNew Nothing Nothing scrolledWindowSetShadowType sw2 ShadowIn containerAdd sw2 descrView scrolledWindowSetPolicy sw2 PolicyAutomatic PolicyAutomatic panedAdd1 pane' sw panedAdd2 pane' sw2 (Rectangle _ _ x y) <- liftIO $ widgetGetAllocation nb panedSetPosition pane' (max 200 (x `quot` 2)) box <- hButtonBoxNew boxSetSpacing box 2 buttonBoxSetLayout box ButtonboxSpread rb1 <- radioButtonNewWithLabel (__ "Package") rb2 <- radioButtonNewWithLabelFromWidget rb1 (__ "Workspace") rb3 <- radioButtonNewWithLabelFromWidget rb1 (__ "System") toggleButtonSetActive rb3 True cb2 <- checkButtonNewWithLabel (__ "Imports") cb <- checkButtonNewWithLabel (__ "Blacklist") boxPackStart box rb1 PackGrow 0 boxPackStart box rb2 PackGrow 0 boxPackStart box rb3 PackGrow 0 boxPackEnd box cb PackNatural 0 boxPackEnd box cb2 PackNatural 0 boxOuter <- vBoxNew False 0 boxPackStart boxOuter box PackNatural 2 boxPackStart boxOuter pane' PackGrow 0 oldState <- liftIO $ newIORef $ SelectionState Nothing Nothing SystemScope False expanderState <- liftIO $ newIORef emptyExpansion scopeRef <- newIORef (SystemScope,True) let modules = IDEModules boxOuter pane' treeView treeStore descrView descrStore descrSortedStore rb1 rb2 rb3 cb2 cb oldState expanderState cid1 <- after treeView focusInEvent $ do liftIO $ reflectIDE (makeActive modules) ideR return True cid2 <- after descrView focusInEvent $ do liftIO $ reflectIDE (makeActive modules) ideR return True (cid3, cid4) <- treeViewContextMenu treeView $ modulesContextMenu ideR treeStore treeView cid5 <- treeView `on` rowActivated $ modulesSelect ideR treeStore treeView (cid6, cid7) <- treeViewContextMenu descrView $ descrViewContextMenu ideR descrStore descrSortedStore descrView cid8 <- descrView `on` rowActivated $ descrViewSelect ideR descrStore descrSortedStore on rb1 toggled (reflectIDE scopeSelection ideR) on rb2 toggled (reflectIDE scopeSelection ideR) on rb3 toggled (reflectIDE scopeSelection ideR) on cb toggled (reflectIDE scopeSelection ideR) on cb2 toggled (reflectIDE scopeSelection ideR) sel <- treeViewGetSelection treeView on sel treeSelectionSelectionChanged $ do fillFacets treeView treeStore descrView descrStore descrSortedStore reflectIDE recordSelHistory ideR return () sel2 <- treeViewGetSelection descrView on sel2 treeSelectionSelectionChanged $ do fillInfo descrView descrStore descrSortedStore ideR reflectIDE recordSelHistory ideR return () return (Just modules,map ConnectC [cid1, cid2, cid3, cid4, cid5, cid6, cid7, cid8]) selectIdentifier :: Descr -> Bool -> IDEAction selectIdentifier idDescr openSource= do liftIO $ debugM "leksah" "selectIdentifier" systemScope <- getSystemInfo workspaceScope <- getWorkspaceInfo packageScope <- getPackageInfo currentScope <- getScope case dsMbModu idDescr of Nothing -> return () Just pm -> case scopeForDescr pm packageScope workspaceScope systemScope of Nothing -> return () Just sc -> do when (fst currentScope < sc) (setScope (sc,snd currentScope)) selectIdentifier' (modu pm) (dscName idDescr) when openSource (goToDefinition idDescr) scopeForDescr :: PackModule -> Maybe (GenScope,GenScope) -> Maybe (GenScope,GenScope) -> Maybe GenScope -> Maybe Scope scopeForDescr pm packageScope workspaceScope systemScope = case ps of (True, r) -> Just (PackageScope r) _ -> case ws of (True, r) -> Just (WorkspaceScope r) _ -> case systemScope of Nothing -> Nothing Just (GenScopeC(PackScope ssc _)) -> if Map.member pid ssc then Just SystemScope else Nothing where pid = pack pm ps = case packageScope of Nothing -> (False,False) Just (GenScopeC (PackScope psc1 _), GenScopeC (PackScope psc2 _)) | Map.member pid psc1 -> (True, False) | Map.member pid psc2 -> (True, True) | otherwise -> (False, False) ws = case workspaceScope of Nothing -> (False,False) Just (GenScopeC (PackScope wsc1 _), GenScopeC (PackScope wsc2 _)) | Map.member pid wsc1 -> (True, False) | Map.member pid wsc2 -> (True, True) | otherwise -> (False, False) selectIdentifier' :: ModuleName -> Text -> IDEAction selectIdentifier' moduleName symbol = let nameArray = map T.pack $ components moduleName in do liftIO $ debugM "leksah" $ "selectIdentifier' " <> show moduleName <> " " <> T.unpack symbol mods <- getModules Nothing mbTree <- liftIO $ treeStoreGetTreeSave (treeStore mods) [] case treePathFromNameArray mbTree nameArray [] of Just treePath -> liftIO $ do treeViewExpandToPath (treeView mods) treePath sel <- treeViewGetSelection (treeView mods) treeSelectionSelectPath sel treePath col <- treeViewGetColumn (treeView mods) 0 treeViewScrollToCell (treeView mods) (Just treePath) col (Just (0.3,0.3)) mbFacetTree <- treeStoreGetTreeSave (descrStore mods) [] selF <- treeViewGetSelection (descrView mods) case findPathFor symbol mbFacetTree of Nothing -> sysMessage Normal (__ "no path found") Just childPath -> do path <- treeModelSortConvertChildPathToPath (descrSortedStore mods) childPath treeViewExpandToPath (descrView mods) path treeSelectionSelectPath selF path col <- treeViewGetColumn (descrView mods) 0 treeViewScrollToCell (descrView mods) (Just path) col (Just (0.3,0.3)) bringPaneToFront mods Nothing -> return () findPathFor :: Text -> Maybe (Tree Descr) -> Maybe TreePath findPathFor symbol (Just (Node _ forest)) = foldr ( \i mbTreePath -> findPathFor' [i] (forest !! i) mbTreePath) Nothing [0 .. (length forest - 1)] where findPathFor' :: TreePath -> Tree Descr -> Maybe TreePath -> Maybe TreePath findPathFor' _ node (Just p) = Just p findPathFor' path (Node wrap sub) Nothing = if dscName wrap == symbol then Just (reverse path) else foldr ( \i mbTreePath -> findPathFor' (i:path) (sub !! i) mbTreePath) Nothing [0 .. (length sub - 1)] findPathFor symbol Nothing = Nothing treePathFromNameArray :: Maybe ModTree -> [Text] -> [Int] -> Maybe [Int] treePathFromNameArray (Just tree) [] accu = Just (reverse accu) treePathFromNameArray (Just tree) (h:t) accu = let names = map (fst . rootLabel) (subForest tree) mbIdx = elemIndex h names in case mbIdx of Nothing -> Nothing Just i -> treePathFromNameArray (Just (subForest tree !! i)) t (i:accu) treePathFromNameArray Nothing _ _ = Nothing treeViewSearch :: TreeView -> TreeStore ModuleRecord -> Text -> TreeIter -> IO Bool treeViewSearch treeView treeStore string iter = do liftIO $ debugM "leksah" "treeViewSearch" path <- treeModelGetPath treeStore iter val <- treeStoreGetValue treeStore path mbTree <- treeStoreGetTreeSave treeStore path exp <- treeViewRowExpanded treeView path when (isJust mbTree && not (null (subForest (fromJust mbTree))) && not exp) $ let found = searchInModSubnodes (fromJust mbTree) string in when found $ do treeViewExpandRow treeView path False return () let str2 = case snd val of Just (mod,_) -> showPackModule (mdModuleId mod) Nothing -> "" let res = T.isInfixOf (T.toLower string) (T.toLower str2) return res searchInModSubnodes :: ModTree -> Text -> Bool searchInModSubnodes tree str = any (\ (_, mbPair) -> case mbPair of Nothing -> False Just (mod, _) -> let cstr = T.pack $ show (Present (mdModuleId mod)) in T.isInfixOf (T.toLower str) (T.toLower cstr)) (concatMap flatten (subForest tree)) descrViewSearch :: TreeView -> TreeStore Descr -> Text -> TreeIter -> IO Bool descrViewSearch descrView descrStore string iter = do liftIO $ debugM "leksah" "descrViewSearch" path <- treeModelGetPath descrStore iter val <- treeStoreGetValue descrStore path tree <- treeStoreGetTree descrStore path exp <- treeViewRowExpanded descrView path when (not (null (subForest tree)) && not exp) $ let found = searchInFacetSubnodes tree string in when found $ do treeViewExpandRow descrView path False return () return (T.isInfixOf (T.toLower string) (T.toLower (descrTreeText val))) searchInFacetSubnodes :: DescrTree -> Text -> Bool searchInFacetSubnodes tree str = any (T.isInfixOf (T.toLower str) . T.toLower . descrTreeText) (concatMap flatten (subForest tree)) -- | Fill facet view with descrs from selected module fillFacets :: TreeView -> TreeStore ModuleRecord -> TreeView -> TreeStore Descr -> TypedTreeModelSort Descr -> IO () fillFacets treeView treeStore descrView descrStore descrSortedStore = do liftIO $ debugM "leksah" "fillFacets" sel <- getSelectionTree treeView treeStore emptyModel <- treeStoreNew [] treeViewSetModel descrView emptyModel treeStoreClear descrStore case sel of Just (_,Just (mod,package)) -> mapM_ (\(e,i) -> treeStoreInsertTree descrStore [] i e) $ zip (buildFacetForrest mod) [0 ..] _ -> return () treeViewSetModel descrView descrSortedStore treeViewSetEnableSearch descrView True treeViewSetSearchEqualFunc descrView (Just (descrViewSearch descrView descrStore)) liftIO $ debugM "leksah" "fillFacets done" getSelectionTree :: TreeView -> TreeStore ModuleRecord -> IO (Maybe ModuleRecord) getSelectionTree treeView treeStore = do liftIO $ debugM "leksah" "getSelectionTree" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of [] -> return Nothing a:r -> do val <- treeStoreGetValue treeStore a return (Just val) -- | Get selected Descr, if any getSelectionDescr :: TreeView -> TreeStore Descr -> TypedTreeModelSort Descr -> IO (Maybe Descr) getSelectionDescr treeView treeStore descrSortedStore = do liftIO $ debugM "leksah" "getSelectionDescr" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of a:_ -> do unsorteda <- treeModelSortConvertPathToChildPath descrSortedStore a val <- treeStoreGetValue treeStore unsorteda return (Just val) _ -> return Nothing -- | Fill info pane with selected Descr if any fillInfo :: TreeView -> TreeStore Descr -> TypedTreeModelSort Descr -> IDERef -> IO () fillInfo treeView lst descrSortedStore ideR = do liftIO $ debugM "leksah" "fillInfo" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of [] -> return () [a] -> do unsorteda <- treeModelSortConvertPathToChildPath descrSortedStore a descr <- treeStoreGetValue lst unsorteda reflectIDE (setInfo descr) ideR return () _ -> return () findDescription :: SymbolTable alpha => PackModule -> alpha -> Text -> Maybe (Text,Descr) findDescription md st s = case filter (\id -> case dsMbModu id of Nothing -> False Just pm -> md == pm) (symLookup s st) of [] -> Nothing l -> Just (s,head l) getEmptyDefaultScope :: Map Text [Descr] getEmptyDefaultScope = Map.empty fillModulesList :: (Scope,Bool) -> IDEAction fillModulesList (scope,useBlacklist) = do liftIO $ debugM "leksah" "fillModulesList" mods <- getModules Nothing prefs <- readIDE prefs case scope of SystemScope -> do accessibleInfo' <- getSystemInfo case accessibleInfo' of Nothing -> liftIO $ treeStoreClear (treeStore mods) --treeStoreInsertTree (treeStore mods) [] 0 (Node ("",[]) []) Just (GenScopeC ai@(PackScope pm ps)) -> let p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else ai (Node _ li) = buildModulesTree (PackScope Map.empty getEmptyDefaultScope,p2) in insertIt li mods WorkspaceScope withImports -> do workspaceInfo' <- getWorkspaceInfo packageInfo' <- getPackageInfo case workspaceInfo' of Nothing -> insertIt [] mods Just (GenScopeC l,GenScopeC p) -> let (l',p'@(PackScope pm ps)) = if withImports then (l, p) else (l, PackScope Map.empty symEmpty) p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else p' (Node _ li) = buildModulesTree (l', p2) in insertIt li mods PackageScope withImports -> do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> insertIt [] mods Just (GenScopeC l,GenScopeC p) -> let (l',p'@(PackScope pm ps)) = if withImports then (l,p) else (l, PackScope Map.empty symEmpty) p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else p' (Node _ li) = buildModulesTree (l', p2) in insertIt li mods where insertIt li mods = liftIO $ do emptyModel <- treeStoreNew [] treeViewSetModel (treeView mods) emptyModel treeStoreClear (treeStore mods) mapM_ (\(e,i) -> treeStoreInsertTree (treeStore mods) [] i e) $ zip li [0 .. length li] treeViewSetModel (treeView mods) (treeStore mods) treeViewSetEnableSearch (treeView mods) True treeViewSetSearchEqualFunc (treeView mods) (Just (treeViewSearch (treeView mods) (treeStore mods))) filterBlacklist :: [Dependency] -> PackageDescr -> Bool filterBlacklist dependencies packageDescr = let packageId = pdPackage packageDescr name = pkgName packageId version = pkgVersion packageId in isNothing $ find (\ (Dependency str vr) -> str == name && withinRange version vr) dependencies type DescrForest = Forest Descr type DescrTree = Tree Descr descrTreeText :: Descr -> Text descrTreeText (Real (RealDescr id _ _ _ _ (InstanceDescr binds) _)) = id <> " " <> printBinds binds where printBinds [] = "" printBinds [a] = a printBinds (a:b) = a <> " " <> printBinds b descrTreeText d = dscName d descrIdType :: Descr -> DescrType descrIdType = descrType . dscTypeHint buildFacetForrest :: ModuleDescr -> DescrForest buildFacetForrest modDescr = let (instances,other) = partition (\id -> case dscTypeHint id of InstanceDescr _ -> True _ -> False) $ take 2000 $ mdIdDescriptions modDescr -- TODO: Patch for toxioc TypeLevel package with 28000 aliases forestWithoutInstances = map buildFacet other (forest2,orphaned) = foldl' addInstances (forestWithoutInstances,[]) instances orphanedNodes = map (\ inst -> Node inst []) orphaned in forest2 ++ reverse orphanedNodes where -- expand nodes in a module desciption for the description tree buildFacet :: Descr -> DescrTree buildFacet descr = case dscTypeHint descr of DataDescr constructors fields -> Node descr (map (\ (SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp})) []) constructors ++ map (\ (SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp})) []) fields) NewtypeDescr (SimpleDescr fn ty loc comm exp) mbField -> Node descr (Node (makeReexported descr (Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp})) [] : case mbField of Just (SimpleDescr fn ty loc comm exp) -> [Node (makeReexported descr (Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp})) []] Nothing -> []) ClassDescr _ methods -> Node descr (map (\(SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = MethodDescr descr, dscExported' = exp})) []) methods) _ -> Node descr [] where makeReexported :: Descr -> Descr -> Descr makeReexported (Reexported d1) d2 = Reexported ReexportedDescr{dsrMbModu = dsrMbModu d1, dsrDescr = d2} makeReexported _ d2 = d2 addInstances :: (DescrForest,[Descr]) -> Descr -> (DescrForest,[Descr]) addInstances (forest,orphaned) instDescr = case foldr (matches instDescr) ([],False) forest of (f,True) -> (f,orphaned) (f,False) -> (forest, instDescr:orphaned) matches :: Descr -> DescrTree -> (DescrForest,Bool) -> (DescrForest,Bool) matches (Real (instDescr@RealDescr{dscTypeHint' = InstanceDescr binds})) (Node dd@(Real (RealDescr id _ _ _ _ (DataDescr _ _) _)) sub) (forest,False) | not (null binds) && id == head binds = (Node dd (sub ++ [Node newInstDescr []]) : forest,True) where newInstDescr = if isNothing (dscMbLocation' instDescr) then Real $ instDescr{dscMbLocation' = dscMbLocation dd} else Real instDescr matches (Real (instDescr@RealDescr{dscTypeHint' = InstanceDescr binds})) (Node dd@(Real (RealDescr id _ _ _ _ (NewtypeDescr _ _) _)) sub) (forest,False) | not (null binds) && id == head binds = (Node dd (sub ++ [Node newInstDescr []]) : forest,True) where newInstDescr = if isNothing (dscMbLocation' instDescr) then Real $ instDescr{dscMbLocation' = dscMbLocation dd} else Real instDescr matches _ node (forest,b) = (node:forest,b) defaultRoot :: Tree ModuleRecord defaultRoot = Node ("",Just (getDefault,getDefault)) [] type ModTree = Tree ModuleRecord -- -- | Make a Tree with a module desription, package description pairs tree to display. -- Their are nodes with a label but without a module (like e.g. Data). -- buildModulesTree :: (SymbolTable alpha, SymbolTable beta) => (PackScope alpha,PackScope beta ) -> ModTree buildModulesTree (PackScope localMap _,PackScope otherMap _) = let modDescrPackDescr = concatMap (\p -> map (\m -> (m,p)) (pdModules p)) (Map.elems localMap ++ Map.elems otherMap) resultTree = foldl' insertPairsInTree defaultRoot modDescrPackDescr in sortTree resultTree -- | Insert module and package info into the tre insertPairsInTree :: ModTree -> (ModuleDescr,PackageDescr) -> ModTree insertPairsInTree tree pair = let nameArray = modTreeName $ fst pair (startArray,last) = splitAt (length nameArray - 1) nameArray pairedWith = map (\ n -> (n, Nothing)) startArray ++ [(head last, Just pair)] in insertNodesInTree pairedWith tree where modTreeName modDescr = let modId = mdModuleId modDescr modName = modu modId mFilePath = mdMbSourcePath modDescr -- show relative file path for Main modules -- since we can have several in case (components modName,mFilePath) of (["Main"],Just fp) -> let sfp = case (pdMbSourcePath (snd pair)) of Nothing -> fp Just pfp -> makeRelative (takeDirectory pfp) fp in [T.pack $ "Main ("++sfp++")"] (cmps,_) -> map T.pack cmps insertNodesInTree :: [ModuleRecord] -> ModTree -> ModTree insertNodesInTree [p1@(str1,Just pair)] (Node p2@(str2,mbPair) forest2) = case partition (\ (Node (s,_) _) -> s == str1) forest2 of ([found],rest) -> case found of Node p3@(_,Nothing) forest3 -> Node p2 (Node p1 forest3 : rest) Node p3@(_,Just pair3) forest3 -> Node p2 (Node p1 [] : Node p3 forest3 : rest) ([],rest) -> Node p2 (Node p1 [] : forest2) (found,rest) -> case head found of Node p3@(_,Nothing) forest3 -> Node p2 (Node p1 forest3 : tail found ++ rest) Node p3@(_,Just pair3) forest3 -> Node p2 (Node p1 [] : Node p3 forest3 : tail found ++ rest) insertNodesInTree li@(hd@(str1,Nothing):tl) (Node p@(str2,mbPair) forest) = case partition (\ (Node (s,_) _) -> s == str1) forest of ([found],rest) -> Node p (insertNodesInTree tl found : rest) ([],rest) -> Node p (makeNodes li : forest) (found,rest) -> Node p (insertNodesInTree tl (head found) : tail found ++ rest) insertNodesInTree [] n = n insertNodesInTree _ _ = error (T.unpack $ __ "Modules>>insertNodesInTree: Should not happen2") makeNodes :: [(Text,Maybe (ModuleDescr,PackageDescr))] -> ModTree makeNodes [(str,mbPair)] = Node (str,mbPair) [] makeNodes ((str,mbPair):tl) = Node (str,mbPair) [makeNodes tl] makeNodes _ = throwIDE (__ "Impossible in makeNodes") instance Ord a => Ord (Tree a) where compare (Node l1 _) (Node l2 _) = compare l1 l2 sortTree :: Ord a => Tree a -> Tree a sortTree (Node l forest) = Node l (sort (map sortTree forest)) getSelectedModuleFile :: Maybe ModuleRecord -> Maybe FilePath getSelectedModuleFile sel = case sel of Just (_,Just (m,p)) -> case (mdMbSourcePath m, pdMbSourcePath p) of (Just fp, Just pp) -> Just $ dropFileName pp </> fp (Just fp, Nothing) -> Just fp _ -> Nothing otherwise -> Nothing modulesContextMenu :: IDERef -> TreeStore ModuleRecord -> TreeView -> Menu -> IO () modulesContextMenu ideR store treeView theMenu = do liftIO $ debugM "leksah" "modulesContextMenu" item1 <- menuItemNewWithLabel (__ "Edit source") item1 `on` menuItemActivate $ do mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> void $ reflectIDE (selectSourceBuf fp) ideR sep1 <- separatorMenuItemNew item2 <- menuItemNewWithLabel (__ "Expand here") item2 `on` menuItemActivate $ expandHere treeView item3 <- menuItemNewWithLabel (__ "Collapse here") item3 `on` menuItemActivate $ collapseHere treeView item4 <- menuItemNewWithLabel (__ "Expand all") item4 `on` menuItemActivate $ treeViewExpandAll treeView item5 <- menuItemNewWithLabel (__ "Collapse all") item5 `on` menuItemActivate $ treeViewCollapseAll treeView sep2 <- separatorMenuItemNew item6 <- menuItemNewWithLabel (__ "Add module") item6 `on` menuItemActivate $ reflectIDE (packageTry $ addModule' treeView store) ideR item7 <- menuItemNewWithLabel (__ "Delete module") item7 `on` menuItemActivate $ do mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> do resp <- reflectIDE respDelModDialog ideR when resp $ do exists <- doesFileExist fp if exists then do reflectIDE (liftIO $ removeFile fp) ideR reflectIDE (packageTry $ delModule treeView store)ideR else reflectIDE (packageTry $ delModule treeView store)ideR reflectIDE (packageTry packageConfig) ideR return () sel <- getSelectionTree treeView store case sel of Just (s, Nothing) -> mapM_ (menuShellAppend theMenu) [castToMenuItem item1, castToMenuItem sep1, castToMenuItem item2, castToMenuItem item3, castToMenuItem item4, castToMenuItem item5, castToMenuItem sep2, castToMenuItem item6] Just (_,Just (m,_)) -> mapM_ (menuShellAppend theMenu) [castToMenuItem item1, castToMenuItem sep1, castToMenuItem item2, castToMenuItem item3, castToMenuItem item4, castToMenuItem item5, castToMenuItem sep2, castToMenuItem item6, castToMenuItem item7] otherwise -> return () modulesSelect :: IDERef -> TreeStore ModuleRecord -> TreeView -> TreePath -> TreeViewColumn -> IO () modulesSelect ideR store treeView path _ = do liftIO $ debugM "leksah" "modulesSelect" treeViewExpandRow treeView path False mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> liftIO $ void (reflectIDE (selectSourceBuf fp) ideR) -- | Build contextual menu on selected Descr descrViewContextMenu :: IDERef -> TreeStore Descr -> TypedTreeModelSort Descr -> TreeView -> Menu -> IO () descrViewContextMenu ideR store descrSortedStore descrView theMenu = do liftIO $ debugM "leksah" "descrViewContextMenu" item1 <- menuItemNewWithLabel (__ "Go to definition") item1 `on` menuItemActivate $ do sel <- getSelectionDescr descrView store descrSortedStore case sel of Just descr -> reflectIDE (goToDefinition descr) ideR otherwise -> sysMessage Normal (__ "Modules>> descrViewPopup: no selection") item2 <- menuItemNewWithLabel (__ "Insert in buffer") item2 `on` menuItemActivate $ do sel <- getSelectionDescr descrView store descrSortedStore case sel of Just descr -> reflectIDE (insertInBuffer descr) ideR otherwise -> sysMessage Normal (__ "Modules>> descrViewPopup: no selection") mapM_ (menuShellAppend theMenu) [item1, item2] -- | Selects the Descr referenced by the path descrViewSelect :: IDERef -> TreeStore Descr -> TypedTreeModelSort Descr -> TreePath -> TreeViewColumn -> IO () descrViewSelect ideR store descrSortedStore path _ = do liftIO $ debugM "leksah" "descrViewSelect" unsortedp <- treeModelSortConvertPathToChildPath descrSortedStore path descr <- treeStoreGetValue store unsortedp reflectIDE (goToDefinition descr) ideR setScope :: (Scope,Bool) -> IDEAction setScope (sc,bl) = do liftIO $ debugM "leksah" "setScope" mods <- getModules Nothing case sc of (PackageScope False) -> liftIO $ do toggleButtonSetActive (packageScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) False (PackageScope True) -> liftIO $ do toggleButtonSetActive (packageScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) True (WorkspaceScope False) -> liftIO $ do toggleButtonSetActive (workspaceScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) False (WorkspaceScope True) -> liftIO $ do toggleButtonSetActive (workspaceScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) True SystemScope -> liftIO $ do toggleButtonSetActive (systemScopeB mods) True widgetSetSensitive (dependsB mods) False liftIO $ toggleButtonSetActive (blacklistB mods) bl selectScope (sc,bl) getScope :: IDEM (Scope,Bool) getScope = do liftIO $ debugM "leksah" "getScope" mods <- getModules Nothing rb1s <- liftIO $ toggleButtonGetActive (packageScopeB mods) rb2s <- liftIO $ toggleButtonGetActive (workspaceScopeB mods) rb3s <- liftIO $ toggleButtonGetActive (systemScopeB mods) cb1s <- liftIO $ toggleButtonGetActive (dependsB mods) cbs <- liftIO $ toggleButtonGetActive (blacklistB mods) let scope | rb1s = PackageScope cb1s | rb2s = WorkspaceScope cb1s | otherwise = SystemScope return (scope,cbs) scopeSelection :: IDEAction scopeSelection = do liftIO $ debugM "leksah" "scopeSelection" (sc,bl) <- getScope setScope (sc,bl) selectScope (sc,bl) selectScope :: (Scope,Bool) -> IDEAction selectScope (sc,bl) = do liftIO $ debugM "leksah" "selectScope" recordExpanderState mods <- getModules Nothing mbTreeSelection <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) mbDescrSelection <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) (descrSortedStore mods) ts <- liftIO $ treeViewGetSelection (treeView mods) withoutRecordingDo $ do liftIO $ treeSelectionUnselectAll ts fillModulesList (sc,bl) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbDescrSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) selectNames mbs recordScopeHistory applyExpanderState liftIO $ bringPaneToFront mods selectNames :: (Maybe ModuleName, Maybe Text) -> IDEAction selectNames (mbModuleName, mbIdName) = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing case mbModuleName of Nothing -> liftIO $ do sel <- treeViewGetSelection (treeView mods) treeSelectionUnselectAll sel selF <- treeViewGetSelection (descrView mods) treeSelectionUnselectAll selF Just moduleName -> let nameArray = map T.pack $ components moduleName in do mbTree <- liftIO $ treeStoreGetTreeSave (treeStore mods) [] case treePathFromNameArray mbTree nameArray [] of Nothing -> return () Just treePath -> liftIO $ do treeViewExpandToPath (treeView mods) treePath sel <- treeViewGetSelection (treeView mods) treeSelectionSelectPath sel treePath col <- treeViewGetColumn (treeView mods) 0 treeViewScrollToCell (treeView mods) (Just treePath) col (Just (0.3,0.3)) case mbIdName of Nothing -> do selF <- treeViewGetSelection (descrView mods) treeSelectionUnselectAll selF Just symbol -> do mbDescrTree <- treeStoreGetTreeSave (descrStore mods) [] selF <- treeViewGetSelection (descrView mods) case findPathFor symbol mbDescrTree of Nothing -> sysMessage Normal (__ "no path found") Just childPath -> do path <- treeModelSortConvertChildPathToPath (descrSortedStore mods) childPath treeSelectionSelectPath selF path col <- treeViewGetColumn (descrView mods) 0 treeViewScrollToCell (descrView mods) (Just path) col (Just (0.3,0.3)) reloadKeepSelection :: Bool -> IDEAction reloadKeepSelection isInitial = do liftIO . debugM "leksah" $ T.unpack (__ ">>>Info Changed!!! ") ++ show isInitial mbMod <- getPane case mbMod of Nothing -> return () Just mods -> do state <- readIDE currentState if not $ isStartingOrClosing state then do mbTreeSelection <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) mbDescrSelection <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) (descrSortedStore mods) sc <- getScope recordExpanderState fillModulesList sc liftIO $ treeStoreClear (descrStore mods) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbDescrSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) applyExpanderState selectNames mbs else when isInitial $ do SelectionState moduleS' facetS' sc bl <- liftIO $ readIORef (oldSelection mods) setScope (sc,bl) fillModulesList (sc, bl) selectNames (moduleS', facetS') applyExpanderState treeStoreGetTreeSave :: TreeStore a -> TreePath -> IO (Maybe (Tree a)) treeStoreGetTreeSave treeStore treePath = catch (do liftIO $ debugM "leksah" "treeStoreGetTreeSave" res <- treeStoreGetTree treeStore treePath return (Just res)) (\ (_ :: SomeException) -> return Nothing) expandHere :: TreeView -> IO () expandHere treeView = do liftIO $ debugM "leksah" "expandHere" sel <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows sel case paths of [] -> return () (hd:_) -> void (treeViewExpandRow treeView hd True) collapseHere :: TreeView -> IO () collapseHere treeView = do liftIO $ debugM "leksah" "collapseHere" sel <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows sel case paths of [] -> return () (hd:_) -> void (treeViewCollapseRow treeView hd) delModule :: TreeView -> TreeStore ModuleRecord -> PackageAction delModule treeview store = do liftIO $ debugM "leksah" "delModule" window <- liftIDE getMainWindow sel <- liftIO $ treeViewGetSelection treeview paths <- liftIO $ treeSelectionGetSelectedRows sel categories <- case paths of [] -> return [] (treePath:_) -> liftIO $ mapM (treeStoreGetValue store . (`take` treePath)) [1 .. length treePath] liftIDE $ ideMessage Normal (T.pack $ printf (__ "categories: %s") (show categories)) let modPacDescr = snd(last categories) case modPacDescr of Nothing -> liftIDE $ ideMessage Normal (__ "This should never be shown!") Just(md,_) -> do let modName = modu.mdModuleId $ md liftIDE $ ideMessage Normal ("modName: " <> T.pack (show modName)) delModuleFromPackageDescr modName respDelModDialog :: IDEM Bool respDelModDialog = do liftIO $ debugM "leksah" "respDelModDialog" window <- getMainWindow resp <- liftIO $ do dia <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (__ "Are you sure?") dialogAddButton dia (__ "_Delete Module") (ResponseUser 1) dialogSetDefaultResponse dia ResponseCancel set dia [ windowWindowPosition := WinPosCenterOnParent ] resp <- dialogRun dia widgetDestroy dia return resp return $ resp == ResponseUser 1 addModule' :: TreeView -> TreeStore ModuleRecord -> PackageAction addModule' treeView store = do liftIO $ debugM "leksah" "addModule'" sel <- liftIO $ treeViewGetSelection treeView paths <- liftIO $ treeSelectionGetSelectedRows sel categories <- case paths of [] -> return [] (treePath:_) -> liftIO $ mapM (treeStoreGetValue store . (`take` treePath)) [1 .. length treePath] addModule (map fst categories) -- Includes non buildable allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ libBuildInfo lib | Just lib <- [library pkg_descr] ] ++ [ buildInfo exe | exe <- executables pkg_descr ] ++ [ testBuildInfo tst | tst <- testSuites pkg_descr ] ++ [ benchmarkBuildInfo tst | tst <- benchmarks pkg_descr ] addModule :: [Text] -> PackageAction addModule modulePrefix = do liftIO $ debugM "leksah" "selectIdentifier" mbPD <- liftIDE getPackageDescriptionAndPath case mbPD of Nothing -> liftIDE $ ideMessage Normal (__ "No package description") Just (pd,cabalPath) -> let srcPaths = nub $ concatMap hsSourceDirs $ allBuildInfo' pd rootPath = dropFileName cabalPath modPath = foldr (\a b -> a <> "." <> b) "" modulePrefix in do window' <- liftIDE getMainWindow mbResp <- liftIO $ addModuleDialog window' modPath srcPaths (hasLibs pd) $ map (T.pack . exeName) (executables pd) ++ map (T.pack . testName) (testSuites pd) ++ map (T.pack . benchmarkName) (benchmarks pd) case mbResp of Nothing -> return () Just addMod@(AddModule modPath srcPath libExposed exesAndTests) -> case simpleParse $ T.unpack modPath of Nothing -> liftIDE $ ideMessage Normal (T.pack $ printf (__ "Not a valid module name : %s") (T.unpack modPath)) Just moduleName -> do package <- ask let target = ipdPackageDir package </> srcPath </> toFilePath moduleName ++ ".hs" liftIO $ createDirectoryIfMissing True (dropFileName target) alreadyExists <- liftIO $ doesFileExist target if alreadyExists then do liftIDE $ ideMessage Normal (T.pack $ printf (__ "File already exists! Importing existing file %s.hs") (takeBaseName target)) addModuleToPackageDescr moduleName $ addModuleLocations addMod packageConfig else do template <- liftIO $ getEmptyModuleTemplate pd modPath liftIO $ T.writeFile target template addModuleToPackageDescr moduleName $ addModuleLocations addMod packageConfig liftIDE $ fileOpenThis target -- | The dialog for adding a new module data AddModule = AddModule { moduleName :: Text, sourceRoot :: FilePath, libExposed :: Maybe Bool, exesAndTests :: Set Text} addModuleLocations :: AddModule -> [ModuleLocation] addModuleLocations addMod = lib (libExposed addMod) ++ map ExeOrTestMod (Set.toList $ exesAndTests addMod) where lib (Just True) = [LibExposedMod] lib (Just False) = [LibOtherMod] lib Nothing = [] -- | Creates and runs a "new module" dialog addModuleDialog :: Window -- ^ The parent window -> Text -- ^ Will be set as default value for the module name -> [FilePath] -- ^ Possible source directories to add it to -> Bool -- ^ Whether the active package has a library -> [Text] -- ^ The components of the active package -> IO (Maybe AddModule) addModuleDialog parent modString sourceRoots hasLib exesTests = do liftIO $ debugM "leksah" "addModuleDialog" dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := __ "Construct new module" ] windowSetDefaultSize dia 400 100 upper <- dialogGetContentArea dia lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (moduleFields sourceRoots hasLib exesTests) (AddModule modString (head sourceRoots) (Just False) Set.empty) bb <- hButtonBoxNew boxSetSpacing bb 6 buttonBoxSetLayout bb ButtonboxSpread cancel <- buttonNewFromStock "gtk-cancel" ok <- buttonNewFromStock "gtk-ok" boxPackEnd bb cancel PackNatural 0 boxPackEnd bb ok PackNatural 0 errorLabel <- labelNew (Nothing :: Maybe String) labelSetLineWrap errorLabel True widgetSetName errorLabel ("errorLabel" :: String) on ok buttonActivated $ do mbAddModule <- ext (AddModule modString (head sourceRoots) (Just False) Set.empty) case mbAddModule of Nothing -> return () Just am -> do let mbModName = simpleParse $ T.unpack (moduleName am) :: Maybe ModuleName case mbModName of Just _ -> dialogResponse dia ResponseOk Nothing -> do boxPackStart (castToBox upper) errorLabel PackNatural 0 boxReorderChild (castToBox upper) errorLabel 0 labelSetText errorLabel ("Invalid module name, use uppercase identifiers seperated by dots. For example Some.New.Module" :: String) widgetShow errorLabel on cancel buttonActivated (dialogResponse dia ResponseCancel) boxPackStart (castToBox upper) widget PackGrow 0 boxPackEnd (castToBox lower) bb PackNatural 5 set ok [widgetCanDefault := True] widgetGrabDefault ok widgetShowAll dia resp <- dialogRun dia value <- ext (AddModule modString (head sourceRoots) (Just False) Set.empty) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing moduleFields :: [FilePath] -> Bool -> [Text] -> FieldDescription AddModule moduleFields list hasLibs exesTests = VFD emptyParams $ [ mkField (paraName <<<- ParaName (__ "New module ") $ emptyParams) moduleName (\ a b -> b{moduleName = a}) (textEditor (const True) True), mkField (paraName <<<- ParaName (__ "Root of the source path") $ paraMultiSel <<<- ParaMultiSel False $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) (T.pack . sourceRoot) (\ a b -> b{sourceRoot = T.unpack a}) (staticListEditor (map T.pack list) id)] ++ [mkField (paraName <<<- ParaName (__ "Library should") $ emptyParams) libExposed (\ a b -> b{libExposed = a}) (maybeEditor (boolEditor, paraName <<<- ParaName (__ "Expose module") $ emptyParams) True (__ "Include module")) | hasLibs] ++ map (\ name -> mkField (paraName <<<- ParaName (__ "Include in " <> name) $ emptyParams) (Set.member name . exesAndTests) (\ a b -> b{exesAndTests = (if a then Set.insert else Set.delete) name (exesAndTests b)}) boolEditor) exesTests -- * Expander State emptyExpansion = ExpanderState ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) recordExpanderState :: IDEAction recordExpanderState = do liftIO $ debugM "leksah" "recordExpanderState" m <- getModules Nothing liftIO $ do oldSel <- readIORef (oldSelection m) let (sc,bl) = (scope' oldSel, blacklist' oldSel) paths1 <- getExpandedRows (treeView m) (treeStore m) paths2 <- getExpandedRows (descrView m) (descrStore m) modifyIORef (expanderState m) (\ es -> case (sc,bl) of (PackageScope False, True) -> es{packageExp = (paths1,paths2)} (PackageScope False, False) -> es{packageExpNoBlack = (paths1,paths2)} (PackageScope True, True) -> es{packageDExp = (paths1,paths2)} (PackageScope True, False) -> es{packageDExpNoBlack = (paths1,paths2)} (WorkspaceScope False, True) -> es{workspaceExp = (paths1,paths2)} (WorkspaceScope False, False) -> es{workspaceExpNoBlack = (paths1,paths2)} (WorkspaceScope True,True) -> es{workspaceDExp = (paths1,paths2)} (WorkspaceScope True,False) -> es{workspaceDExpNoBlack = (paths1,paths2)} (SystemScope,True) -> es{systemExp = (paths1,paths2)} (SystemScope,False) -> es{systemExpNoBlack = (paths1,paths2)}) st <- readIORef (expanderState m) return () getExpandedRows :: TreeView -> TreeStore alpha -> IO [TreePath] getExpandedRows view store = do liftIO $ debugM "leksah" "getExpandedRows" mbIter <- treeModelGetIterFirst store case mbIter of Nothing -> return [] Just iter -> expandedFor iter [] where expandedFor :: TreeIter -> [TreePath] -> IO [TreePath] expandedFor iter accu = do path <- treeModelGetPath store iter expanded <- treeViewRowExpanded view path res <- if expanded then do mbIter <- treeModelIterChildren store iter case mbIter of Nothing -> return (path : accu) Just iter -> expandedFor iter (path : accu) else return accu next <- treeModelIterNext store iter case next of Nothing -> return res Just iter -> expandedFor iter res applyExpanderState :: IDEAction applyExpanderState = do liftIO $ debugM "leksah" "applyExpanderState" m <- getModules Nothing (sc,bl) <- getScope liftIO $ do es <- readIORef (expanderState m) let (paths1,paths2) = case (sc,bl) of (PackageScope False, True) -> packageExp es (PackageScope False, False) -> packageExpNoBlack es (PackageScope True,True) -> packageDExp es (PackageScope True,False) -> packageDExpNoBlack es (WorkspaceScope False, True) -> workspaceExp es (WorkspaceScope False, False) -> workspaceExpNoBlack es (WorkspaceScope True,True) -> workspaceDExp es (WorkspaceScope True,False) -> workspaceDExpNoBlack es (SystemScope,True) -> systemExp es (SystemScope,False) -> systemExpNoBlack es mapM_ (treeViewExpandToPath (treeView m)) paths1 mapM_ (treeViewExpandToPath (descrView m)) paths2 -- * GUI History recordSelHistory :: IDEAction recordSelHistory = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing ideR <- ask selTree <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) selDescr <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) (descrSortedStore mods) let selMod = case selTree of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing let selFacet = case selDescr of Nothing -> Nothing Just descr -> Just (dscName descr) oldSel <- liftIO $ readIORef (oldSelection mods) triggerEventIDE (RecordHistory (ModuleSelected selMod selFacet, ModuleSelected (moduleS' oldSel) (facetS' oldSel))) liftIO $ writeIORef (oldSelection mods) (oldSel{moduleS'= selMod, facetS' = selFacet}) return () replaySelHistory :: Maybe ModuleName -> Maybe Text -> IDEAction replaySelHistory mbModName mbFacetName = do liftIO $ debugM "leksah" "replaySelHistory" mods <- getModules Nothing selectNames (mbModName, mbFacetName) oldSel <- liftIO $ readIORef (oldSelection mods) liftIO $ writeIORef (oldSelection mods) (oldSel{moduleS'= mbModName, facetS' = mbFacetName}) recordScopeHistory :: IDEAction recordScopeHistory = do liftIO $ debugM "leksah" "recordScopeHistory" (sc,bl) <- getScope ideR <- ask mods <- getModules Nothing oldSel <- liftIO $ readIORef (oldSelection mods) triggerEventIDE (RecordHistory (ScopeSelected sc bl, ScopeSelected (scope' oldSel) (blacklist' oldSel))) liftIO $ writeIORef (oldSelection mods) (oldSel{scope'= sc, blacklist' = bl}) return () replayScopeHistory :: Scope -> Bool -> IDEAction replayScopeHistory sc bl = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing liftIO $ do toggleButtonSetActive (blacklistB mods) bl toggleButtonSetActive (packageScopeB mods) (sc == PackageScope False) toggleButtonSetActive (workspaceScopeB mods) (sc == PackageScope True) toggleButtonSetActive (systemScopeB mods) (sc == SystemScope) setScope (sc,bl) oldSel <- liftIO $ readIORef (oldSelection mods) liftIO $ writeIORef (oldSelection mods) (oldSel{scope'= sc, blacklist' = bl})
jaccokrijnen/leksah
src/IDE/Pane/Modules.hs
gpl-2.0
69,143
5
34
25,445
17,800
8,774
9,026
1,288
12
{-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE OverloadedLists #-} {-# LANGUAGE DeriveGeneric #-} ------------------------------------------------------------------------------- -- | -- Module : OpenSandbox.Protocol.Packet -- Copyright : (c) 2016 Michael Carpenter -- License : GPL3 -- Maintainer : Michael Carpenter <[email protected]> -- Stability : experimental -- Portability : portable -- ------------------------------------------------------------------------------- module OpenSandbox.Protocol.Packet ( SBHandshaking (..) , CBStatus (..) , SBStatus (..) , CBLogin (..) , SBLogin (..) , CBPlay (..) , SBPlay (..) ) where import qualified Data.Aeson as Aeson import qualified Data.ByteString as B import Data.Int import qualified Data.Text as T import Data.Serialize import Data.UUID import qualified Data.Vector as V import Data.Word import GHC.Generics import OpenSandbox.Protocol.Types import OpenSandbox.World import Prelude hiding (max) data SBHandshaking = SBHandshake VarInt T.Text Short ProtocolState | SBLegacyServerListPing deriving (Show,Eq,Generic) instance Serialize SBHandshaking where put (SBHandshake protocolVersion srvAddress srvPort nextState) = do putWord8 0x00 putVarInt protocolVersion putText srvAddress put srvPort put nextState put SBLegacyServerListPing = do putWord8 0xfe putWord8 0x01 get = do packetID <- getWord8 case packetID of 0x00 -> SBHandshake <$> getVarInt <*> getText <*> getInt16be <*> get 0xfe -> do _ <- getWord8 ln <- remaining _ <- getBytes ln return SBLegacyServerListPing err -> fail $ "Error: Unrecognized packetID: " ++ show err data CBStatus = CBResponse T.Text Word8 Word8 Word8 T.Text | CBPong Int64 deriving (Show,Eq,Generic) instance Serialize CBStatus where put (CBResponse mvVersion versionID currentPlayers maxPlayers motd) = do putWord8 0x00 encodeStatusPayload mvVersion versionID currentPlayers maxPlayers motd put (CBPong payload) = do putWord8 0x01 put payload get = do packetID <- getWord8 case packetID of 0x00 -> do rawJSON <- getNetcodeByteString let eitherJSON = Aeson.eitherDecodeStrict rawJSON case eitherJSON of Left err -> fail err Right json -> return $ CBResponse (name . version $ json) (protocol . version $ json) (online . players $ json) (max . players $ json) (text' . description $ json) 0x01 -> CBPong <$> getInt64be err -> fail $ "Error: Unrecognized packetID: " ++ show err where text' :: Description -> T.Text text' (Description t) = t data SBStatus = SBRequest | SBPing Int64 deriving (Show,Eq,Generic) instance Serialize SBStatus where put SBRequest = putWord8 0x00 put (SBPing payload) = do putWord8 0x01 put payload get = do packetID <- getWord8 case packetID of 0x00 -> return SBRequest 0x01 -> SBPing <$> getInt64be err -> fail $ "Error: Unrecognized packetID: " ++ show err data CBLogin = CBLoginDisconnect T.Text | CBEncryptionRequest T.Text B.ByteString B.ByteString | CBLoginSuccess UUID T.Text | CBSetCompression VarInt deriving (Show,Eq,Generic) instance Serialize CBLogin where put (CBLoginDisconnect reason) = do putWord8 0x00 putText reason put (CBEncryptionRequest srvID publicKey verifyToken) = do putWord8 0x01 putText srvID putNetcodeByteString publicKey putNetcodeByteString verifyToken put (CBLoginSuccess uuid username) = do putWord8 0x02 putUUID uuid putText username put (CBSetCompression threshold) = do putWord8 0x03 putVarInt threshold get = do packetID <- getWord8 case packetID of 0x00 -> CBLoginDisconnect <$> getText 0x01 -> CBEncryptionRequest <$> getText <*> getNetcodeByteString <*> getNetcodeByteString 0x02 -> CBLoginSuccess <$> getUUID <*> getText 0x03 -> CBSetCompression <$> getVarInt err -> fail $ "Error: Unrecognized packetID: " ++ show err data SBLogin = SBLoginStart T.Text | SBEncryptionResponse B.ByteString B.ByteString deriving (Show,Eq,Generic) instance Serialize SBLogin where put (SBLoginStart name) = do putWord8 0x00 putText name put (SBEncryptionResponse sharedSecret verifyToken) = do putWord8 0x01 putNetcodeByteString sharedSecret putNetcodeByteString verifyToken get = do packetID <- getWord8 case packetID of 0x00 -> SBLoginStart <$> getText 0x01 -> SBEncryptionResponse <$> getNetcodeByteString <*> getNetcodeByteString err -> fail $ "Error: Unrecognized packetID: " ++ show err data CBPlay = CBSpawnObject VarInt UUID Int8 Double Double Double Angle Angle Int32 Short Short Short | CBSpawnExperienceOrb VarInt Double Double Double Int16 | CBSpawnGlobalEntity VarInt Int8 Double Double Double | CBSpawnMob VarInt UUID Word8 Double Double Double Angle Angle Angle Short Short Short EntityMetadata | CBSpawnPainting VarInt UUID T.Text Position Int8 | CBSpawnPlayer VarInt UUID Double Double Double Angle Angle EntityMetadata | CBAnimation VarInt Animation | CBStatistics (V.Vector Statistic) | CBBlockBreakAnimation VarInt Position Int8 | CBUpdateBlockEntity Position UpdateBlockEntityAction NBT | CBBlockAction Position BlockAction | CBBlockChange Position VarInt | CBBossBar UUID BossBarAction | CBServerDifficulty Difficulty | CBTabComplete (V.Vector T.Text) | CBChatMessage Chat Int8 | CBMultiBlockChange Int32 Int32 (V.Vector BlockChange) | CBConfirmTransaction Int8 Short Bool | CBCloseWindow Word8 | CBOpenWindow Word8 (Either Int32 T.Text) Chat Word8 | CBWindowItems Word8 (V.Vector Slot) | CBWindowProperty Word8 Int16 Int16 | CBSetSlot Int8 Short Slot | CBSetCooldown VarInt VarInt | CBPluginMessage T.Text B.ByteString | CBNamedSoundEffect T.Text VarInt Int32 Int32 Int32 Float Float | CBPlayDisconnect Chat | CBEntityStatus Int32 EntityStatus | CBExplosion Float Float Float Float (V.Vector (Int8,Int8,Int8)) Float Float Float | CBUnloadChunk Int32 Int32 | CBChangeGameState GameChangeReason Float | CBKeepAlive VarInt | CBChunkData ChunkColumn | CBEffect Int32 Position Int32 Bool | CBParticle Int32 Bool Float Float Float Float Float Float Float (V.Vector VarInt) | CBJoinGame Int32 GameMode Dimension Difficulty Word8 T.Text Bool | CBMap VarInt Int8 Bool (V.Vector Icon) UpdatedColumns | CBEntityRelativeMove VarInt Short Short Short Bool | CBEntityLookAndRelativeMove VarInt Short Short Short Angle Angle Bool | CBEntityLook VarInt Angle Angle Bool | CBEntity VarInt | CBVehicleMove Double Double Double Float Float | CBOpenSignEditor Position | CBPlayerAbilities Int8 Float Float | CBCombatEvent CombatEvent | CBPlayerListItem PlayerListEntries | CBPlayerPositionAndLook Double Double Double Float Float Int8 VarInt | CBUseBed VarInt Position | CBDestroyEntities (V.Vector VarInt) | CBRemoveEntityEffect VarInt Int8 | CBResourcePackSend T.Text T.Text | CBRespawn Dimension Difficulty GameMode T.Text | CBEntityHeadLook VarInt Angle | CBWorldBorder WorldBorderAction | CBCamera VarInt | CBHeldItemChange Int8 | CBDisplayScoreboard Int8 T.Text | CBEntityMetadata VarInt EntityMetadata | CBAttachEntity Int32 Int32 | CBEntityVelocity VarInt Short Short Short | CBEntityEquipment VarInt VarInt Slot | CBSetExperience Float VarInt VarInt | CBUpdateHealth Float VarInt Float | CBScoreboardObjective T.Text ScoreboardMode | CBSetPassengers VarInt (V.Vector VarInt) | CBTeams T.Text TeamMode | CBUpdateScore UpdateScoreAction | CBSpawnPosition Position | CBTimeUpdate Int64 Int64 | CBTitle TitleAction | CBSoundEffect VarInt VarInt Int32 Int32 Int32 Float Float | CBPlayerListHeaderAndFooter Chat Chat | CBCollectItem VarInt VarInt | CBEntityTeleport VarInt Double Double Double Angle Angle Bool | CBEntityProperties VarInt (V.Vector EntityProperty) | CBEntityEffect VarInt Int8 Int8 VarInt Word8 deriving (Show,Eq,Generic) instance Serialize CBPlay where put (CBSpawnObject entityID objectUUID entityType x y z pitch yaw dat vX vY vZ) = do putWord8 0x00 putVarInt entityID putUUID objectUUID put entityType putFloat64be x putFloat64be y putFloat64be z putAngle pitch putAngle yaw put dat put vX put vY put vZ put (CBSpawnExperienceOrb entityID x y z count) = do putWord8 0x01 putVarInt entityID putFloat64be x putFloat64be y putFloat64be z put count put (CBSpawnGlobalEntity entityID entityType x y z) = do putWord8 0x02 putVarInt entityID put entityType putFloat64be x putFloat64be y putFloat64be z put (CBSpawnMob entityID entityUUID entityType x y z yaw pitch headPitch vX vY vZ metadata) = do putWord8 0x03 putVarInt entityID putUUID entityUUID putWord8 entityType putFloat64be x putFloat64be y putFloat64be z putAngle yaw putAngle pitch putAngle headPitch put vX put vY put vZ putEntityMetadata metadata put (CBSpawnPainting entityID entityUUID title location direction) = do putWord8 0x04 putVarInt entityID putUUID entityUUID putText title putPosition location put direction put (CBSpawnPlayer entityID playerUUID x y z yaw pitch metadata) = do putWord8 0x05 putVarInt entityID putUUID playerUUID putFloat64be x putFloat64be y putFloat64be z putAngle yaw putAngle pitch putEntityMetadata metadata put (CBAnimation entityID animation) = do putWord8 0x06 putVarInt entityID putWord8 . toEnum . fromEnum $ animation put (CBStatistics statistics) = do putWord8 0x07 putVarInt . V.length $ statistics mapM_ put statistics put (CBBlockBreakAnimation entityID location destroyStage) = do putWord8 0x08 putVarInt entityID putPosition location put destroyStage put (CBUpdateBlockEntity location action nbtData) = do putWord8 0x09 putPosition location putWord8 . toEnum . fromEnum $ action put nbtData put (CBBlockAction location blockAction) = do putWord8 0x0A putPosition location put blockAction put (CBBlockChange location blockID) = do putWord8 0x0B putPosition location putVarInt blockID put (CBBossBar uuid bossBarAction) = do putWord8 0x0C putUUID uuid put bossBarAction put (CBServerDifficulty difficulty) = do putWord8 0x0D putWord8 . toEnum . fromEnum $ difficulty put (CBTabComplete matches) = do putWord8 0x0E putVarInt . V.length $ matches mapM_ putText matches put (CBChatMessage jsonData position) = do putWord8 0x0F put jsonData put position put (CBMultiBlockChange chunkX chunkZ records) = do putWord8 0x10 put chunkX put chunkZ putVarInt . V.length $ records mapM_ put records put (CBConfirmTransaction windowID actionNumber accepted) = do putWord8 0x11 put windowID put actionNumber putWord8 . toEnum . fromEnum $ accepted put (CBCloseWindow windowID) = do putWord8 0x12 putWord8 windowID put (CBOpenWindow windowID windowType windowTitle numOfSlots) = do putWord8 0x13 putWord8 windowID case windowType of Left entityID -> do putText "EntityHorse" put windowTitle putWord8 numOfSlots put entityID Right windowType' -> do putText windowType' put windowTitle putWord8 numOfSlots put (CBWindowItems windowID slotData) = do putWord8 0x14 putWord8 windowID put (toEnum . V.length $ slotData :: Int16) mapM_ put slotData put (CBWindowProperty windowID property value) = do putWord8 0x15 putWord8 windowID put property -- Should move to WindowProperty put value put (CBSetSlot windowID slot slotData) = do putWord8 0x16 put windowID put slot put slotData put (CBSetCooldown itemID cooldownTicks) = do putWord8 0x17 putVarInt itemID putVarInt cooldownTicks put (CBPluginMessage channel dat) = do putWord8 0x18 putText channel putByteString dat put (CBNamedSoundEffect soundName soundCategory effPosX effPosY effPosZ volume pitch) = do putWord8 0x19 putText soundName putVarInt soundCategory put effPosX put effPosY put effPosZ putFloat32be volume putFloat32be pitch put (CBPlayDisconnect reason) = do putWord8 0x1A put reason put (CBEntityStatus entityID entityStatus) = do putWord8 0x1B put entityID put (toEnum . fromEnum $ entityStatus :: Int8) put (CBExplosion x y z radius records pMotionX pMotionY pMotionZ) = do putWord8 0x1C putFloat32be x putFloat32be y putFloat32be z putFloat32be radius put (toEnum . V.length $ records :: Int32) mapM_ (\(a,b,c) -> do { put a; put b; put c}) records putFloat32be pMotionX putFloat32be pMotionY putFloat32be pMotionZ put (CBUnloadChunk chunkX chunkZ) = do putWord8 0x1D put chunkX put chunkZ put (CBChangeGameState reason value) = do putWord8 0x1E put reason putFloat32be value put (CBKeepAlive keepAliveID) = do putWord8 0x1F putVarInt keepAliveID put (CBChunkData chunkColumnData) = do putWord8 0x20 put chunkColumnData -- (NOTE) Should be better typed to Effect IDs that actually exist put (CBEffect effectID location dat disableRelativeVolume) = do putWord8 0x21 put effectID putPosition location put dat put disableRelativeVolume put (CBParticle particleID longDistance x y z offsetX offsetY offsetZ particleData dat) = do putWord8 0x22 put particleID put longDistance putFloat32be x putFloat32be y putFloat32be z putFloat32be offsetX putFloat32be offsetY putFloat32be offsetZ putFloat32be particleData put (toEnum . V.length $ dat :: Int32) mapM_ putVarInt dat put (CBJoinGame entityID gameMode dimension difficulty maxPlayers levelType reduceDebug) = do putWord8 0x23 put entityID put gameMode put dimension put difficulty putWord8 maxPlayers putText levelType put reduceDebug put (CBMap itemDamage scale trackingPosition icons updatedColumns) = do putWord8 0x24 putVarInt itemDamage put scale put trackingPosition putVarInt . V.length $ icons mapM_ put icons put updatedColumns put (CBEntityRelativeMove entityID dX dY dZ onGround) = do putWord8 0x25 putVarInt entityID put dX put dY put dZ put onGround put (CBEntityLookAndRelativeMove entityID dX dY dZ yaw pitch onGround) = do putWord8 0x26 putVarInt entityID put dX put dY put dZ putAngle yaw putAngle pitch put onGround put (CBEntityLook entityID yaw pitch onGround) = do putWord8 0x27 putVarInt entityID putAngle yaw putAngle pitch put onGround put (CBEntity entityID) = do putWord8 0x28 putVarInt entityID put (CBVehicleMove x y z yaw pitch) = do putWord8 0x29 putFloat64be x putFloat64be y putFloat64be z putFloat32be yaw putFloat32be pitch put (CBOpenSignEditor location) = do putWord8 0x2A putPosition location put (CBPlayerAbilities flags flyingSpeed viewModifiers) = do putWord8 0x2B put flags putFloat32be flyingSpeed putFloat32be viewModifiers put (CBCombatEvent combatEvent) = do putWord8 0x2C put combatEvent put (CBPlayerListItem entries) = do putWord8 0x2D put entries -- flags should be better typed put (CBPlayerPositionAndLook x y z yaw pitch flags teleportID) = do putWord8 0x2E putFloat64be x putFloat64be y putFloat64be z putFloat32be yaw putFloat32be pitch put flags putVarInt teleportID put (CBUseBed entityID location) = do putWord8 0x2F putVarInt entityID putPosition location put (CBDestroyEntities entityIDs) = do putWord8 0x30 putVarInt . V.length $ entityIDs mapM_ putVarInt entityIDs put (CBRemoveEntityEffect entityID effectID) = do putWord8 0x31 putVarInt entityID put effectID put (CBResourcePackSend url hash) = do putWord8 0x32 putText url putText hash put (CBRespawn dimension difficulty gameMode levelType) = do putWord8 0x33 put dimension put difficulty put gameMode putText levelType put (CBEntityHeadLook entityID headYaw) = do putWord8 0x34 putVarInt entityID putAngle headYaw put (CBWorldBorder worldBorderAction) = do putWord8 0x35 put worldBorderAction put (CBCamera cameraID) = do putWord8 0x36 putVarInt cameraID put (CBHeldItemChange slot) = do putWord8 0x37 put slot put (CBDisplayScoreboard position scoreName) = do putWord8 0x38 put position putText scoreName put (CBEntityMetadata entityID metadata) = do putWord8 0x39 putVarInt entityID putEntityMetadata metadata put (CBAttachEntity attachedEntityID holdingEntityID) = do putWord8 0x3A put attachedEntityID put holdingEntityID put (CBEntityVelocity entityID vX vY vZ) = do putWord8 0x3B putVarInt entityID put vX put vY put vZ put (CBEntityEquipment entityID slot item) = do putWord8 0x3C putVarInt entityID putVarInt slot put item put (CBSetExperience experienceBar level totalExperience) = do putWord8 0x3D putFloat32be experienceBar putVarInt level putVarInt totalExperience put (CBUpdateHealth health food foodSaturation) = do putWord8 0x3E putFloat32be health putVarInt food putFloat32be foodSaturation put (CBScoreboardObjective objectiveName mode) = do putWord8 0x3F putText objectiveName put mode put (CBSetPassengers entityID passengers) = do putWord8 0x40 putVarInt entityID putVarInt . V.length $ passengers mapM_ putVarInt passengers put (CBTeams teamName mode) = do putWord8 0x41 putText teamName put mode put (CBUpdateScore action) = do putWord8 0x42 put action put (CBSpawnPosition location) = do putWord8 0x43 putPosition location put (CBTimeUpdate worldAge timeOfDay) = do putWord8 0x44 put worldAge put timeOfDay put (CBTitle titleAction) = do putWord8 0x45 put titleAction put (CBSoundEffect soundID soundCategory effPosX effPosY effPosZ volume pitch) = do putWord8 0x46 putVarInt soundID putVarInt soundCategory put effPosX put effPosY put effPosZ put volume put pitch put (CBPlayerListHeaderAndFooter header footer) = do putWord8 0x47 put header put footer put (CBCollectItem collectedEntityID collectorEntityID) = do putWord8 0x48 putVarInt collectedEntityID putVarInt collectorEntityID put (CBEntityTeleport entityID x y z yaw pitch onGround) = do putWord8 0x49 putVarInt entityID putFloat64be x putFloat64be y putFloat64be z putAngle yaw putAngle pitch put onGround -- Needs to be better typed put (CBEntityProperties entityID properties) = do putWord8 0x4A putVarInt entityID put (toEnum . V.length $ properties :: Int32) mapM_ put properties put (CBEntityEffect entityID effectID amplifier duration hideParticles) = do putWord8 0x4B putVarInt entityID put effectID put amplifier putVarInt duration put hideParticles get = do packetID <- getWord8 case packetID of 0x00 -> do entityID <- getVarInt objectUUID <- getUUID t <- getInt8 x <- getFloat64be y <- getFloat64be z <- getFloat64be pitch <- getAngle yaw <- getAngle dat <- getInt32be vX <- getInt16be vY <- getInt16be vZ <- getInt16be return $ CBSpawnObject entityID objectUUID t x y z pitch yaw dat vX vY vZ 0x01 -> CBSpawnExperienceOrb <$> getVarInt <*> getFloat64be <*> getFloat64be <*> getFloat64be <*> getInt16be 0x02 -> CBSpawnGlobalEntity <$> getVarInt <*> getInt8 <*> getFloat64be <*> getFloat64be <*> getFloat64be 0x03 -> do entityID <- getVarInt entityUUID <- getUUID t <- getWord8 x <- getFloat64be y <- getFloat64be z <- getFloat64be yaw <- getAngle pitch <- getAngle headPitch <- getAngle vX <- getInt16be vY <- getInt16be vZ <- getInt16be metadata <- getEntityMetadata return $ CBSpawnMob entityID entityUUID t x y z yaw pitch headPitch vX vY vZ metadata 0x04 -> do entityID <- getVarInt entityUUID <- getUUID title <- getText location <- getPosition direction <- getInt8 return $ CBSpawnPainting entityID entityUUID title location direction 0x05 -> do entityID <- getVarInt playerUUID <- getUUID x <- getFloat64be y <- getFloat64be z <- getFloat64be yaw <- getAngle pitch <- getAngle metadata <- getEntityMetadata return $ CBSpawnPlayer entityID playerUUID x y z yaw pitch metadata 0x06 -> CBAnimation <$> getVarInt <*> get 0x07 -> CBStatistics <$> (getVarInt >>= \n -> V.replicateM (fromEnum n) get) 0x08 -> CBBlockBreakAnimation <$> getVarInt <*> getPosition <*> getInt8 0x09 -> CBUpdateBlockEntity <$> getPosition <*> get <*> get 0x0A -> CBBlockAction <$> getPosition <*> get 0x0B -> CBBlockChange <$> getPosition <*> getVarInt 0x0C -> CBBossBar <$> getUUID <*> get 0x0D -> CBServerDifficulty <$> get 0x0E -> CBTabComplete <$> (getVarInt >>= \n -> V.replicateM n getText) 0x0F -> CBChatMessage <$> get <*> getInt8 0x10 -> CBMultiBlockChange <$> getInt32be <*> getInt32be <*> (getVarInt >>= \n -> V.replicateM n get) 0x11 -> CBConfirmTransaction <$> getInt8 <*> getInt16be <*> get 0x12 -> CBCloseWindow <$> getWord8 0x13 -> do windowID <- getWord8 windowType <- getText windowTitle <- get numberOfSlots <- getWord8 case windowType of "EntityHorse" -> do entityID <- getInt32be return $ CBOpenWindow windowID (Left entityID) windowTitle numberOfSlots _ -> return $ CBOpenWindow windowID (Right windowType) windowTitle numberOfSlots 0x14 -> do windowID <- getWord8 count <- fmap fromEnum getInt16be slotData <- V.replicateM count get return $ CBWindowItems windowID slotData 0x15 -> CBWindowProperty <$> getWord8 <*> getInt16be <*> getInt16be 0x16 -> CBSetSlot <$> getInt8 <*> getInt16be <*> get 0x17 -> CBSetCooldown <$> getVarInt <*> getVarInt 0x18 -> CBPluginMessage <$> getText <*> (remaining >>= \n -> getByteString n) 0x19 -> do soundName <- getText soundCategory <- getVarInt effectPosX <- getInt32be effectPosY <- getInt32be effectPosZ <- getInt32be volume <- getFloat32be pitch <- getFloat32be return $ CBNamedSoundEffect soundName soundCategory effectPosX effectPosY effectPosZ volume pitch 0x1A -> CBPlayDisconnect <$> get 0x1B -> CBEntityStatus <$> getInt32be <*> get 0x1C -> do x <- getFloat32be y <- getFloat32be z <- getFloat32be radius <- getFloat32be count <- fmap fromEnum getInt32be records <- V.replicateM count (do a <- getInt8 b <- getInt8 c <- getInt8 return (a,b,c)) pMotionX <- getFloat32be pMotionY <- getFloat32be pMotionZ <- getFloat32be return $ CBExplosion x y z radius records pMotionX pMotionY pMotionZ 0x1D -> CBUnloadChunk <$> getInt32be <*> getInt32be 0x1E -> CBChangeGameState <$> get <*> getFloat32be 0x1F -> CBKeepAlive <$> getVarInt 0x20 -> CBChunkData <$> get 0x21 -> CBEffect <$> getInt32be <*> getPosition <*> getInt32be <*> get 0x22 -> do particleID <- getInt32be longDistance <- get x <- getFloat32be y <- getFloat32be z <- getFloat32be offsetX <- getFloat32be offsetY <- getFloat32be offsetZ <- getFloat32be particleData <- getFloat32be particleCount <- getInt32be dat <- V.replicateM (fromEnum particleCount) getVarInt return $ CBParticle particleID longDistance x y z offsetX offsetY offsetZ particleData dat 0x23 -> do entityID <- getInt32be gameMode <- get dimension <- get difficulty <- get maxPlayers <- getWord8 levelType <- getText reducedDebugInfo <- get return $ CBJoinGame entityID gameMode dimension difficulty maxPlayers levelType reducedDebugInfo 0x24 -> do itemDamage <- getVarInt scale <- getInt8 trackingPositon <- get count <- getVarInt icons <- V.replicateM count get updateColumns <- get return $ CBMap itemDamage scale trackingPositon icons updateColumns 0x25 -> CBEntityRelativeMove <$> getVarInt <*> getInt16be <*> getInt16be <*> getInt16be <*> get 0x26 -> do entityID <- getVarInt dX <- getInt16be dY <- getInt16be dZ <- getInt16be yaw <- getAngle pitch <- getAngle onGround <- get return $ CBEntityLookAndRelativeMove entityID dX dY dZ yaw pitch onGround 0x27 -> CBEntityLook <$> getVarInt <*> getAngle <*> getAngle <*> get 0x28 -> CBEntity <$> getVarInt 0x29 -> CBVehicleMove <$> getFloat64be <*> getFloat64be <*> getFloat64be <*> getFloat32be <*> getFloat32be 0x2A -> CBOpenSignEditor <$> getPosition 0x2B -> CBPlayerAbilities <$> getInt8 <*> getFloat32be <*> getFloat32be 0x2C -> CBCombatEvent <$> get 0x2D -> CBPlayerListItem <$> get 0x2E -> do x <- getFloat64be y <- getFloat64be z <- getFloat64be yaw <- getFloat32be pitch <- getFloat32be flags <- getInt8 teleportID <- getVarInt return $ CBPlayerPositionAndLook x y z yaw pitch flags teleportID 0x2F -> CBUseBed <$> getVarInt <*> getPosition 0x30 -> CBDestroyEntities <$> (getVarInt >>= \n -> V.replicateM n getVarInt) 0x31 -> CBRemoveEntityEffect <$> getVarInt <*> getInt8 0x32 -> CBResourcePackSend <$> getText <*> getText 0x33 -> CBRespawn <$> get <*> get <*> get <*> getText 0x34 -> CBEntityHeadLook <$> getVarInt <*> getAngle 0x35 -> CBWorldBorder <$> get 0x36 -> CBCamera <$> getVarInt 0x37 -> CBHeldItemChange <$> getInt8 0x38 -> CBDisplayScoreboard <$> getInt8 <*> getText 0x39 -> CBEntityMetadata <$> getVarInt <*> getEntityMetadata 0x3A -> CBAttachEntity <$> getInt32be <*> getInt32be 0x3B -> CBEntityVelocity <$> getVarInt <*> getInt16be <*> getInt16be <*> getInt16be 0x3C -> CBEntityEquipment <$> getVarInt <*> getVarInt <*> get 0x3D -> CBSetExperience <$> getFloat32be <*> getVarInt <*> getVarInt 0x3E -> CBUpdateHealth <$> getFloat32be <*> getVarInt <*> getFloat32be 0x3F -> CBScoreboardObjective <$> getText <*> get 0x40 -> CBSetPassengers <$> getVarInt <*> (getVarInt >>= \n -> V.replicateM n getVarInt) 0x41 -> CBTeams <$> getText <*> get 0x42 -> CBUpdateScore <$> get 0x43 -> CBSpawnPosition <$> getPosition 0x44 -> CBTimeUpdate <$> getInt64be <*> getInt64be 0x45 -> CBTitle <$> get 0x46 -> CBSoundEffect <$> getVarInt <*> getVarInt <*> getInt32be <*> getInt32be <*> getInt32be <*> getFloat32be <*> getFloat32be 0x47 -> CBPlayerListHeaderAndFooter <$> get <*> get 0x48 -> CBCollectItem <$> getVarInt <*> getVarInt 0x49 -> CBEntityTeleport <$> getVarInt <*> getFloat64be <*> getFloat64be <*> getFloat64be <*> getAngle <*> getAngle <*> get 0x4A -> CBEntityProperties <$> getVarInt <*> (getInt32be >>= \n -> V.replicateM (fromEnum n) get) 0x4B -> CBEntityEffect <$> getVarInt <*> getInt8 <*> getInt8 <*> getVarInt <*> get err -> fail $ "Unrecognized packetID: " ++ show err data SBPlay = SBTeleportConfirm VarInt | SBTabComplete T.Text Bool (Maybe Position) | SBChatMessage T.Text | SBClientStatus VarInt | SBClientSettings T.Text Int8 VarInt Bool Word8 VarInt | SBConfirmTransaction Int8 Short Bool | SBEnchantItem Int8 Int8 | SBClickWindow Word8 Short Int8 Short VarInt Slot | SBCloseWindow Word8 | SBPluginMessage T.Text B.ByteString | SBUseEntity VarInt UseEntityType | SBKeepAlive VarInt | SBPlayerPosition Double Double Double Bool | SBPlayerPositionAndLook Double Double Double Float Float Bool | SBPlayerLook Float Float Bool | SBPlayer Bool | SBVehicleMove Double Double Double Float Float | SBSteerBoat Bool Bool | SBPlayerAbilities Int8 Float Float | SBPlayerDigging VarInt Position Int8 | SBEntityAction VarInt VarInt VarInt | SBSteerVehicle Float Float Word8 | SBResourcePackStatus VarInt | SBHeldItemChange Short | SBCreativeInventoryAction Short Slot | SBUpdateSign Position T.Text T.Text T.Text T.Text | SBAnimation VarInt | SBSpectate UUID | SBPlayerBlockPlacement Position VarInt VarInt Word8 Word8 Word8 | SBUseItem VarInt deriving (Show,Eq,Generic) instance Serialize SBPlay where put (SBTeleportConfirm teleportID) = do putWord8 0x00 putVarInt teleportID put (SBTabComplete text assumeCommand lookedAtBlock) = do putWord8 0x01 putText text put assumeCommand case lookedAtBlock of Just lookedAtBlock' -> do put True putPosition lookedAtBlock' Nothing -> do put False put (SBChatMessage message) = do putWord8 0x02 putText message put (SBClientStatus actionID) = do putWord8 0x03 putVarInt actionID put (SBClientSettings locale viewDistance chatMode chatColors displayedSkinParts mainHand) = do putWord8 0x04 putText locale put viewDistance putVarInt chatMode (putWord8 . toEnum . fromEnum $ chatColors) putWord8 displayedSkinParts putVarInt mainHand put (SBConfirmTransaction windowID actionNumber accepted) = do putWord8 0x05 put windowID put actionNumber put accepted put (SBEnchantItem windowID enchantment) = do putWord8 0x06 put windowID put enchantment put (SBClickWindow windowID slot button actionNumber mode clickedItem) = do putWord8 0x07 putWord8 windowID put slot put button put actionNumber putVarInt mode put clickedItem put (SBCloseWindow windowID) = do putWord8 0x08 putWord8 windowID put (SBPluginMessage channel dat) = do putWord8 0x09 putText channel putNetcodeByteString dat put (SBUseEntity target t) = do putWord8 0x0A putVarInt target put t put (SBKeepAlive keepAliveID) = do putWord8 0x0B putVarInt keepAliveID put (SBPlayerPosition x feetY z onGround) = do putWord8 0x0C putFloat64be x putFloat64be feetY putFloat64be z put onGround put (SBPlayerPositionAndLook x feetY z yaw pitch onGround) = do putWord8 0x0D putFloat64be x putFloat64be feetY putFloat64be z putFloat32be yaw putFloat32be pitch put onGround put (SBPlayerLook yaw pitch onGround) = do putWord8 0x0E putFloat32be yaw putFloat32be pitch put onGround put (SBPlayer onGround) = do putWord8 0x0F put onGround put (SBVehicleMove x y z yaw pitch) = do putWord8 0x10 putFloat64be x putFloat64be y putFloat64be z putFloat32be yaw putFloat32be pitch put (SBSteerBoat rightPaddle leftPaddle) = do putWord8 0x11 put rightPaddle put leftPaddle put (SBPlayerAbilities flags flyingSpeed walkingSpeed) = do putWord8 0x12 put flags putFloat32be flyingSpeed putFloat32be walkingSpeed put (SBPlayerDigging status location face) = do putWord8 0x13 putVarInt status putPosition location put face put (SBEntityAction entityID actionID jumpBoost) = do putWord8 0x14 putVarInt entityID putVarInt actionID putVarInt jumpBoost put (SBSteerVehicle sideways forward flags) = do putWord8 0x15 putFloat32be sideways putFloat32be forward putWord8 flags put (SBResourcePackStatus result) = do putWord8 0x16 putVarInt result put (SBHeldItemChange slot) = do putWord8 0x17 put slot put (SBCreativeInventoryAction slot clickedItem) = do putWord8 0x18 put slot put clickedItem put (SBUpdateSign location line1 line2 line3 line4) = do putWord8 0x19 putPosition location putText line1 putText line2 putText line3 putText line4 put (SBAnimation hand) = do putWord8 0x1A putVarInt hand put (SBSpectate targetPlayer) = do putWord8 0x1B putUUID targetPlayer put (SBPlayerBlockPlacement location face hand cursorPosX cursorPosY cursorPosZ) = do putWord8 0x1C putPosition location putVarInt face putVarInt hand putWord8 cursorPosX putWord8 cursorPosY putWord8 cursorPosZ put (SBUseItem hand) = do putWord8 0x1D putVarInt hand get = do packetID <- getWord8 case packetID of 0x00 -> SBTeleportConfirm <$> getVarInt 0x01 -> do text <- getText assumeCommand <- get hasPosition <- get if hasPosition then do lookedAtBlock <- getPosition return $ SBTabComplete text assumeCommand (Just lookedAtBlock) else return $ SBTabComplete text assumeCommand Nothing 0x02 -> SBChatMessage <$> getText 0x03 -> SBClientStatus <$> getVarInt 0x04 -> SBClientSettings <$> getText <*> getInt8 <*> getVarInt <*> get <*> getWord8 <*> getVarInt 0x05 -> SBConfirmTransaction <$> getInt8 <*> getInt16be <*> get 0x06 -> SBEnchantItem <$> getInt8 <*> getInt8 0x07 -> SBClickWindow <$> getWord8 <*> getInt16be <*> getInt8 <*> getInt16be <*> getVarInt <*> get 0x08 -> SBCloseWindow <$> getWord8 0x09 -> SBPluginMessage <$> getText <*> (getVarInt >>= \n -> getByteString n) 0x0A -> SBUseEntity <$> getVarInt <*> get 0x0B -> SBKeepAlive <$> getVarInt 0x0C -> SBPlayerPosition <$> getFloat64be <*> getFloat64be <*> getFloat64be <*> get 0x0D -> SBPlayerPositionAndLook <$> getFloat64be <*> getFloat64be <*> getFloat64be <*> getFloat32be <*> getFloat32be <*> get 0x0E -> SBPlayerLook <$> getFloat32be <*> getFloat32be <*> get 0x0F -> SBPlayer <$> get 0x10 -> SBVehicleMove <$> getFloat64be <*> getFloat64be <*> getFloat64be <*> getFloat32be <*> getFloat32be 0x11 -> SBSteerBoat <$> get <*> get 0x12 -> SBPlayerAbilities <$> getInt8 <*> getFloat32be <*> getFloat32be 0x13 -> SBPlayerDigging <$> getVarInt <*> getPosition <*> getInt8 0x14 -> SBEntityAction <$> getVarInt <*> getVarInt <*> getVarInt 0x15 -> SBSteerVehicle <$> getFloat32be <*> getFloat32be <*> getWord8 0x16 -> SBResourcePackStatus <$> getVarInt 0x17 -> SBHeldItemChange <$> getInt16be 0x18 -> SBCreativeInventoryAction <$> getInt16be <*> get 0x19 -> SBUpdateSign <$> getPosition <*> getText <*> getText <*> getText <*> getText 0x1A -> SBAnimation <$> getVarInt 0x1B -> SBSpectate <$> getUUID 0x1C -> SBPlayerBlockPlacement <$> getPosition <*> getVarInt <*> getVarInt <*> getWord8 <*> getWord8 <*> getWord8 0x1D -> SBUseItem <$> getVarInt err -> fail $ "Unrecognized packetID: " ++ show err
oldmanmike/opensandbox
src/OpenSandbox/Protocol/Packet.hs
gpl-3.0
35,952
0
21
9,093
10,270
4,688
5,582
1,062
0
{-# LANGUAGE GADTs,Trustworthy #-} module Datatypes where import qualified Data.Matrix as M import qualified Numeric.LinearAlgebra.Data as LAD import Data.Hashable type ModulusTensor = Int -> Int -> Int -> Int -> Double type Strain = M.Matrix Double type Stress = Int -> Int -> Double class Property a where value :: a -> Double name :: a -> String data Properties where Properties :: Property a => a -> Properties newtype Youngs = Youngs Double newtype Poisson = Poisson Double newtype Shear = Shear Double newtype Bulk = Bulk Double instance Property Youngs where value (Youngs i) = i name (Youngs _) = "youngs" instance Property Poisson where value (Poisson i) = i name (Poisson _) = "poisson" instance Property Shear where value (Shear i) = i name (Shear _) = "shear" instance Property Bulk where value (Bulk i) = i name (Bulk _) = "bulk" class MaterialModel a where stress :: [Properties] -> a -> Strain -> Stress modulus :: [Properties] -> a -> Strain -> ModulusTensor data NeoHookean = NeoHookean type NID = Int type ElNum = Int type ElNodeNum = Int data Node = Node { nid :: NID, coords :: [Double] } deriving (Show,Eq) type Nodes = [Node] instance Hashable Node where hashWithSalt i x = i + nid x + hashWithSalt i (coords x) type Displacements = [Double] type ShapeFunction = [Double] -> Double type ShapeFunctions = [ShapeFunction] type ShapeFunctionDerivs = [[ShapeFunction]] type Stiffness = Int -> Int -> Int -> Int -> Double type Force = Int -> Int -> Double type Weights = [Double] type IPs = [[Double]] data Element where Element :: MaterialModel a => { mm :: a , elstiff :: Stiffness , elforce :: Force , elnode :: Nodes , elstrain :: [Double] -> [[Double]] } -> Element instance Show Element where show (Element _ _ _ nodes _) = "Element {elnode = " ++ show nodes ++ "}" type GlobalStiffness = LAD.Matrix Double type GlobalForce = LAD.Matrix Double data DOFBC = DOFBC Int Int Double deriving Show type Converged = Bool type Diverged = Bool type Iteration = Int type PNode = (Int, [Double]) type PElement = (Int, [Int]) type PNodes = [PNode] type PElements = [PElement] type IElement = (Int, Nodes) type IElements = [IElement] type NodeData = [(Int,[Double])] type ElementData = [(Int,[[Double]])]
chiraag-nataraj/HFEM
Datatypes.hs
gpl-3.0
2,304
0
10
473
822
477
345
-1
-1
-- Copyright (C) 2017 Jonathan W. Armond module Loco.Error where import Control.Monad.Except type LocoEval = Either LocoError data LocoError = ArgError Int Int | TypeError String | ParserError String | UndeclaredVarError String | InvalidLineError Integer | UnknownCommand String | UnknownError String instance Show LocoError where show = showError showError :: LocoError -> String showError (ArgError n m) = "expected " ++ show n ++ " args but found " ++ show m showError (TypeError msg) = "invalid types: " ++ msg showError (ParserError msg) = "parse error: " ++ msg showError (UndeclaredVarError msg) = "undeclared variable: " ++ msg showError (InvalidLineError n) = "invalid line number: " ++ show n showError (UnknownCommand n) = "unknown command: " ++ show n showError (UnknownError msg) = msg type IOLocoEval = ExceptT LocoError IO trapError :: IOLocoEval () -> IOLocoEval () trapError action = catchError action $ (liftIO . putStrLn . show) runIOEval :: IOLocoEval () -> IO () runIOEval action = runExceptT (trapError action) >>= printError printError :: LocoEval a -> IO () printError (Left err) = print err printError (Right _) = return () extractValue :: LocoEval a -> a extractValue (Right val) = val liftIOEval :: LocoEval a -> IOLocoEval a liftIOEval (Left err) = throwError err liftIOEval (Right val) = return val liftIOEval1 :: (a -> LocoEval r) -> a -> IOLocoEval r liftIOEval1 f = liftIOEval . f liftIOEval2 :: (a1 -> a2 -> LocoEval r) -> a1 -> a2 -> IOLocoEval r liftIOEval2 f a b = liftIOEval $ f a b
jarmond/locomotive-haskell
src/Loco/Error.hs
gpl-3.0
1,622
0
9
357
546
274
272
36
1
module ATP.Prop ( eval , atoms , apply , distrib , simplify , simplify1 , onallvaluations , dual , truthtable , unsatisfiable , satisfiable , trivial , tautology , occurrences , subsume , nnf , nenf , simpcnf , cnf , purecnf , purednf , simpdnf , dnf -- * Testing , forms , tests ) where import ATP.Util.Prelude import qualified ATP.Formula as F import ATP.FormulaSyn import qualified ATP.Util.List as List import qualified ATP.Util.ListSet as Set import ATP.Util.ListSet ((∪)) import qualified ATP.Util.Print as PP import qualified Control.Monad as M import qualified Data.Map as Map import Data.Map(Map) import qualified Test.QuickCheck as Q import Test.QuickCheck (Gen, Property) class Apply a where apply :: Map Rel Formula -> a -> a instance Apply Formula where apply env = F.onatoms (\p -> case Map.lookup p env of Just p' -> p' Nothing -> Atom p) eval :: Formula -> (Rel -> Bool) -> Bool eval fm v = case fm of [$form| ⊤ |] -> True [$form| ⊥ |] -> False [$form| ^a |] -> v a [$form| ¬ $p |] -> not (eval p v) [$form| $p ∧ $q |] -> eval p v && eval q v [$form| $p ∨ $q |] -> eval p v || eval q v [$form| $p ⊃ $q |] -> not (eval p v) || (eval q v) [$form| $p ⇔ $q |] -> eval p v == eval q v _ -> error "quantifier in prop eval" atoms :: Formula -> [Rel] atoms = List.sort . F.atomUnion (\x -> [x]) onallvaluations :: Eq a => ((a -> Bool) -> b) -> (b -> b -> b) -> (a -> Bool) -> [a] -> b onallvaluations subfn comb v pvs = case pvs of [] -> subfn v p:ps -> let v' t q = if q == p then t else v q in comb (onallvaluations subfn comb (v' False) ps) (onallvaluations subfn comb (v' True) ps) truthtable :: Formula -> String truthtable fm = PP.render (truthtableDoc fm) where truthtableDoc fm' = let pvs = atoms fm' width = foldr (max . length . show) 5 pvs + 1 fixw s = s ++ replicate (width - length s) ' ' truthstring p = fixw (if p then "⊤" else "⊥") separator = replicate (width * length pvs + 9) '-' row v = let lis = map (truthstring . v) pvs ans = truthstring(eval fm' v) in [lis ++ [ans]] rows = onallvaluations row (++) (const False) pvs rowStr r = let (lis, ans) = splitAt (length r - 1) r in (foldr (++) ("| " ++ head ans) lis) in PP.vcat [ PP.text (foldr (\s t -> fixw(show s) ++ t) "| formula" pvs) , PP.empty , PP.text separator , PP.empty , PP.vcat (map (PP.text . rowStr) rows) , PP.text separator ] tautology :: Formula -> Bool tautology fm = onallvaluations (eval fm) (&&) (const False) (atoms fm) unsatisfiable :: Formula -> Bool unsatisfiable = tautology . Not satisfiable :: Formula -> Bool satisfiable = not . unsatisfiable dual :: Formula -> Formula dual fm = case fm of [$form| ⊥ |] -> (⊤) [$form| ⊤ |] -> (⊥) [$form| ^_ |] -> fm [$form| ¬ $p |] -> (¬) $ dual p [$form| $p ∧ $q |] -> p' ∨ q' where p' = dual p q' = dual q [$form| $p ∨ $q |] -> p' ∧ q' where p' = dual p q' = dual q _ -> error "Formula involves connectives ⊃ and ⇔" simplify :: Formula -> Formula simplify fm = case fm of [$form| ¬ $p |] -> simplify1 $ (¬) p' where p' = simplify p [$form| $p ∧ $q |] -> simplify1 $ p' ∧ q' where p' = simplify p q' = simplify q [$form| $p ∨ $q |] -> simplify1 $ p' ∨ q' where p' = simplify p q' = simplify q [$form| $p ⊃ $q |] -> simplify1 $ p' ⊃ q' where p' = simplify p q' = simplify q [$form| $p ⇔ $q |] -> simplify1 $ p' ⇔ q' where p' = simplify p q' = simplify q _ -> fm simplify1 :: Formula -> Formula simplify1 fm = case fm of [$form| ¬ ⊥ |] -> (⊤) [$form| ¬ ⊤ |] -> (⊥) [$form| ¬ ¬ $p |] -> p [$form| ⊥ ∧ _ |] -> (⊥) [$form| _ ∧ ⊥ |] -> (⊥) [$form| ⊤ ∧ $q |] -> q [$form| $p ∧ ⊤ |] -> p [$form| ⊥ ∨ $q |] -> q [$form| $p ∨ ⊥ |] -> p [$form| ⊤ ∨ _ |] -> (⊤) [$form| _ ∨ ⊤ |] -> (⊤) [$form| ⊥ ⊃ _ |] -> (⊤) [$form| _ ⊃ ⊤ |] -> (⊤) [$form| ⊤ ⊃ $q |] -> q [$form| $p ⊃ ⊥ |] -> (¬) p [$form| ⊤ ⇔ $q |] -> q [$form| $p ⇔ ⊤ |] -> p [$form| ⊥ ⇔ ⊥ |] -> (⊤) [$form| ⊥ ⇔ $q |] -> (¬) q [$form| $p ⇔ ⊥ |] -> (¬) p _ -> fm nnf :: Formula -> Formula nnf = nnf' . simplify nnf' :: Formula -> Formula nnf' fm = case fm of [$form| $p ∧ $q |] -> p' ∧ q' where p' = nnf' p q' = nnf' q [$form| $p ∨ $q |] -> p' ∨ q' where p' = nnf' p q' = nnf' q [$form| $p ⊃ $q |] -> np' ∨ q' where np' = nnf' $ (¬) p q' = nnf' q [$form| $p ⇔ $q |] -> p' ∧ q' ∨ p'' ∧ q'' where p' = nnf' p q' = nnf' q p'' = nnf' $ (¬) p q'' = nnf' $ (¬) q [$form| ¬ ¬ $p |] -> nnf' p [$form| ¬ ($p ∧ $q) |] -> p' ∨ q' where p' = nnf' $ (¬) p q' = nnf' $ (¬) q [$form| ¬ ($p ∨ $q) |] -> p' ∧ q' where p' = nnf' $ (¬) p q' = nnf' $ (¬) q [$form| ¬ ($p ⊃ $q) |] -> p' ∧ q' where p' = nnf' p q' = nnf' $ (¬) q [$form| ¬ ($p ⇔ $q) |] -> p' ∧ q'' ∨ p'' ∧ q' where p' = nnf' p q' = nnf' q p'' = nnf' $ (¬) p q'' = nnf' $ (¬) q _ -> fm nenf :: Formula -> Formula nenf = nenf' . simplify nenf' :: Formula -> Formula nenf' fm = case fm of [$form| ¬¬$p |] -> nenf' p [$form| ¬($p ∧ $q) |] -> [$form| $p' ∨ $q' |] where p' = nenf' [$form| ¬ $p |] q' = nenf' [$form| ¬ $q |] [$form| ¬($p ∨ $q) |] -> [$form| $p' ∧ $q' |] where p' = nenf' [$form| ¬ $p |] q' = nenf' [$form| ¬ $q |] [$form| ¬($p ⊃ $q) |] -> [$form| $p' ∧ $q' |] where p' = nenf' p q' = nenf' [$form| ¬ $q |] [$form| ¬($p ⇔ $q) |] -> [$form| $p' ⇔ $q' |] where p' = nenf' p q' = nenf' [$form| ¬ $q |] [$form| $p ∧ $q |] -> [$form| $p' ∧ $q' |] where p' = nenf' p q' = nenf' q [$form| $p ∨ $q |] -> [$form| $p' ∨ $q' |] where p' = nenf' p q' = nenf' q [$form| $p ⊃ $q |] -> [$form| $p' ∨ $q' |] where p' = nenf' [$form| ¬ $p |] q' = nenf' q [$form| $p ⇔ $q |] -> [$form| $p' ⇔ $q' |] where p' = nenf' p q' = nenf' q _ -> fm occurrences :: Rel -> Formula -> (Bool, Bool) occurrences x fm = case fm of [$form| ^y |] -> (x == y, False) [$form| ¬ $p |] -> (neg, pos) where (pos, neg) = occurrences x p [$form| $p ∧ $q |] -> (pos1 || pos2, neg1 || neg2) where (pos1, neg1) = occurrences x p (pos2, neg2) = occurrences x q [$form| $p ∨ $q |] -> (pos1 || pos2, neg1 || neg2) where (pos1, neg1) = occurrences x p (pos2, neg2) = occurrences x q [$form| $p ⊃ $q |] -> (neg1 || pos2, pos1 || neg2) where (pos1, neg1) = occurrences x p (pos2, neg2) = occurrences x q [$form| $p ⇔ $q |] -> if pos1 || pos2 || neg1 || neg2 then (True, True) else (False, False) where (pos1, neg1) = occurrences x p (pos2, neg2) = occurrences x q _ -> (False, False) distrib :: [[Formula]] -> [[Formula]] -> [[Formula]] distrib = List.allPairs Set.union subsume :: [[Formula]] -> [[Formula]] subsume cls = filter (\cl -> not(any (\cl' -> Set.psubset cl' cl) cls)) cls dnf :: Formula -> Formula dnf f = --trace' "dnf: in" (pPrint f) $ let f' = (F.listDisj . map F.listConj . simpdnf) f in --trace' "dnf: out" (pPrint f') $ f' f' simpdnf :: Formula -> [[Formula]] simpdnf Bot = [] simpdnf Top = [[]] simpdnf fm = (subsume . filter (not.trivial) . purednf . nnf) fm purednf :: Formula -> [[Formula]] purednf fm = case fm of And p q -> distrib (purednf p) (purednf q) Or p q -> purednf p ∪ purednf q _ -> [[fm]] trivial :: [Formula] -> Bool trivial lits = let (pos, neg) = List.partition F.positive lits in Set.intersect pos (map F.opp neg) /= [] cnf :: Formula -> Formula cnf = F.listConj . map F.listDisj . simpcnf simpcnf :: Formula -> [[Formula]] simpcnf Bot = [[]] simpcnf Top = [] simpcnf fm = let cjs = filter (not . trivial) (purecnf $ nnf fm) in filter (\c -> not $ any (\c' -> Set.psubset c' c) cjs) cjs purecnf :: Formula -> [[Formula]] purecnf = map (map F.opp) . (purednf . nnf . Not) {- nnf [$form| p ⇔ (q ⇔ r) |] cnf [$form| p ⇔ (q ⇔ r) |] dnf [$form| p ⇔ (q ⇔ r) |] -} -- ----------------------------------------------------------------------------- -- Tests -- ----------------------------------------------------------------------------- props :: Int -> Gen Rel props n = fmap (\i -> R ("p" ++ show i) []) $ Q.choose (0, n) forms :: Int -> Gen Formula forms 0 = Q.oneof [ fmap Atom (props 10), return Top, return Bot ] forms n | n > 0 = Q.oneof [ forms (n-1) , M.liftM Not fms , M.liftM2 And fms fms , M.liftM2 Or fms fms , M.liftM2 Imp fms fms , M.liftM2 Iff fms fms ] | otherwise = error "Impossible" where fms = forms $ n - 1 prop_nnf_correct :: Property prop_nnf_correct = Q.label "nnf_correct" $ Q.forAll (forms 5) $ \f -> tautology (f ⇔ nnf f) prop_cnf_correct :: Property prop_cnf_correct = Q.label "cnf_correct" $ Q.forAll (forms 5) $ \f -> tautology (f ⇔ cnf f) prop_dnf_correct :: Property prop_dnf_correct = Q.label "dnf_correct" $ Q.forAll (forms 5) $ \f -> tautology (f ⇔ dnf f) tests :: IO () tests = do Q.quickCheck prop_nnf_correct Q.quickCheck prop_cnf_correct Q.quickCheck prop_dnf_correct
andre-artus/handbook-of-practical-logic-and-automated-reasoning-haskell
src/ATP/Prop.hs
gpl-3.0
10,023
564
12
3,150
4,539
2,421
2,118
-1
-1
{-# LANGUAGE Arrows #-} module FRP.Events ( SDLEvents, getSDLEvents, sdlKeyPresses, sdlKeys, sdlAllKeys, sdlKeyIsDown, sdlMousePos, sdlMouseIsDown, sdlMouseClicks, sdlQuitEvents, kEqIgn, mkKey ) where import Control.Applicative import Control.Arrow import Control.Monad.Loops import Data.List import Data.Maybe import Data.Word import FRP.Yampa import Graphics.UI.SDL hiding (Event, NoEvent) import qualified Graphics.UI.SDL as SDL type SDLEvents = [SDL.Event] -- TODO: check that these events are in order getSDLEvents :: IO SDLEvents getSDLEvents = unfoldWhileM (/= SDL.NoEvent) pollEvent -- count key presses sdlKeyPresses :: Keysym -> Bool -> SF (Event SDLEvents) (Event Int) sdlKeyPresses sym ignModifiers = arr$ \e -> length <$> filterSDLEvents (if ignModifiers then fi else f) e where f (KeyDown k) = k == sym f _ = False fi (KeyDown k) = k `kEqIgn` sym fi _ = False sdlKeys :: [Keysym] -> Bool -> SF (Event SDLEvents) (Event [Keysym]) sdlKeys syms ignModifiers = arr$ \e -> catMaybeSDLEvents$ (fmap.fmap) (if ignModifiers then fi else f)$ e where f (KeyDown k) = if k `elem` syms then Just k else Nothing f _ = Nothing fi (KeyDown k) = if isJust$ find (k `kEqIgn`) syms then Just k else Nothing fi _ = Nothing sdlAllKeys :: SF (Event SDLEvents) (Event [Keysym]) sdlAllKeys = arr$ \e -> catMaybeSDLEvents$ (fmap.fmap) f$ e where f (KeyDown k) = Just k f _ = Nothing -- is a key currently pressed sdlKeyIsDown :: Keysym -> Bool -> SF (Event SDLEvents) Bool sdlKeyIsDown sym ignModifiers = (hold False) <<< (arr$ \e -> isKeyDown.last <$> filterSDLEvents (if ignModifiers then fi else f) e) where f (KeyDown k) = k == sym f (KeyUp k) = k == sym f _ = False fi (KeyDown k) = k `kEqIgn` sym fi (KeyUp k) = k `kEqIgn` sym fi _ = False isKeyDown (KeyDown _) = True isKeyDown _ = False sdlMousePos :: SF (Event SDLEvents) (Word16, Word16) sdlMousePos = (hold (0, 0)) <<< (arr$ (last <$>).catMaybeSDLEvents.((map mouseCoords) <$>)) where mouseCoords (MouseMotion x y _ _) = Just (x, y) mouseCoords _ = Nothing sdlMouseIsDown :: MouseButton -> SF (Event SDLEvents) Bool sdlMouseIsDown bt = (hold False) <<< (arr$ \e -> isBtDown.last <$> filterSDLEvents f e) where f (MouseButtonDown _ _ b) = b == bt f (MouseButtonUp _ _ b) = b == bt f _ = False isBtDown (MouseButtonDown _ _ _) = True isBtDown _ = False sdlMouseClicks :: MouseButton -> SF (Event SDLEvents) (Event Int) sdlMouseClicks bt = arr$ (length <$>).filterSDLEvents f where f (MouseButtonDown _ _ b) = b == bt f _ = False sdlQuitEvents :: SF (Event SDLEvents) (Event Int) sdlQuitEvents = arr$ \ev -> case length.filter (== SDL.Quit) <$> ev of Event 0 -> NoEvent x -> x filterSDLEvents :: (SDL.Event -> Bool) -> Event SDLEvents -> Event SDLEvents filterSDLEvents f = (filterE (not.null)).(filter f <$>) catMaybeSDLEvents :: Event ([Maybe a]) -> Event [a] catMaybeSDLEvents = (filterE (not.null)).(catMaybes <$>) kEqIgn :: Keysym -> Keysym -> Bool kEqIgn a b = noMods a == noMods b where noMods (Keysym k _ u) = Keysym k [] u mkKey :: SDLKey -> Keysym mkKey k = Keysym k [] '\0'
CLowcay/CC_Clones
src/FRP/Events.hs
gpl-3.0
3,136
37
12
614
1,345
717
628
85
7