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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# 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 _ entries)
-> 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-ext-core-source"
-> putStr (gen_ext_core_source entries)
"--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-ext-core-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"
++ "-----------------------------------------------------------------------------\n"
++ "-- |\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"
++ "-----------------------------------------------------------------------------\n"
++ "{-# LANGUAGE MagicHash, MultiParamTypeClasses, NoImplicitPrelude, UnboxedTuples #-}\n"
++ "module GHC.Prim (\n"
++ unlines (map (("\t" ++) . hdr) entries')
++ ") where\n"
++ "\n"
++ "{-\n"
++ unlines (map opt defaults)
++ "-}\n"
++ 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 (PrimClassSpec { cls = TyApp (TyCon n) _ }) = wrapTy n ++ ","
hdr (PrimClassSpec {}) = error "Illegal class 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@(PrimClassSpec {}) = 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
PrimOpSpec { name = n, ty = t, opts = options } ->
[ pprFixity fixity n | OptionFixity (Just fixity) <- options ]
++
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PrimVecOpSpec { name = n, ty = t, opts = options } ->
[ pprFixity fixity n | OptionFixity (Just fixity) <- options ]
++
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PseudoOpSpec { name = n, ty = t } ->
[ wrapOp n ++ " :: " ++ pprTy t,
wrapOp n ++ " = let x = x in x" ]
PrimTypeSpec { ty = t } ->
[ "data " ++ pprTy t ]
PrimClassSpec { cls = t } ->
[ "class " ++ pprTy t ]
PrimVecTypeSpec { ty = t } ->
[ "data " ++ pprTy t ]
Section { } -> []
comm = case (desc o) of
[] -> ""
d -> "\n" ++ (unlines $ map ("-- " ++ ) $ lines $ unlatex $ escape $ "|" ++ d)
wrapOp nm | isAlpha (head nm) = nm
| otherwise = "(" ++ nm ++ ")"
wrapTy nm | isAlpha (head nm) = nm
| otherwise = "(" ++ nm ++ ")"
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
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 ++ ")"
--
-- Generates the type environment that the stand-alone External Core tools use.
gen_ext_core_source :: [Entry] -> String
gen_ext_core_source entries =
"-----------------------------------------------------------------------\n"
++ "-- This module is automatically generated by the GHC utility\n"
++ "-- \"genprimopcode\". Do not edit!\n"
++ "-----------------------------------------------------------------------\n"
++ "module Language.Core.PrimEnv(primTcs, primVals, intLitTypes, ratLitTypes,"
++ "\n charLitTypes, stringLitTypes) where\nimport Language.Core.Core"
++ "\nimport Language.Core.Encoding\n\n"
++ "primTcs :: [(Tcon, Kind)]\n"
++ "primTcs = [\n"
++ printList tcEnt entries
++ " ]\n"
++ "primVals :: [(Var, Ty)]\n"
++ "primVals = [\n"
++ printList valEnt entries
++ "]\n"
++ "intLitTypes :: [Ty]\n"
++ "intLitTypes = [\n"
++ printList tyEnt (intLitTys entries)
++ "]\n"
++ "ratLitTypes :: [Ty]\n"
++ "ratLitTypes = [\n"
++ printList tyEnt (ratLitTys entries)
++ "]\n"
++ "charLitTypes :: [Ty]\n"
++ "charLitTypes = [\n"
++ printList tyEnt (charLitTys entries)
++ "]\n"
++ "stringLitTypes :: [Ty]\n"
++ "stringLitTypes = [\n"
++ printList tyEnt (stringLitTys entries)
++ "]\n\n"
where printList f = concat . intersperse ",\n" . filter (not . null) . map f
tcEnt (PrimTypeSpec {ty=t}) =
case t of
TyApp tc args -> parens (show tc) (tcKind tc args)
_ -> error ("tcEnt: type in PrimTypeSpec is not a type"
++ " constructor: " ++ show t)
tcEnt _ = ""
-- hack alert!
-- The primops.txt.pp format doesn't have enough information in it to
-- print out some of the information that ext-core needs (like kinds,
-- and later on in this code, module names) so we special-case. An
-- alternative would be to refer to things indirectly and hard-wire
-- certain things (e.g., the kind of the Any constructor, here) into
-- ext-core's Prims module again.
tcKind (TyCon "Any") _ = "Klifted"
tcKind tc [] | last (show tc) == '#' = "Kunlifted"
tcKind _ [] | otherwise = "Klifted"
-- assumes that all type arguments are lifted (are they?)
tcKind tc (_v:as) = "(Karrow Klifted " ++ tcKind tc as
++ ")"
valEnt (PseudoOpSpec {name=n, ty=t}) = valEntry n t
valEnt (PrimOpSpec {name=n, ty=t}) = valEntry n t
valEnt _ = ""
valEntry name' ty' = parens name' (mkForallTy (freeTvars ty') (pty ty'))
where pty (TyF t1 t2) = mkFunTy (pty t1) (pty t2)
pty (TyC t1 t2) = mkFunTy (pty t1) (pty t2)
pty (TyApp tc ts) = mkTconApp (mkTcon tc) (map pty ts)
pty (TyUTup ts) = mkUtupleTy (map pty ts)
pty (TyVar tv) = paren $ "Tvar \"" ++ tv ++ "\""
mkFunTy s1 s2 = "Tapp " ++ (paren ("Tapp (Tcon tcArrow)"
++ " " ++ paren s1))
++ " " ++ paren s2
mkTconApp tc args = foldl tapp tc args
mkTcon tc = paren $ "Tcon " ++ paren (qualify True (show tc))
mkUtupleTy args = foldl tapp (tcUTuple (length args)) args
mkForallTy [] t = t
mkForallTy vs t = foldr
(\ v s -> "Tforall " ++
(paren (quote v ++ ", " ++ vKind v)) ++ " "
++ paren s) t vs
-- hack alert!
vKind "o" = "Kopen"
vKind _ = "Klifted"
freeTvars (TyF t1 t2) = freeTvars t1 `union` freeTvars t2
freeTvars (TyC t1 t2) = freeTvars t1 `union` freeTvars t2
freeTvars (TyApp _ tys) = freeTvarss tys
freeTvars (TyVar v) = [v]
freeTvars (TyUTup tys) = freeTvarss tys
freeTvarss = nub . concatMap freeTvars
tapp s nextArg = paren $ "Tapp " ++ s ++ " " ++ paren nextArg
tcUTuple n = paren $ "Tcon " ++ paren (qualify False $ "Z"
++ show n ++ "H")
tyEnt (PrimTypeSpec {ty=(TyApp tc _args)}) = " " ++ paren ("Tcon " ++
(paren (qualify True (show tc))))
tyEnt _ = ""
-- more hacks. might be better to do this on the ext-core side,
-- as per earlier comment
qualify _ tc | tc == "Bool" = "Just boolMname" ++ ", "
++ ze True tc
qualify _ tc | tc == "()" = "Just baseMname" ++ ", "
++ ze True tc
qualify enc tc = "Just primMname" ++ ", " ++ (ze enc tc)
ze enc tc = (if enc then "zEncodeString " else "")
++ "\"" ++ tc ++ "\""
intLitTys = prefixes ["Int", "Word", "Addr", "Char"]
ratLitTys = prefixes ["Float", "Double"]
charLitTys = prefixes ["Char"]
stringLitTys = prefixes ["Addr"]
prefixes ps = filter (\ t ->
case t of
(PrimTypeSpec {ty=(TyApp tc _args)}) ->
any (\ p -> p `isPrefixOf` show tc) ps
_ -> False)
parens n ty' = " (zEncodeString \"" ++ n ++ "\", " ++ ty' ++ ")"
paren s = "(" ++ s ++ ")"
quote s = "\"" ++ s ++ "\""
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 (PrimClassSpec {cls=t,desc=d,opts=o}) =
"\\primclassspec{"
++ 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`
[-- C code generator can't handle these
"seq#",
"tagToEnum#",
-- not interested in parallel support
"par#", "parGlobal#", "parLocal#", "parAt#",
"parAtAbs#", "parAtRel#", "parAtForNow#"
]
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 =
"\t" ++ 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 "MutableByteArray#") [x]) = "mkMutableByteArrayPrimTy "
++ ppType x
ppType (TyApp (TyCon "Array#") [x]) = "mkArrayPrimTy " ++ ppType x
ppType (TyApp (TyCon "ArrayArray#") []) = "mkArrayArrayPrimTy"
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 UnboxedTuple "
++ 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
|
lukexi/ghc-7.8-arm64
|
utils/genprimopcode/Main.hs
|
bsd-3-clause
| 41,034 | 0 | 34 | 16,606 | 11,469 | 5,769 | 5,700 | 794 | 75 |
{-| Some utility functions, based on the Confd client, providing data
in a ready-to-use way.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Confd.ClientFunctions
( getInstances
, getInstanceDisks
) where
import Control.Monad (liftM)
import qualified Text.JSON as J
import Ganeti.BasicTypes as BT
import Ganeti.Confd.Types
import Ganeti.Confd.Client
import Ganeti.Objects
-- | Get the list of instances the given node is ([primary], [secondary]) for.
-- The server address and the server port parameters are mainly intended
-- for testing purposes. If they are Nothing, the default values will be used.
getInstances
:: String
-> Maybe String
-> Maybe Int
-> BT.ResultT String IO ([Ganeti.Objects.Instance], [Ganeti.Objects.Instance])
getInstances node srvAddr srvPort = do
client <- liftIO $ getConfdClient srvAddr srvPort
reply <- liftIO . query client ReqNodeInstances $ PlainQuery node
case fmap (J.readJSON . confdReplyAnswer) reply of
Just (J.Ok instances) -> return instances
Just (J.Error msg) -> fail msg
Nothing -> fail "No answer from the Confd server"
-- | Get the list of disks that belong to a given instance
-- The server address and the server port parameters are mainly intended
-- for testing purposes. If they are Nothing, the default values will be used.
getDisks
:: Ganeti.Objects.Instance
-> Maybe String
-> Maybe Int
-> BT.ResultT String IO [Ganeti.Objects.Disk]
getDisks inst srvAddr srvPort = do
client <- liftIO $ getConfdClient srvAddr srvPort
reply <- liftIO . query client ReqInstanceDisks . PlainQuery . instUuid $ inst
case fmap (J.readJSON . confdReplyAnswer) reply of
Just (J.Ok disks) -> return disks
Just (J.Error msg) -> fail msg
Nothing -> fail "No answer from the Confd server"
-- | Get the list of instances on the given node along with their disks
-- The server address and the server port parameters are mainly intended
-- for testing purposes. If they are Nothing, the default values will be used.
getInstanceDisks
:: String
-> Maybe String
-> Maybe Int
-> BT.ResultT String IO [(Ganeti.Objects.Instance, [Ganeti.Objects.Disk])]
getInstanceDisks node srvAddr srvPort =
liftM (uncurry (++)) (getInstances node srvAddr srvPort) >>=
mapM (\i -> liftM ((,) i) (getDisks i srvAddr srvPort))
|
apyrgio/ganeti
|
src/Ganeti/Confd/ClientFunctions.hs
|
bsd-2-clause
| 3,574 | 0 | 13 | 616 | 530 | 275 | 255 | 41 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
module Common where
import Web.Twitter.Conduit
import Control.Applicative
import Control.Lens
import qualified Data.ByteString.Char8 as S8
import qualified Data.CaseInsensitive as CI
import qualified Data.Map as M
import Network.HTTP.Conduit
import qualified Network.URI as URI
import System.Environment
import Web.Authenticate.OAuth as OA
getOAuthTokens :: IO (OAuth, Credential)
getOAuthTokens = do
consumerKey <- getEnv' "OAUTH_CONSUMER_KEY"
consumerSecret <- getEnv' "OAUTH_CONSUMER_SECRET"
accessToken <- getEnv' "OAUTH_ACCESS_TOKEN"
accessSecret <- getEnv' "OAUTH_ACCESS_SECRET"
let oauth = twitterOAuth
{ oauthConsumerKey = consumerKey
, oauthConsumerSecret = consumerSecret
}
cred = Credential
[ ("oauth_token", accessToken)
, ("oauth_token_secret", accessSecret)
]
return (oauth, cred)
where
getEnv' = (S8.pack <$>) . getEnv
getProxyEnv :: IO (Maybe Proxy)
getProxyEnv = do
env <- M.fromList . over (mapped . _1) CI.mk <$> getEnvironment
let u = M.lookup "https_proxy" env <|>
M.lookup "http_proxy" env <|>
M.lookup "proxy" env >>= URI.parseURI >>= URI.uriAuthority
return $ Proxy <$> (S8.pack . URI.uriRegName <$> u) <*> (parsePort . URI.uriPort <$> u)
where
parsePort :: String -> Int
parsePort [] = 8080
parsePort (':':xs) = read xs
parsePort xs = error $ "port number parse failed " ++ xs
getTWInfoFromEnv :: IO TWInfo
getTWInfoFromEnv = do
pr <- getProxyEnv
(oa, cred) <- getOAuthTokens
return $ (setCredential oa cred def) { twProxy = pr }
|
asi1024/twchs
|
src/Common.hs
|
mit
| 1,751 | 0 | 15 | 404 | 468 | 254 | 214 | 44 | 3 |
<?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="fa-IR">
<title>TreeTools</title>
<maps>
<homeID>treetools</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/treetools/src/main/javahelp/help_fa_IR/helpset_fa_IR.hs
|
apache-2.0
| 960 | 77 | 66 | 155 | 404 | 205 | 199 | -1 | -1 |
-- (c) The FFI task force, [2000..2001]
--
-- Bundles the language-independent FFI library functionality
module Foreign (
module Int,
module Word,
module Ptr,
module ForeignPtr,
module StablePtr,
module Storable,
module MarshalAlloc,
module MarshalArray,
module MarshalError,
module MarshalUtils
) where
import Int
import Word
import Ptr
import ForeignPtr
import StablePtr
import Storable
import MarshalAlloc
import MarshalArray
import MarshalError
import MarshalUtils
|
mimi1vx/gtk2hs
|
tools/c2hs/doc/c2hs/lib/Foreign.hs
|
gpl-3.0
| 492 | 0 | 4 | 83 | 79 | 57 | 22 | 21 | 0 |
foo = qux (\x -> f x >>= g)
|
mpickering/hlint-refactor
|
tests/examples/Default128.hs
|
bsd-3-clause
| 28 | 0 | 9 | 9 | 24 | 12 | 12 | 1 | 1 |
-- | The organization members API as described on
-- <http://developer.github.com/v3/orgs/members/>.
module Github.Organizations.Members (
membersOf
,module Github.Data
) where
import Github.Data
import Github.Private
-- | All the users who are members of the specified organization.
--
-- > membersOf "thoughtbot"
membersOf :: String -> IO (Either Error [GithubOwner])
membersOf organization = githubGet ["orgs", organization, "members"]
|
bitemyapp/github
|
Github/Organizations/Members.hs
|
bsd-3-clause
| 442 | 0 | 9 | 58 | 76 | 46 | 30 | 7 | 1 |
-- Test type errors contain field names, not selector names
{-# LANGUAGE DuplicateRecordFields #-}
data T = MkT { x :: Int }
y = x x
main = return ()
|
sgillespie/ghc
|
testsuite/tests/overloadedrecflds/should_fail/overloadedrecfldsfail07.hs
|
bsd-3-clause
| 154 | 0 | 8 | 35 | 36 | 20 | 16 | 4 | 1 |
{-# OPTIONS -XImpredicativeTypes -fno-warn-deprecated-flags #-}
module ShouldFail where
import Control.Concurrent
-- Attempt to put a polymorphic value in an MVar
-- Fails, but the error message is worth keeping an eye on
--
-- Actually (Dec 06) it succeeds now
--
-- In GHC 7.0 it fails again! (and rightly so)
foo = do var <- newEmptyMVar :: IO (MVar (forall a. Show a => a -> String))
putMVar var (show :: forall b. Show b => b -> String)
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/typecheck/should_fail/tcfail165.hs
|
bsd-3-clause
| 456 | 0 | 14 | 94 | 89 | 50 | 39 | -1 | -1 |
module Main (main) where
import T4012_A
import T4012_B
main :: IO ()
main = do a
b
|
urbanslug/ghc
|
testsuite/tests/ffi/should_run/T4012.hs
|
bsd-3-clause
| 97 | 0 | 6 | 31 | 36 | 20 | 16 | 6 | 1 |
{-# htermination lookupWithDefaultFM :: (Ord a, Ord k) => FiniteMap (a,k) b -> b -> (a,k) -> b #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_lookupWithDefaultFM_12.hs
|
mit
| 116 | 0 | 3 | 21 | 5 | 3 | 2 | 1 | 0 |
data List a = Empty | Cons a (List a)
deriving Show
fromList :: [a] -> List a
fromList (x:xs) = Cons x (fromList xs)
fromList [] = Empty
toList :: List a -> [a]
toList (Cons x xs) = x:(toList xs)
toList Empty = []
|
dzeban/haskell-exercises
|
rwh/ch03/List.hs
|
mit
| 230 | 0 | 8 | 62 | 137 | 68 | 69 | 8 | 1 |
module Jakway.Blackjack.Match where
import Jakway.Blackjack.CardOps
import Jakway.Blackjack.Result
data Match = Match
{ dealersHand :: Hand
, playerIds :: [Int]
, playersHands :: [Hand]
, playerResults :: [Result]
}
deriving (Eq, Show)
|
tjakway/blackjack-simulator
|
src/Jakway/Blackjack/Match.hs
|
mit
| 310 | 0 | 9 | 105 | 72 | 46 | 26 | 9 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE PackageImports #-}
import "class-load" Application (getApplicationDev)
import Network.Wai.Handler.Warp
(runSettings, defaultSettings, setPort)
import Control.Concurrent (forkIO)
import System.Directory (doesFileExist, removeFile)
import System.Exit (exitSuccess)
import Control.Concurrent (threadDelay)
#ifndef mingw32_HOST_OS
import System.Posix.Signals (installHandler, sigINT, Handler(Catch))
#endif
main :: IO ()
main = do
#ifndef mingw32_HOST_OS
_ <- installHandler sigINT (Catch $ return ()) Nothing
#endif
putStrLn "Starting devel application"
(port, app) <- getApplicationDev
forkIO $ runSettings (setPort port defaultSettings) app
loop
loop :: IO ()
loop = do
threadDelay 100000
e <- doesFileExist "yesod-devel/devel-terminate"
if e then terminateDevel else loop
terminateDevel :: IO ()
terminateDevel = exitSuccess
|
gsingh93/class-load
|
devel.hs
|
mit
| 894 | 2 | 12 | 134 | 245 | 131 | 114 | 24 | 2 |
-- Printer Errors
-- http://www.codewars.com/kata/56541980fa08ab47a0000040/
module Codewars.G964.Printer where
printerError :: String -> String
printerError s = show ((+ length s) . negate . length . filter (`elem` ['a'..'m']) $ s) ++ "/" ++ show (length s)
|
gafiatulin/codewars
|
src/7 kyu/Printer.hs
|
mit
| 260 | 0 | 14 | 38 | 86 | 48 | 38 | 3 | 1 |
module Diamond (diamond) where
import Data.Char (ord, chr)
diamond :: Char -> Maybe [String]
diamond c | c `notElem` ['A'..'Z'] = Nothing
diamond c = Just . mirror . map row $ [0..n] where
n = ord c - ord 'A'
mirror top = top ++ tail (reverse top)
row i = mirror $ spaces (n - i) ++ [letter i] ++ spaces i
letter i = chr (ord 'A' + i)
spaces i = replicate i ' '
|
exercism/xhaskell
|
exercises/practice/diamond/.meta/examples/success-standard/src/Diamond.hs
|
mit
| 374 | 0 | 12 | 91 | 201 | 102 | 99 | 10 | 1 |
module ProjectEuler.Problem7
( problem
) where
import Petbox
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 7 Solved result
result :: Int
result = primes !! (10001-1) -- since list indices are 0-based
|
Javran/Project-Euler
|
src/ProjectEuler/Problem7.hs
|
mit
| 230 | 0 | 7 | 42 | 58 | 34 | 24 | 8 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Y2020.M11.D20.Solution where
{--
Okay, so we created folders, and, hypothetically, we can even create sub-
folders, if we wished, but, today, instead of building on this folder-
skeleton, we're going to focus on just one country and its airbases.
Which country?
Let's find out.
Today's Haskell problem.
Rank countries by number of their airbases. The country with the most airbases,
first. Okay, which country is that?
Now, look through this list. Pick a country that has a "reasonable" number of
airbases. "Reasonable number" is, of course, a number you're comfortable working
with. With that country, and its airbases, create:
1. a placemark of the lat/long of that country's capital. Label it.
2. placemarks for each of the airbases of that country.
3. linkages from the country's capital to each of its airbases.
Output this structure as KML, view it in a KML-viewer, such as
earth.google.com.
Share your results here.
--}
import Y2020.M10.D12.Solution (Country, AirBase, Icao)
import qualified Y2020.M10.D12.Solution as A
import Y2020.M11.D17.Solution -- for Country capitals
import Data.Aeson.WikiDatum
import Data.XHTML.KML
import Control.Arrow ((&&&))
import Data.List (sortOn)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Ord -- for Down
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
type AirBaseByCountry = Map Country (Set AirBase)
{--
>>> A.loadBases (A.workingDir ++ A.file)
>>> let bases = A.byICAO it
--}
airbaseByCountry :: Map Icao AirBase -> AirBaseByCountry
airbaseByCountry = foldr inserter Map.empty . Map.elems
where inserter ab = Map.insert (A.country ab) . inserterer ab <*> id
inserterer :: AirBase -> AirBaseByCountry -> Set AirBase
inserterer ab = maybe Set.empty (Set.insert ab) . Map.lookup (A.country ab)
airbaseCountByCountry :: AirBaseByCountry -> [(Country,Int)]
airbaseCountByCountry = sortOn (Down . snd) . Map.toList . Map.map Set.size
{--
1. which country has the most airbases? Which countries have no airbases?
>>> let abc = airbaseByCountry bases
>>> take 3 (airbaseCountByCountry abc)
[("United States of America",141),("United Kingdom",81),("Germany",62)]
>>> map fst $ filter ((== 0) . snd) (airbaseCountByCountry abc)
["Algeria","Argentina","Austria","Bahrain","Bolivia","Bosnia and Herzegovina",
"Djibouti","Dominican Republic","Ecuador","El Salvador","Ethiopia","Georgia",
"Greenland","Honduras","Kazakhstan","Lebanon","Myanmar","Niger","Panama",
"Papua New Guinea","Qatar","Saint Helena, Ascension and Tristan da Cunha",
"Slovakia","Sudan","Tanzania","Tunisia","Turkish Republic of Northern Cyprus",
"Tuvalu","Uruguay","Yugoslavia","Zimbabwe"]
2. How many countries do have airbases?
>>> length $ filter ((> 0) . snd) (airbaseCountByCountry abc)
77
--}
----- AND NOW! To the mapping-on-a-globe-work!
{--
For the countries that have airbases, create a mapping of countries to their
capitals. See yesterday's exercise.
>>> readCapitals (capitalDir ++ capitalsJSON)
>>> let cim = it
Now, for a country with a 'reasonable' number of airbases, get that country,
its capital, and the airbases.
--}
data AirPower = AirPower CountryInfo (Set AirBase)
deriving (Eq, Show)
airbasesOf :: AirBaseByCountry -> CountryInfoMap -> Country -> Maybe AirPower
airbasesOf abc cim c = AirPower <$> Map.lookup c cim <*> Map.lookup c abc
{--
>>> :set -XOverloadedStrings
>>> airbasesOf abc cim "Belgium"
Just (AirPower (CI {country = WD {qid = "http://www.wikidata.org/entity/Q31",...
3. Output the XML for the country and its airbases, something like:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.0">
<Document>
<name>Belgium's Air Power</name>
<Folder>
<name>Belgium</name>
<Description>It's Tuesday</Description>
<Placemark>
<name>Brussels</name>
<Description>Capital</Description>
<Point>
<coordinates>4.351666666,50.846666666,1000.0</coordinates>
</Point>
</Placemark>
<Folder>
<name>Air Bases</name>
<Folder>
<name>Jehonville Air Base</name>
<Placemark>
<name>Jehonville Air Base</name>
<Point>
<coordinates>5.22389,49.89167,1000.0</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Brussels - Jehonville Air Base</name>
<LineString>
<coordinates>
4.351666666,50.846666666,1000.0
5.22389,49.89167,1000.0
</coordinates>
</LineString>
</Placemark>
</Folder>
...
A sample, demonstrative, KML is located in this directory.
--}
belgianDir :: FilePath
belgianDir = "Y2020/M11/D20/"
belgianKML :: FilePath
belgianKML = "belgian-airbases.kml"
sname :: WikiDatum -> String
sname = T.unpack . name
airpower2KML :: AirPower -> KML
airpower2KML (AirPower (CI country cap latlong) airbases) =
KML "Belgium's Air Power"
[F (Folder (sname country) (Just "It's Tuesday")
(place cap latlong:foldAirs cap latlong airbases))]
foldAirs :: WikiDatum -> LongLat -> Set AirBase -> [Key]
foldAirs cap latlong abs | Set.size abs == 0 = []
| otherwise =
[F . Folder "Air Bases" Nothing
. map (airbnb cap latlong) $ Set.toList abs]
place :: WikiDatum -> LongLat -> Key
place cap = P . Placemark (sname cap) (Just "Capital") . return . Pt . pt
pt :: LongLat -> Point
pt ll = Coord (lat ll) (lon ll) 1000.0
airbnb :: WikiDatum -> LongLat -> AirBase -> Key
airbnb capw ll ab =
let airname = T.unpack $ A.val ab
p n = P . Placemark n Nothing . return
cap = sname capw
in F . Folder airname Nothing
$ [p airname . Pt $ pt (A.pos ab),
p (concat [cap, " - ", airname]) $ line ll ab]
line :: LongLat -> AirBase -> PointOrLine
line ll = Ln . Line . map pt . (ll:) . return . A.pos
-- and with that, you should be able to KMLify the Airbases-as-KML
kmlify :: AirPower -> IO ()
kmlify = skeletonKML . airpower2KML
belgium :: IO ()
belgium = A.loadBases (A.workingDir ++ A.file) >>= \b0 ->
readCapitals (capitalDir ++ capitalsJSON) >>= \cim ->
let bases = A.byICAO b0
abc = airbaseByCountry bases
belgAirbases = fromJust (airbasesOf abc cim "Belgium")
in kmlify belgAirbases
-- ... and: BOOM! It's Tuesday! ;)
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M11/D20/Solution.hs
|
mit
| 6,393 | 0 | 15 | 1,247 | 1,057 | 559 | 498 | 67 | 1 |
module Y2017.M04.D05.Exercise where
import Data.Time
import Network.HTTP
-- below modules available via 1HaskellADay git repository
import Control.Scan.CSV
import Data.Monetary.BitCoin
import Data.Monetary.USD
import Data.Percentage
{--
In this tweet
https://twitter.com/ohiobitcoin/status/849368023588909057
@ohiobitcoin claims that the Ukraine increased its investment in bitcoin by
500%. Wow. 500%. But how much did bitcoin rise over the past year?
Today's Haskell problem.
Download the daily bitcoin price per dollar over the last year, then determine
its percentage increase.
--}
url :: FilePath
url = "http://data.bitcoinity.org/export_data.csv?currency=USD"
++ "&data_type=price&exchange=kraken&r=day&t=l×pan=2y"
-- the above URL gives 2 years of BitCoin data as price per USD
btcPrices :: FilePath -> IO BitCoinPrices
btcPrices url = undefined
-- load in the Date,ave,max,min and return the (Day,average) pairs
-- hint: Data.Monetary.BitCoin functions MAY help.
-- What is the percentage rise of BTC price from the most recent date of the
-- BTC data from the price of BTC a year ago?
annualPercentageRise :: BitCoinPrices -> Percentage
annualPercentageRise btcData = undefined
-- What is your investment growth for
-- 1. investing a lump-sum a year ago?
lumpSumInvestmentGrowth :: BitCoinPrices -> USD -> USD
lumpSumInvestmentGrowth btcData investment = undefined
-- 2. investing monthly a set amount?
monthlyInvestmentGrowth :: BitCoinPrices -> USD -> USD
monthlyInvestmentGrowth btcData monthlyInvest = undefined
-- 3. investing weekly a set amount?
weeklyInvestmentGrowth :: BitCoinPrices -> USD -> USD
weeklyInvestmentGrowth btcData weeklyInvest = undefined
-- 4. What is the percentage growth for each type of investment above?
percentageGrowth :: USD -> USD -> Percentage
percentageGrowth initialAmt finalPortfolioValue = undefined
-- Caveat: these queries are 'back-testing' data which have been notoriously
-- misused to forecast future growth. Back-testing only shows historical growth.
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M04/D05/Exercise.hs
|
mit
| 2,038 | 0 | 6 | 296 | 198 | 116 | 82 | 22 | 1 |
-- | Author : John Allard
-- | Date : Jan 15th 2016
-- | Class : CMPS 112 UCSC
-- | I worked alone, no partners to list.
-- | Homework #1 |--
import Data.Char
import Data.List
import Text.Regex
import Text.Regex.Posix
-- | 1.) Write a function that turns a first and last name into "$last, $first"
citeAuthor :: String -> String -> String
citeAuthor first last = last ++ ", " ++ first
-- | 2.) Write a function that produces the initials given a first and last name
initials :: String -> String -> String
initials first last = [toUpper (head first) ] ++ "." ++ [toUpper (head last)] ++ "."
-- | 3.) Take an (Author, title, date) tuple and return the title
title :: (String, String, Int) -> String
title (author, title, date) = title
-- | 4.) Take a author, title, date tuple and return a citation-formatted string
citeBook :: (String, String, Int) -> String
citeBook (author, title, date) = title ++ " (" ++ author ++ ", " ++ (show date) ++ ")"
-- | 5.) Write a function that takes a list of citation-tuples and formats them as
-- the last function did, except putting a newline between each formatted citation
bibliography_rec :: [(String, String, Int)] -> String
bibliography_rec [] = ""
bibliography_rec (x:y) = citeBook x ++ "\n" ++ bibliography_rec y
-- | 6.) Write a function that returns the average publication year from a list of books
-- ** note ** - this seems like it should return a float or fractional but the assignment
-- required an int so that's what I'm doing
averageYear :: [(String, String, Int)] -> Int
averageYear x = sum (map (\(x, y, z) -> z) x) `div` genericLength x
-- | 7.) Take the definition of txt given below and write a function 'references'
-- which takes a text with references in the format [n] and returns the total
-- number of references.
txt :: String
txt = "[1] and [2] both feature characters who will do whatever it takes to " ++
"get to their goal, and in the end the thing they want the most ends " ++
"up destroying them. In case of [2] this is a whale..."
references :: String -> Int
references intxt = genericLength (filter (=~"\\[([1-9]+)]") (words intxt))
-- | 8.) Write a function citeText which takes a list of books and a text with references
-- in the form [n] and returns a tet with all references replaces by a citation of the
-- nth book using the citeBook function from problem 5
-- take a "[index_str]" and return cites[index_str]
citeTextHelper :: [(String, String, Int)] -> String -> String
citeTextHelper cites index_str = citeBook (cites !! (index_str =~ "([0-9]+)"))
citeText :: [(String, String, Int)] -> String -> String
citeText cites str = intercalate " " (map (\x -> if (x =~"\\[([1-9]+)]") then citeTextHelper cites x else x) (words str))
|
jhallard/WinterClasses16
|
CS112/hw/hw1/hw1.hs
|
mit
| 2,789 | 0 | 12 | 572 | 567 | 314 | 253 | 27 | 2 |
module Ratscrew.Cards.Arbitrary where
import Ratscrew.Cards
import Test.Tasty.QuickCheck
instance Arbitrary Suit where
arbitrary = oneof (map return [Diamonds .. Spades])
instance Arbitrary Rank where
arbitrary = oneof $ map return [Ace .. King]
instance Arbitrary Card where
arbitrary = do
s <- arbitrary
r <- arbitrary
return (Card s r)
|
smobs/Ratscrew
|
tests/Ratscrew/Cards/Arbitrary.hs
|
mit
| 379 | 0 | 10 | 89 | 117 | 62 | 55 | 12 | 0 |
module Servant (
-- | This module and its submodules can be used to define servant APIs. Note
-- that these API definitions don't directly implement a server (or anything
-- else).
module Servant.API,
-- | For implementing servers for servant APIs.
module Servant.Server,
-- | Utilities on top of the servant core
module Servant.Links,
module Servant.Server.StaticFiles,
-- | Useful re-exports
Proxy(..),
throwError
) where
import Control.Monad.Error.Class
(throwError)
import Data.Proxy
import Servant.API
import Servant.Links
import Servant.Server
import Servant.Server.StaticFiles
|
zoomhub/zoomhub
|
vendor/servant/servant-server/src/Servant.hs
|
mit
| 688 | 0 | 5 | 182 | 85 | 58 | 27 | 14 | 0 |
{-
Hake: a meta build system for Barrelfish
Copyright (c) 2009, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Main where
import System.Environment
import System.IO
import System.Directory
import System.Exit
import GHC hiding (Target)
import GHC.Paths ( libdir )
import DynFlags ( defaultFlushOut, defaultFatalMessager,
xopt_set,
ExtensionFlag (Opt_DeriveDataTypeable) )
import Data.Dynamic
import Data.Maybe
import Data.List
import Control.Monad
import Control.Parallel.Strategies
import RuleDefs
import HakeTypes
import qualified Path
import qualified Args
import qualified Config
--
-- Command line options and parsing code
--
data Opts = Opts { opt_makefilename :: String,
opt_installdir :: String,
opt_sourcedir :: String,
opt_bfsourcedir :: String,
opt_usage_error :: Bool,
opt_architectures :: [String],
opt_verbosity :: Integer
}
deriving (Show,Eq)
parse_arguments :: [String] -> Opts
parse_arguments [] =
Opts { opt_makefilename = "Makefile",
opt_installdir = Config.install_dir,
opt_sourcedir = Config.source_dir,
opt_bfsourcedir = Config.source_dir,
opt_usage_error = False,
opt_architectures = [],
opt_verbosity = 1 }
parse_arguments ("--install-dir" : (s : t)) =
(parse_arguments t) { opt_installdir = s }
parse_arguments ("--source-dir" : s : t) =
(parse_arguments t) { opt_sourcedir = s }
parse_arguments ("--bfsource-dir" : s : t) =
(parse_arguments t) { opt_bfsourcedir = s }
parse_arguments ("--output-filename" : s : t) =
(parse_arguments t) { opt_makefilename = s }
parse_arguments ("--quiet" : t ) =
(parse_arguments t) { opt_verbosity = 0 }
parse_arguments ("--verbose" : t ) =
(parse_arguments t) { opt_verbosity = 2 }
parse_arguments ("--architecture" : a : t ) =
let
o2 = parse_arguments t
arches = (a : opt_architectures o2)
in
o2 { opt_architectures = arches }
parse_arguments _ =
(parse_arguments []) { opt_usage_error = True }
usage :: String
usage = unlines [ "Usage: hake <options>",
" --source-dir <dir> (required)",
" --bfsource-dir <dir> (defaults to source dir)",
" --install-dir <dir> (defaults to source dir)",
" --quiet",
" --verbose"
]
--
-- Handy path operator
--
infix 4 ./.
root ./. path = Path.relToDir path root
--
-- Walk all over a directory tree and build a complete list of pathnames
--
listFilesR :: FilePath -> IO [FilePath]
listFilesR path = let
isDODD :: String -> Bool
isDODD f = not $ (isSuffixOf "/." f)
|| (isSuffixOf "/.." f)
|| (isSuffixOf "CMakeFiles" f)
|| (isPrefixOf (path ++ "/.hg") f)
|| (isPrefixOf (path ++ "/build") f)
|| (isPrefixOf (path ++ "/.git") f)
listDirs :: [FilePath] -> IO [FilePath]
listDirs = filterM doesDirectoryExist
listFiles :: [FilePath] -> IO [FilePath]
listFiles = filterM doesFileExist
joinFN :: String -> String -> FilePath
-- joinFN p1 p2 = joinPath [p1, p2]
joinFN p1 p2 = p1 ++ "/" ++ p2
in do
allfiles <- getDirectoryContents path
no_dots <- filterM (return . isDODD) (map (joinFN path) allfiles)
dirs <- listDirs no_dots
subdirfiles <- (mapM listFilesR dirs >>= return . concat)
files <- listFiles no_dots
return $ files ++ subdirfiles
--
-- Return a list of pairs of (Hakefile name, contents)
--
readHakeFiles :: [FilePath] -> IO [ (String,String) ]
readHakeFiles [] = return []
readHakeFiles (h:hs) = do { r <- readFile h;
rs <- readHakeFiles hs;
return ((h,r):rs)
}
--
-- Look for Hakefiles in a list of path names
--
hakeFiles :: [FilePath] -> [String]
hakeFiles f = [ fp | fp <- f, isSuffixOf "/Hakefile" fp ]
---
--- Functions to resolve relative path names in rules.
---
--- First, the outer function: resolve path names in an HRule. The
--- third argument, 'root', is frequently the pathname of the Hakefile
--- relative to the source tree - since relative pathnames in
--- Hakefiles are interpreted relative to the Hakefile location.
---
resolveRelativePaths :: Opts -> HRule -> String -> HRule
resolveRelativePaths o (Rules hrules) root
= Rules [ resolveRelativePaths o r root | r <- hrules ]
resolveRelativePaths o (Rule tokens) root
= Rule [ resolveRelativePath o t root | t <- tokens ]
resolveRelativePaths o (Include token) root
= Include ( resolveRelativePath o token root )
resolveRelativePaths o (Error s) root
= (Error s)
--- Now resolve at the level of individual rule tokens. At this
--- level, we need to take into account the tree (source, build, or
--- install).
resolveRelativePath :: Opts -> RuleToken -> String -> RuleToken
resolveRelativePath o (In t a f) root =
(In t a (resolveRelativePathName o t a f root))
resolveRelativePath o (Out a f) root =
(Out a (resolveRelativePathName o BuildTree a f root))
resolveRelativePath o (Dep t a f) root =
(Dep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (NoDep t a f) root =
(NoDep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (PreDep t a f) root =
(PreDep t a (resolveRelativePathName o t a f root))
resolveRelativePath o (Target a f) root =
(Target a (resolveRelativePathName o BuildTree a f root))
resolveRelativePath _ (Str s) _ = (Str s)
resolveRelativePath _ (NStr s) _ = (NStr s)
resolveRelativePath _ (ContStr b s1 s2) _ = (ContStr b s1 s2)
resolveRelativePath _ (ErrorMsg s) _ = (ErrorMsg s)
resolveRelativePath _ NL _ = NL
--- Now we get down to the nitty gritty. We have a tree (source,
--- build, or install), an architecture (e.g. ARM), a pathname, and
--- the pathname of the Hakefile in which it occurs.
resolveRelativePathName :: Opts -> TreeRef -> String -> String -> String -> String
resolveRelativePathName o InstallTree "root" f root =
resolveRelativePathName' ((opt_installdir o)) "root" f root
resolveRelativePathName o _ "root" f root =
"." ./. f
resolveRelativePathName o SrcTree a f root =
resolveRelativePathName' (opt_sourcedir o) a f root
resolveRelativePathName o BuildTree a f root =
resolveRelativePathName' ("." ./. a) a f root
resolveRelativePathName o InstallTree a f root =
resolveRelativePathName' ((opt_installdir o) ./. a) a f root
--- This is where the work is done: take 'root' (pathname relative to
--- us of the Hakefile) and resolve the filename we're interested in
--- relative to this. This gives us a pathname relative to some root
--- of some architecture tree, then return this relative to the actual
--- tree we're interested in. It's troubling that this takes more
--- bytes to explain than to code.
resolveRelativePathName' d a f root =
let af = Path.relToFile f root
rf = Path.makeRel $ Path.relToDir af "/"
in Path.relToDir rf d
--
-- Generating a list of build directories
--
makeDirectories :: [(String, HRule)] -> String
makeDirectories r =
let alldirs = makeDirs1 (Rules [ rl | (f,rl) <- r ]) `using` parListChunk 200 rdeepseq
marker d = d ./. ".marker"
in unlines ([ "# Directories follow" ] ++
[ "hake_dirs: " ++ (marker d) ++ "\n\n" ++
(marker d) ++ ": \n" ++
"\tmkdir -p " ++ d ++ "\n" ++
"\ttouch " ++ (marker d) ++ "\n"
| d <- nub alldirs])
makeDirs1 :: HRule -> [String]
makeDirs1 (Rules hrules) = concat [ makeDirs1 r | r <- hrules]
makeDirs1 (Include tok) =
case tokDir tok of
Nothing -> []
Just d -> [d]
makeDirs1 (Rule toks) = [d | Just d <- [ tokDir t | t <- toks ]]
makeDirs1 (Error s) = []
tokDir :: RuleToken -> Maybe String
tokDir (In t a f) = tokDir1 f
tokDir (Out a f) = tokDir1 f
tokDir (Dep t a f) = tokDir1 f
tokDir (NoDep t a f) = tokDir1 f
tokDir (PreDep t a f) = tokDir1 f
tokDir (Target a f) = tokDir1 f
tokDir (Str s) = Nothing
tokDir (NStr s) = Nothing
tokDir (ContStr b s1 s2) = Nothing
tokDir (ErrorMsg s) = Nothing
tokDir NL = Nothing
tokDir1 f
| (Path.dirname f) `Path.isBelow` "." = Just (Path.dirname f)
| otherwise = Nothing
--
-- filter rules by the set of architectures in Config.architectures
--
filterRuleByArch :: HRule -> Maybe HRule
filterRuleByArch (Rule toks) = if allowedArchs (map frArch toks) then Just (Rule toks) else Nothing
filterRuleByArch (Include tok) = if allowedArchs [frArch tok] then Just (Include tok) else Nothing
filterRuleByArch (Rules rules) = Just (Rules (catMaybes $ map filterRuleByArch rules))
filterRuleByArch x = Just x
-- a rule is included if it has only "special" architectures and enabled architectures
allowedArchs :: [String] -> Bool
allowedArchs = all (\a -> a `elem` (Config.architectures ++ specialArchitectures))
where specialArchitectures = ["", "src", "hake", "root", "tools", "docs"]
--
-- Functions to format rules as Makefile rules
--
makeMakefile :: [(String, HRule)] -> String
makeMakefile r =
unlines $ intersperse "" ([makeMakefileSection f rl | (f,rl) <- r] `using` parList rdeepseq)
makeMakefileSection :: String -> HRule -> String
makeMakefileSection fname rules =
"# From: " ++ fname ++ "\n\n" ++ makeMakeRules rules
makeMakeRules :: HRule -> String
makeMakeRules (Rules hrules)
= unlines [ s | s <- [ makeMakeRules h | h <- hrules ], s /= "" ]
makeMakeRules (Include token) = unlines [
"ifeq ($(MAKECMDGOALS),clean)",
"else ifeq ($(MAKECMDGOALS),rehake)",
"else ifeq ($(MAKECMDGOALS),Makefile)",
"else",
"include " ++ (formatToken token),
"endif"]
makeMakeRules (Error s) = "$(error " ++ s ++ ")\n"
makeMakeRules (Rule tokens) =
let outs = nub [ f | (Out a f) <- tokens ] ++ [ f | (Target a f) <- tokens ]
dirs = nub [ (Path.dirname f) ./. ".marker" | f <- outs ]
deps = nub [ f | (In t a f) <- tokens ] ++ [ f | (Dep t a f) <- tokens ]
predeps = nub [ f | (PreDep t a f) <- tokens ]
spaceSep :: [ String ] -> String
spaceSep sl = concat (intersperse " " sl)
ruleBody = (concat[ formatToken t | t <- tokens, inRule t ])
in if outs == [] then
("# hake: omitted rule with no output: " ++ ruleBody)
else
(spaceSep outs) ++ ": "
++
-- It turns out that if you add 'dirs' here, in an attempt to
-- get Make to build the directories as well, it goes a bit
-- pear-shaped: whenever the directory "changes" it goes out of
-- date, so you end up rebuilding dependencies every time.
(spaceSep (deps ++ dirs))
++
(if (predeps == []) then "" else " | " ++ spaceSep (predeps))
++ "\n"
++
(if (ruleBody == "") then "" else "\t" ++ ruleBody ++ "\n")
preamble :: Opts -> [String] -> String
preamble opts args =
unlines ( [ "# This Makefile is generated by Hake. Do not edit!",
"# ",
"# Hake was invoked with the following command line args:" ] ++
[ "# " ++ a | a <- args ] ++
[ "# ",
"SRCDIR=" ++ (opt_sourcedir opts),
"HAKE_ARCHS=" ++ (concat $ intersperse " " Config.architectures),
"include ./symbolic_targets.mk" ] )
stripSrcDir :: String -> String
stripSrcDir s = Path.removePrefix Config.source_dir s
hakeModule :: [String] -> [(String,String)] -> String
hakeModule allfiles hakefiles =
let unqual_imports = ["RuleDefs", "HakeTypes", "Path", "Args"]
qual_imports = ["Config", "Data.List" ]
relfiles = [ stripSrcDir f | f <- allfiles ]
wrap1 n c = wrapLet "build a"
("(buildFunction a) allfiles " ++ (show n) ++ " a")
c
wrap n c = "(" ++ (show n) ++ ", "
++ wrapLet "find fn arg"
("(fn allfiles " ++ (show n) ++ " arg)")
("Rules (" ++ (wrap1 n c) ++ ")")
++ ")"
flatten :: [String] -> String
flatten s = foldl (++) "" (intersperse ",\n" s)
addHeader (fn,fc) = (fn, "{-# LINE 1 \"" ++ fn ++ "\" #-}\n" ++ fc)
files = flatten [ wrap (stripSrcDir fn) fc | (fn,fc) <- map addHeader hakefiles ]
in
unlines ( [ "module Hakefiles where {" ]
++
[ "import " ++ i ++ ";" | i <- unqual_imports ]
++
[ "import qualified " ++ i ++ ";" | i <- qual_imports ]
++
[ "allfiles = " ++ (show relfiles) ++ ";" ]
++
[ "hf = [" ]
) ++ files ++ "];\n}"
wrapLet :: String -> String -> String -> String
wrapLet var expr body =
"(let " ++ var ++ " = " ++ expr ++ " in\n" ++ body ++ ")"
evalHakeFiles :: Opts -> [String] -> [(String,String)]
-> IO [(String,HRule)]
evalHakeFiles o allfiles hakefiles =
let imports = [ "Hakefiles"]
all_imports = ("Prelude":"HakeTypes":imports)
moddirs = [ (opt_installdir o) ./. "hake",
".",
(opt_bfsourcedir o) ./. "hake" ]
in do
defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
runGhc (Just libdir) $ do
dflags <- getSessionDynFlags
let dflags1 = foldl xopt_set dflags [ Opt_DeriveDataTypeable ]
_ <- setSessionDynFlags dflags1{
importPaths = moddirs,
hiDir = Just "./hake",
objectDir = Just "./hake"
}
targets <- mapM (\m -> guessTarget m Nothing) imports
setTargets targets
load LoadAllTargets
setContext [(IIDecl . simpleImportDecl) (mkModuleName m) | m <- (all_imports)]
val <- dynCompileExpr "Hakefiles.hf :: [(String, HRule)]"
return (fromDyn val [("failed",Error "failed")])
--
-- Generate dependencies of the Makefile on all the Hakefiles
--
--resolveRelativePaths o (Rules hrules) root
--- resolveRelativePath o (In t a f) root =
makeHakeDeps :: Opts -> [ String ] -> String
makeHakeDeps o l =
let hake = resolveRelativePath o (In InstallTree "root" "/hake/hake") ""
makefile = resolveRelativePath o (Out "root" (opt_makefilename o)) "/Hakefile"
rule = Rule ( [ hake,
Str "--source-dir", Str (opt_sourcedir o),
Str "--install-dir", Str (opt_installdir o),
Str "--output-filename", makefile
] ++
[ Dep SrcTree "root" h | h <- l ]
)
in
(makeMakeRules rule)
++ ".DELETE_ON_ERROR:\n\n" -- this applies to all targets in the Makefile
makeHakeDeps1 :: Opts -> [ String ] -> String
makeHakeDeps1 _ l =
"Makefile: ./hake/hake "
++ concat (intersperse " " l)
++ "\n\t./hake/hake Makefile\n"
++ ".DELETE_ON_ERROR:\n\n" -- this applies to all targets in the Makefile
-- check the configuration options, returning an error string if they're insane
configErrors :: Maybe String
configErrors
| unknownArchs /= [] = Just ("unknown architecture(s) specified: "
++ (concat $ intersperse ", " unknownArchs))
| Config.architectures == [] = Just "no architectures defined"
| Config.lazy_thc && not Config.use_fp = Just "Config.use_fp must be true to use Config.lazy_thc."
| otherwise = Nothing
where
unknownArchs = Config.architectures \\ Args.allArchitectures
---
--- Convert a Hakefile name to one relative to the root of the source tree.
---
strip_hfn :: Opts -> String -> String
strip_hfn opts f = Path.removePrefix (opt_sourcedir opts) f
main :: IO()
main = do
-- parse arguments; architectures default to config file
args <- System.Environment.getArgs
let o1 = parse_arguments args
al = if opt_architectures o1 == []
then Config.architectures
else opt_architectures o1
opts = o1 { opt_architectures = al }
if opt_usage_error opts then do
hPutStrLn stderr usage
exitWith $ ExitFailure 1
else do
-- sanity-check configuration settings
-- this is currently known at compile time, but might not always be!
if isJust configErrors then do
hPutStrLn stderr $ "Error in configuration: " ++ (fromJust configErrors)
exitWith $ ExitFailure 2
else do
hPutStrLn stdout ("Source directory: " ++ opt_sourcedir opts)
hPutStrLn stdout ("BF Source directory: " ++ opt_bfsourcedir opts)
hPutStrLn stdout ("Install directory: " ++ opt_installdir opts)
hPutStrLn stdout "Reading directory tree..."
l <- listFilesR (opt_sourcedir opts)
hPutStrLn stdout "Reading Hakefiles..."
hfl <- readHakeFiles $ hakeFiles l
hPutStrLn stdout "Writing HakeFile module..."
modf <- openFile ("Hakefiles.hs") WriteMode
hPutStrLn modf $ hakeModule l hfl
hClose modf
hPutStrLn stdout "Evaluating Hakefiles..."
inrules <- evalHakeFiles opts l hfl
hPutStrLn stdout "Done!"
-- filter out rules for unsupported architectures and resolve relative paths
let rules =
([(f, resolveRelativePaths opts (fromJust (filterRuleByArch rl)) (strip_hfn opts f))
| (f,rl) <- inrules, isJust (filterRuleByArch rl) ])
hPutStrLn stdout $ "Generating " ++ (opt_makefilename opts) ++ " - this may take some time (and RAM)..."
makef <- openFile(opt_makefilename opts) WriteMode
hPutStrLn makef $ preamble opts args
-- let hfl2 = [ strip_hfn opts (fst h) | h <- hfl ]
hPutStrLn makef $ makeHakeDeps opts $ map fst hfl
hPutStrLn makef $ makeMakefile rules
hPutStrLn makef $ makeDirectories rules
hClose makef
exitWith ExitSuccess
|
UWNetworksLab/arrakis
|
hake/Main.hs
|
mit
| 18,163 | 39 | 22 | 4,960 | 4,997 | 2,611 | 2,386 | -1 | -1 |
module Oczor.Parser.Types where
import Text.Megaparsec hiding (label)
import qualified Oczor.Parser.Lexer as L
import ClassyPrelude as C hiding (try)
import Oczor.Syntax.Syntax
import qualified Oczor.Desugar.Desugar as Desugar
import Oczor.Parser.ParserState
import Oczor.Utl
typeDecl :: Parser Expr
typeDecl = do
name <- try (L.rword "type") *> L.identType
param <- many typeParam <* L.rop "="
body <- typeRecordIdent
return $ Desugar.typeDecl name param body
typeUnion :: Parser TypeExpr
typeUnion = TypeUnion <$> try (L.sepBy2 typeUnionItem (L.rop "|"))
typeConstrain :: Parser (String, [String])
typeConstrain = unsafeHead . C.uncons <$> try (some L.ident)
typeConstraints :: Parser TypeExpr
typeConstraints = do
list <- try (L.commaSep1 typeConstrain <* L.rop "<:")
tp <- typeItem
return $ TypeConstraints (separateVarConstraints list) tp
where
separateVarConstraints list = list >>= (\(x, y) -> y &map (\y -> (TypeVar x,y)))
typeVar :: Parser TypeExpr
typeVar = TypeVar <$> L.ident
typeFunc :: Parser TypeExpr
typeFunc = do
var <- try (typeRecordComma <* L.rop "=>")
body <- typeItem
return $ TypeFunc var body
typeApplyParam :: Parser TypeExpr
typeApplyParam = do
name <- typeIdent <|> typeVar
args <- some typeArg
return $ TypeApply name args
typeUnionItem = choice
[L.parens typeRecord,
typeConstraints,
try typeApplyParam,
typeLabel,
typeVar,
typeIdent]
typeItem = typeUnion <|> typeUnionItem
typeArg = choice
[L.parens typeRecord,
typeConstraints,
typeLabel,
typeVar,
typeIdent]
typeIdent :: Parser TypeExpr
typeIdent = TypeIdent <$> L.identType
typeIdentWithConstains :: Parser TypeExpr
typeIdentWithConstains = TypeIdent <$> L.identType
typeLabelWith :: Parser String -> Parser TypeExpr
typeLabelWith x = liftA2 TypeLabel
(try (x <* L.rop ":" <* notFollowedBy (L.rop "=")))
(typeFunc <|> typeUnionItem)
typeLabel :: Parser TypeExpr
typeLabel = typeLabelWith L.ident
typeRecord = newTypeRecord <$> L.commaSep1 (typeFunc <|> typeItem)
typeRecordComma = newTypeRecord <$> L.commaSep1 typeItem
typeRecordIdent = newTypeRecord <$> L.indentOrComma typeItem
typeParam :: Parser TypeExpr
typeParam = TypeVar <$> L.ident
|
ptol/oczor
|
src/Oczor/Parser/Types.hs
|
mit
| 2,202 | 0 | 15 | 358 | 725 | 376 | 349 | 65 | 1 |
module Protocol where
class Connection a where
connect :: a -> IO a
disconnect :: a -> IO a
readMessage :: a -> IO String
writeMessage :: a -> String -> IO ()
|
nablaa/hirchess
|
src/Protocol.hs
|
gpl-2.0
| 192 | 0 | 10 | 66 | 67 | 34 | 33 | 6 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for ganeti-htools.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
-}
module Test.Ganeti.HTools.Instance
( testHTools_Instance
, genInstanceSmallerThanNode
, genInstanceMaybeBiggerThanNode
, genInstanceSmallerThan
, genInstanceOnNodeList
, genInstanceList
, Instance.Instance(..)
) where
import Test.QuickCheck hiding (Result)
import Test.Ganeti.TestHelper
import Test.Ganeti.TestCommon
import Test.Ganeti.HTools.Types ()
import Ganeti.BasicTypes
import qualified Ganeti.HTools.Instance as Instance
import qualified Ganeti.HTools.Node as Node
import qualified Ganeti.HTools.Container as Container
import qualified Ganeti.HTools.Loader as Loader
import qualified Ganeti.HTools.Types as Types
-- * Arbitrary instances
-- | Generates a random instance with maximum disk/mem/cpu values.
genInstanceSmallerThan :: Int -> Int -> Int -> Gen Instance.Instance
genInstanceSmallerThan lim_mem lim_dsk lim_cpu = do
name <- genFQDN
mem <- choose (0, lim_mem)
dsk <- choose (0, lim_dsk)
run_st <- arbitrary
pn <- arbitrary
sn <- arbitrary
vcpus <- choose (0, lim_cpu)
dt <- arbitrary
return $ Instance.create name mem dsk vcpus run_st [] True pn sn dt 1
-- | Generates an instance smaller than a node.
genInstanceSmallerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceSmallerThanNode node =
genInstanceSmallerThan (Node.availMem node `div` 2)
(Node.availDisk node `div` 2)
(Node.availCpu node `div` 2)
-- | Generates an instance possibly bigger than a node.
genInstanceMaybeBiggerThanNode :: Node.Node -> Gen Instance.Instance
genInstanceMaybeBiggerThanNode node =
genInstanceSmallerThan (Node.availMem node + Types.unitMem * 2)
(Node.availDisk node + Types.unitDsk * 3)
(Node.availCpu node + Types.unitCpu * 4)
-- | Generates an instance with nodes on a node list.
-- The following rules are respected:
-- 1. The instance is never bigger than its primary node
-- 2. If possible the instance has different pnode and snode
-- 3. Else disk templates which require secondary nodes are disabled
genInstanceOnNodeList :: Node.List -> Gen Instance.Instance
genInstanceOnNodeList nl = do
let nsize = Container.size nl
pnode <- choose (0, nsize-1)
let (snodefilter, dtfilter) =
if nsize >= 2
then ((/= pnode), const True)
else (const True, not . Instance.hasSecondary)
snode <- choose (0, nsize-1) `suchThat` snodefilter
i <- genInstanceSmallerThanNode (Container.find pnode nl) `suchThat` dtfilter
return $ i { Instance.pNode = pnode, Instance.sNode = snode }
-- | Generates an instance list given an instance generator.
genInstanceList :: Gen Instance.Instance -> Gen Instance.List
genInstanceList igen = fmap (snd . Loader.assignIndices) names_instances
where names_instances =
(fmap . map) (\n -> (Instance.name n, n)) $ listOf igen
-- let's generate a random instance
instance Arbitrary Instance.Instance where
arbitrary = genInstanceSmallerThan maxMem maxDsk maxCpu
-- * Test cases
-- Simple instance tests, we only have setter/getters
prop_creat :: Instance.Instance -> Property
prop_creat inst =
Instance.name inst ==? Instance.alias inst
prop_setIdx :: Instance.Instance -> Types.Idx -> Property
prop_setIdx inst idx =
Instance.idx (Instance.setIdx inst idx) ==? idx
prop_setName :: Instance.Instance -> String -> Bool
prop_setName inst name =
Instance.name newinst == name &&
Instance.alias newinst == name
where newinst = Instance.setName inst name
prop_setAlias :: Instance.Instance -> String -> Bool
prop_setAlias inst name =
Instance.name newinst == Instance.name inst &&
Instance.alias newinst == name
where newinst = Instance.setAlias inst name
prop_setPri :: Instance.Instance -> Types.Ndx -> Property
prop_setPri inst pdx =
Instance.pNode (Instance.setPri inst pdx) ==? pdx
prop_setSec :: Instance.Instance -> Types.Ndx -> Property
prop_setSec inst sdx =
Instance.sNode (Instance.setSec inst sdx) ==? sdx
prop_setBoth :: Instance.Instance -> Types.Ndx -> Types.Ndx -> Bool
prop_setBoth inst pdx sdx =
Instance.pNode si == pdx && Instance.sNode si == sdx
where si = Instance.setBoth inst pdx sdx
prop_shrinkMG :: Instance.Instance -> Property
prop_shrinkMG inst =
Instance.mem inst >= 2 * Types.unitMem ==>
case Instance.shrinkByType inst Types.FailMem of
Ok inst' -> Instance.mem inst' ==? Instance.mem inst - Types.unitMem
Bad msg -> failTest msg
prop_shrinkMF :: Instance.Instance -> Property
prop_shrinkMF inst =
forAll (choose (0, 2 * Types.unitMem - 1)) $ \mem ->
let inst' = inst { Instance.mem = mem}
in isBad $ Instance.shrinkByType inst' Types.FailMem
prop_shrinkCG :: Instance.Instance -> Property
prop_shrinkCG inst =
Instance.vcpus inst >= 2 * Types.unitCpu ==>
case Instance.shrinkByType inst Types.FailCPU of
Ok inst' -> Instance.vcpus inst' ==? Instance.vcpus inst - Types.unitCpu
Bad msg -> failTest msg
prop_shrinkCF :: Instance.Instance -> Property
prop_shrinkCF inst =
forAll (choose (0, 2 * Types.unitCpu - 1)) $ \vcpus ->
let inst' = inst { Instance.vcpus = vcpus }
in isBad $ Instance.shrinkByType inst' Types.FailCPU
prop_shrinkDG :: Instance.Instance -> Property
prop_shrinkDG inst =
Instance.dsk inst >= 2 * Types.unitDsk ==>
case Instance.shrinkByType inst Types.FailDisk of
Ok inst' -> Instance.dsk inst' ==? Instance.dsk inst - Types.unitDsk
Bad msg -> failTest msg
prop_shrinkDF :: Instance.Instance -> Property
prop_shrinkDF inst =
forAll (choose (0, 2 * Types.unitDsk - 1)) $ \dsk ->
let inst' = inst { Instance.dsk = dsk }
in isBad $ Instance.shrinkByType inst' Types.FailDisk
prop_setMovable :: Instance.Instance -> Bool -> Property
prop_setMovable inst m =
Instance.movable inst' ==? m
where inst' = Instance.setMovable inst m
testSuite "HTools/Instance"
[ 'prop_creat
, 'prop_setIdx
, 'prop_setName
, 'prop_setAlias
, 'prop_setPri
, 'prop_setSec
, 'prop_setBoth
, 'prop_shrinkMG
, 'prop_shrinkMF
, 'prop_shrinkCG
, 'prop_shrinkCF
, 'prop_shrinkDG
, 'prop_shrinkDF
, 'prop_setMovable
]
|
damoxc/ganeti
|
test/hs/Test/Ganeti/HTools/Instance.hs
|
gpl-2.0
| 7,132 | 0 | 13 | 1,457 | 1,763 | 925 | 838 | 136 | 2 |
module TS.Page.Caesar where
import TS.Logic
import TS.Utils
import TS.App
import Yesod
caesarForm :: Html -> MForm Handler (FormResult CSubmission, Widget)
caesarForm =
renderDivs $ CSubmission
<$> areq (selectFieldList opLst) "Would you like to encrypt or decrypt a message? " Nothing
<*> (unTextarea <$> areq textareaField "Please enter a message: " Nothing)
<*> areq intField "Please enter the message key: " Nothing
caesarSubmitSuccess :: CSubmission -> WidgetT TS IO ()
caesarSubmitSuccess (CSubmission op msg key) = do
let res = pack $ caesarShift (if op then key else negate key) (filterChars $ unpack msg)
[whamlet|
<div .mTheme>
<h1>Result
<p>#{res}
|]
caesarWidget :: (ToWidget TS w,ToMarkup e) => (w, e) -> WidgetT TS IO ()
caesarWidget (widget, enctype) = do
[whamlet|
<div .mTheme>
<div .formTheme>
<h1>Thoughtspread Caesar Encryption Widget
<form method=post action=@{CResultR} enctype=#{enctype}>
^{widget}
<button>Submit
|]
|
Sheerfreeze/thoughtspread
|
TS/Page/Caesar.hs
|
gpl-2.0
| 1,088 | 0 | 14 | 282 | 250 | 134 | 116 | -1 | -1 |
{--
GenReconOS.hs
This file contains all of the necessary functions to generate an executable VHDL model of
an ReconOS FSM description
--}
module GenReconOS where
import LangAST
import Text.PrettyPrint
import Data.List(groupBy,sortBy,intersperse,nub,mapAccumL,find)
import Data.Maybe(catMaybes)
import ExpandMem(addressSig, readEnableSig, writeEnableSig, dataInSig, dataOutSig, getAllDependencies)
import ExpandChannels(elaborateChannelsBody, fullSig, existsSig, channelReadEnableSig, channelWriteEnableSig, channelInSig, channelOutSig)
-- Function used to "nextify" a string
nextify s = s
-- Transforms an expression into a VHDL string
--dispExpr (Mem_access m index p) = text m <> brackets (text index)
dispExpr (Mem_access m index p) = text m <> brackets (dispExpr index)
dispExpr (Var_access t) = text (unvar t)
dispExpr (Channel_access t) = text "#" <> text t
dispExpr (Channel_check_full t) = text (fullSig t)
dispExpr (Channel_check_exists t) = text (existsSig t)
dispExpr (Const_access a) = dispConst a
dispExpr (UnaryOp s a) = text s <+> (dispExpr a)
dispExpr (BinaryOp s a b) = (dispExpr a) <+> text s <+> (dispExpr b)
dispExpr (FuncApp s args) = (text s) <> parens (hcat (punctuate comma (map dispExpr args)))
dispExpr (ParensExpr e) = text "(" <+> (dispExpr e) <+> text ")"
-- Transforms an expression into a VHDL string
expr2string (Mem_access m index p) = text m <> (expr2string index)
expr2string (Var_access t) = text (unvar t)
expr2string (Channel_access t) = text "chan" <> text t
expr2string (Channel_check_full t) = text (fullSig t)
expr2string (Channel_check_exists t) = text (existsSig t)
expr2string (Const_access a) = const2string a
expr2string (UnaryOp s a) = text s <> (expr2string a)
expr2string (BinaryOp s a b) = (expr2string a) <> text s <> (expr2string b)
expr2string (FuncApp s args) = (text s) <> (hcat (punctuate (text "_") (map expr2string args)))
expr2string (ParensExpr e) = text "p_" <> (expr2string e) <> text "_p"
-- Transforms all the types of VHDL constants to a string for use in code generation
dispConst (V_integer i) = integer i
dispConst (V_tick c) = quotes (char c)
dispConst (V_binary_quote c) = doubleQuotes (text c)
dispConst (V_hex_quote c) = text "x" <> doubleQuotes (text c)
dispConst (V_hex_quote2 c) = text "X" <> doubleQuotes (text c)
const2string (V_integer i) = integer i
const2string (V_tick c) = (char c)
const2string (V_binary_quote c) = (text c)
const2string (V_hex_quote c) = text "x" <> (text c)
-- Function: getStates
-- Purpose: get a list of all of the states in a machine
getStates :: [Node] -> [String]
getStates trans = nub $ concatMap getState trans
where getState (TRANS_DECL from to _ _) = [from,to]
-- Function: getReverseTranstitions
-- Purpose: get a list of all of the transitions in a machine in reversed tuple form (to,from)
getReverseTransitions trans = map getTs trans
where getTs (TRANS_DECL from to _ _) = (to, from)
-- Function: getTranstitions
-- Purpose: get a list of all of the transitions in a machine in tuple form (from,to)
getTransitions trans = map getTs trans
where getTs (TRANS_DECL from to _ _) = (from, to)
genReachabilityTable initialState ts =
let all_states = (getStates ts)
reachabilityTable = (gatherReachability all_states (getTransitions ts))
(transitive_closure,root_reachable) = tclose reachabilityTable initialState
in
unlines $ [
"**** Unreachable States: ****",
unlines (displayUnreachable initialState all_states root_reachable),
--"**** Transitive Closure: ****",
--(displayReachability transitive_closure),
--"**** Reachability Table: ****",
--(displayReachability reachabilityTable),
""
]
displayUnreachable initialState [] tclos = []
displayUnreachable initialState (s:ss) tclos =
if (s /= initialState)
then
case (find (==s) tclos) of
Nothing -> s:(displayUnreachable initialState ss tclos)
Just x -> displayUnreachable initialState ss tclos
else
displayUnreachable initialState ss tclos
tclose states start = let states' = expand states
Just snow = lookup start states
Just snext = lookup start states'
in if snow == snext
then (states',snext)
else tclose states' start
expand states = map exp states
where exp (cur,nexts) = (cur, nub $ nexts ++ (concat $ catMaybes $ map (\v -> lookup v states) nexts))
displayReachability [] = []
displayReachability ((a,t):ts) =
a ++ ":\n" ++ unlines t ++ "\n" ++ (displayReachability ts)
gatherReachability ss all_ts = map (calcReachability [] all_ts) ss
calcReachability acc [] start = (start,(nub acc))
calcReachability acc ((src,dest):ts) start =
if start == src && start /= dest
then
(calcReachability (dest:acc) ts start )
else
(calcReachability acc ts start)
-- Function: genStateEnum
-- Purpose: Generate the contents of the state enumeration type
genStateEnum :: [Node] -> String
genStateEnum ts = concat $ intersperse ",\n" (getStates ts)
-- Function: untype
-- Purpose: Converts a VHDL type container into a string
untype (STLV s a b) =
let a' = render $ dispExpr a
b' = render $ dispExpr b in
s++"("++a'++" to "++b'++")"
untype (STL s ) = s
-- Function: unvar
-- Purpose: Converts a VHDL var access into a string
--unvar (VarSelRange s a b) = s++"("++show a++" to "++show b++")"
--unvar (VarSelBit s a) = s++"("++show a++")"
--unvar (JustVar s ) = s
unvar (VarSelRange s a b) =
let a' = render $ dispExpr a
b' = render $ dispExpr b in
s++"("++a'++" to "++b'++")"
unvar (VarSelBit s a) =
let a' = render $ dispExpr a in
s++"("++a'++")"
unvar (JustVar "ALL_ZEROS") = "(others => '0')"
unvar (JustVar "ALL_ONES") = "(others => '1')"
unvar (JustVar s ) = s
-- Function: genSigResets
-- Purpose: Generates a set of assignment statements to reset all FSM sigs to zero(s)
genSigResets ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++n++(resetSig t)
-- Function: genSigTrans
-- Purpose: Generates a set of assignment statements to transition all FSM sigs to their next state
genSigTrans ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++n++" <= "++ (nextify n) ++";\n"
-- Function: genSigStay
-- Purpose: Generates a set of assignment statements to transition all FSM sigs to their same state
genSigStay ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++n++" <= "++ (n) ++";\n"
-- Function: genSigDefaults
-- Purpose: Generates a set of assignment statements to assign default values for each FSM signal
genSigDefaults ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++ (nextify n)++" <= "++n++";\n"
-- Function: resetSig
-- Purpose: Converts a VHDL type container into an assignment statement used during reset (assignment to zero)
resetSig (STLV s a b) = " <= (others => '0');\n"
resetSig (STL "integer" ) = " <= 0;\n"
resetSig (STL "INTEGER" ) = " <= 0;\n"
resetSig (STL "Integer" ) = " <= 0;\n"
resetSig (STL s ) = " <= '0';\n"
-- Function: genBody
-- Purpose: Generates the body of the FSM (each "when" clause and it's associated transitions)
-- ns = next state signal
-- l = original list of transitions
genBody :: String -> [Node] -> String
genBody ns ts = render $ nest 8 $ vcat $ map (genState ns) groups
where groups = groupBy grouping $ sortBy sorting ts
sorting (TRANS_DECL s _ _ _) (TRANS_DECL s' _ _ _) = compare s s'
grouping (TRANS_DECL s _ _ _) (TRANS_DECL s' _ _ _) = s == s'
-- Old version
-- Generates if-endifs
-- genState generates a 'when' clause for a set of state originating in the same
-- start state
{-genState ns ts@((TRANS_DECL start _ _ _):_) =
text "when" <+> text start <+> text "=>" $$
nest 2 (vcat (map (genTrans ns) ts))
-}
-- New version
-- Generates if-elseif-else-endifs
genState ns ts@((TRANS_DECL start _ _ _):_) =
text "when" <+> text start <+> text "=>" $$
nest 2 ((genSuperTrans start ns ts))
-- genTrans generates the signal assignments for a given transition
genTrans ns (TRANS_DECL _ end NoGuard body) =
vcat (map genAssign body) $$
text ns <+> text "<=" <+> text end <> text ";"
genTrans ns (TRANS_DECL _ end (Guard guard) body) =
text "if" <+> dispExpr guard <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text "<=" <+> text end <> text ";") $$
text "end if;"
genVTrans ns (TRANS_DECL _ end NoGuard body) =
vcat (map genAssign body) $$
text ns <+> text ":=" <+> text end <> text ";"
genVTrans ns (TRANS_DECL _ end (Guard guard) body) =
text "if" <+> dispExpr guard <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text ":=" <+> text end <> text ";") $$
text "end if;"
unguardedCheck acc [] = acc
unguardedCheck acc ((TRANS_DECL _ _ g _):ts) =
case g of
NoGuard -> (unguardedCheck (acc+1) ts)
_ -> (unguardedCheck acc ts)
genSuperTrans start ns ts =
if ((unguardedCheck 0 ts) > 1)
then
error $ "Invalid FSM - state has more than one un-guarded transition! ("++start++")"
else
case ts of
(a:[]) -> (genVTrans ns a)
ts@(a:as) -> (genVIfElses ns 0 (sortBy sorting ts))
-- Function used to make sure that "un-guarded transitions are always last
where sorting (TRANS_DECL _ _ g1 _) (TRANS_DECL _ _ g2 _) =
case g1 of
NoGuard -> case g2 of
NoGuard -> EQ
_ -> GT
_ -> EQ
genIfElses ns acc [] = text "end if;"
genIfElses ns acc ((TRANS_DECL _ end guard body):[]) =
if acc == 0
then
text "if" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text "<=" <+> text end <> text ";") $$
(genIfElses ns (acc+1) [])
else
(prefixGuard guard) $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text "<=" <+> text end <> text ";") $$
(genIfElses ns (acc+1) [])
genIfElses ns acc ((TRANS_DECL _ end guard body):ts) =
if acc == 0
then
text "if" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text "<=" <+> text end <> text ";") $$
(genIfElses ns (acc+1) ts)
else
text "elsif" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text "<=" <+> text end <> text ";") $$
(genIfElses ns (acc+1) ts)
genVIfElses ns acc [] = text "end if;"
genVIfElses ns acc ((TRANS_DECL _ end guard body):[]) =
if acc == 0
then
text "if" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text ":=" <+> text end <> text ";") $$
(genVIfElses ns (acc+1) [])
else
(prefixGuard guard) $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text ":=" <+> text end <> text ";") $$
(genVIfElses ns (acc+1) [])
genVIfElses ns acc ((TRANS_DECL _ end guard body):ts) =
if acc == 0
then
text "if" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text ":=" <+> text end <> text ";") $$
(genVIfElses ns (acc+1) ts)
else
text "elsif" <+> (checkGuard guard) <+> text "then" $$
nest 2 ((vcat (map genAssign body)) $$
text ns <+> text ":=" <+> text end <> text ";") $$
(genVIfElses ns (acc+1) ts)
checkGuard NoGuard = text "(true)"
checkGuard (Guard g) = dispExpr g
prefixGuard NoGuard = text "else"
prefixGuard x@(Guard g) = text "elsif" <+> (checkGuard x) <+> text "then"
-- genAssign generates the signal assignment for a statement
genAssign (Assign_stmt l r) = (dispExpr l) <+> text "<=" <+> (dispExpr r) <> text ";"
genAssign (VAssign_stmt l r) = (dispExpr l) <+> text ":=" <+> (dispExpr r) <> text ";"
genAssign (Func_stmt a) = (dispExpr a) <> text ";"
-- Function: genPorts
-- Purpose: Generates port definition strings
genPorts ps = concatMap gp ps
where gp (PORT_DECL n d t) = "\t"++n++" : "++d++" "++(untype t)++";\n"
-- Function: genGenerics
-- Purpose: Generates generic definition strings
genGenerics [] = ""
--genGenerics ps = "generic(\n"++concatMap gp ps++"\n);"
genGenerics ps =
"generic(\n"
++(concat $ intersperse ";\n" $ map gp ps)
++"\n);"
where gp (GENERIC_DECL n t v) = "\t"++n++" : "++(untype t)++" := "++(render (dispConst v))
-- Function: genGenericMPD
genGenericMPD as = concatMap gg as
where gg (GENERIC_DECL n t v) = "PARAMETER "++n++" = "++(render (dispConst v))++", DT = "++(untype t)++"\n"
memNameMPD n = n++"_PORT"
channelNameMasterMPD n = n++"_MASTER"
channelNameSlaveMPD n = n++"_SLAVE"
-- Function: genMemoryMPD
genMemoryMPD as = concatMap gg as
where gg (MEM_DECL n t s InternalMem) = ""
gg (MEM_DECL n t s ExternalMem) =
let s' = render $ dispExpr s
t' = render $ dispExpr t in
unlines [
"BUS_INTERFACE BUS = "++(memNameMPD n)++", BUS_STD = XIL_BRAM, BUS_TYPE = INITIATOR",
"PORT "++(addressSig n 0)++" = BRAM_Addr, DIR = O, VEC=[0:("++s'++" - 1)], BUS = "++(memNameMPD n),
"PORT "++(dataInSig n 0)++" = BRAM_Dout, DIR = O, VEC=[0:("++t'++" - 1)], BUS = "++(memNameMPD n),
"PORT "++(dataOutSig n 0)++" = BRAM_Din, DIR = I, VEC=[0:("++t'++" - 1)], BUS = "++(memNameMPD n),
"PORT "++(readEnableSig n 0)++" = BRAM_En, DIR = O, BUS = "++(memNameMPD n),
"PORT "++(writeEnableSig n 0)++" = BRAM_WEN, DIR = O, BUS = "++(memNameMPD n),
""
]
-- Function : genChannelMPD
genChannelMPD as = concatMap gg as
where gg (CHANNEL_DECL n e) =
let e' = render $ dispExpr e in
unlines [
"BUS_INTERFACE BUS = "++(channelNameMasterMPD n)++", BUS_STD = FSL, BUS_TYPE = MASTER",
"BUS_INTERFACE BUS = "++(channelNameSlaveMPD n)++", BUS_STD = FSL, BUS_TYPE = SLAVE",
"PORT "++(channelInSig n)++" = FSL_M_Data, DIR = O, VEC=[0:("++e'++" - 1)], BUS = "++(channelNameMasterMPD n),
"PORT "++(channelOutSig n)++" = FSL_S_Data, DIR = I, VEC=[0:("++e'++" - 1)], BUS = "++(channelNameSlaveMPD n),
"PORT "++(existsSig n)++" = FSL_S_Exists, DIR = I, BUS = "++(channelNameSlaveMPD n),
"PORT "++(fullSig n)++" = FSL_M_Full, DIR = I, BUS = "++(channelNameMasterMPD n),
"PORT "++(channelReadEnableSig n)++" = FSL_S_Read, DIR = O, BUS = "++(channelNameSlaveMPD n),
"PORT "++(channelWriteEnableSig n)++" = FSL_M_Write, DIR = O, BUS = "++(channelNameMasterMPD n),
"\t"
]
-- Function : genPortMPD
genPortMPD as = concatMap gg as
where gg (PORT_DECL n d t) = "PORT "++n++" = \"\", DIR = "++(genDirMPD d)++" "++(genTypeMPD t)++"\n"
genDirMPD d = d
genTypeMPD (STL s) = ""
genTypeMPD (STLV s a b) =
let a' = render $ dispExpr a
b' = render $ dispExpr b in
", VEC = ["++a'++":"++b'++"]"
genMemPorts ms = concatMap f ms
where f (MEM_DECL n t s InternalMem) = ""
f (MEM_DECL "local_ram" t s ExternalMem) = ""
f (MEM_DECL n t s ExternalMem) =
let s' = render $ dispExpr s
t' = render $ dispExpr t in
unlines [
"\t"++(addressSig n 0)++" : out std_logic_vector(0 to ("++s'++" - 1));",
"\t"++(dataInSig n 0)++" : out std_logic_vector(0 to ("++t'++" - 1));",
"\t"++(dataOutSig n 0)++" : in std_logic_vector(0 to ("++t'++" - 1));",
"\t"++(readEnableSig n 0)++" : out std_logic;",
"\t"++(writeEnableSig n 0)++" : out std_logic;"
]
genChannelPorts ms = concatMap f ms
where f (CHANNEL_DECL n e) =
let e' = render $ dispExpr e in
unlines [
"\t"++(channelInSig n)++" : out std_logic_vector(0 to ("++e'++" - 1));",
"\t"++(channelOutSig n)++" : in std_logic_vector(0 to ("++e'++" - 1));",
"\t"++(existsSig n)++" : in std_logic;",
"\t"++(fullSig n)++" : in std_logic;",
"\t"++(channelReadEnableSig n)++" : out std_logic;",
"\t"++(channelWriteEnableSig n)++" : out std_logic;"
]
-- Function: genPermanentConnections
-- Purpose: Generate permanent connections
genPermanentConnections ss = concatMap sp ss
where sp (CONNECTION_DECL a) = case (getAllDependencies [a]) of
[] -> render $ genAssign a <+> text "\n"
(x:xs) -> error $ ("Connections cannot contain memory accesses! Error in:\n"++ (render (genAssign a)))
-- Function: genMemorySigDefs
-- Purpose: Generate signal definition strings for the memories
genMemorySigDefs ss = concatMap sp ss
where sp (MEM_DECL n t s ExternalMem) = ""
sp (MEM_DECL n t s InternalMem) =
let s' = render $ dispExpr s
t' = render $ dispExpr t in
unlines [ "-- **************************",
"-- BRAM Signals for "++n,
"-- **************************",
"signal "++(addressSig n 0)++" : std_logic_vector(0 to ("++s'++" - 1));",
"signal "++(dataInSig n 0)++" : std_logic_vector(0 to ("++t'++" - 1));",
"signal "++(dataOutSig n 0)++" : std_logic_vector(0 to ("++t'++" - 1));",
"signal "++(readEnableSig n 0)++" : std_logic;",
"signal "++(writeEnableSig n 0)++" : std_logic;",
"signal "++(addressSig n 1)++" : std_logic_vector(0 to ("++s'++" - 1));",
"signal "++(dataInSig n 1)++" : std_logic_vector(0 to ("++t'++" - 1));",
"signal "++(dataOutSig n 1)++" : std_logic_vector(0 to ("++t'++" - 1));",
"signal "++(readEnableSig n 1)++" : std_logic;",
"signal "++(writeEnableSig n 1)++" : std_logic;",
""
]
-- Function: genMemoryInstantiations
-- Purpose: Generate instantiations for each individual BRAM
genMemoryInstantiations ss = concatMap sp ss
where sp (MEM_DECL n t s ExternalMem) = ""
sp (MEM_DECL n t s InternalMem) =
let s' = render $ dispExpr s
t' = render $ dispExpr t in
unlines [ n++"_BRAM : infer_bram",
"generic map (",
" ADDRESS_BITS => "++s'++",",
" DATA_BITS => "++t',
")",
"port map (",
" CLKA => clk,",
" ENA => "++(readEnableSig n 0)++",",
" WEA => "++(writeEnableSig n 0)++",",
" ADDRA => "++(addressSig n 0)++",",
" DIA => "++(dataInSig n 0)++",",
" DOA => "++(dataOutSig n 0)++",",
" CLKB => clk,",
" ENB => "++(readEnableSig n 1)++",",
" WEB => "++(writeEnableSig n 1)++",",
" ADDRB => "++(addressSig n 1)++",",
" DIB => "++(dataInSig n 1)++",",
" DOB => "++(dataOutSig n 1),
");",
""
]
-- Function: genMemDefaults
-- Purpose: Generates a set of assignment statements to assign default values for each memory (BRAM signal)
genMemDefaults ss = concatMap sp ss
where sp (MEM_DECL n t s ExternalMem) = unlines [
"\t"++(addressSig n 0)++" <= (others => '0');",
"\t"++(dataInSig n 0)++" <= (others => '0');",
"\t"++(readEnableSig n 0)++" <= '0';",
"\t"++(writeEnableSig n 0)++" <= '0';",
"\t"
]
sp (MEM_DECL n t s InternalMem) = unlines [
"\t"++(addressSig n 0)++" <= (others => '0');",
"\t"++(dataInSig n 0)++" <= (others => '0');",
"\t"++(readEnableSig n 0)++" <= '0';",
"\t"++(writeEnableSig n 0)++" <= '0';",
"\t"++(addressSig n 1)++" <= (others => '0');",
"\t"++(dataInSig n 1)++" <= (others => '0');",
"\t"++(readEnableSig n 1)++" <= '0';",
"\t"++(writeEnableSig n 1)++" <= '0';",
""
]
-- Function: genChannelDefaults
-- Purpose: Generates a set of assignment statements to assign default values for each channel
genChannelDefaults ss = concatMap sp ss
where sp (CHANNEL_DECL n _) = unlines [
"\t"++(channelInSig n)++" <= (others => '0');",
"\t"++(channelReadEnableSig n)++" <= '0';",
"\t"++(channelWriteEnableSig n)++" <= '0';",
""
]
-- Function: genSigDefs
-- Purpose: Generate signal definition strings
genSigDefs ss = concatMap sp ss
where sp (FSM_SIG n t) = "signal "++n++" : "++(untype t)++";\n"
-- Function: genVarDefs
-- Purpose: Generate variable definition strings
genVarDefs ss = concatMap sp ss
where sp (VAR_DECL n t) = "\t\t"++"variable "++n++" : "++(untype t)++";\n"
-- Function: genSyncSensitivity
-- Purpose: Generate sensitivity list for synchronous FSM process (only the FSM SIGs)
genSyncSensitivity ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++(nextify n)++",\n"
-- Function: genCombSensitivity
-- Purpose: Generate sensitivity list for combinational FSM process (only the FSM SIGs)
genCombSensitivity ss = concatMap sp ss
where sp (FSM_SIG n t) = "\t\t"++n++",\n"
-- Function: genMemSensitivity
-- Purpose: Generate sensitivity list for combinational FSM process for memory (BRAM) signals
genMemSensitivity ss = concatMap sp ss
where sp (MEM_DECL n t s InternalMem) = "\t\t"++(dataOutSig n 0)++","++" "++(dataOutSig n 1)++",\n"
sp (MEM_DECL n t s ExternalMem) = "\t\t"++(dataOutSig n 0)++",\n"
-- Function: genChannelSensitivity
-- Purpose: Generate sensitivity list for combinational FSM process for channel (FSL) signals
genChannelSensitivity ss = concatMap sp ss
where sp (CHANNEL_DECL n _) = "\t\t"++(channelOutSig n)++", "++(fullSig n)++", "++(existsSig n)++",\n"
-- Function: genPortSensitivity
-- Purpose: Generate sensitivity list for combinational FSM process for top-level input ports
genPortSensitivity ss = concatMap sp ss
where sp (PORT_DECL n d t) = if (d == "in") then ("\t"++n++",\n") else ""
-- Function that generates an MPD template of the FSM
mpd_template entity_name ports generics mems channels =
unlines [
"BEGIN "++entity_name,
"",
"## Peripheral Options",
"OPTION IPTYPE = PERIPHERAL",
"OPTION IMP_NETLIST = TRUE",
"OPTION HDL = verilog",
"OPTION USAGE_LEVEL = BASE_USER",
"OPTION STYLE = MIX",
"##OPTION CORE_STATE = DEVELOPMENT",
"",
"## Generics:",
(genGenericMPD generics),
"",
"## Memory Interfaces:",
(genMemoryMPD mems),
"",
"## Channel Interfaces:",
(genChannelMPD channels),
"",
"## Ports:",
"PORT clock_sig = \"\", DIR = IN, SIGIS = CLK",
"PORT reset_sig = \"\", DIR = IN, SIGIS = Rst",
(genPortMPD ports),
""
]
-- Function that generates VHDL template of the FSM
-- *******************************************************
-- cs_name = Name of signal for current state
-- ns_name = Name of signal for next state
-- entity_name = Name of entity
-- ports = List of ports from Description AST
-- connections = List of connections from the Description AST
-- mems = List of mems from Description AST
-- transitions = List of transitions from Desription AST
-- initialState = String that represents the initial state to start at
-- signals = List of FSM signals from Description AST
-- signals = List of FSM variables from Description AST
-- vhdl = Big string of default VHDL to insert before architecture begin
-- *******************************************************
template ver cs_name ns_name entity_name ports generics connections mems channels transitions initialState signals variables vhdl =
unlines [
"-- ************************************",
"-- Automatically Generated ReconOS FSM",
"-- " ++ entity_name,
"-- ************************************",
"",
"-- **********************",
"-- Library inclusions",
"-- **********************",
"library ieee;",
"use ieee.std_logic_1164.all;",
"use ieee.numeric_std.all;",
"use ieee.std_logic_unsigned.all;",
"",
"library reconos_" ++ ver ++ ";",
"use reconos_" ++ ver ++ ".reconos_pkg.all;",
"",
"-- **********************",
"-- Entity Definition",
"-- **********************",
"entity " ++ entity_name ++ " is",
(genGenerics generics),
"generic",
"(",
"\t" ++ "C_TASK_BURST_AWIDTH : integer := 11;",
"\t" ++ "C_TASK_BURST_DWIDTH : integer := 32",
");",
"port",
"(",
(genMemPorts mems),
(genChannelPorts channels),
(genPorts ports),
"\t" ++ "clk : in std_logic;",
"\t" ++ "reset : in std_logic;",
"\t" ++ "i_osif : in osif_os2task_t;",
"\t" ++ "o_osif : out osif_task2os_t;",
"",
"\t" ++ "-- burst ram interface",
"\t" ++ "o_RAMAddr : out std_logic_vector( 0 to C_TASK_BURST_AWIDTH-1 );",
"\t" ++ "o_RAMData : out std_logic_vector( 0 to C_TASK_BURST_DWIDTH-1 );",
"\t" ++ "i_RAMData : in std_logic_vector( 0 to C_TASK_BURST_DWIDTH-1 );",
"\t" ++ "o_RAMWE : out std_logic;",
"\t" ++ "o_RAMClk : out std_logic",
"\t" ++ ");",
"end entity " ++ entity_name ++ ";",
"",
"-- *************************",
"-- Architecture Definition",
"-- *************************",
"architecture Behavioral of " ++ entity_name ++ " is",
"",
"\tattribute keep_hierarchy : string;",
"\tattribute keep_hierarchy of Behavioral: architecture is \"true\";",
"",
"-- ****************************************************",
"-- Type definitions for state signals",
"-- ****************************************************",
"type STATE_MACHINE_TYPE is",
"( ",
(genStateEnum transitions),
");",
"signal " ++ cs_name ++ ": STATE_MACHINE_TYPE := " ++ initialState ++ ";",
"signal o_RAMRE : std_logic := '0';",
"",
"-- ****************************************************",
"-- Type definitions for FSM signals",
"-- ****************************************************",
(genSigDefs signals),
(genMemorySigDefs mems),
"-- ****************************************************",
"-- User-defined VHDL Section",
"-- ****************************************************",
(vhdl),
"-- Architecture Section",
"begin",
"",
"\to_RAMClk <= clk;",
"",
"-- ************************",
"-- Permanent Connections",
"-- ************************",
(genPermanentConnections connections),
"",
"-- ************************",
"-- BRAM implementations",
"-- ************************",
(genMemoryInstantiations mems),
"-- ****************************************************",
"-- Process to handle the synchronous portion of an FSM",
"-- ****************************************************",
"RECONOS_FSM_SYNC_PROCESS : process(",
"\tclk, reset) is",
"\t-- done for Reconos methods",
"\tvariable done : boolean;",
"\t-- success for Reconos methods",
"\tvariable success : boolean;",
"\t-- next state",
"\tvariable " ++ ns_name ++ " : STATE_MACHINE_TYPE := " ++ initialState ++ ";",
"\t-- **********************",
"\t-- Variable Definitions",
"\t-- **********************",
(genVarDefs variables),
"begin",
"",
"\tif (reset = '1') then",
(genSigResets signals),
"\t\to_RAMAddr <= (others=>'0');",
"\t\to_RAMData <= (others=>'0');",
"\t\to_RAMWE <= '0';",
"\t\treconos_reset( o_osif, i_osif );",
"\t\t"++cs_name++" <= "++initialState++";",
"\t\t" ++ ns_name ++ " := " ++ initialState ++ ";",
"\t\tdone := false;",
"\telsif (rising_edge(clk)) then",
"",
"\t\to_RAMWE <= '0';",
"",
"\t\treconos_begin( o_osif, i_osif );",
"\t\tif (reconos_ready( i_osif )) then",
"\t\t-- Transition to next state",
"\t\tcase ("++cs_name++") is",
"",
genBody ns_name transitions,
"\t\twhen others => ",
"\t\t\t"++ns_name++" := "++initialState++";",
"",
"\t\t\tend case;",
"\t\t\tif done then",
"\t\t\t\t" ++ cs_name ++ " <= " ++ ns_name ++ ";",
"\t\t\tend if;",
"\t\tend if;",
"\tend if;",
"end process RECONOS_FSM_SYNC_PROCESS;",
"",
"end architecture Behavioral;",
""
]
|
luebbers/reconos
|
tools/fsmLanguage/fpga_scripts/generate_fsm/src/GenReconOS.hs
|
gpl-3.0
| 27,909 | 480 | 17 | 6,508 | 8,442 | 4,345 | 4,097 | 514 | 5 |
{---------------------------------------------------------------------}
{- Copyright 2015 Nathan Bloomfield -}
{- -}
{- This file is part of Feivel. -}
{- -}
{- Feivel is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Feivel 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 Feivel. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
module Feivel.Parse (
module Feivel.Parse.Util,
module Feivel.Parse.Expr,
module Feivel.Parse.Store,
module Feivel.Parse.Format,
module Feivel.Parse.ParseM
) where
import Feivel.Parse.Util
import Feivel.Parse.Expr
import Feivel.Parse.Store
import Feivel.Parse.Format
import Feivel.Parse.ParseM
|
nbloomf/feivel
|
src/Feivel/Parse.hs
|
gpl-3.0
| 1,530 | 0 | 5 | 563 | 90 | 67 | 23 | 11 | 0 |
module Main
where
import Prelude hiding (FilePath)
import Orwell.Analyse
import Orwell.Elastic
import Data.Maybe
import Shelly hiding (find)
import Control.Monad
import System.Console.GetOpt
import System.Environment
import Data.List as L
import Data.Text as T (Text, pack)
data Flag = TestOwner | TestContrib |
ElasticUrlArg {
url :: ElasticServerUrl
} |
Period {
period :: String
} |
Repository {
repo :: String
}
deriving (Show, Eq)
main = shelly $ silently $ do
args <- liftIO $ getArgs
opts <- liftIO $ orwellOpts args
commits <- commitInfos (optionPeriod opts) (optionRepo opts)
when (optionElastic opts) $ do
liftIO $ mapM_ (submitCommitMetaData (optionElasticUrl opts)) commits
when (optionContrib opts) $ do
liftIO $ analyseTestContribution commits
when (optionOwner opts) $ do
analyseTestOwnership (optionRepo opts)
{-
Command-Line Options
-}
orwellOpts :: [String] -> IO [Flag]
orwellOpts args =
case getOpt Permute options args of
(o,[],[] ) -> return o
(_,_,errs) -> ioError (userError (concat errs ++ usageInfo header options))
where header = "Usage: orwell [OPTION...]"
options :: [OptDescr Flag]
options =
[ Option ['p'] ["period"] (ReqArg Period "PERIOD") "Gibt den Zeitraum an, der analysiert werden soll (Git Syntax)"
, Option ['r'] ["repo"] (ReqArg Repository "REPO") "Das zu analysierende Repository"
, Option ['e'] ["elastic"] (ReqArg ElasticUrlArg "URL") "Überträgt die Commit-Daten zusätzlich an den angegebenen Elastic-Server"
, Option ['o'] ["ownership"] (NoArg TestOwner) "Ermittelt die Anzahl Tests und deren Eigentümer im aktuellen HEAD"
, Option ['c'] ["contribution"] (NoArg TestContrib) "Ermittelt die Beiträge pro Entwickler{Woche, Monat, Jahr} zum Testcode für den angegeben Zeitraum (PERIOD)"
]
optionOwner :: [Flag] -> Bool
optionOwner = any (== TestOwner)
optionContrib :: [Flag] -> Bool
optionContrib = any (== TestContrib)
optionElastic :: [Flag] -> Bool
optionElastic = any elasticUrlArgP
optionElasticUrl :: [Flag] -> String
optionElasticUrl = elasticUrlArg.fromJust.(L.find elasticUrlArgP)
optionPeriod :: [Flag] -> String
optionPeriod = period.fromJust.(L.find periodArgP)
optionRepo :: [Flag] -> FilePath
optionRepo = fromText.repoArg.fromJust.(L.find repoArgP)
periodArg :: Flag -> String
periodArg (Period p) = p
elasticUrlArgP :: Flag -> Bool
elasticUrlArgP (ElasticUrlArg _) = True
elasticUrlArgP _ = False
elasticUrlArg :: Flag -> ElasticServerUrl
elasticUrlArg (ElasticUrlArg d) = d
periodArgP :: Flag -> Bool
periodArgP (Period _) = True
periodArgP _ = False
repoArg :: Flag -> T.Text
repoArg (Repository r) = T.pack r
repoArgP :: Flag -> Bool
repoArgP (Repository _) = True
repoArgP _ = False
{-
END Command-Line Options
-}
|
Ragnaroek/orwell
|
src/Main.hs
|
gpl-3.0
| 2,858 | 3 | 16 | 553 | 866 | 464 | 402 | 69 | 2 |
module Log (logHvc) where
import System.IO (withFile, hGetLine, IOMode(..))
import System.Directory (getDirectoryContents)
import Control.Monad (forM, forM_)
import System.FilePath (combine)
import Data.List
import Data.Time.Clock (UTCTime)
import Utils
loadCommitSummary :: FilePath -> IO CommitSummary
loadCommitSummary path = withFile path ReadMode $ \f -> do
line <- hGetLine f
return $ read line
getCommitPaths :: FilePath -> IO [FilePath]
getCommitPaths dir = do
let commitDir = commitsDir dir
commits <- getDirectoryContents commitDir
return $ map (combine commitDir) $ filter (`notElem` [".", ".."]) commits
loadSortedCommits :: [FilePath] -> IO [CommitSummary]
loadSortedCommits paths = do
summaries <- forM paths loadCommitSummary
return $ reverse $ sortOn (\(CommitSummary _ date _) -> read date :: UTCTime) summaries
execLog :: FilePath -> IO ()
execLog dir = do
paths <- getCommitPaths dir
sortedCommits <- loadSortedCommits paths
forM_ sortedCommits $ \(CommitSummary msg date hash) -> do
putStrLn $ "commit " ++ hash
putStrLn $ ">>= date: " ++ date
putStrLn $ ">>= message: " ++ msg
putStrLn ""
logHvc :: FilePath -> IO ()
logHvc dir = execIfHvc dir (execLog dir)
|
federicotdn/hvc
|
src/Log.hs
|
gpl-3.0
| 1,221 | 0 | 12 | 214 | 434 | 220 | 214 | 32 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.QPXExpress.Types.Sum
-- 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)
--
module Network.Google.QPXExpress.Types.Sum where
import Network.Google.Prelude hiding (Bytes)
|
brendanhay/gogol
|
gogol-qpxexpress/gen/Network/Google/QPXExpress/Types/Sum.hs
|
mpl-2.0
| 609 | 0 | 5 | 101 | 35 | 29 | 6 | 8 | 0 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ReplicaPool.Replicas.List
-- 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)
--
-- Lists all replicas in a pool.
--
-- /See:/ <https://developers.google.com/compute/docs/replica-pool/ Replica Pool API Reference> for @replicapool.replicas.list@.
module Network.Google.Resource.ReplicaPool.Replicas.List
(
-- * REST Resource
ReplicasListResource
-- * Creating a Request
, replicasList
, ReplicasList
-- * Request Lenses
, rlPoolName
, rlZone
, rlProjectName
, rlPageToken
, rlMaxResults
) where
import Network.Google.Prelude
import Network.Google.ReplicaPool.Types
-- | A resource alias for @replicapool.replicas.list@ method which the
-- 'ReplicasList' request conforms to.
type ReplicasListResource =
"replicapool" :>
"v1beta1" :>
"projects" :>
Capture "projectName" Text :>
"zones" :>
Capture "zone" Text :>
"pools" :>
Capture "poolName" Text :>
"replicas" :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] ReplicasListResponse
-- | Lists all replicas in a pool.
--
-- /See:/ 'replicasList' smart constructor.
data ReplicasList =
ReplicasList'
{ _rlPoolName :: !Text
, _rlZone :: !Text
, _rlProjectName :: !Text
, _rlPageToken :: !(Maybe Text)
, _rlMaxResults :: !(Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReplicasList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rlPoolName'
--
-- * 'rlZone'
--
-- * 'rlProjectName'
--
-- * 'rlPageToken'
--
-- * 'rlMaxResults'
replicasList
:: Text -- ^ 'rlPoolName'
-> Text -- ^ 'rlZone'
-> Text -- ^ 'rlProjectName'
-> ReplicasList
replicasList pRlPoolName_ pRlZone_ pRlProjectName_ =
ReplicasList'
{ _rlPoolName = pRlPoolName_
, _rlZone = pRlZone_
, _rlProjectName = pRlProjectName_
, _rlPageToken = Nothing
, _rlMaxResults = 500
}
-- | The replica pool name for this request.
rlPoolName :: Lens' ReplicasList Text
rlPoolName
= lens _rlPoolName (\ s a -> s{_rlPoolName = a})
-- | The zone where the replica pool lives.
rlZone :: Lens' ReplicasList Text
rlZone = lens _rlZone (\ s a -> s{_rlZone = a})
-- | The project ID for this request.
rlProjectName :: Lens' ReplicasList Text
rlProjectName
= lens _rlProjectName
(\ s a -> s{_rlProjectName = a})
-- | Set this to the nextPageToken value returned by a previous list request
-- to obtain the next page of results from the previous list request.
rlPageToken :: Lens' ReplicasList (Maybe Text)
rlPageToken
= lens _rlPageToken (\ s a -> s{_rlPageToken = a})
-- | Maximum count of results to be returned. Acceptable values are 0 to 100,
-- inclusive. (Default: 50)
rlMaxResults :: Lens' ReplicasList Int32
rlMaxResults
= lens _rlMaxResults (\ s a -> s{_rlMaxResults = a})
. _Coerce
instance GoogleRequest ReplicasList where
type Rs ReplicasList = ReplicasListResponse
type Scopes ReplicasList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/ndev.cloudman",
"https://www.googleapis.com/auth/ndev.cloudman.readonly",
"https://www.googleapis.com/auth/replicapool",
"https://www.googleapis.com/auth/replicapool.readonly"]
requestClient ReplicasList'{..}
= go _rlProjectName _rlZone _rlPoolName _rlPageToken
(Just _rlMaxResults)
(Just AltJSON)
replicaPoolService
where go
= buildClient (Proxy :: Proxy ReplicasListResource)
mempty
|
brendanhay/gogol
|
gogol-replicapool/gen/Network/Google/Resource/ReplicaPool/Replicas/List.hs
|
mpl-2.0
| 4,697 | 0 | 19 | 1,184 | 651 | 383 | 268 | 101 | 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.Compute.SSLCertificates.Insert
-- 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 SslCertificate resource in the specified project using the
-- data included in the request.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.sslCertificates.insert@.
module Network.Google.Resource.Compute.SSLCertificates.Insert
(
-- * REST Resource
SSLCertificatesInsertResource
-- * Creating a Request
, sslCertificatesInsert
, SSLCertificatesInsert
-- * Request Lenses
, sciRequestId
, sciProject
, sciPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.sslCertificates.insert@ method which the
-- 'SSLCertificatesInsert' request conforms to.
type SSLCertificatesInsertResource =
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"global" :>
"sslCertificates" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SSLCertificate :>
Post '[JSON] Operation
-- | Creates a SslCertificate resource in the specified project using the
-- data included in the request.
--
-- /See:/ 'sslCertificatesInsert' smart constructor.
data SSLCertificatesInsert =
SSLCertificatesInsert'
{ _sciRequestId :: !(Maybe Text)
, _sciProject :: !Text
, _sciPayload :: !SSLCertificate
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SSLCertificatesInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sciRequestId'
--
-- * 'sciProject'
--
-- * 'sciPayload'
sslCertificatesInsert
:: Text -- ^ 'sciProject'
-> SSLCertificate -- ^ 'sciPayload'
-> SSLCertificatesInsert
sslCertificatesInsert pSciProject_ pSciPayload_ =
SSLCertificatesInsert'
{ _sciRequestId = Nothing
, _sciProject = pSciProject_
, _sciPayload = pSciPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
sciRequestId :: Lens' SSLCertificatesInsert (Maybe Text)
sciRequestId
= lens _sciRequestId (\ s a -> s{_sciRequestId = a})
-- | Project ID for this request.
sciProject :: Lens' SSLCertificatesInsert Text
sciProject
= lens _sciProject (\ s a -> s{_sciProject = a})
-- | Multipart request metadata.
sciPayload :: Lens' SSLCertificatesInsert SSLCertificate
sciPayload
= lens _sciPayload (\ s a -> s{_sciPayload = a})
instance GoogleRequest SSLCertificatesInsert where
type Rs SSLCertificatesInsert = Operation
type Scopes SSLCertificatesInsert =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient SSLCertificatesInsert'{..}
= go _sciProject _sciRequestId (Just AltJSON)
_sciPayload
computeService
where go
= buildClient
(Proxy :: Proxy SSLCertificatesInsertResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/SSLCertificates/Insert.hs
|
mpl-2.0
| 4,514 | 0 | 16 | 1,000 | 484 | 292 | 192 | 76 | 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.CloudIOT.Projects.Locations.Registries.Groups.TestIAMPermissions
-- 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)
--
-- Returns permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a NOT_FOUND error.
--
-- /See:/ <https://cloud.google.com/iot Cloud IoT API Reference> for @cloudiot.projects.locations.registries.groups.testIamPermissions@.
module Network.Google.Resource.CloudIOT.Projects.Locations.Registries.Groups.TestIAMPermissions
(
-- * REST Resource
ProjectsLocationsRegistriesGroupsTestIAMPermissionsResource
-- * Creating a Request
, projectsLocationsRegistriesGroupsTestIAMPermissions
, ProjectsLocationsRegistriesGroupsTestIAMPermissions
-- * Request Lenses
, plrgtipXgafv
, plrgtipUploadProtocol
, plrgtipAccessToken
, plrgtipUploadType
, plrgtipPayload
, plrgtipResource
, plrgtipCallback
) where
import Network.Google.CloudIOT.Types
import Network.Google.Prelude
-- | A resource alias for @cloudiot.projects.locations.registries.groups.testIamPermissions@ method which the
-- 'ProjectsLocationsRegistriesGroupsTestIAMPermissions' request conforms to.
type ProjectsLocationsRegistriesGroupsTestIAMPermissionsResource
=
"v1" :>
CaptureMode "resource" "testIamPermissions" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] TestIAMPermissionsRequest :>
Post '[JSON] TestIAMPermissionsResponse
-- | Returns permissions that a caller has on the specified resource. If the
-- resource does not exist, this will return an empty set of permissions,
-- not a NOT_FOUND error.
--
-- /See:/ 'projectsLocationsRegistriesGroupsTestIAMPermissions' smart constructor.
data ProjectsLocationsRegistriesGroupsTestIAMPermissions =
ProjectsLocationsRegistriesGroupsTestIAMPermissions'
{ _plrgtipXgafv :: !(Maybe Xgafv)
, _plrgtipUploadProtocol :: !(Maybe Text)
, _plrgtipAccessToken :: !(Maybe Text)
, _plrgtipUploadType :: !(Maybe Text)
, _plrgtipPayload :: !TestIAMPermissionsRequest
, _plrgtipResource :: !Text
, _plrgtipCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsRegistriesGroupsTestIAMPermissions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plrgtipXgafv'
--
-- * 'plrgtipUploadProtocol'
--
-- * 'plrgtipAccessToken'
--
-- * 'plrgtipUploadType'
--
-- * 'plrgtipPayload'
--
-- * 'plrgtipResource'
--
-- * 'plrgtipCallback'
projectsLocationsRegistriesGroupsTestIAMPermissions
:: TestIAMPermissionsRequest -- ^ 'plrgtipPayload'
-> Text -- ^ 'plrgtipResource'
-> ProjectsLocationsRegistriesGroupsTestIAMPermissions
projectsLocationsRegistriesGroupsTestIAMPermissions pPlrgtipPayload_ pPlrgtipResource_ =
ProjectsLocationsRegistriesGroupsTestIAMPermissions'
{ _plrgtipXgafv = Nothing
, _plrgtipUploadProtocol = Nothing
, _plrgtipAccessToken = Nothing
, _plrgtipUploadType = Nothing
, _plrgtipPayload = pPlrgtipPayload_
, _plrgtipResource = pPlrgtipResource_
, _plrgtipCallback = Nothing
}
-- | V1 error format.
plrgtipXgafv :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions (Maybe Xgafv)
plrgtipXgafv
= lens _plrgtipXgafv (\ s a -> s{_plrgtipXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plrgtipUploadProtocol :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions (Maybe Text)
plrgtipUploadProtocol
= lens _plrgtipUploadProtocol
(\ s a -> s{_plrgtipUploadProtocol = a})
-- | OAuth access token.
plrgtipAccessToken :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions (Maybe Text)
plrgtipAccessToken
= lens _plrgtipAccessToken
(\ s a -> s{_plrgtipAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plrgtipUploadType :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions (Maybe Text)
plrgtipUploadType
= lens _plrgtipUploadType
(\ s a -> s{_plrgtipUploadType = a})
-- | Multipart request metadata.
plrgtipPayload :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions TestIAMPermissionsRequest
plrgtipPayload
= lens _plrgtipPayload
(\ s a -> s{_plrgtipPayload = a})
-- | REQUIRED: The resource for which the policy detail is being requested.
-- See the operation documentation for the appropriate value for this
-- field.
plrgtipResource :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions Text
plrgtipResource
= lens _plrgtipResource
(\ s a -> s{_plrgtipResource = a})
-- | JSONP
plrgtipCallback :: Lens' ProjectsLocationsRegistriesGroupsTestIAMPermissions (Maybe Text)
plrgtipCallback
= lens _plrgtipCallback
(\ s a -> s{_plrgtipCallback = a})
instance GoogleRequest
ProjectsLocationsRegistriesGroupsTestIAMPermissions
where
type Rs
ProjectsLocationsRegistriesGroupsTestIAMPermissions
= TestIAMPermissionsResponse
type Scopes
ProjectsLocationsRegistriesGroupsTestIAMPermissions
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloudiot"]
requestClient
ProjectsLocationsRegistriesGroupsTestIAMPermissions'{..}
= go _plrgtipResource _plrgtipXgafv
_plrgtipUploadProtocol
_plrgtipAccessToken
_plrgtipUploadType
_plrgtipCallback
(Just AltJSON)
_plrgtipPayload
cloudIOTService
where go
= buildClient
(Proxy ::
Proxy
ProjectsLocationsRegistriesGroupsTestIAMPermissionsResource)
mempty
|
brendanhay/gogol
|
gogol-cloudiot/gen/Network/Google/Resource/CloudIOT/Projects/Locations/Registries/Groups/TestIAMPermissions.hs
|
mpl-2.0
| 6,860 | 0 | 16 | 1,409 | 788 | 463 | 325 | 126 | 1 |
module HTTP.Form.Data
( FormData(..)
) where
import Control.Applicative ((<|>))
import qualified Data.Aeson as JSON
import qualified Data.ByteString as BS
import qualified Data.Map.Strict as Map
import Network.Wai.Parse (FileInfo)
data FormData a = FormData
{ formDataQuery :: Map.Map BS.ByteString (Maybe BS.ByteString)
, formDataPost :: Map.Map BS.ByteString BS.ByteString
, formDataJSON :: Maybe JSON.Value
, formDataFiles :: Map.Map BS.ByteString (FileInfo a)
}
instance Monoid (FormData a) where
mempty = FormData mempty mempty Nothing mempty
mappend (FormData q1 p1 j1 f1) (FormData q2 p2 j2 f2) =
FormData (mappend q1 q2) (mappend p1 p2) (j1 <|> j2) (mappend f1 f2)
|
databrary/databrary
|
src/HTTP/Form/Data.hs
|
agpl-3.0
| 699 | 0 | 12 | 121 | 248 | 140 | 108 | 16 | 0 |
module Linguisticks.Parser where
import Linguisticks.Util ( P
, maybeP
, zeroState
, primaryStress
, secondaryStress
, Syllables ( Syllables )
, SyllState ( nextStress )
, Stress ( NoStress, Secondary, Primary )
)
import Text.ParserCombinators.Parsec
import Data.Maybe ( isJust, fromMaybe, fromJust, isNothing, catMaybes )
import Debug.Trace ( trace )
import Control.Monad ( join )
-- Some example transcriptions
trousers = "trˈaʊzəz"
improvements = "ɪmprˈuːvmənts"
glimpsed = "glˈɪmpst"
table = "tɛɪbɫ̩"
rhythm = "rɪðm̩"
-- ONSETS SECTION
singleOnsets = ["p", "b", "t", "d", "k", "g", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "ʧ", "ʤ", "m", "n", "l", "r", "w", "j", "h"]
doubleOnsets = ["pl", "pr", "pj", "bl", "br", "bj", "tr", "tj", "tw", "dr", "dj", "dw", "kl", "kr", "kj", "kw", "gl", "gr", "gj", "gw", "mj", "nj", "fl", "fr", "fj", "vj", "θr", "θj", "θw", "sl", "sj", "sw", "sp", "st", "sk", "sm", "sn", "ʃr", "hj", "lj"]
tripleOnsets = ["spl", "spr", "spj", "str", "stj", "skl", "skr", "skj", "skw"]
validOnsets :: [[Char]]
validOnsets = tripleOnsets ++ doubleOnsets ++ singleOnsets ++ [""]
-- NUCLEI SECTION
syllabicConsonants = ["ɫ̩", "n̩", "m̩", "r̩"]
dipthongs = ["ɛɪ", "aɪ", "ɔɪ", "əʊ", "aʊ", "iə", "ɛə", "uə", "eɪ", "ɑɪ", "ʌʊ", "oʊ", "ɛʊ", "eʊ", "eə", "ʊə", "ɪə"]
longVowels = ["iː", "ɑː", "ɔː", "uː", "ɜː", "eː", "oː", "ɪː"]
shortVowels = ["ɪ", "ɛ", "a", "ʌ", "ɒ", "ʊ", "ə", "i", "e", "o", "u", "ɔ"]
validNuclei :: [[Char]]
validNuclei = syllabicConsonants ++ dipthongs ++ longVowels ++ shortVowels
validNucleiParsers :: [P String]
validNucleiParsers = map (try . string) validNuclei
-- CODAS SECTION
singleCodas = ["p", "b", "t", "d", "k", "g", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "ʧ", "ʤ", "m", "n", "ŋ", "l", "r"]
doubleCodas = ["pt", "pθ", "ps", "tθ", "ts", "kt", "ks", "kθ", "bd", "bz", "dz", "gd", "gz", "ʧt", "ʤd", "mp", "md", "mf", "mθ", "mz", "nt", "nd", "nʧ", "nʤ", "nθ", "ns", "nz", "ŋd", "ŋk", "ŋz", "ŋθ", "lp", "lt", "lk", "lb", "ld", "lʧ", "lʤ", "lm", "ln", "lf", "lv", "lθ", "ls", "lz", "lʃ", "ft", "fθ", "fs", "vd", "vz", "θt", "θs", "ðd", "ðz", "sp", "st", "sk", "zd", "ʃt", "ʒd", "rp", "rb", "rt", "rd", "rt", "rʧ", "rʤ", "rk", "rg", "rm", "rn", "rl"]
tripleCodas = ["pts", "pst", "pθs", "tst", "tθs", "dst", "kts", "kst", "ksθ", "kθs", "mpt", "mps", "mfs", "ntθ", "nts", "ndz", "nʧt", "nʤd", "nθs", "nst", "nzd", "ŋkt", "ŋkθ", "ŋks", "lpt", "lps", "lts", "lkt", "lks", "lbz", "ldz", "lʧt", "lʤd", "lmd", "lmz", "lnz", "lfs", "lfθ", "lvd", "lvz", "lθs", "lst", "fts", "fθs", "spt", "sps", "sts", "skt", "sks", "rmθ", "rpt", "rps", "rts", "rst", "rkt"]
quadCodas = ["mpts", "mpst", "lkts", "lpts", "lfθs", "ksts", "ksθs", "ntθs"]
validCodas :: [[Char]]
validCodas = [""] ++ singleCodas ++ doubleCodas ++ tripleCodas ++ quadCodas
-- Convenience functions for the parser and representations
parseSyllables :: String -> Either ParseError Syllables
parseSyllables s = runParser (maybeP syllables) zeroState "" s
traceParser :: String -> P ()
traceParser prefix = do st <- getState
input <- getInput
let output = prefix ++ ": " ++ show input ++ " " ++ show st
trace output $ return ()
-- THE PARSER
stressString :: String -> P String
stressString = let setStress c | c == primaryStress = updateState $ \s -> s { nextStress = Primary }
| c == secondaryStress = updateState $ \s -> s { nextStress = Secondary }
| otherwise = fail "stress setting went wrong. this is a bug."
checkStress :: P ()
checkStress = do optionMaybe $ do s <- char primaryStress <|> char secondaryStress
setStress s
return ()
parseString :: String -> P String
parseString "" = do checkStress
return ""
parseString (s:ss) = do checkStress
char s
rest <- parseString ss
return (s:rest)
in parseString
popStress :: P Stress
popStress = do stress <- fmap nextStress getState
updateState $ \s -> s { nextStress = NoStress }
return stress
syllables :: P (Maybe Syllables)
syllables = (fmap Just $ onset) <|> (eof >> return Nothing)
onset :: P Syllables
onset = let onset' ons = try $ do stressString ons
nucleus ons
in choice $ map onset' validOnsets
nucleus :: String -> P Syllables
nucleus ons = do nuc <- choice validNucleiParsers
stress <- popStress
coda ons nuc stress
coda :: String -> String -> Stress -> P Syllables
coda ons nuc stress = let coda' cod = try $ do stressString cod
next <- syllables
return $ Syllables ons nuc cod stress next
in choice $ map (coda') validCodas
|
jmacmahon/syllabify
|
Linguisticks/Parser.hs
|
agpl-3.0
| 5,470 | 0 | 16 | 1,675 | 1,753 | 1,026 | 727 | 79 | 2 |
{-|
Module : HackerRank.Utilities.Manager
Description : Exposes Manager.
License : Unlicense
Stability : experimental
Portability : POSIX
Re-exposes Manager
-}
module HackerRank.Utilities (
-- * Modules
module HackerRank.Utilities.Manager
) where
import HackerRank.Utilities.Manager
|
oopsno/hrank
|
src/HackerRank/Utilities.hs
|
unlicense
| 303 | 0 | 5 | 52 | 23 | 16 | 7 | 3 | 0 |
module IO.Step where
import Data.Const
import Data.World
import Data.Define
import Data.Monster (units)
import Utils.Changes
import Utils.Monsters
import Utils.Step
import Utils.Items
import Items.Items
import Items.ItemsOverall
import Items.Craft
import Monsters.Move
import Monsters.AI (runAI)
import Monsters.AIrepr
import IO.Messages
import IO.Colors
import IO.Texts
import IO.Show(castEnum)
import Data.Set (empty)
import Data.Maybe (isJust, fromMaybe)
import System.Random (randomR)
import Data.Char (isSpace)
import Data.Functor ((<$>))
import qualified Data.Map as M
-- | gives XP level of the player
playerLevel :: World -> Int
playerLevel w = intLog $ xp player where
player = snd . head $ M.toList $ M.filter (("You" ==) . name) $ units w
-- | converts a char from the player to some action or end of game
step :: World -> Char -> Either World (Exit, World)
step world c
| alive mon =
if isPlayerNow world
then case action world of
AfterSpace -> justStep c stun world
Move -> justStep c stun world
Quaff -> doIfCorrect $ quaffFirst c world
Read -> doIfCorrect $ readFirst c world
Zap2 -> doIfCorrect $ zapFirst c world
Fire2 -> doIfCorrect $ fireFirst c world
Use2 -> doIfCorrect $ useFirst c world
Drop -> doIfCorrect $ dropFirst c world False
Bind -> doIfCorrect $ bindFirst c world
Eat -> doIfCorrect $ eatFirst c world
Craft -> doIfCorrect $ craftByChar c world
Zap1 -> Left $ addDefaultMessage msgAskDir world
{prevAction = c, action = Zap2}
SetTrap ->
if c == '-'
then doIfCorrect $ untrapFirst world
else doIfCorrect $ trapFirst c world
Fire1 -> Left $ addDefaultMessage msgAskDir world
{prevAction = c, action = Fire2}
Use1 -> Left $ addDefaultMessage msgAskDir world
{prevAction = c, action = Use2}
Inventory ->
if isSpace c || c == '\ESC'
then Left $ world {action = Move}
else Left world
DropMany ->
if isSpace c
then Left $ fromMaybe (world {action = Move, chars = empty})
$ changeChar c <$> dropManyFirst world
else Left $ changeChar c world
Pick ->
if isSpace c
then case pickFirst world of
(Nothing, s) -> Left $ addDefaultMessage s
world {action = Move, chars = empty}
(Just pick, _) -> Left $ newWaveIf pick
else Left $ changeChar c world
Equip
| isSpace c -> Left world {action = Bind}
| c == '\ESC' -> Left world {action = Move}
| otherwise -> case dir c of
Nothing -> Left world
Just (dx, dy) -> Left $ changeSlotOn dx
$ changeShiftOn dy world
Call ->
if c == 'y' || c == 'Y'
then Left $ callUpon world
else Left world {action = Move}
Split1 -> Left $ addDefaultMessage msgPutSize world
{prevAction = c, numToSplit = 0, action = Split2}
Split2 ->
if isSpace c
then Left $ splitFirst world {action = Move}
else Left $ addNumber c world
Info ->
if c == '.'
then Left $ getInfo world
else case dir c of
Nothing -> Left world
Just (dx, dy) -> Left $ world {xInfo = xInfo world + dx,
yInfo = yInfo world + dy}
Options -> Left $ (case c of
'a' -> world {colorHeight = Absolute}
'b' -> world {colorHeight = Relative}
'c' -> world {colorHeight = NoColor}
'd' -> world {symbolHeight = Numbers}
'e' -> world {symbolHeight = SymbolHeight $ castEnum '.'}
'f' -> world {symbolHeight = SymbolHeight filledSquare}
_ -> world {message = [(msgUnkOpt, defaultc)]}) {action = Move}
Save -> Right (ExitSave, world)
_ -> putWE $ "step: action = " ++ show (action world)
else
let newMWorld = runAI aiNow x y peace world
in Left $ newWaveIf newMWorld
| name mon == "You" =
Right (Die (wave world - 1) (playerLevel world), world)
| otherwise =
let (deadMonster, newStdGen) = addDeathDrop mon (stdgen world)
in Left $ remFirst $ dropAll $ changeMon deadMonster
$ addMessage (name mon ++ " die!", cyan) world {stdgen = newStdGen}
where
stun = (isJust (temp mon !! fromEnum Stun) ||
isJust (temp mon !! fromEnum Conf) && 5*p > 1) &&
canWalk mon
p :: Float
(p, g) = randomR (0.0, 1.0) $ stdgen world
mon = getFirst world
AI aiNow = if stun then AI $ getPureAI RandomAI else ai mon
(xR, g1) = randomR (0, maxX) g
(yR, _) = randomR (0, maxY) g1
(x, y, peace) = case closestPlayerChar (xFirst world)
(yFirst world) world of
Just (xP, yP) -> (xP, yP, False)
Nothing -> (xR, yR, True)
-- | case when action is just move
justStep :: Char -> Bool -> World -> Either World (Exit, World)
justStep c stun world = case dir c of
Just (dx, dy) -> doIfCorrect $ moveFirst dx' dy' world {stdgen = g'} where
(px, g) = randomR (-1, 1) $ stdgen world
(py, g') = randomR (-1, 1) g
(dx', dy') = if stun then (px, py) else (dx, dy)
Nothing ->
if isSpace c then Left $ world {action = AfterSpace} else case c of
'D' -> Left world {action = DropMany}
'i' -> Left world {action = Inventory}
',' -> Left world {action = Pick}
'S' -> Left world {action = Save}
'P' -> Left world {action = Previous}
'&' -> Left world {action = Craft}
'O' -> Left world {action = Options}
'Q' -> Right (ExitQuit (wave world - 1) (playerLevel world), world)
'q' -> actionByKey "quaff" isPotion Quaff world
'r' -> actionByKey "read" isScroll Read world
'z' -> actionByKey "zap" isWand Zap1 world
'd' -> actionByKey "drop" (const True) Drop world
'f' -> actionByKey "fire" isMissile Fire1 world
'e' -> actionByKey "eat" isFood Eat world
's' -> actionByKey "split" (const True) Split1 world
'U' -> actionByKey "use" isTool Use1 world
't' ->
Left $ addDefaultMessage (msgAsk ++ "set? ["
++ listOfValidChars isTrap world ++ "] or - to untrap")
world {action = SetTrap}
'E' ->
Left world {shift = 0, slot = minBound :: Slot, action = Equip}
'C' ->
Left $ addDefaultMessage msgConfirmCall world {action = Call}
'?' ->
Left $ addDefaultMessage
msgInfo world {xInfo = xFirst world,
yInfo = yFirst world, action = Info}
_ ->
Left $ addMessage (msgUnkAct ++ show (fromEnum c), yellow) world
-- | action with key choose and 'action' changing
actionByKey :: String -> (Object -> Bool) -> Action -> World -> Either World a
actionByKey word isType char world = Left $ addDefaultMessage (msgAsk
++ word ++ "? [" ++ listOfValidChars isType world ++ "]")
world {action = char}
|
green-orange/trapHack
|
src/IO/Step.hs
|
unlicense
| 6,350 | 88 | 19 | 1,484 | 2,532 | 1,322 | 1,210 | 167 | 45 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric, GeneralizedNewtypeDeriving, DeriveTraversable #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
module Kubernetes.Utils where
import Data.Aeson
import Servant.API
import GHC.Generics
import qualified Data.Text as T
import Data.Text (Text)
import Control.Monad (mzero)
import Data.Scientific (coefficient)
-- | List of elements parsed from a query.
newtype QueryList (p :: CollectionFormat) a = QueryList { fromQueryList :: [a] }
deriving (Functor, Applicative, Monad, Foldable, Traversable)
-- | Formats in which a list can be encoded into a HTTP path.
data CollectionFormat = CommaSeparated -- ^ CSV format for multiple parameters.
| SpaceSeparated -- ^ Also called "SSV"
| TabSeparated -- ^ Also called "TSV"
| PipeSeparated -- ^ `value1|value2|value2`
| MultiParamArray -- ^ Using multiple GET parameters, e.g. `foo=bar&foo=baz`. Only for GET params.
instance FromHttpApiData a => FromHttpApiData (QueryList 'CommaSeparated a) where
parseQueryParam = parseSeparatedQueryList ','
instance FromHttpApiData a => FromHttpApiData (QueryList 'TabSeparated a) where
parseQueryParam = parseSeparatedQueryList '\t'
instance FromHttpApiData a => FromHttpApiData (QueryList 'SpaceSeparated a) where
parseQueryParam = parseSeparatedQueryList ' '
instance FromHttpApiData a => FromHttpApiData (QueryList 'PipeSeparated a) where
parseQueryParam = parseSeparatedQueryList '|'
instance FromHttpApiData a => FromHttpApiData (QueryList 'MultiParamArray a) where
parseQueryParam = error "unimplemented FromHttpApiData for MultiParamArray collection format"
parseSeparatedQueryList :: FromHttpApiData a => Char -> Text -> Either Text (QueryList p a)
parseSeparatedQueryList char = fmap QueryList . mapM parseQueryParam . T.split (== char)
instance ToHttpApiData a => ToHttpApiData (QueryList 'CommaSeparated a) where
toQueryParam = formatSeparatedQueryList ','
instance ToHttpApiData a => ToHttpApiData (QueryList 'TabSeparated a) where
toQueryParam = formatSeparatedQueryList '\t'
instance ToHttpApiData a => ToHttpApiData (QueryList 'SpaceSeparated a) where
toQueryParam = formatSeparatedQueryList ' '
instance ToHttpApiData a => ToHttpApiData (QueryList 'PipeSeparated a) where
toQueryParam = formatSeparatedQueryList '|'
instance ToHttpApiData a => ToHttpApiData (QueryList 'MultiParamArray a) where
toQueryParam = error "unimplemented ToHttpApiData for MultiParamArray collection format"
formatSeparatedQueryList :: ToHttpApiData a => Char -> QueryList p a -> Text
formatSeparatedQueryList char = T.intercalate (T.singleton char) . map toQueryParam . fromQueryList
newtype IntOrText = IntOrText { intOrText :: Either Int Text } deriving (Eq, Show, Generic)
instance FromJSON IntOrText where
parseJSON (Data.Aeson.Number i) = return . IntOrText . Left . fromInteger . coefficient $ i
parseJSON (Data.Aeson.String s) = return . IntOrText . Right $ s
parseJSON _ = mzero
instance ToJSON IntOrText where
toJSON (IntOrText (Left i)) = Data.Aeson.Number . fromInteger . toInteger $ i
toJSON (IntOrText (Right s)) = Data.Aeson.String s
|
minhdoboi/deprecated-openshift-haskell-api
|
kubernetes/lib/Kubernetes/Utils.hs
|
apache-2.0
| 3,193 | 0 | 10 | 465 | 772 | 404 | 368 | 52 | 1 |
module Main where
import Control.Monad
import System.Random
printDiceRolls = do
gen <- newStdGen
print $ takeWhile (/=(6::Int)) $ randomRs (1,6) gen
hi5 = endLine $ replicateM_ 5 action
where action = putStr "Hello"
endLine a = a >> putChar '\n'
countDown = mapM_ (\n -> putStr $ show n ++ " .. ") [10,9..1] >> putStr "LiftOff!"
|
dterei/Scraps
|
haskell/langreg.org.hs
|
bsd-3-clause
| 356 | 0 | 11 | 84 | 144 | 76 | 68 | 10 | 1 |
module Types.Plugin
( module RPC.Util
, Plugins
, PluginName (..)
, PluginOptions (..)
) where
import RPC.Util
import Control.Applicative ((<$>))
import qualified Data.Map as Map
--------------------------------------------------------------------------------
newtype PluginName = PluginName
{ pluginName :: String
} deriving (Show,Eq,Ord)
instance ToObject PluginName where
toObject (PluginName n) = toObject n
instance FromObject PluginName where
fromObject obj = PluginName <$> fromObject obj
--------------------------------------------------------------------------------
newtype PluginOptions = PluginOptions
{ pluginOptions :: Map.Map String String
} deriving (Show,Eq,Ord)
instance ToObject PluginOptions where
toObject (PluginOptions m) = toObject m
instance FromObject PluginOptions where
fromObject obj = PluginOptions <$> fromObject obj
--------------------------------------------------------------------------------
type Plugins = [PluginName]
|
GaloisInc/msf-haskell
|
src/Types/Plugin.hs
|
bsd-3-clause
| 997 | 0 | 8 | 137 | 227 | 130 | 97 | 23 | 0 |
{-# LANGUAGE TemplateHaskell, TypeOperators #-}
--------------------------------------------------------------------
-- |
-- Executable : mbox-pick
-- Copyright : (c) Nicolas Pouillard 2008, 2009, 2011
-- License : BSD3
--
-- Maintainer: Nicolas Pouillard <[email protected]>
-- Stability : provisional
-- Portability:
--
--------------------------------------------------------------------
import Control.Arrow
import Control.Lens
import Control.Applicative
import Data.Maybe (fromMaybe, listToMaybe)
import qualified Data.ByteString.Lazy.Char8 as C
import Codec.Mbox (mboxMsgBody,parseOneMboxMessage)
import Email (readEmail)
import EmailFmt (putEmails,ShowFormat(..),fmtOpt,defaultShowFormat,showFormatsDoc)
import System.Environment (getArgs)
import System.Console.GetOpt
import System.IO (IOMode(..), stdin, openFile, hClose)
mayRead :: Read a => String -> Maybe a
mayRead s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
parseSeq :: C.ByteString -> Maybe [Integer]
parseSeq = mapM (mayRead . C.unpack) . C.split ','
data Settings = Settings { _fmt :: ShowFormat
, _help :: Bool
}
$(makeLenses ''Settings)
type Flag = Settings -> Settings
pickMbox :: Settings -> String -> Maybe FilePath -> IO ()
pickMbox opts sequ' mmbox = do
mbox <- maybe (return stdin) (`openFile` ReadMode) mmbox
sequ <- maybe (fail "badly formatted comma separated offset sequence") return $ parseSeq $ C.pack sequ'
mails <- mapM ((((readEmail . view mboxMsgBody) &&& id) <$>) . parseOneMboxMessage (fromMaybe "" mmbox) mbox) sequ
putEmails (opts^.fmt) mails
hClose mbox
defaultSettings :: Settings
defaultSettings = Settings { _fmt = defaultShowFormat
, _help = False
}
usage :: String -> a
usage msg = error $ unlines [msg, usageInfo header options, showFormatsDoc]
where header = "Usage: mbox-pick [OPTION] <offset0>,<offset1>,...,<offsetN> <mbox-file>"
options :: [OptDescr Flag]
options =
[ fmtOpt usage (set fmt)
, Option "?" ["help"] (NoArg (set help True)) "Show this help message"
]
main :: IO ()
main = do
args <- getArgs
let (flags, nonopts, errs) = getOpt Permute options args
let opts = foldr ($) defaultSettings flags
if opts^.help
then usage ""
else
case (nonopts, errs) of
([], []) -> usage "Too few arguments"
(_:_:_:_, []) -> usage "Too many arguments"
(sequ : mbox, []) -> pickMbox opts sequ $ listToMaybe mbox
(_, _) -> usage (concat errs)
|
np/mbox-tools
|
mbox-pick.hs
|
bsd-3-clause
| 2,570 | 1 | 16 | 545 | 784 | 420 | 364 | 51 | 5 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Exception
import Control.Monad
import Data.Time.Clock
import Data.Time.Format
import Debug.Trace
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import System.IO.Temp
import Test.Common
import Test.CommonUtils
import Test.HUnit
import qualified Data.Set as S
-- ---------------------------------------------------------------------
data Verbosity = Debug | Status | None deriving (Eq, Show, Ord, Enum)
verb :: Verbosity
verb = Debug
-- ---------------------------------------------------------------------
writeCPP :: FilePath -> IO ()
writeCPP fp = appendFileFlush cppFile (('\n' : fp))
writeError = writeCPP
writeParseFail :: FilePath -> String -> IO ()
writeParseFail fp _s = appendFileFlush parseFailFile (('\n' : fp))
-- writeParseFail fp s = appendFileFlush parseFailFile (('\n' : (fp ++ " " ++ s)))
writeProcessed :: FilePath -> IO ()
writeProcessed fp = appendFileFlush processed (('\n' : fp))
writeFailed :: FilePath -> IO ()
writeFailed fp = appendFileFlush processedFailFile (('\n' : fp))
writeLog :: String -> IO ()
writeLog msg = appendFileFlush logFile (('\n' : msg))
getTimeStamp :: IO String
getTimeStamp = do
t <- getCurrentTime
return $ formatTime defaultTimeLocale (iso8601DateFormat (Just "%H%M%S")) t
writeFailure :: FilePath -> String -> IO ()
writeFailure fp db = do
ts <- getTimeStamp
let outname = failuresDir </> takeFileName fp <.> ts <.> "out"
writeFile outname db
appendFileFlush :: FilePath -> String -> IO ()
appendFileFlush f txt = withFile f AppendMode (\ hdl -> hPutStr hdl txt >> hFlush hdl)
-- ---------------------------------------------------------------------
readFileIfPresent fileName = do
isPresent <- doesFileExist fileName
if isPresent
then lines <$> readFile fileName
else return []
-- ---------------------------------------------------------------------
main :: IO ()
main = do
createDirectoryIfMissing True workDir
createDirectoryIfMissing True configDir
createDirectoryIfMissing True failuresDir
as <- getArgs
case as of
[] -> putStrLn "Must enter directory to process"
["failures"] -> do
fs <- lines <$> readFile origFailuresFile
() <$ runTests (TestList (map mkParserTest fs))
["clean"] -> do
putStrLn "Cleaning..."
writeFile processed ""
writeFile parseFailFile ""
writeFile cppFile ""
writeFile logFile ""
writeFile processedFailFile ""
removeDirectoryRecursive failuresDir
createDirectory failuresDir
putStrLn "Done."
-- ds -> () <$ (runTests =<< (TestList <$> mapM tests ds))
ds -> do
!blackList <- readFileIfPresent blackListed
!knownFailures <- readFileIfPresent knownFailuresFile
!processedList <- lines <$> readFile processed
!cppList <- lines <$> readFile cppFile
!parseFailList <- lines <$> readFile parseFailFile
let done = S.fromList (processedList ++ cppList ++ blackList ++ knownFailures ++ parseFailList)
tsts <- TestList <$> mapM (tests done) ds
runTests tsts
return ()
runTests :: Test -> IO Counts
runTests t = do
let n = testCaseCount t
putStrLn $ "Running " ++ show n ++ " tests."
putStrLn $ "Verbosity: " ++ show verb
runTestTT t
tests :: S.Set String -> FilePath -> IO Test
tests done dir = do
roundTripHackage done dir
-- Selection:
-- Hackage dir
roundTripHackage :: S.Set String -> FilePath -> IO Test
roundTripHackage done hackageDir = do
packageDirs <- drop 2 <$> getDirectoryContents hackageDir
when (verb <= Debug) (traceShowM hackageDir)
when (verb <= Debug) (traceShowM packageDirs)
TestList <$> mapM (roundTripPackage done) (zip [0..] (map (hackageDir </>) packageDirs))
roundTripPackage :: S.Set String -> (Int, FilePath) -> IO Test
roundTripPackage done (n, dir) = do
putStrLn (show n)
when (verb <= Status) (traceM dir)
hsFiles <- filter (flip S.notMember done) <$> findSrcFiles dir
return (TestLabel (dropFileName dir) (TestList $ map mkParserTest hsFiles))
mkParserTest :: FilePath -> Test
mkParserTest fp =
TestLabel fp $
TestCase (do writeLog $ "starting:" ++ fp
r1 <- catchAny (roundTripTest fp) $ \e -> do
writeError fp
throwIO e
case r1 of
Left (ParseFailure _ s) -> do
writeParseFail fp s
exitFailure
Right r -> do
writeProcessed fp
unless (status r == Success) (writeFailure fp (debugTxt r) >> writeFailed fp)
assertBool fp (status r == Success))
catchAny :: IO a -> (SomeException -> IO a) -> IO a
catchAny = Control.Exception.catch
|
mpickering/ghc-exactprint
|
tests/Roundtrip.hs
|
bsd-3-clause
| 4,889 | 0 | 20 | 1,086 | 1,468 | 707 | 761 | 118 | 4 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Lib
( toField
, Field
, GameState
, gsStatus
, gsPos
, Direction(..)
, GameUI(..)
, GameStatus(..)
, playGame
, runGame
, execGame
, evalGame
, cellToChar
) where
import Control.Monad.Trans.Class
import Control.Monad.Trans.Maybe
import Control.Monad.State
import Control.Monad.Reader
import Control.Monad.Identity
import Control.Monad
import Control.Exception
import qualified Data.Vector as V
import Data.Vector((!))
import Control.Applicative
-- FIXME: ??? data Cell = Exit('x'), Wall('#'), Free(' ')
data Cell = Exit | Wall | Free
deriving (Show, Eq)
toCell :: Char -> Maybe Cell
toCell c = case c of
'x' -> pure Exit
'#' -> pure Wall
' ' -> pure Free
_ -> mzero
cellToChar :: Cell -> Char
cellToChar cell = case cell of
Exit -> 'x'
Wall -> '#'
Free -> ' '
type Position = (Int, Int)
type Vector2D a = V.Vector (V.Vector a)
type Field = Vector2D Cell
toField :: String -> Maybe Field
toField s = do
guard $ length (filter (== Just Exit) (toCell <$> s)) == 1
field <- unchecked
let width = V.length $ field ! 0
guard $ all (\row -> V.length row == width) field
return field
where
unchecked = sequence $ V.fromList $ (sequence . (toCell <$>) . V.init . V.fromList) <$> lines s
data GameStatus = Win | InGame | Lose | Stop
deriving (Eq, Show)
data GameState = GameState { gsPos :: Position, gsStatus :: GameStatus }
deriving Show
data Direction = North | South | West | East
deriving (Eq, Show)
newtype Game ui a = Game (ReaderT Field (StateT GameState ui) a)
deriving (Functor, Applicative, Monad, MonadState GameState, MonadReader Field)
runGame :: Game ui a -> Field -> Position -> ui (a, GameState)
runGame (Game game) field pos = runStateT (runReaderT game field) initState
where
initState = GameState { gsPos = pos, gsStatus = InGame }
execGame :: GameUI ui => Game ui a -> Field -> Position -> ui GameState
execGame game field pos = snd <$> runGame game field pos
evalGame :: GameUI ui => Game ui a -> Field -> Position -> ui a
evalGame game field pos = fst <$> runGame game field pos
instance MonadTrans Game where
lift f = Game $ lift $ lift f
class Monad ui => GameUI ui where
initialize :: ui ()
nextStep :: ui (Maybe Direction)
movePlayer :: Position -> ui ()
evalStep :: GameUI ui => Game ui ()
evalStep = do
mbDir <- lift nextStep
gs <- get
case mbDir of
Nothing -> put $ gs { gsStatus = Stop }
Just dir -> do
let newPos@(x, y) = go (gsPos gs) dir
field <- ask
if x >= 0 && y >= 0 && V.length field /= 0
&& x < V.length field && y < V.length (field ! x)
then do
let cell = field ! x ! y
when (cell /= Wall) $ do
lift $ movePlayer newPos
put $ gs { gsPos = newPos }
when (cell == Exit) $
put $ gs { gsStatus = Win }
else
put $ gs { gsStatus = Lose }
where
go (x, y) dir = case dir of
South -> (x + 1, y)
North -> (x - 1, y)
West -> (x, y - 1)
East -> (x, y + 1)
playGame :: GameUI ui => Game ui ()
playGame = do
lift initialize
gameLoop
where
gameLoop = do
evalStep
status <- gets gsStatus
when (status == InGame)
gameLoop
|
xosmig/haskell-hw-game
|
src/Lib.hs
|
bsd-3-clause
| 3,352 | 0 | 21 | 937 | 1,293 | 681 | 612 | 103 | 6 |
module River.Effect (
HasEffect(..)
) where
class HasEffect p where
hasEffect :: p -> Bool
|
jystic/river
|
src/River/Effect.hs
|
bsd-3-clause
| 101 | 0 | 7 | 25 | 33 | 19 | 14 | 4 | 0 |
{-# OPTIONS_GHC -fno-warn-unused-matches -fno-warn-name-shadowing -fno-warn-unused-imports #-}
{-# LANGUAGE UnboxedTuples #-}
-- We expect unused binds and name shadowing in foo5 test.
module Singletons.Lambdas where
import Data.Proxy
import Data.Singletons
import Data.Singletons.TH
$(singletons [d|
-- nothing in scope
foo0 :: a -> b -> a
foo0 = (\x y -> x)
-- eta-reduced function
foo1 :: a -> b -> a
foo1 x = (\_ -> x)
-- same as before, but without eta-reduction
foo2 :: a -> b -> a
foo2 x y = (\_ -> x) y
foo3 :: a -> a
foo3 x = (\y -> y) x
-- more lambda parameters + returning in-scope variable
foo4 :: a -> b -> c -> a
foo4 x y z = (\_ _ -> x) y z
-- name shadowing
-- Note: due to -dsuppress-uniques output of this test does not really
-- prove that the result is correct. Compiling this file manually and
-- examining dumped splise of relevant Lamdba reveals that indeed that Lambda
-- returns its last parameter (ie. y passed in a call) rather than the
-- first one (ie. x that is shadowed by the binder in a lambda).
foo5 :: a -> b -> b
foo5 x y = (\x -> x) y
-- nested lambdas
foo6 :: a -> b -> a
foo6 a b = (\x -> \_ -> x) a b
-- tuple patterns
foo7 :: a -> b -> b
foo7 x y = (\(_, b) -> b) (x, y)
-- constructor patters=ns
data Foo a b = Foo a b
foo8 :: Foo a b -> a
foo8 x = (\(Foo a _) -> a) x
|])
foo1a :: Proxy (Foo1 Int Char)
foo1a = Proxy
foo1b :: Proxy Int
foo1b = foo1a
foo2a :: Proxy (Foo2 Int Char)
foo2a = Proxy
foo2b :: Proxy Int
foo2b = foo2a
foo3a :: Proxy (Foo3 Int)
foo3a = Proxy
foo3b :: Proxy Int
foo3b = foo3a
foo4a :: Proxy (Foo4 Int Char Bool)
foo4a = Proxy
foo4b :: Proxy Int
foo4b = foo4a
foo5a :: Proxy (Foo5 Int Bool)
foo5a = Proxy
foo5b :: Proxy Bool
foo5b = foo5a
foo6a :: Proxy (Foo6 Int Char)
foo6a = Proxy
foo6b :: Proxy Int
foo6b = foo6a
foo7a :: Proxy (Foo7 Int Char)
foo7a = Proxy
foo7b :: Proxy Char
foo7b = foo7a
|
int-index/singletons
|
tests/compile-and-dump/Singletons/Lambdas.hs
|
bsd-3-clause
| 1,954 | 0 | 7 | 480 | 277 | 151 | 126 | -1 | -1 |
--
-- Functions to generate VHDL from FlatFunctions
--
module CLasH.VHDL where
-- Standard modules
import qualified Data.Map as Map
import qualified Maybe
import qualified Control.Arrow as Arrow
import Data.Accessor
import qualified Data.Accessor.Monad.Trans.StrictState as MonadState
-- VHDL Imports
import qualified Language.VHDL.AST as AST
-- GHC API
import qualified CoreSyn
-- Local imports
import CLasH.Translator.TranslatorTypes
import CLasH.VHDL.VHDLTypes
import CLasH.VHDL.VHDLTools
import CLasH.VHDL.Constants
import CLasH.VHDL.Generate
createDesignFiles ::
[CoreSyn.CoreBndr] -- ^ Top binders
-> TranslatorSession [(AST.VHDLId, AST.DesignFile)]
createDesignFiles topbndrs = do
bndrss <- mapM recurseArchitectures topbndrs
let bndrs = concat bndrss
lunits <- mapM createLibraryUnit bndrs
typepackage <- createTypesPackage
let files = map (Arrow.second $ AST.DesignFile full_context) lunits
return $ typepackage : files
where
full_context =
mkUseAll ["work", "types"]
: (mkUseAll ["work"]
: ieee_context)
ieee_context = [
AST.Library $ mkVHDLBasicId "IEEE",
mkUseAll ["IEEE", "std_logic_1164"],
mkUseAll ["IEEE", "numeric_std"],
mkUseAll ["std", "textio"]
]
-- | Find out which entities are needed for the given top level binders.
recurseArchitectures ::
CoreSyn.CoreBndr -- ^ The top level binder
-> TranslatorSession [CoreSyn.CoreBndr]
-- ^ The binders of all needed functions.
recurseArchitectures bndr = do
-- See what this binder directly uses
(_, used) <- getArchitecture bndr
-- Recursively check what each of the used functions uses
useds <- mapM recurseArchitectures used
-- And return all of them
return $ bndr : (concat useds)
-- | Creates the types package, based on the current type state.
createTypesPackage ::
TranslatorSession (AST.VHDLId, AST.DesignFile)
-- ^ The id and content of the types package
createTypesPackage = do
tyfuns <- MonadState.get (tsType .> tsTypeFuns)
let tyfun_decls = mkBuiltInShow ++ map snd (Map.elems tyfuns)
ty_decls_maybes <- MonadState.get (tsType .> tsTypeDecls)
let ty_decls = Maybe.catMaybes ty_decls_maybes
let subProgSpecs = map (\(AST.SubProgBody spec _ _) -> AST.PDISS spec) tyfun_decls
let type_package_dec = AST.LUPackageDec $ AST.PackageDec (mkVHDLBasicId "types") ([tfvec_index_decl] ++ ty_decls ++ subProgSpecs)
let type_package_body = AST.LUPackageBody $ AST.PackageBody typesId tyfun_decls
return (mkVHDLBasicId "types", AST.DesignFile ieee_context [type_package_dec, type_package_body])
where
tfvec_index_decl = AST.PDISD $ AST.SubtypeDec tfvec_indexTM tfvec_index_def
tfvec_range = AST.ConstraintRange $ AST.SubTypeRange (AST.PrimLit "-1") (AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerTM) (AST.NSimple highId) Nothing)
tfvec_index_def = AST.SubtypeIn integerTM (Just tfvec_range)
-- Create a use foo.bar.all statement. Takes a list of components in the used
-- name. Must contain at least two components
mkUseAll :: [String] -> AST.ContextItem
mkUseAll ss =
AST.Use $ from AST.:.: AST.All
where
base_prefix = (AST.NSimple $ mkVHDLBasicId $ head ss)
from = foldl select base_prefix (tail ss)
select prefix s = AST.NSelected $ prefix AST.:.: (AST.SSimple $ mkVHDLBasicId s)
createLibraryUnit ::
CoreSyn.CoreBndr
-> TranslatorSession (AST.VHDLId, [AST.LibraryUnit])
createLibraryUnit bndr = do
entity <- getEntity bndr
(arch, _) <- getArchitecture bndr
return (ent_id entity, [AST.LUEntity (ent_dec entity), AST.LUArch arch])
|
christiaanb/clash
|
clash/CLasH/VHDL.hs
|
bsd-3-clause
| 3,575 | 0 | 15 | 591 | 926 | 490 | 436 | 66 | 1 |
#!/usr/bin/env runhaskell
{-# LANGUAGE TemplateHaskell, QuasiQuotes #-}
{-# OPTIONS_GHC -fno-cse #-}
module Main where
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.Function
import Data.Global
import Data.IORef
import Data.Time.Clock.POSIX
import System.CPUTime
import Text.Printf
un "waitThreads" =:: (utl [ud| fix $ writeIORef waitThreads |], ut [t| IO () |] :: UT IORef)
un "waits" =:: ([| () |], ut [t| () |] :: UT (UDEmpty Chan))
-- | Fork a thread; waitForThreadsToFinish will not terminate until every thread created by this does.
forkIO' :: IO () -> IO ThreadId
forkIO' m = do
atomicModifyIORef waitThreads $ \a -> (a >> readChan waits, ())
forkIO $ m >> writeChan waits ()
forkIO'' :: IO () -> IO ()
forkIO'' = void . forkIO'
-- | Alias to reading action stored in 'waitThreads' and executing it.
waitForThreadsToFinish :: IO ()
waitForThreadsToFinish = join $ readIORef waitThreads
un "vacant_study_rooms" =:: ([| 10 :: QSemQuantity |], ut [t| () |] :: UT (Const QSem))
-- | Calling thread sleeps (GHC only)
sleepSeconds :: Integer -> IO ()
sleepSeconds = threadDelay . fromIntegral . (* 1000000)
un "epoch" =:: (uninitialized, ut [t| Integer |] :: UT IORef)
putStrCPUSecsLn :: String -> IO ()
--putStrMCPUSecsLn s = ((`div` 1000000000) <$> getCPUTime) >>= (\t -> putStrLn $ printf "[%dms] %s" t s)
--putStrCPUSecsLn s = ((`div` 1000000000000) <$> getCPUTime) >>= (\t -> putStrLn $ printf "[%ds] %s" t s)
putStrCPUSecsLn s = ((`div` 1000000000000) <$> getCPUTime) >>= (\t -> putStrLn $ printf "[%02ds] %s" t s) -- Formatted for just this program
putStrSecsLn :: String -> IO ()
putStrSecsLn s = getSecondsSinceEpoch >>= (\t -> putStrLn $ printf "[%02ds] %s" t s) -- Formatted for just this program
setEpoch :: IO ()
setEpoch = writeIORef epoch =<< getSecondsSince
getMicrosecondsSince :: IO Integer
getMicrosecondsSince = round . (* 1000000) <$> getPOSIXTime
getSecondsSince :: IO Integer
getSecondsSince = round <$> getPOSIXTime
getSecondsSinceEpoch :: IO Integer
getSecondsSinceEpoch = pure (-) <*> getSecondsSince <*> readIORef epoch
requestRoomSeconds :: String -> Integer -> IO ()
requestRoomSeconds name seconds = forkIO'' $ do
putStrSecsLn $ printf "%-30s requests a study room for %02d seconds" name seconds
waitQSem vacant_study_rooms
putStrSecsLn $ printf "%-30s enters a study room for %02d seconds" name seconds
sleepSeconds seconds
putStrSecsLn $ printf "%-30s leaves a study room after %02d seconds" name seconds
signalQSem vacant_study_rooms
data LibraryEvent =
WaitSeconds Integer
| RequestRoom String Integer
newtype Library = Library {unLibrary :: [LibraryEvent]}
runLibraryEvent :: LibraryEvent -> IO ()
runLibraryEvent (WaitSeconds seconds) = sleepSeconds seconds
runLibraryEvent (RequestRoom name seconds) = requestRoomSeconds name seconds
runLibrary :: Library -> IO ()
runLibrary = mapM_ runLibraryEvent . unLibrary
main :: IO ()
main = (>> waitForThreadsToFinish) $ do
setEpoch
runLibrary es
putStrSecsLn $ printf "No more requests"
where room = flip RequestRoom
wait = WaitSeconds
es = Library $
[ room 20 "Manuel Chakravarty"
, wait 5
, room 15 "Tim Chevalier"
, room 20 "Duncan Coutts"
, room 15 "Iavor S Diatchki"
, room 15 "Andy Gill"
, wait 5
, room 05 "David Himmelstrup"
, room 15 "Roman Leshchinskiy"
, room 20 "Ben Lippmeier"
, room 20 "Andres Loeh"
, room 10 "Ian Lynagh"
, room 20 "Simon Marlow"
, room 10 "John Meacham"
, room 15 "Ross Paterson"
, room 15 "Sven Panne"
, room 20 "Simon Peyton Jones"
, room 10 "Norman Ramsey"
, room 20 "Don Stewart"
, room 15 "Josef Svenningsson"
, wait 5
, room 10 "Audrey Tang"
, room 10 "David Terei"
, room 05 "Wolfgang Thaller"
, room 10 "David Waern"
, wait 5
, room 05 "Malcolm Wallace"
, room 05 "Ashley Yakeley"
, wait 10
, room 01 "Krasimir Angelov"
, room 05 "Lennart Augustsson"
, room 03 "Jean-Philippe Bernardy"
, room 02 "Jost Berthold"
, room 04 "Bjorn Bringert"
, room 01 "Sebastien Carlier"
, room 05 "Andrew Cheadle"
, room 01 "Sigbjorn Finne"
, room 01 "Kevin Glynn"
, room 04 "John Goerzen"
, room 03 "Cordy Hall"
, room 05 "Kevin Hammond"
, room 01 "Tim Harris"
, room 04 "José Iborra"
, room 03 "Isaac Jones"
, room 02 "Ralf Laemmel"
, room 05 "Hans Wolfgang Loidl"
, room 01 "John Launchbury"
, room 03 "Ryan Lortie"
, room 01 "Jim Mattson"
, room 05 "Darren Moffat"
, room 03 "Nick Nethercote"
, room 04 "Thomas Nordin"
, room 05 "Bryan O'Sullivan"
, room 04 "Sungwoo Park"
, room 04 "Will Partain"
, room 01 "Juan Quintela"
, room 05 "Alastair Reid"
, room 01 "Ben Rudiak-Gould"
, room 03 "Patrick Sansom"
, room 03 "André Santos"
, room 04 "Sean Seefried"
, room 04 "Julian Seward"
, room 04 "Dominic Steinitz"
, room 04 "Volker Stolz"
, room 05 "Dinko Tenev"
, room 05 "Mike Thomas"
, room 01 "Reuben Thomas"
, room 03 "Christopher D. Thompson-Walsh"
, room 01 "Dylan Thurston"
, room 03 "Phil Trinder"
, room 03 "Mark Tullsen"
, room 01 "David N Turner"
, room 03 "Philip Wadler"
, room 01 "Michael Weber"
, room 04 "N. Xu"
, wait 15
, room 01 "Sigbjorn Finne"
, room 04 "Simon Marlow"
, room 05 "Simon Peyton Jones"
, room 03 "FreeBSD Haskell Team"
, room 01 "Matthias Kilian"
, room 01 "Sven Panne,Ralf Hinze"
, room 02 "Gentoo Haskell team"
, room 02 "Kari Pahula"
, room 05 "Manuel Chakravarty"
, room 05 "Fedora Haskell SIG"
, room 05 "Audrey Tang"
, room 05 "Ryan Lortie"
, room 01 "Gentoo Haskell team"
, room 03 "Kari Pahula"
, room 01 "Wolfgang Thaller,Thorkil Naur"
, room 02 "Fedora Haskell SIG"
, room 03 "Ben Lippmeier"
, room 03 "Gentoo Haskell team"
, room 01 "Kari Pahula"
, room 01 "Simon Marlow"
, room 03 "Gentoo Haskell team"
, room 04 "Kari Pahula"
, room 02 "FreeBSD Haskell Team"
, room 03 "Matthias Kilian"
, room 04 "Fedora Haskell SIG"
, room 04 "Don Stewart"
, room 01 "Kari Pahula"
, room 05 "Kari Pahula"
, room 02 "Matt Chapman"
, room 01 "Gentoo Haskell team"
, room 01 "Kari Pahula"
, room 03 "Ken Shan"
, room 04 "Gentoo Haskell team"
, room 04 "Kari Pahula"
, room 01 "Gentoo Haskell team"
, room 04 "Kari Pahula"
, room 03 "Kari Pahula"
, room 05 "Kari Pahula"
]
|
bairyn/global
|
examples/semaphore/Main.hs
|
bsd-3-clause
| 7,786 | 0 | 11 | 2,777 | 1,720 | 885 | 835 | 177 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | This module contains Dhall's parsing logic
module Dhall.Parser (
-- * Utilities
exprFromText
, exprAndHeaderFromText
, censor
, createHeader
-- * Parsers
, expr, exprA
-- * Types
, Header(..)
, Src(..)
, SourcedException(..)
, ParseError(..)
, Parser(..)
) where
import Control.Applicative (many)
import Control.Exception (Exception)
import Data.Text (Text)
import Data.Void (Void)
import Dhall.Src (Src (..))
import Dhall.Syntax
import Text.Megaparsec (ParseErrorBundle (..), PosState (..))
import qualified Data.Text as Text
import qualified Dhall.Core as Core
import qualified Text.Megaparsec
import Dhall.Parser.Combinators
import Dhall.Parser.Expression
import Dhall.Parser.Token hiding (text)
-- | Parser for a top-level Dhall expression
expr :: Parser (Expr Src Import)
expr = exprA (Text.Megaparsec.try import_)
-- | Parser for a top-level Dhall expression. The expression is parameterized
-- over any parseable type, allowing the language to be extended as needed.
exprA :: Parser a -> Parser (Expr Src a)
exprA = completeExpression
{-# DEPRECATED exprA "Support for parsing custom imports will be dropped in a future release" #-}
-- | A parsing error
data ParseError = ParseError {
unwrap :: Text.Megaparsec.ParseErrorBundle Text Void
, input :: Text
}
{-| Replace the source code with spaces when rendering error messages
This utility is used to implement the @--censor@ flag
-}
censor :: ParseError -> ParseError
censor parseError =
parseError
{ unwrap =
(unwrap parseError)
{ bundlePosState =
(bundlePosState (unwrap parseError))
{ pstateInput =
Core.censorText
(pstateInput (bundlePosState (unwrap parseError)))
}
}
}
instance Show ParseError where
show (ParseError {..}) =
"\n\ESC[1;31mError\ESC[0m: Invalid input\n\n" <> Text.Megaparsec.errorBundlePretty unwrap
instance Exception ParseError
-- | Parse an expression from `Text.Text` containing a Dhall program
exprFromText
:: String -- ^ User-friendly name describing the input expression,
-- used in parsing error messages
-> Text -- ^ Input expression to parse
-> Either ParseError (Expr Src Import)
exprFromText delta text = fmap snd (exprAndHeaderFromText delta text)
-- | A header corresponds to the leading comment at the top of a Dhall file.
--
-- The header includes comment characters but is stripped of leading spaces and
-- trailing newlines
newtype Header = Header Text deriving Show
-- | Create a header with stripped leading spaces and trailing newlines
createHeader :: Text -> Header
createHeader text = Header (prefix <> newSuffix)
where
isWhitespace c = c == ' ' || c == '\n' || c == '\r' || c == '\t'
prefix = Text.dropAround isWhitespace text
newSuffix
| Text.null prefix = ""
| otherwise = "\n"
-- | Like `exprFromText` but also returns the leading comments and whitespace
-- (i.e. header) up to the last newline before the code begins
--
-- In other words, if you have a Dhall file of the form:
--
-- > -- Comment 1
-- > {- Comment -} 2
--
-- Then this will preserve @Comment 1@, but not @Comment 2@
--
-- This is used by @dhall-format@ to preserve leading comments and whitespace
exprAndHeaderFromText
:: String -- ^ User-friendly name describing the input expression,
-- used in parsing error messages
-> Text -- ^ Input expression to parse
-> Either ParseError (Header, Expr Src Import)
exprAndHeaderFromText delta text = case result of
Left errInfo -> Left (ParseError { unwrap = errInfo, input = text })
Right (txt, r) -> Right (createHeader txt, r)
where
parser = do
(bytes, _) <- Text.Megaparsec.match (many shebang *> whitespace)
r <- expr
Text.Megaparsec.eof
return (bytes, r)
result = Text.Megaparsec.parse (unParser parser) delta text
|
Gabriel439/Haskell-Dhall-Library
|
dhall/src/Dhall/Parser.hs
|
bsd-3-clause
| 4,203 | 0 | 17 | 1,063 | 779 | 447 | 332 | 74 | 2 |
{-# LANGUAGE Rank2Types #-}
module Test.Sloth.Generics
(
Compose(..), inCompose,
fromConstrWithChildren,
gunfoldM, gunfoldWithIndex
) where
import Control.Monad.State ( State, evalState, get, put )
import Data.Data ( Data, Constr, gunfold, fromConstrM )
-- | Compose two type constructors
newtype Compose f g a = Compose { compose :: f (g a) }
-- | Lift a function on nested type constructors to a function on
-- composed type constructors
inCompose :: (f (g a) -> f (g b)) -> Compose f g a -> Compose f g b
inCompose f (Compose x) = Compose (f x)
-- | An implementation of gunfold with additional monadic context
gunfoldM :: Data a
=> (forall b r. Data b => m (c (b -> r)) -> m (c r))
-> (forall r. r -> m (c r)) -> Constr -> m (c a)
gunfoldM k z c = compose (gunfold (inCompose k) (Compose . z) c)
-- | An implementation of gunfold which additionally provides the
-- index for every child (zero-based).
gunfoldWithIndex :: Data a => (forall b r. Data b => Int -> c (b -> r) -> c r)
-> (forall r. r -> c r) -> Constr -> c a
gunfoldWithIndex k z c =
evalState (gunfoldM (applyWithIndex k) (return . z) c) 0
applyWithIndex :: (Int -> a -> b) -> State Int a -> State Int b
applyWithIndex k cf = do
f <- cf
n <- get
put (n+1)
return (k n f)
-- | Build a term from a list of subterms and a generic function for
-- these subterms
fromConstrWithChildren :: Data a => (forall b. Data b => c -> b) -> [c]
-> Constr -> a
fromConstrWithChildren toData children c =
evalState (fromConstrM (fmap toData nextChild) c) children
where
nextChild = do
xxs <- get
case xxs of
[] -> error "fromConstRec: Constr expects arguments but none \
\are provided"
x:xs -> put xs >> return x
|
plancalculus/sloth
|
Test/Sloth/Generics.hs
|
bsd-3-clause
| 1,818 | 0 | 15 | 478 | 650 | 339 | 311 | 34 | 2 |
import System.Environment (getArgs)
import Data.List (intercalate)
factors :: Int -> [Int]
factors n = [x | x <- [1..n], mod n x == 0]
prime :: Int -> Bool
prime x = factors x == [1, x]
m :: Int -> Int
m x = 2^x - 1
mersenne :: Int -> [Int]
mersenne n = map m $ takeWhile (\x -> m x < n) [x | x <- 2 : [3, 5..], prime x]
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (intercalate ", " . map show . mersenne . read) $ lines input
|
nikai3d/ce-challenges
|
easy/mersenne_prime.hs
|
bsd-3-clause
| 498 | 3 | 14 | 129 | 292 | 144 | 148 | 15 | 1 |
{-# LANGUAGE TemplateHaskell #-}
-- | In this module there is a helper function called 'wsass''. You need to use
-- it to define another function where the first argument is the path to be used
-- to resolve @include, like this:
--
-- >>> let wsass = wass' "sass_include/"
--
-- Please, check the install instructions of hlibsass at
-- <https://github.com/jakubfijalkowski/hlibsass>
--
module Text.Sass.QQ
( sass
, wsass'
) where
import Prelude hiding (exp)
import Text.Sass
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Data.Default (def)
import Text.Lucius (toCss)
import qualified Data.Text as T
import Yesod.Core.Widget (toWidget, CssBuilder(..))
data Ctx = Pat | Type | Dec
qq :: String -> (String -> Q Exp) -> QuasiQuoter
qq name exp = QuasiQuoter { quoteExp = exp
, quotePat = error $ errorString Pat
, quoteType = error $ errorString Type
, quoteDec = error $ errorString Dec
}
where
errorString ctx =
"You can't use the " ++ name ++ " quasiquoter in " ++ ctxName ctx
ctxName Pat = "a pattern"
ctxName Type = "a type"
ctxName Dec = "a declaration"
-- | Quasiquoter that generate a string from Sass code
sass :: QuasiQuoter
sass = qq "sass" exp
where
exp :: String -> Q Exp
exp str = do
css <- runIO $ compileSass Nothing str
[| $(stringE css) |]
-- | Quasiquoter that generate a yesod widget from Sass code
--
wsass' :: FilePath -- ^ path of the sass files to use with @include
-> QuasiQuoter
wsass' include = qq "wsass" exp
where
exp :: String -> Q Exp
exp str = do
css <- runIO $ compileSass (Just [include]) str
[| toWidget $ CssBuilder $(stringE css) |]
compileSass :: Maybe [FilePath] -> String -> IO String
compileSass include str = do
result <- compileString str (def { sassIncludePaths = include } )
case result of
Left err -> do
err' <- errorMessage err
error err'
Right compiled -> return . resultString $ compiled
|
fgaray/yesod-sass
|
src/Text/Sass/QQ.hs
|
bsd-3-clause
| 2,180 | 0 | 14 | 651 | 482 | 264 | 218 | 44 | 3 |
{-# LANGUAGE FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.LAPACK
-- Copyright : Copyright (c) 2010, Patrick Perry <[email protected]>
-- License : BSD3
-- Maintainer : Patrick Perry <[email protected]>
-- Stability : experimental
--
-- Types with a Linear Algebra PACKage.
--
module Foreign.LAPACK (
-- * LAPACK typeclass
LAPACK(..),
-- * Enums
module Foreign.LAPACK.Types,
) where
import Control.Monad( forM_, when )
import Control.Exception( assert )
import Data.Complex( Complex )
import Foreign
import Foreign.BLAS
import Foreign.LAPACK.Types
import Foreign.LAPACK.Double
import Foreign.LAPACK.Zomplex
-- | Types with LAPACK operations.
class (BLAS3 e) => LAPACK e where
geqrf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()
gelqf :: Int -> Int -> Ptr e -> Int -> Ptr e -> IO ()
heevr :: EigJob -> EigRange -> Uplo -> Int -> Ptr e -> Int -> Double
-> Ptr Double -> Ptr e -> Int -> Ptr Int -> IO Int
larfg :: Int -> Ptr e -> Ptr e -> Int -> IO e
potrf :: Uplo -> Int -> Ptr e -> Int -> IO Int
potrs :: Uplo -> Int -> Int -> Ptr e -> Int -> Ptr e -> Int -> IO ()
pptrf :: Uplo -> Int -> Ptr e -> IO Int
pptrs :: Uplo -> Int -> Int -> Ptr e -> Ptr e -> Int -> IO ()
unmqr :: Side -> Trans -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()
unmlq :: Side -> Trans -> Int -> Int -> Int -> Ptr e -> Int -> Ptr e -> Ptr e -> Int -> IO ()
callWithWork :: (Storable e) => (Ptr e -> Ptr LAInt -> Ptr LAInt -> IO ()) -> IO LAInt
callWithWork call =
alloca $ \pquery ->
with (-1) $ \pnone ->
alloca $ \pinfo -> do
call pquery pnone pinfo
lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)
allocaArray lwork $ \pwork ->
withEnum lwork $ \plwork -> do
call pwork plwork pinfo
peek pinfo
callWithWorkIWork :: (Storable e)
=> (Ptr e -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> IO ())
-> IO LAInt
callWithWorkIWork call =
alloca $ \pquery ->
alloca $ \piquery ->
with (-1) $ \pnone ->
alloca $ \pinfo -> do
call pquery pnone piquery pnone pinfo
lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)
liwork <- max 1 `fmap` peek piquery
allocaArray lwork $ \pwork ->
withEnum lwork $ \plwork ->
allocaArray (fromEnum liwork) $ \piwork ->
with liwork $ \pliwork -> do
call pwork plwork piwork pliwork pinfo
peek pinfo
callWithWorkRWorkIWork :: (Storable e)
=> (Ptr e -> Ptr LAInt -> Ptr Double -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> Ptr LAInt -> IO ())
-> IO LAInt
callWithWorkRWorkIWork call =
alloca $ \pquery ->
alloca $ \prquery ->
alloca $ \piquery ->
with (-1) $ \pnone ->
alloca $ \pinfo -> do
call pquery pnone prquery pnone piquery pnone pinfo
lwork <- (ceiling . max 1) `fmap` (peek (castPtr pquery) :: IO Double)
lrwork <- (ceiling . max 1) `fmap` peek prquery
liwork <- max 1 `fmap` peek piquery
allocaArray lwork $ \pwork ->
withEnum lwork $ \plwork ->
allocaArray lrwork $ \prwork ->
withEnum lrwork $ \plrwork ->
allocaArray (fromEnum liwork) $ \piwork ->
with liwork $ \pliwork -> do
call pwork plwork prwork plrwork piwork pliwork pinfo
peek pinfo
checkInfo :: (Num info) => info -> IO ()
checkInfo info = assert (info == 0) $ return ()
withEnum :: (Enum a, Storable a) => Int -> (Ptr a -> IO b) -> IO b
withEnum = with . toEnum
{-# INLINE withEnum #-}
instance LAPACK Double where
geqrf m n pa lda ptau =
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
checkInfo =<< callWithWork (dgeqrf pm pn pa plda ptau)
gelqf m n pa lda ptau =
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
checkInfo =<< callWithWork (dgelqf pm pn pa plda ptau)
heevr jobz range uplo n pa lda abstol pw pz ldz psuppz =
withEigJob jobz $ \pjobz ->
withEigRange range $ \prange pvl pvu pil piu ->
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
with abstol $ \pabstol ->
alloca $ \pm ->
withEnum ldz $ \pldz ->
allocaArray nsuppz $ \psuppz' -> do
checkInfo =<<
(callWithWorkIWork $
dsyevr pjobz prange puplo pn pa plda pvl pvu pil piu
pabstol pm pw pz pldz psuppz')
m <- fromEnum `fmap` peek pm
when (psuppz /= nullPtr) $
forM_ [ 0..2*m - 1 ] $ \i -> do
s <- peekElemOff psuppz' i
pokeElemOff psuppz i (fromEnum s)
return m
where
nsuppz = if psuppz == nullPtr then 0 else 2 * max 1 n
unmqr side trans m n k pa lda ptau pc ldc =
withSide side $ \pside ->
withTrans trans $ \ptrans ->
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum k $ \pk ->
withEnum lda $ \plda ->
withEnum ldc $ \pldc ->
checkInfo =<< callWithWork (dormqr pside ptrans pm pn pk pa plda ptau pc pldc)
unmlq side trans m n k pa lda ptau pc ldc =
withSide side $ \pside ->
withTrans trans $ \ptrans ->
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum k $ \pk ->
withEnum lda $ \plda ->
withEnum ldc $ \pldc ->
checkInfo =<< callWithWork (dormlq pside ptrans pm pn pk pa plda ptau pc pldc)
larfg n palpha px incx =
withEnum n $ \pn ->
withEnum incx $ \pincx ->
alloca $ \ptau -> do
dlarfg pn palpha px pincx ptau
peek ptau
potrf uplo n pa lda =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
alloca $ \pinfo -> do
dpotrf puplo pn pa plda pinfo
info <- fromEnum `fmap` peek pinfo
assert (info >= 0) $ return info
potrs uplo n nrhs pa lda pb ldb =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum nrhs $ \pnrhs ->
withEnum lda $ \plda ->
withEnum ldb $ \pldb ->
alloca $ \pinfo -> do
dpotrs puplo pn pnrhs pa plda pb pldb pinfo
checkInfo =<< peek pinfo
pptrf uplo n pa =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
alloca $ \pinfo -> do
dpptrf puplo pn pa pinfo
info <- fromEnum `fmap` peek pinfo
assert (info >= 0) $ return info
pptrs uplo n nrhs pa pb ldb =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum nrhs $ \pnrhs ->
withEnum ldb $ \pldb ->
alloca $ \pinfo -> do
dpptrs puplo pn pnrhs pa pb pldb pinfo
checkInfo =<< peek pinfo
instance LAPACK (Complex Double) where
geqrf m n pa lda ptau =
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
checkInfo =<< callWithWork (zgeqrf pm pn pa plda ptau)
gelqf m n pa lda ptau =
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
checkInfo =<< callWithWork (zgelqf pm pn pa plda ptau)
heevr jobz range uplo n pa lda abstol pw pz ldz psuppz =
withEigJob jobz $ \pjobz ->
withEigRange range $ \prange pvl pvu pil piu ->
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
with abstol $ \pabstol ->
alloca $ \pm ->
withEnum ldz $ \pldz ->
allocaArray nsuppz $ \psuppz' -> do
checkInfo =<<
(callWithWorkRWorkIWork $
zheevr pjobz prange puplo pn pa plda pvl pvu pil piu
pabstol pm pw pz pldz psuppz')
m <- fromEnum `fmap` peek pm
when (psuppz /= nullPtr) $
forM_ [ 0..2*m - 1 ] $ \i -> do
s <- peekElemOff psuppz' i
pokeElemOff psuppz i (fromEnum s)
return m
where
nsuppz = if psuppz == nullPtr then 0 else 2 * max 1 n
unmqr side trans m n k pa lda ptau pc ldc =
withSide side $ \pside ->
withTrans trans $ \ptrans ->
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum k $ \pk ->
withEnum lda $ \plda ->
withEnum ldc $ \pldc ->
checkInfo =<< callWithWork (zunmqr pside ptrans pm pn pk pa plda ptau pc pldc)
unmlq side trans m n k pa lda ptau pc ldc =
withSide side $ \pside ->
withTrans trans $ \ptrans ->
withEnum m $ \pm ->
withEnum n $ \pn ->
withEnum k $ \pk ->
withEnum lda $ \plda ->
withEnum ldc $ \pldc ->
checkInfo =<< callWithWork (zunmlq pside ptrans pm pn pk pa plda ptau pc pldc)
larfg n palpha px incx =
withEnum n $ \pn ->
withEnum incx $ \pincx ->
alloca $ \ptau -> do
zlarfg pn palpha px pincx ptau
peek ptau
potrf uplo n pa lda =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum lda $ \plda ->
alloca $ \pinfo -> do
zpotrf puplo pn pa plda pinfo
info <- fromEnum `fmap` peek pinfo
assert (info >= 0) $ return info
potrs uplo n nrhs pa lda pb ldb =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum nrhs $ \pnrhs ->
withEnum lda $ \plda ->
withEnum ldb $ \pldb ->
alloca $ \pinfo -> do
zpotrs puplo pn pnrhs pa plda pb pldb pinfo
checkInfo =<< peek pinfo
pptrf uplo n pa =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
alloca $ \pinfo -> do
zpptrf puplo pn pa pinfo
info <- fromEnum `fmap` peek pinfo
assert (info >= 0) $ return info
pptrs uplo n nrhs pa pb ldb =
withUplo uplo $ \puplo ->
withEnum n $ \pn ->
withEnum nrhs $ \pnrhs ->
withEnum ldb $ \pldb ->
alloca $ \pinfo -> do
zpptrs puplo pn pnrhs pa pb pldb pinfo
checkInfo =<< peek pinfo
|
patperry/hs-linear-algebra
|
lib/Foreign/LAPACK.hs
|
bsd-3-clause
| 10,594 | 0 | 32 | 3,947 | 3,914 | 1,933 | 1,981 | 254 | 1 |
module Haskell99Pointfree.P33
(p33_1, p33_2, p33_3, p33_4,p33_5
) where
import Control.Monad
import Haskell99Pointfree.P32
p33_1 :: Int -> Int -> Bool
p33_1 = ((==) 1 . ) . gcd
--using own gcd version
p33_2 :: Int -> Int -> Bool
p33_2 = ((==) 1 . ) . p32_1
p33_3 :: Int -> Int -> Bool
p33_3 = ap (const (== 1) ) . gcd
p33_4 :: Int -> Int -> Bool
p33_4 = fmap (== 1) . gcd
p33_5 :: Int -> Int -> Bool
p33_5 = liftM (== 1) . gcd
|
SvenWille/Haskell99Pointfree
|
src/Haskell99Pointfree/P33.hs
|
bsd-3-clause
| 444 | 0 | 9 | 107 | 189 | 109 | 80 | 14 | 1 |
{-# LANGUAGE CPP #-}
module Driver (
E,
V,
M,
AEq,
(===),
(~==),
field,
mytest,
mycheck,
mytests,
done,
) where
import Data.AEq( AEq )
import qualified Data.AEq as AEq
import Data.Complex
import Data.List
import Debug.Trace
import System.IO
import System.Random
import Test.QuickCheck
import Text.Printf
import Text.Show.Functions
import Data.Vector.Dense( Vector )
import Data.Matrix.Dense( Matrix )
#ifdef COMPLEX
field = "Complex Double"
type E = Complex Double
#else
field = "Double"
type E = Double
#endif
type V = Vector Int E
type M = Matrix (Int,Int) E
infix 4 ===, ~==
x === y | (AEq.===) x y = True
| otherwise = trace (printf "expected `%s', but got `%s'" (show y) (show x)) False
x ~== y | (AEq.~==) x y = True
| otherwise = trace (printf "expected `%s', but got `%s'" (show y) (show x)) False
------------------------------------------------------------------------
--
-- QC driver ( taken from xmonad-0.6 )
--
debug = False
mytest :: Testable a => a -> Int -> IO (Bool, Int)
mytest a n = mycheck defaultConfig
{ configMaxTest=n
, configEvery = \n args -> let s = show n in s ++ [ '\b' | _ <- s ] } a
-- , configEvery= \n args -> if debug then show n ++ ":\n" ++ unlines args else [] } a
mycheck :: Testable a => Config -> a -> IO (Bool, Int)
mycheck config a = do
rnd <- newStdGen
mytests config (evaluate a) rnd 0 0 []
mytests :: Config -> Gen Result -> StdGen -> Int -> Int -> [[String]] -> IO (Bool, Int)
mytests config gen rnd0 ntest nfail stamps
| ntest == configMaxTest config = done "OK," ntest stamps >> return (True, ntest)
| nfail == configMaxFail config = done "Arguments exhausted after" ntest stamps >> return (True, ntest)
| otherwise =
do putStr (configEvery config ntest (arguments result)) >> hFlush stdout
case ok result of
Nothing ->
mytests config gen rnd1 ntest (nfail+1) stamps
Just True ->
mytests config gen rnd1 (ntest+1) nfail (stamp result:stamps)
Just False ->
putStr ( "Falsifiable after "
++ show ntest
++ " tests:\n"
++ unlines (arguments result)
) >> hFlush stdout >> return (False, ntest)
where
result = generate (configSize config ntest) rnd2 gen
(rnd1,rnd2) = split rnd0
done :: String -> Int -> [[String]] -> IO ()
done mesg ntest stamps = putStr ( mesg ++ " " ++ show ntest ++ " tests" ++ table )
where
table = display
. map entry
. reverse
. sort
. map pairLength
. group
. sort
. filter (not . null)
$ stamps
display [] = ".\n"
display [x] = " (" ++ x ++ ").\n"
display xs = ".\n" ++ unlines (map (++ ".") xs)
pairLength xss@(xs:_) = (length xss, xs)
entry (n, xs) = percentage n ntest
++ " "
++ concat (intersperse ", " xs)
percentage n m = show ((100 * n) `div` m) ++ "%"
------------------------------------------------------------------------
|
patperry/lapack
|
tests/Driver.hs
|
bsd-3-clause
| 3,216 | 0 | 18 | 1,002 | 1,095 | 572 | 523 | 81 | 3 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Time.BG.Tests
( tests
) where
import Data.Aeson
import Data.Aeson.Types ((.:), parseMaybe, withObject)
import Data.String
import Data.Text (Text)
import Prelude
import Test.Tasty
import Test.Tasty.HUnit
import Duckling.Dimensions.Types
import Duckling.Locale
import Duckling.Resolve
import Duckling.Testing.Asserts
import Duckling.Testing.Types hiding (examples)
import Duckling.Time.BG.Corpus
import Duckling.TimeGrain.Types (Grain(..))
import Duckling.Types (Range(..))
tests :: TestTree
tests = testGroup "BG Tests"
[ makeCorpusTest [Seal Time] corpus
, makeNegativeCorpusTest [Seal Time] negativeCorpus
]
|
facebookincubator/duckling
|
tests/Duckling/Time/BG/Tests.hs
|
bsd-3-clause
| 881 | 0 | 9 | 118 | 185 | 117 | 68 | 22 | 1 |
module Llvm.Pass.PassTester where
import Llvm.Hir.Data
import Llvm.Query.HirCxt
import Llvm.Query.Hir
import qualified Compiler.Hoopl as H
import qualified Data.Set as Ds
type Optimization m a u x = IrCxt -> a -> H.Label -> H.Graph (Node u) H.C H.C -> m (H.Graph (Node u) H.C H.C, x)
opt :: (H.CheckpointMonad m, H.FuelMonad m) => IrCxt -> a -> Optimization m a u x -> Toplevel u ->
m [(Toplevel u, (FunctionInterface, x))]
opt dl gs f (ToplevelDefine (TlDefine fn entry graph)) =
do { (graph', x) <- f dl gs entry graph
; return [(ToplevelDefine $ TlDefine fn entry graph', (fn, x))]
}
opt _ _ _ _ = return []
optModule :: (H.CheckpointMonad m, H.FuelMonad m) => Optimization m (Ds.Set (Dtype, GlobalId)) u x -> Module u ->
m (Module u, [(FunctionInterface, x)])
optModule f (Module l) =
let gs = globalIdOfModule (Module l)
dl = irCxtOfModule (Module l)
in mapM (opt dl gs f) l >>= \x -> let (lx, ly) = unzip $ concat x
in return (Module lx, ly)
|
sanjoy/hLLVM
|
src/Llvm/Pass/PassTester.hs
|
bsd-3-clause
| 1,037 | 0 | 14 | 260 | 485 | 258 | 227 | 20 | 1 |
module Main where
import Lib
main :: IO ()
main = do
putStrLn "Excercises from Chapter 27: Non-strictness."
putStrLn "Some examples commented out in main function."
putStrLn "Use 'stack ghci' to start ghci to play around. Enjoy."
-- Examples for playing around
-- print $ take' 10 $ map' (+1) (repeat' 1) -- This will not return
|
backofhan/HaskellExercises
|
CH27/app/Main.hs
|
bsd-3-clause
| 343 | 0 | 7 | 71 | 42 | 21 | 21 | 7 | 1 |
{-# OPTIONS -Wall #-}
module Chap7 where
-- import Lib
--test x = x * 42
-- Exercises: Grap Bag
-- 1.
mTh1 x y z = x * y * z
test1 = mTh1 99 2 27
mTh2 x y = \z -> x * y * z
test2 = mTh2 99 2 27
mTh3 x = \y -> \z -> x * y * z
test3 = mTh3 99 2 27
mTh4 = \x -> \y -> \z -> x * y * z
test4 = mTh4 99 2 27
testBool1 :: Bool
testBool1 = test1 == test2 && test1 == test3 && test1 == test4
-- True!
-- 2.
-- b)
-- 3.
-- a)
addOneIfOdd n = case odd n of
True -> f n
False -> n
where f n = n + 1
addOneIfOdd' n = case odd n of
True -> f n
False -> n
where f = \n -> n + 1
-- b)
addFive x y = (if x > y then y else x) + 5
addFive' = \x -> \y -> (if x > y then y else x) + 5
-- c)
mflip f = \x -> \y -> f y x
mflip' f x y = f y x
-- Exercises: Variety Pack
-- 1.
-- a), b)
k :: (x, y) -> x
k (x, y) = x
k1 :: Integer
k1 = k ((4 - 1), 10)
k2 :: String
k2 = k ("three", (1 + 2))
k3 :: Integer
k3 = k (3, True)
-- c)
-- k1, k3
-- 2.
fV2 :: (a, b, c) -> (d, e, f) -> ((a, d), (c, f))
fV2 (a, b, c) (d, e, f) = ((a, d), (c, f))
-- Exercises: Case Practice
-- 1.
functionC x y = if (x > y) then x else y
functionC' x y =
case x > y of
True -> x
False -> y
-- 2.
ifEvenAdd2 n = if even n then (n + 2) else n
ifEvenAdd2' n =
case even n of
True -> n + 2
False -> n
-- 3.
nums x =
case compare x 0 of
LT -> -1
GT -> 1
nums' x =
case compare x 0 of
LT -> -1
GT -> 1
EQ -> 0
-- Exercises: Artful Dodgy
dodgy :: Num a => a -> a -> a
dodgy x y = x + y * 10
oneIsOne :: Num a => a -> a
oneIsOne = dodgy 1
oneIsTwo :: Num a => a -> a
oneIsTwo = (flip dodgy) 2
d2 = dodgy 1 1
d3 = dodgy 2 2
d4 = dodgy 1 2
d5 = dodgy 2 1
d6 = oneIsOne 1
d7 = oneIsOne 2
d8 = oneIsTwo 1
d9 = oneIsTwo 2
d10 = oneIsOne 3
d11 = oneIsTwo 3
-- Exercise: Guard Duty
avgGrade :: (Fractional a, Ord a) => a -> Char
avgGrade x
| y >= 0.9 = 'A'
| y >= 0.8 = 'B'
| y >= 0.7 = 'C'
| y >= 0.59 = 'D'
| y < 0.59 = 'F'
where y = x / 100
-- 1.
-- test for top-most otherwise (makes no sense)
-- all inputs yield 'F'
avgGradeBroken :: (Fractional a, Ord a) => a -> Char
avgGradeBroken x
| otherwise = 'F'
| y >= 0.9 = 'A'
| y >= 0.8 = 'B'
| y >= 0.7 = 'C'
| y >= 0.59 = 'D'
where y = x / 100
-- 2.
-- Gruard reorder test
-- Inputs >= 70 yield result 'C'
avgGradeBroken2 :: (Fractional a, Ord a) => a -> Char
avgGradeBroken2 x
| y >= 0.7 = 'C'
| y >= 0.9 = 'A'
| y >= 0.8 = 'B'
| y >= 0.59 = 'D'
| y < 0.59 = 'F'
where y = x / 100
-- 3., 4., 5.
-- b.
pal :: Eq a => [a] -> Bool
pal xs
| xs == reverse xs = True
| otherwise = False
-- 6., 7., 8.
-- c.
numbers ::(Ord a, Num a, Num b) => a -> b
numbers x
| x < 0 = -1
| x == 0 = 0
| x > 0 = 1
-- Chapter Exercises
-- Multiple choise
-- 1. d.
-- 2. b.
-- 3. d.
-- 4. b.
-- 5.
-- :t fChap55 True
-- fChapE True :: Bool
fChapE5 :: a -> a
fChapE5 x = x
-- Let's write code
-- 1.
tensDigit :: Integral a => a -> a
tensDigit x = d
where xLast = x `div` 10
d = xLast `mod` 10
-- a), b)
-- This is just weird, so maybe I am missing something
tensDigit' :: Integral a => a -> a
tensDigit' x = d
where xLast = fst . divMod x $ 10
d = snd . divMod xLast $ 10
--c)
hunsDigit :: Integral a => a -> a
hunsDigit x = d
where xLast = fst . divMod x $ 100
d = snd . divMod xLast $ 10
-- extra
nthDigit :: Integral a => a -> a -> a
nthDigit x n = digit
where divisor = 10 ^ (n - 1)
xLast = fst . divMod x $ divisor
digit = snd . divMod xLast $ 10
-- 2.
foolBool3 :: a -> a -> Bool -> a
foolBool3 x y True = x
foolBool3 x y False = y
foolBool1 :: a -> a -> Bool -> a
foolBool1 x y bool =
case bool of
True -> x
False -> y
foolBool2 :: a -> a -> Bool -> a
foolBool2 x y bool
| bool == True = x
| bool == False = y
-- 3.
g :: (a -> b) -> (a, c) -> (b, c)
g f (x, y) = (f x, y)
|
tkasu/haskellbook-adventure
|
app/Chap7.hs
|
bsd-3-clause
| 3,919 | 0 | 10 | 1,270 | 1,870 | 993 | 877 | 135 | 3 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE NoImplicitPrelude #-}
------------------------------------------------------------------------------
-- |
-- Module : Instances
-- Copyright : (C) 2014 Samuli Thomasson
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Samuli Thomasson <[email protected]>
-- Stability : experimental
-- Portability : non-portable
------------------------------------------------------------------------------
module Instances where
import ClassyPrelude
import Database.Persist.Sql
import qualified Text.PrettyPrint.ANSI.Leijen as P
instance P.Pretty Text where
pretty = P.pretty . unpack
|
SimSaladin/animu-watch
|
src/Instances.hs
|
bsd-3-clause
| 684 | 0 | 7 | 105 | 55 | 39 | 16 | 8 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
-- | Blockchain listener.
-- Callbacks on application and rollback.
module Pos.DB.Block.BListener
( MonadBListener (..)
, onApplyBlocksStub
, onRollbackBlocksStub
) where
import Universum
import Control.Monad.Trans (MonadTrans (..))
import Pos.Chain.Block (Blund)
import Pos.Core (ProtocolConstants)
import Pos.Core.Chrono (NE, NewestFirst (..), OldestFirst (..))
import Pos.Core.NetworkMagic (NetworkMagic)
import Pos.DB.BatchOp (SomeBatchOp)
class Monad m => MonadBListener m where
-- Callback will be called after putting blocks into BlocksDB
-- and before changing of GStateDB.
-- Callback action will be performed under block lock.
onApplyBlocks :: NetworkMagic -> OldestFirst NE Blund -> m SomeBatchOp
-- Callback will be called before changing of GStateDB.
-- Callback action will be performed under block lock.
onRollbackBlocks :: NetworkMagic -> ProtocolConstants -> NewestFirst NE Blund -> m SomeBatchOp
instance {-# OVERLAPPABLE #-}
( MonadBListener m, Monad m, MonadTrans t, Monad (t m)) =>
MonadBListener (t m)
where
onApplyBlocks nm = lift . onApplyBlocks nm
onRollbackBlocks nm pc = lift . onRollbackBlocks nm pc
onApplyBlocksStub
:: Monad m
=> NetworkMagic -> OldestFirst NE Blund -> m SomeBatchOp
onApplyBlocksStub _ _ = pure mempty
onRollbackBlocksStub
:: Monad m
=> NetworkMagic -> NewestFirst NE Blund -> m SomeBatchOp
onRollbackBlocksStub _ _ = pure mempty
|
input-output-hk/pos-haskell-prototype
|
db/src/Pos/DB/Block/BListener.hs
|
mit
| 1,611 | 0 | 10 | 374 | 344 | 189 | 155 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./Comorphisms/CoCASL2CoSubCFOL.hs
Description : Extension of CASL2SubCFOL to CoCASL
Copyright : (c) Till Mossakowski, C.Maeder, Uni Bremen 2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (imports Logic.Comorphism)
coding out partiality, lifted to the level of CoCASL
-}
module Comorphisms.CoCASL2CoSubCFOL where
import Logic.Logic
import Logic.Comorphism
-- CoCASL
import CoCASL.Logic_CoCASL
import CoCASL.AS_CoCASL
import CoCASL.StatAna
import CoCASL.Sublogic
import CASL.Sublogic as SL
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.Morphism
import CASL.Fold
import CASL.Simplify
import Comorphisms.CASL2SubCFOL
import qualified Data.Map as Map
import qualified Data.Set as Set
import Common.AS_Annotation
import Common.ProofUtils
-- | The identity of the comorphism
data CoCASL2CoSubCFOL = CoCASL2CoSubCFOL deriving (Show)
instance Language CoCASL2CoSubCFOL -- default definition is okay
instance Comorphism CoCASL2CoSubCFOL
CoCASL CoCASL_Sublogics
C_BASIC_SPEC CoCASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CSign
CoCASLMor
Symbol RawSymbol ()
CoCASL CoCASL_Sublogics
C_BASIC_SPEC CoCASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CSign
CoCASLMor
Symbol RawSymbol () where
sourceLogic CoCASL2CoSubCFOL = CoCASL
sourceSublogic CoCASL2CoSubCFOL = SL.caslTop
targetLogic CoCASL2CoSubCFOL = CoCASL
mapSublogic CoCASL2CoSubCFOL sl = Just $
if has_part sl then sl
{ has_part = False -- partiality is coded out
, has_pred = True
, which_logic = max Horn $ which_logic sl
, has_eq = True} else sl
map_theory CoCASL2CoSubCFOL (sig, sens) =
let bsrts = sortsWithBottom (formulaTreatment defaultCASL2SubCFOL)
sig $ Set.unions $ map (botCoFormulaSorts . sentence) sens
e = encodeSig bsrts sig
sens1 = map (mapNamed mapFORMULA) $ generateAxioms
(uniqueBottom defaultCASL2SubCFOL) bsrts sig
sens2 = map (mapNamed (simplifyFormula simC_FORMULA
. codeCoFormula bsrts)) sens
in return (e, nameAndDisambiguate $ sens1 ++ sens2)
map_morphism CoCASL2CoSubCFOL mor@Morphism {msource = src, mtarget = tar} =
let mkBSrts s = sortsWithBottom
(formulaTreatment defaultCASL2SubCFOL) s Set.empty
in return mor
{ msource = encodeSig (mkBSrts src) src
, mtarget = encodeSig (mkBSrts tar) tar
, op_map = Map.map (\ (i, _) -> (i, Total)) $ op_map mor }
map_sentence CoCASL2CoSubCFOL sig sen =
return $ simplifyFormula simC_FORMULA $ codeCoFormula
(sortsWithBottom (formulaTreatment defaultCASL2SubCFOL)
sig $ botCoFormulaSorts sen) sen
map_symbol CoCASL2CoSubCFOL _ s =
Set.singleton s {symbType = totalizeSymbType $ symbType s}
has_model_expansion CoCASL2CoSubCFOL = True
is_weakly_amalgamable CoCASL2CoSubCFOL = True
codeCoRecord :: Set.Set SORT
-> Record C_FORMULA (FORMULA C_FORMULA) (TERM C_FORMULA)
codeCoRecord bsrts =
codeRecord (uniqueBottom defaultCASL2SubCFOL) bsrts $ codeC_FORMULA bsrts
codeCoFormula :: Set.Set SORT -> FORMULA C_FORMULA -> FORMULA C_FORMULA
codeCoFormula = foldFormula . codeCoRecord
codeC_FORMULA :: Set.Set SORT -> C_FORMULA -> C_FORMULA
codeC_FORMULA bsrts = foldC_Formula (codeCoRecord bsrts) mapCoRecord
{foldCoSort_gen_ax = \ _ s o b -> CoSort_gen_ax s (map totalizeOpSymb o) b}
simC_FORMULA :: C_FORMULA -> C_FORMULA
simC_FORMULA = foldC_Formula (simplifyRecord simC_FORMULA) mapCoRecord
botCoSorts :: C_FORMULA -> Set.Set SORT
botCoSorts =
foldC_Formula (botSorts botCoSorts) (constCoRecord Set.unions Set.empty)
botCoFormulaSorts :: FORMULA C_FORMULA -> Set.Set SORT
botCoFormulaSorts = foldFormula $ botSorts botCoSorts
|
spechub/Hets
|
Comorphisms/CoCASL2CoSubCFOL.hs
|
gpl-2.0
| 4,122 | 0 | 15 | 960 | 906 | 474 | 432 | 81 | 1 |
{-# LANGUAGE MultiParamTypeClasses, DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Morphism extension for modal signature morphisms
Copyright : DFKI GmbH 2009
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
-}
module ExtModal.MorphismExtension where
import Data.Data
import qualified Data.Map as Map
import qualified Data.Set as Set
import CASL.Morphism
import CASL.Sign
import CASL.MapSentence
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.Utils
import qualified Common.Lib.MapSet as MapSet
import ExtModal.ExtModalSign
import ExtModal.AS_ExtModal
import ExtModal.Print_AS ()
data MorphExtension = MorphExtension
{ mod_map :: Map.Map Id Id
, nom_map :: Map.Map Id Id
} deriving (Show, Eq, Ord, Typeable, Data)
emptyMorphExtension :: MorphExtension
emptyMorphExtension = MorphExtension Map.empty Map.empty
instance Pretty MorphExtension where
pretty me = pretty (mod_map me) $+$ pretty (nom_map me)
instance MorphismExtension EModalSign MorphExtension where
ideMorphismExtension _ = emptyMorphExtension
composeMorphismExtension fme1 fme2 = let
me1 = extended_map fme1
me2 = extended_map fme2
src = msource fme1
mSrc = extendedInfo src
in return $ MorphExtension
(composeMap (MapSet.setToMap $ modalities mSrc) (mod_map me1)
$ mod_map me2)
$ composeMap (MapSet.setToMap $ nominals mSrc) (nom_map me1)
$ nom_map me2
-- ignore inverses
isInclusionMorphismExtension me =
Map.null (mod_map me) && Map.null (nom_map me)
inducedEMsign :: InducedSign EM_FORMULA EModalSign MorphExtension EModalSign
inducedEMsign sm om pm m sig =
let ms = extendedInfo sig
mods = mod_map m
tmods = termMods ms
msm i = Map.findWithDefault i i
$ if Set.member i tmods then sm else mods
in ms
{ flexOps = inducedOpMap sm om $ flexOps ms
, flexPreds = inducedPredMap sm pm $ flexPreds ms
, modalities = Set.map msm $ modalities ms
, timeMods = Set.map msm $ timeMods ms
, termMods = Set.map (\ i -> Map.findWithDefault i i sm) tmods
, nominals = Set.map (\ i -> Map.findWithDefault i i $ nom_map m)
$ nominals ms
}
mapEMmod :: Morphism EM_FORMULA EModalSign MorphExtension -> MODALITY
-> MODALITY
mapEMmod morph tm = case tm of
SimpleMod sm -> case Map.lookup (simpleIdToId sm) $ mod_map
$ extended_map morph of
Just ni -> SimpleMod $ idToSimpleId ni
Nothing -> tm
ModOp o tm1 tm2 -> ModOp o (mapEMmod morph tm1) $ mapEMmod morph tm2
TransClos tm1 -> TransClos $ mapEMmod morph tm1
Guard frm -> Guard $ mapSen mapEMform morph frm
TermMod trm -> TermMod $ mapTerm mapEMform morph trm
mapEMprefix :: Morphism EM_FORMULA EModalSign MorphExtension -> FormPrefix
-> FormPrefix
mapEMprefix morph pf = case pf of
BoxOrDiamond choice tm leq_geq num ->
BoxOrDiamond choice (mapEMmod morph tm) leq_geq num
_ -> pf
-- Modal formula mapping via signature morphism
mapEMform :: MapSen EM_FORMULA EModalSign MorphExtension
mapEMform morph frm =
let rmapf = mapSen mapEMform morph
em = extended_map morph
in case frm of
PrefixForm p f pos -> PrefixForm (mapEMprefix morph p) (rmapf f) pos
UntilSince choice f1 f2 pos -> UntilSince choice (rmapf f1) (rmapf f2) pos
ModForm (ModDefn ti te is fs pos) -> ModForm $ ModDefn ti te
(map (fmap $ \ i -> Map.findWithDefault i i
$ if Set.member i $ sortSet $ msource morph then
sort_map morph else mod_map em) is)
(map (fmap $ mapEMframe morph) fs) pos
mapEMframe :: Morphism EM_FORMULA EModalSign MorphExtension -> FrameForm
-> FrameForm
mapEMframe morph (FrameForm vs fs r) =
FrameForm vs (map (fmap $ mapSen mapEMform morph) fs) r
|
keithodulaigh/Hets
|
ExtModal/MorphismExtension.hs
|
gpl-2.0
| 3,901 | 0 | 22 | 892 | 1,180 | 590 | 590 | 86 | 6 |
{-#LANGUAGE TypeOperators, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
module Carnap.Languages.PureFirstOrder.Logic.IchikawaJenkins (ichikawaJenkinsQLCalc, parseIchikawaJenkinsQL) where
import Data.Map as M (lookup, Map,empty)
import Text.Parsec
import Carnap.Core.Data.Types (Form)
import Carnap.Languages.PureFirstOrder.Syntax
import Carnap.Languages.PureFirstOrder.Parser
import Carnap.Languages.PureFirstOrder.Logic.Magnus
import Carnap.Languages.PurePropositional.Logic.IchikawaJenkins
import Carnap.Calculi.NaturalDeduction.Syntax
import Carnap.Calculi.NaturalDeduction.Parser
import Carnap.Calculi.NaturalDeduction.Checker (hoProcessLineFitchMemo, hoProcessLineFitch)
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericConstructors
import Carnap.Languages.PureFirstOrder.Logic.Rules
import Carnap.Languages.PurePropositional.Logic.Rules (premConstraint,axiom)
data IchikawaJenkinsQL = IJSL IchikawaJenkinsSL | QL MagnusQL
deriving Eq
instance Show IchikawaJenkinsQL where
show (IJSL x) = show x
show (QL x) = show x
instance Inference IchikawaJenkinsQL PureLexiconFOL (Form Bool) where
ruleOf (QL x) = ruleOf x
premisesOf (IJSL x) = map liftSequent (premisesOf x)
premisesOf r = upperSequents (ruleOf r)
conclusionOf (IJSL x) = liftSequent (conclusionOf x)
conclusionOf r = lowerSequent (ruleOf r)
indirectInference (IJSL x) = indirectInference x
indirectInference (QL x) = indirectInference x
restriction (QL x) = restriction x
--XXX: handle stricter eigenconstraint here
restriction _ = Nothing
isAssumption (IJSL x) = isAssumption x
isAssumption _ = False
isPremise (IJSL x) = isPremise x
isPremise (QL x) = isPremise x
isPremise _ = False
parseIchikawaJenkinsQL rtc = try quantRule <|> liftProp
where liftProp = do r <- parseIchikawaJenkinsSL (RuntimeNaturalDeductionConfig mempty mempty)
return (map IJSL r)
quantRule = do r <- choice (map (try . string) ["∀I", "AI", "∀E", "AE", "∃I", "EI", "∃E", "EE", "=I","=E","PR"])
case r of
r | r `elem` ["∀I","AI"] -> returnQL [UI]
| r `elem` ["∀E","AE"] -> returnQL [UE]
| r `elem` ["∃I","EI"] -> returnQL [EI]
| r `elem` ["∃E","EE"] -> returnQL [EE1, EE2]
| r == "PR" -> returnQL [Pr (problemPremises rtc)]
| r == "=I" -> returnQL [IDI]
| r == "=E" -> returnQL [IDE1,IDE2]
returnQL = return . map QL
parseIchikawaJenkinsQLProof :: RuntimeNaturalDeductionConfig PureLexiconFOL (Form Bool) -> String -> [DeductionLine IchikawaJenkinsQL PureLexiconFOL (Form Bool)]
parseIchikawaJenkinsQLProof rtc = toDeductionFitch (parseIchikawaJenkinsQL rtc) magnusFOLFormulaParser
ichikawaJenkinsQLCalc = mkNDCalc
{ ndRenderer = FitchStyle StandardFitch
, ndParseProof = parseIchikawaJenkinsQLProof
, ndProcessLine = hoProcessLineFitch
, ndProcessLineMemo = Just hoProcessLineFitchMemo
, ndParseSeq = parseSeqOver magnusFOLFormulaParser
, ndParseForm = magnusFOLFormulaParser
, ndNotation = ndNotation ichikawaJenkinsSLCalc
}
|
gleachkr/Carnap
|
Carnap/src/Carnap/Languages/PureFirstOrder/Logic/IchikawaJenkins.hs
|
gpl-3.0
| 3,453 | 0 | 17 | 756 | 906 | 494 | 412 | 61 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudTrail.UpdateTrail
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- From the command line, use 'update-subscription'.
--
-- Updates the settings that specify delivery of log files. Changes to a
-- trail do not require stopping the CloudTrail service. Use this action to
-- designate an existing bucket for log delivery. If the existing bucket
-- has previously been a target for CloudTrail log files, an IAM policy
-- exists for the bucket.
--
-- /See:/ <http://docs.aws.amazon.com/awscloudtrail/latest/APIReference/API_UpdateTrail.html AWS API Reference> for UpdateTrail.
module Network.AWS.CloudTrail.UpdateTrail
(
-- * Creating a Request
updateTrail
, UpdateTrail
-- * Request Lenses
, utS3KeyPrefix
, utSNSTopicName
, utCloudWatchLogsLogGroupARN
, utIncludeGlobalServiceEvents
, utCloudWatchLogsRoleARN
, utS3BucketName
, utName
-- * Destructuring the Response
, updateTrailResponse
, UpdateTrailResponse
-- * Response Lenses
, utrsS3KeyPrefix
, utrsSNSTopicName
, utrsCloudWatchLogsLogGroupARN
, utrsName
, utrsIncludeGlobalServiceEvents
, utrsCloudWatchLogsRoleARN
, utrsS3BucketName
, utrsResponseStatus
) where
import Network.AWS.CloudTrail.Types
import Network.AWS.CloudTrail.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Specifies settings to update for the trail.
--
-- /See:/ 'updateTrail' smart constructor.
data UpdateTrail = UpdateTrail'
{ _utS3KeyPrefix :: !(Maybe Text)
, _utSNSTopicName :: !(Maybe Text)
, _utCloudWatchLogsLogGroupARN :: !(Maybe Text)
, _utIncludeGlobalServiceEvents :: !(Maybe Bool)
, _utCloudWatchLogsRoleARN :: !(Maybe Text)
, _utS3BucketName :: !(Maybe Text)
, _utName :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateTrail' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utS3KeyPrefix'
--
-- * 'utSNSTopicName'
--
-- * 'utCloudWatchLogsLogGroupARN'
--
-- * 'utIncludeGlobalServiceEvents'
--
-- * 'utCloudWatchLogsRoleARN'
--
-- * 'utS3BucketName'
--
-- * 'utName'
updateTrail
:: Text -- ^ 'utName'
-> UpdateTrail
updateTrail pName_ =
UpdateTrail'
{ _utS3KeyPrefix = Nothing
, _utSNSTopicName = Nothing
, _utCloudWatchLogsLogGroupARN = Nothing
, _utIncludeGlobalServiceEvents = Nothing
, _utCloudWatchLogsRoleARN = Nothing
, _utS3BucketName = Nothing
, _utName = pName_
}
-- | Specifies the Amazon S3 key prefix that precedes the name of the bucket
-- you have designated for log file delivery.
utS3KeyPrefix :: Lens' UpdateTrail (Maybe Text)
utS3KeyPrefix = lens _utS3KeyPrefix (\ s a -> s{_utS3KeyPrefix = a});
-- | Specifies the name of the Amazon SNS topic defined for notification of
-- log file delivery.
utSNSTopicName :: Lens' UpdateTrail (Maybe Text)
utSNSTopicName = lens _utSNSTopicName (\ s a -> s{_utSNSTopicName = a});
-- | Specifies a log group name using an Amazon Resource Name (ARN), a unique
-- identifier that represents the log group to which CloudTrail logs will
-- be delivered. Not required unless you specify CloudWatchLogsRoleArn.
utCloudWatchLogsLogGroupARN :: Lens' UpdateTrail (Maybe Text)
utCloudWatchLogsLogGroupARN = lens _utCloudWatchLogsLogGroupARN (\ s a -> s{_utCloudWatchLogsLogGroupARN = a});
-- | Specifies whether the trail is publishing events from global services
-- such as IAM to the log files.
utIncludeGlobalServiceEvents :: Lens' UpdateTrail (Maybe Bool)
utIncludeGlobalServiceEvents = lens _utIncludeGlobalServiceEvents (\ s a -> s{_utIncludeGlobalServiceEvents = a});
-- | Specifies the role for the CloudWatch Logs endpoint to assume to write
-- to a user’s log group.
utCloudWatchLogsRoleARN :: Lens' UpdateTrail (Maybe Text)
utCloudWatchLogsRoleARN = lens _utCloudWatchLogsRoleARN (\ s a -> s{_utCloudWatchLogsRoleARN = a});
-- | Specifies the name of the Amazon S3 bucket designated for publishing log
-- files.
utS3BucketName :: Lens' UpdateTrail (Maybe Text)
utS3BucketName = lens _utS3BucketName (\ s a -> s{_utS3BucketName = a});
-- | Specifies the name of the trail.
utName :: Lens' UpdateTrail Text
utName = lens _utName (\ s a -> s{_utName = a});
instance AWSRequest UpdateTrail where
type Rs UpdateTrail = UpdateTrailResponse
request = postJSON cloudTrail
response
= receiveJSON
(\ s h x ->
UpdateTrailResponse' <$>
(x .?> "S3KeyPrefix") <*> (x .?> "SnsTopicName") <*>
(x .?> "CloudWatchLogsLogGroupArn")
<*> (x .?> "Name")
<*> (x .?> "IncludeGlobalServiceEvents")
<*> (x .?> "CloudWatchLogsRoleArn")
<*> (x .?> "S3BucketName")
<*> (pure (fromEnum s)))
instance ToHeaders UpdateTrail where
toHeaders
= const
(mconcat
["X-Amz-Target" =#
("com.amazonaws.cloudtrail.v20131101.CloudTrail_20131101.UpdateTrail"
:: ByteString),
"Content-Type" =#
("application/x-amz-json-1.1" :: ByteString)])
instance ToJSON UpdateTrail where
toJSON UpdateTrail'{..}
= object
(catMaybes
[("S3KeyPrefix" .=) <$> _utS3KeyPrefix,
("SnsTopicName" .=) <$> _utSNSTopicName,
("CloudWatchLogsLogGroupArn" .=) <$>
_utCloudWatchLogsLogGroupARN,
("IncludeGlobalServiceEvents" .=) <$>
_utIncludeGlobalServiceEvents,
("CloudWatchLogsRoleArn" .=) <$>
_utCloudWatchLogsRoleARN,
("S3BucketName" .=) <$> _utS3BucketName,
Just ("Name" .= _utName)])
instance ToPath UpdateTrail where
toPath = const "/"
instance ToQuery UpdateTrail where
toQuery = const mempty
-- | Returns the objects or data listed below if successful. Otherwise,
-- returns an error.
--
-- /See:/ 'updateTrailResponse' smart constructor.
data UpdateTrailResponse = UpdateTrailResponse'
{ _utrsS3KeyPrefix :: !(Maybe Text)
, _utrsSNSTopicName :: !(Maybe Text)
, _utrsCloudWatchLogsLogGroupARN :: !(Maybe Text)
, _utrsName :: !(Maybe Text)
, _utrsIncludeGlobalServiceEvents :: !(Maybe Bool)
, _utrsCloudWatchLogsRoleARN :: !(Maybe Text)
, _utrsS3BucketName :: !(Maybe Text)
, _utrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'UpdateTrailResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utrsS3KeyPrefix'
--
-- * 'utrsSNSTopicName'
--
-- * 'utrsCloudWatchLogsLogGroupARN'
--
-- * 'utrsName'
--
-- * 'utrsIncludeGlobalServiceEvents'
--
-- * 'utrsCloudWatchLogsRoleARN'
--
-- * 'utrsS3BucketName'
--
-- * 'utrsResponseStatus'
updateTrailResponse
:: Int -- ^ 'utrsResponseStatus'
-> UpdateTrailResponse
updateTrailResponse pResponseStatus_ =
UpdateTrailResponse'
{ _utrsS3KeyPrefix = Nothing
, _utrsSNSTopicName = Nothing
, _utrsCloudWatchLogsLogGroupARN = Nothing
, _utrsName = Nothing
, _utrsIncludeGlobalServiceEvents = Nothing
, _utrsCloudWatchLogsRoleARN = Nothing
, _utrsS3BucketName = Nothing
, _utrsResponseStatus = pResponseStatus_
}
-- | Specifies the Amazon S3 key prefix that precedes the name of the bucket
-- you have designated for log file delivery.
utrsS3KeyPrefix :: Lens' UpdateTrailResponse (Maybe Text)
utrsS3KeyPrefix = lens _utrsS3KeyPrefix (\ s a -> s{_utrsS3KeyPrefix = a});
-- | Specifies the name of the Amazon SNS topic defined for notification of
-- log file delivery.
utrsSNSTopicName :: Lens' UpdateTrailResponse (Maybe Text)
utrsSNSTopicName = lens _utrsSNSTopicName (\ s a -> s{_utrsSNSTopicName = a});
-- | Specifies the Amazon Resource Name (ARN) of the log group to which
-- CloudTrail logs will be delivered.
utrsCloudWatchLogsLogGroupARN :: Lens' UpdateTrailResponse (Maybe Text)
utrsCloudWatchLogsLogGroupARN = lens _utrsCloudWatchLogsLogGroupARN (\ s a -> s{_utrsCloudWatchLogsLogGroupARN = a});
-- | Specifies the name of the trail.
utrsName :: Lens' UpdateTrailResponse (Maybe Text)
utrsName = lens _utrsName (\ s a -> s{_utrsName = a});
-- | Specifies whether the trail is publishing events from global services
-- such as IAM to the log files.
utrsIncludeGlobalServiceEvents :: Lens' UpdateTrailResponse (Maybe Bool)
utrsIncludeGlobalServiceEvents = lens _utrsIncludeGlobalServiceEvents (\ s a -> s{_utrsIncludeGlobalServiceEvents = a});
-- | Specifies the role for the CloudWatch Logs endpoint to assume to write
-- to a user’s log group.
utrsCloudWatchLogsRoleARN :: Lens' UpdateTrailResponse (Maybe Text)
utrsCloudWatchLogsRoleARN = lens _utrsCloudWatchLogsRoleARN (\ s a -> s{_utrsCloudWatchLogsRoleARN = a});
-- | Specifies the name of the Amazon S3 bucket designated for publishing log
-- files.
utrsS3BucketName :: Lens' UpdateTrailResponse (Maybe Text)
utrsS3BucketName = lens _utrsS3BucketName (\ s a -> s{_utrsS3BucketName = a});
-- | The response status code.
utrsResponseStatus :: Lens' UpdateTrailResponse Int
utrsResponseStatus = lens _utrsResponseStatus (\ s a -> s{_utrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-cloudtrail/gen/Network/AWS/CloudTrail/UpdateTrail.hs
|
mpl-2.0
| 10,278 | 0 | 18 | 2,302 | 1,577 | 938 | 639 | 179 | 1 |
module Main where
import HplAssets.Hephaestus.IO
import FeatureModel.Types
main = buildHpl fcAllIn
where
fcAllIn = FeatureConfiguration
$ Root
(f { fId = "HephaestusPL_AllIn" })
[
Root
(f { fId = "SPLAsset" }) [
Leaf $ f { fId = "UseCase" },
Leaf $ f { fId = "BusinessProcess" },
Leaf $ f { fId = "DTMC" },
Leaf $ f { fId = "Code" },
Leaf $ f { fId = "Requirement" },
Leaf $ f { fId = "Cloud" }],
Root
(f { fId = "OutpuFormat" }) [
Leaf $ f { fId = "UcmToXML" },
Leaf $ f { fId = "UcmToLatex"},
Leaf $ f { fId = "ReqToLatex"},
Leaf $ f { fId = "BpmToXML" }]
]
-- To turn off warnings
f = Feature {
fId = undefined,
fName = undefined,
fType = undefined,
groupType = undefined,
properties = undefined
}
|
alessandroleite/hephaestus-pl
|
src/meta-hephaestus/HplDrivers/BuildAllFeatures.hs
|
lgpl-3.0
| 1,159 | 2 | 14 | 602 | 278 | 167 | 111 | 28 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, BangPatterns #-}
-- | Definitions concerning the 'ScionM' monad.
module Scion.Types.Monad
( module Scion.Types.Monad,
module Scion.Types.Core
)
where
import Scion.Types.Compiler
import Scion.Types.Session
import Scion.Types.Core
import Control.Applicative
import Control.Monad ( when )
import qualified Data.Map as M
import Data.IORef
import System.IO ( hFlush, stdout )
-- * The Scion Monad and Session State
data GlobalState = GlobalState
{ gsSessions :: M.Map SessionId SessionState
, gsNextSessionId :: !SessionId
, gsWorkerStarter :: WorkerStarter
, gsLogLevel :: Verbosity
, gsExtensions :: Maybe [Extension]
, gsCleanupTodos :: [IO ()] -- in reversed order
}
mkGlobalState :: IO (IORef GlobalState)
mkGlobalState = newIORef
GlobalState { gsSessions = M.empty
, gsNextSessionId = firstSessionId
, gsWorkerStarter = defaultWorkerStarter "scion-worker"
, gsLogLevel = normal
, gsExtensions = Nothing
, gsCleanupTodos = []
}
-- | The 'ScionM' monad. It contains the state to manage multiple
-- active sessions.
newtype ScionM a
= ScionM { unScionM :: IORef GlobalState -> IO a }
runScion :: ScionM a -> IO a
runScion m = do
ref <- mkGlobalState
unScionM m ref `finally`
(cleanup =<< (reverse . gsCleanupTodos <$> readIORef ref))
where
cleanup = mapM_ (\c -> c `onException` return ())
instance Monad ScionM where
return x = ScionM $ \_ -> return x
(ScionM ma) >>= fb = ScionM $ \s -> do
a <- ma s
unScionM (fb a) s
fail msg = ScionM $ \_ -> throwIO $ ScionException $ "FATAL: " ++ msg
instance Functor ScionM where
fmap f (ScionM ma) = ScionM (fmap f . ma)
instance Applicative ScionM where
pure a = ScionM $ \_ -> return a
ScionM mf <*> ScionM ma =
ScionM $ \s -> do f <- mf s; a <- ma s; return (f a)
liftScionM :: IO a -> ScionM a
liftScionM m = ScionM $ \_ -> m
genSessionId :: ScionM SessionId
genSessionId = ScionM $ \ref ->
atomicModifyIORef ref $ \gs ->
let !sid = gsNextSessionId gs in
(gs{ gsNextSessionId = succ sid }, sid)
-- | Register a 'SessionState' with the given 'SessionId'. (Internal)
--
-- Assumes that no other state is registered with this @SessionId@.
registerSession :: SessionId -> SessionState -> ScionM ()
registerSession sid sess = ScionM $ \r ->
atomicModifyIORef r $ \gs ->
let !sessions' = M.insert sid sess (gsSessions gs) in
(gs{ gsSessions = sessions' }, ())
-- | Return the state for the 'SessionId'. The session must exist.
getSessionState :: SessionId -> ScionM SessionState
getSessionState sid = ScionM $ \r -> do
gs <- readIORef r
case M.lookup sid (gsSessions gs) of
Just s -> return s
Nothing -> scionError $ "Not an active session: " ++ show sid
doesSessionExist :: SessionId -> ScionM Bool
doesSessionExist sid = ScionM $ \r -> do
gs <- readIORef r
case M.lookup sid (gsSessions gs) of
Just _ -> return True
Nothing -> return False
activeSessions :: ScionM [SessionId]
activeSessions = ScionM $ \r -> do
M.keys . gsSessions <$> readIORef r
activeSessionsFull :: ScionM (M.Map SessionId SessionState)
activeSessionsFull = ScionM $ \r -> gsSessions <$> readIORef r
-- | Unregister a 'SessionId'. NOTE: Does not stop the worker.
unregisterSession :: SessionId -> ScionM ()
unregisterSession sid = ScionM $ \r ->
atomicModifyIORef r $ \gs ->
let !sessions' = M.delete sid (gsSessions gs) in
let !gs' = gs{ gsSessions = sessions' } in
(gs', ())
-- | Set the function that starts a worker process. See
-- 'WorkerStarter'.
setWorkerStarter :: WorkerStarter -> ScionM ()
setWorkerStarter f = ScionM $ \r ->
atomicModifyIORef r $ \gs -> (gs{ gsWorkerStarter = f }, ())
-- | Get the current function that starts a worker process. See
-- 'WorkerStarter'.
getWorkerStarter :: ScionM WorkerStarter
getWorkerStarter =
ScionM $ \r -> gsWorkerStarter `fmap` readIORef r
modifySessionState :: SessionId -> (SessionState -> (SessionState, a))
-> ScionM a
modifySessionState sid f = ScionM $ \r ->
atomicModifyIORef r $ \gs ->
case M.lookup sid (gsSessions gs) of
Just ss -> do
let (!ss', a) = f ss
(gs{ gsSessions = M.insert sid ss' (gsSessions gs) }, a)
Nothing ->
error $ "modifySessionState: Not an active session: " ++ show sid
getExtensions :: ScionM (Maybe [Extension])
getExtensions = ScionM $ \r -> gsExtensions <$> readIORef r
setExtensions :: [Extension] -> ScionM ()
setExtensions exts = ScionM $ \r ->
atomicModifyIORef r $ \gs ->
(gs{ gsExtensions = Just exts }, ())
instance MonadIO ScionM where
liftIO m = liftScionM $ liftIO m
instance ExceptionMonad ScionM where
gcatch (ScionM act) handler =
ScionM $ \s -> act s `gcatch` (\e -> unScionM (handler e) s)
gblock (ScionM act) = ScionM $ \s -> gblock (act s)
gunblock (ScionM act) = ScionM $ \s -> gunblock (act s)
instance LogMonad ScionM where
setVerbosity v = ScionM $ \r ->
atomicModifyIORef r (\gs -> (gs{ gsLogLevel = v }, ()))
getVerbosity = ScionM $ \r -> gsLogLevel <$> readIORef r
message verb msg = do
v <- getVerbosity
when (verb <= v) $ io $ putStrLn msg >> hFlush stdout
addCleanupTodo :: IO () -> ScionM ()
addCleanupTodo cleanup = ScionM $ \r ->
atomicModifyIORef r $ \gs ->
(gs{ gsCleanupTodos = cleanup : gsCleanupTodos gs }, ())
|
nominolo/scion
|
src/Scion/Types/Monad.hs
|
bsd-3-clause
| 5,547 | 0 | 19 | 1,322 | 1,809 | 941 | 868 | 124 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Sensor_msgs.Imu where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Ros.Internal.Msg.HeaderSupport
import qualified Data.Vector.Storable as V
import qualified Ros.Geometry_msgs.Quaternion as Quaternion
import qualified Ros.Geometry_msgs.Vector3 as Vector3
import qualified Ros.Std_msgs.Header as Header
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data Imu = Imu { _header :: Header.Header
, _orientation :: Quaternion.Quaternion
, _orientation_covariance :: V.Vector P.Double
, _angular_velocity :: Vector3.Vector3
, _angular_velocity_covariance :: V.Vector P.Double
, _linear_acceleration :: Vector3.Vector3
, _linear_acceleration_covariance :: V.Vector P.Double
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''Imu)
instance RosBinary Imu where
put obj' = put (_header obj') *> put (_orientation obj') *> put (_orientation_covariance obj') *> put (_angular_velocity obj') *> put (_angular_velocity_covariance obj') *> put (_linear_acceleration obj') *> put (_linear_acceleration_covariance obj')
get = Imu <$> get <*> get <*> get <*> get <*> get <*> get <*> get
putMsg = putStampedMsg
instance HasHeader Imu where
getSequence = view (header . Header.seq)
getFrame = view (header . Header.frame_id)
getStamp = view (header . Header.stamp)
setSequence = set (header . Header.seq)
instance MsgInfo Imu where
sourceMD5 _ = "6a62c6daae103f4ff57a132d6f95cec2"
msgTypeName _ = "sensor_msgs/Imu"
instance D.Default Imu
|
acowley/roshask
|
msgs/Sensor_msgs/Ros/Sensor_msgs/Imu.hs
|
bsd-3-clause
| 1,966 | 1 | 14 | 357 | 522 | 300 | 222 | 42 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main (main) where
import Prelude ()
import Prelude.Compat
import Blaze.ByteString.Builder (toLazyByteString)
import Blaze.ByteString.Builder.Char.Utf8 (fromString)
import Control.DeepSeq (NFData(rnf))
import Criterion.Main
import qualified Data.Aeson as A
import qualified Data.Aeson.Text as A
import qualified Data.ByteString.Lazy as BL
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Builder as TLB
import qualified Data.Text.Lazy.Encoding as TLE
import qualified Text.JSON as J
instance (NFData v) => NFData (J.JSObject v) where
rnf o = rnf (J.fromJSObject o)
instance NFData J.JSValue where
rnf J.JSNull = ()
rnf (J.JSBool b) = rnf b
rnf (J.JSRational a b) = rnf a `seq` rnf b `seq` ()
rnf (J.JSString s) = rnf (J.fromJSString s)
rnf (J.JSArray lst) = rnf lst
rnf (J.JSObject o) = rnf o
decodeJ :: String -> J.JSValue
decodeJ s =
case J.decodeStrict s of
J.Ok v -> v
J.Error _ -> error "fail to parse via JSON"
decodeA :: BL.ByteString -> A.Value
decodeA s = case A.decode s of
Just v -> v
Nothing -> error "fail to parse via Aeson"
decodeA' :: BL.ByteString -> A.Value
decodeA' s = case A.decode' s of
Just v -> v
Nothing -> error "fail to parse via Aeson"
encodeJ :: J.JSValue -> BL.ByteString
encodeJ = toLazyByteString . fromString . J.encode
encodeToText :: A.Value -> TL.Text
encodeToText = TLB.toLazyText . A.encodeToTextBuilder . A.toJSON
encodeViaText :: A.Value -> BL.ByteString
encodeViaText = TLE.encodeUtf8 . encodeToText
main :: IO ()
main = do
let enFile = "json-data/twitter100.json"
jpFile = "json-data/jp100.json"
enA <- BL.readFile enFile
enJ <- readFile enFile
jpA <- BL.readFile jpFile
jpJ <- readFile jpFile
defaultMain [
bgroup "decode" [
bgroup "en" [
bench "aeson/lazy" $ nf decodeA enA
, bench "aeson/strict" $ nf decodeA' enA
, bench "json" $ nf decodeJ enJ
]
, bgroup "jp" [
bench "aeson" $ nf decodeA jpA
, bench "json" $ nf decodeJ jpJ
]
]
, bgroup "encode" [
bgroup "en" [
bench "aeson-to-bytestring" $ nf A.encode (decodeA enA)
, bench "aeson-via-text-to-bytestring" $ nf encodeViaText (decodeA enA)
, bench "aeson-to-text" $ nf encodeToText (decodeA enA)
, bench "json" $ nf encodeJ (decodeJ enJ)
]
, bgroup "jp" [
bench "aeson-to-bytestring" $ nf A.encode (decodeA jpA)
, bench "aeson-via-text-to-bytestring" $ nf encodeViaText (decodeA jpA)
, bench "aeson-to-text" $ nf encodeToText (decodeA jpA)
, bench "json" $ nf encodeJ (decodeJ jpJ)
]
]
]
|
tolysz/prepare-ghcjs
|
spec-lts8/aeson/benchmarks/CompareWithJSON.hs
|
bsd-3-clause
| 2,775 | 0 | 16 | 704 | 922 | 476 | 446 | 71 | 2 |
module School (School, empty, grade, add, sorted) where
import qualified Data.Map as M
import qualified Data.Set as S
import Control.Arrow (second)
type Grade = Int
type Student = String
newtype School = School { unSchool :: M.Map Grade (S.Set Student) }
empty :: School
empty = School M.empty
sorted :: School -> [(Grade, [Student])]
sorted = map (second S.toAscList) . M.toAscList . unSchool
grade :: Grade -> School -> [Student]
grade gradeNum = S.toAscList . M.findWithDefault S.empty gradeNum . unSchool
add :: Grade -> Student -> School -> School
add gradeNum student =
School . M.insertWith S.union gradeNum (S.singleton student) . unSchool
|
pminten/xhaskell
|
grade-school/example.hs
|
mit
| 655 | 0 | 10 | 109 | 246 | 139 | 107 | 16 | 1 |
import StackTest
main :: IO ()
main = do
putStrLn "Disabled: CI doesn't have GHC 8.8.1"
--stack ["build"]
|
juhp/stack
|
test/integration/tests/cabal-public-sublibraries/Main.hs
|
bsd-3-clause
| 111 | 0 | 7 | 23 | 26 | 13 | 13 | 4 | 1 |
module Invariant where
import General
import Dictionary
data Invariant = Invariant
deriving (Show,Eq,Enum,Ord,Bounded)
instance Param Invariant
where values = enum
instance Dict Invariant
where category = const "Invariant"
invar = "Invariant"
type Invar = (Invariant -> Str)
invarEntry :: String -> Entry
invarEntry = entry . mkInvar
mkInvar :: String -> Invar
mkInvar s = const (mkStr s)
|
isido/functional-morphology-for-koine-greek
|
lib/Invariant.hs
|
gpl-3.0
| 408 | 0 | 7 | 77 | 131 | 72 | 59 | 15 | 1 |
--
-- Copyright (c) 2012 Citrix Systems, Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards #-}
module Migrations.M_12 (migration) where
import UpgradeEngine
import Data.List (foldl')
migration = Migration {
sourceVersion = 12
, targetVersion = 13
, actions = act
}
act :: IO ()
act = flask
flask = xformVmJSON xform where
xform tree
| Just t <- typ, t `elem` ["pvm","svm"] = set_flask tree
| otherwise = tree
where
typ = jsUnboxString `fmap` (jsGet "/type" tree)
set_flask tree = jsSet "/config/flask-label" (jsBoxString "system_u:system_r:hvm_dom0IO_t")
. jsRm "/config/extra-xenvm"
$ tree
|
jean-edouard/manager
|
upgrade-db/Migrations/M_12.hs
|
gpl-2.0
| 1,467 | 0 | 11 | 392 | 192 | 112 | 80 | 18 | 1 |
module Types where
import Control.Monad.Except (ExceptT)
import Data.Carthage.Cartfile (Version)
import Data.Carthage.TargetPlatform
import qualified Data.Map.Strict as M
import Data.Romefile (FrameworkName, GitRepoName)
import qualified Network.AWS.Env as AWS (Env)
import Types.Commands
type UploadDownloadCmdEnv = (AWS.Env, CachePrefix, SkipLocalCacheFlag, Bool)
type UploadDownloadEnv = (AWS.Env, CachePrefix, Bool)
type RomeMonad = ExceptT String IO
type RepositoryMap = M.Map GitRepoName [FrameworkName]
type InvertedRepositoryMap = M.Map FrameworkName GitRepoName
type RomeVersion = (Int, Int, Int, Int)
type GitRepoNameAndVersion = (GitRepoName, Version)
-- | A wrapper around `String` used to specify what prefix to user
-- | when determining remote paths of artifacts
newtype CachePrefix = CachePrefix { _unCachePrefix :: String }
deriving (Show, Eq)
-- | Represents the name of a framework together with its version
data FrameworkVersion = FrameworkVersion { _frameworkName :: FrameworkName
, _frameworkVersion :: Version
}
deriving (Show, Eq)
-- | Represents the availability of a framework for a given `TargetPlatform`
data PlatformAvailability = PlatformAvailability { _availabilityPlatform :: TargetPlatform
, _isAvailable :: Bool
}
deriving (Show, Eq)
-- | Represents the availablity of a given `GitRepoName` at a given `Version`
-- | as a list of `PlatformAvailability`s
data GitRepoAvailability = GitRepoAvailability { _availabilityRepo :: GitRepoName
, _availabilityVersion :: Version
, _repoPlatformAvailabilities :: [PlatformAvailability]
}
deriving (Show, Eq)
-- | Represents the availability of a `FrameworkVersion` as a list of
-- | `PlatformAvailability`s
data FrameworkAvailability = FrameworkAvailability { _availabilityFramework :: FrameworkVersion
, _frameworkPlatformAvailabilities :: [PlatformAvailability]
}
deriving (Show, Eq)
|
mheinzel/Rome
|
src/Types.hs
|
mit
| 2,697 | 0 | 9 | 1,068 | 352 | 222 | 130 | 30 | 0 |
{-# LANGUAGE OverloadedStrings, RecordWildCards #-}
module Morse.Web.Json where
import Data.Aeson
import Data.Text (Text)
data MorseRes = MorseRes
{ morseResInput :: Text
, morseResResult :: Text
}
instance ToJSON MorseRes where
toJSON MorseRes{..} = object
[ "input" .= morseResInput
, "result" .= morseResResult
]
data MsgRes = MsgRes Text
instance ToJSON MsgRes where
toJSON (MsgRes msg) = object
[ "msg" .= msg
]
|
rjregenold/morse
|
src/Morse/Web/Json.hs
|
mit
| 455 | 0 | 8 | 100 | 124 | 69 | 55 | 15 | 0 |
module Main where
data Expr a = Lit Integer
| Add (Expr a) (Expr a)
| Let (Expr a) (a -> Expr a)
| Var a
eval :: Expr Integer -> Integer
eval (Lit d ) = d
eval (Add e0 e1) = eval e0 + eval e1
eval (Let e f ) = eval (f (eval e))
eval (Var v ) = v
instance Num (Expr a) where
fromInteger = Lit . fromInteger
(+) = Add
(*) = undefined
abs = undefined
signum = undefined
negate = undefined
tree :: (Num a, Eq a) => a -> Expr b
tree 0 = 1
tree n = Let (tree (n - 1)) ((\shared -> shared + shared) . Var)
text :: Expr String -> String
text e = go e (0 :: Integer)
where
go (Lit j ) _ = show j
go (Add e0 e1) c = "(Add " ++ go e0 c ++ " " ++ go e1 c ++ ")"
go (Let e0 f) c =
"(Let " ++ v ++ " " ++ go e0 (c + 1) ++ " in " ++ go (f v) (c + 1) ++ ")"
where v = "v" ++ show c
go (Var x) _ = x
main :: IO ()
main = do
let t1024 :: Expr Integer = tree (1024 :: Integer)
print . eval $ t1024
let t3 :: Expr String = tree (3 :: Integer)
putStrLn . text $ t3
|
genos/Programming
|
workbench/edsl/src/Main.hs
|
mit
| 1,033 | 0 | 13 | 334 | 577 | 294 | 283 | -1 | -1 |
{-# LANGUAGE TypeOperators #-}
module PigmentPrelude
( ev
, fakeNameSupply
, assertRight
, assertChecks
, assertNoCheck
, module X
) where
import Data.Either
import Test.Tasty
import Test.Tasty.HUnit
import Evidences.DefinitionalEquality as X
import Evidences.Eval as X
import Evidences.Operators as X
import Evidences.TypeChecker as X
import Evidences.Tm as X
import Kit.BwdFwd as X
import NameSupply.NameSupplier as X
import NameSupply.NameSupply as X
assertThrows :: String -> ProofState a -> IO ()
assertThrows msg script = case runProofState script emptyContext of
Left _ -> return ()
Right _ -> assertFailure msg
runScript :: ProofState a -> (a -> IO ()) -> IO ()
runScript script continue = case runProofState script emptyContext of
Left e -> assertFailure (renderHouseStyle (prettyStackError e))
Right (a, _) -> continue a
ev :: (TY :>: VAL) -> Either (StackError VAL) ((TY :>: VAL) :=>: VAL)
ev tx@(_ :>: x) = Right (tx :=>: x)
fakeNameSupply :: NameSupply
fakeNameSupply = (B0, 0)
assertRight :: (Eq a, Show a, Show b) => String -> a -> Either b a -> Assertion
assertRight msg _ (Left err) = assertFailure (msg ++ " " ++ show err)
assertRight msg a (Right a') = assertEqual msg a a'
assertChecks :: (TY :>: INTM) -> VAL -> Assertion
assertChecks start finish =
let resultVal = do
_ :=>: val <- typeCheck (check start) fakeNameSupply
return val
in assertRight "checks" finish resultVal
assertNoCheck :: (TY :>: INTM) -> Assertion
assertNoCheck problem =
let result = typeCheck (check problem) fakeNameSupply
in assertBool "doesn't check" (isLeft result)
assertInfers :: EXTM -> (VAL :<: TY) -> Assertion
assertInfers start finish =
let resultVal = typeCheck (infer start) fakeNameSupply
in assertRight "infers" finish resultVal
easiestest =
let bool = SUMD UNIT UNIT ?? SET
in typeCheck (infer bool) (B0, 0)
easiest =
let arr = LAV "A" (SUMD (NV 0) UNIT)
arrTy = ARR SET SET
bool = (arr ?? arrTy) $## [UNIT]
in typeCheck (infer bool) (B0, 1)
easier =
-- (A, B)
-- let pairer = PIV "A" SET
-- (PIV "B" SET
-- (SUMD (NV 1) (NV 0)))
let pairer = LAV "A" (LAV "B" (SUMD (NV 1) (NV 0)))
pairerTy = ARR SET (ARR SET SET)
-- let a = N (P ([("A", 0)] := DECL :<: SET))
-- b = N (P ([("B", 0)] := DECL :<: SET))
-- pairer = SUMD a b
bool = (pairer ?? pairerTy) $## [UNIT, UNIT]
in typeCheck (infer bool) (B0, 2)
-- in equal (SET :>: (N bool, SUMD UNIT UNIT)) fakeNameSupply
-- eliminated =
-- let bool = SUMD UNIT UNIT
-- -- \Either () () -> a or b
-- chooser = LAV "b" (
-- result = pair $$ Fst
-- in equal (SET :>: (result, UNIT)) fakeNameSupply
-- ex :: Either (StackError INTM) (VAL :<: TY)
-- ex = typeCheck (check (PIV "bool" (PAIR UNIT UNIT) (
-- ex = typeCheck (infer (LAV "x" (NV 0) ?? PI SET (LK SET))) fakeNameSupply
|
kwangkim/pigment
|
tests/PigmentPrelude.hs
|
mit
| 3,093 | 0 | 15 | 852 | 884 | 469 | 415 | 61 | 2 |
{-# LANGUAGE FlexibleContexts #-}
module Yage.Image.SDF
( signedNearDistance
, signedDistanceFieldProgressed
, signedDistanceField
) where
import Yage.Prelude
import Yage.Math
import Control.Monad.ST
import Codec.Picture
import Codec.Picture.Types
data InOut = Inside | Outside
deriving (Show, Eq)
signedDistanceFieldProgressed :: Image Pixel8 -> Int -> (Int -> IO ()) -> IO (Image Pixel8)
signedDistanceFieldProgressed bitmap spread incrCall = do
let w = imageWidth bitmap
h = imageHeight bitmap
img <- createMutableImage w h (minBound :: Pixel8)
forM_ [0..h-1] $ \y -> do
forM_ [0..w-1] $ \x ->
writePixel img x y $ signedNearDistance bitmap spread x y
incrCall w
unsafeFreezeImage img
{--
where
parImage :: (Storable (PixelBaseComponent a), NFData (PixelBaseComponent a)) => Strategy (Image a)
parImage Image{..} = return $ Image imageWidth imageHeight (imageData `using` parVector imageWidth)
--}
signedDistanceField :: Image Pixel8 -> Int -> Image Pixel8
signedDistanceField bitmap spread = runST $ do
let w = imageWidth bitmap
h = imageHeight bitmap
img <- createMutableImage w h (minBound :: Pixel8)
forM_ [0..h-1] $ \y ->
forM_ [0..w-1] $ \x ->
writePixel img x y (signedNearDistance bitmap spread x y)
unsafeFreezeImage img
signedNearDistance :: Image Pixel8 -> Int -> Int -> Int -> Pixel8
signedNearDistance bitmap spread x y =
let s, upperPx, maxDist2 :: Double
s = fromIntegral spread
maxDist2 = s * s
upperPx = fromIntegral (maxBound :: Pixel8)
halfPx = upperPx / 2.0
msqr = headMay $ sort distSqr's
signing = if activeSide == Inside then id else negate
dist = signing $ sqrt $ maybe maxDist2 fromIntegral msqr
--val = round $ dist * ( half / s ) + half
--val = round $ (dist + s) / ( 2.0 * s ) * upperPx
val = round $ dist / s * halfPx + halfPx
in clamp val minBound maxBound
where
activeSide = toInside $ pixelAt bitmap x y
{-# INLINE activeSide #-}
toInside px = if px == maxBound then Inside else Outside
{-# INLINE toInside #-}
distSqr's = do
offx <- [ -spread .. spread ]
offy <- [ -spread .. spread ]
guard $ (offx, offy) /= (0,0)
-- out of radius
let distSqr = offx * offx + offy * offy
guard $ distSqr <= spread * spread
let xi = x + offx
yi = y + offy
guard $ xi >= 0 && xi < imageWidth bitmap
guard $ yi >= 0 && yi < imageHeight bitmap
-- pixel is on the other side?
guard $ toInside (pixelAt bitmap xi yi) /= activeSide
return distSqr
{-# INLINE signedNearDistance #-}
|
MaxDaten/yage
|
src/Yage/Image/SDF.hs
|
mit
| 2,832 | 0 | 14 | 854 | 791 | 405 | 386 | 60 | 3 |
module Main (main) where
import Data.List (genericLength)
import Data.Maybe (catMaybes)
import System.Exit (exitFailure, exitSuccess)
import System.Process (readProcess)
import Text.Regex (matchRegex, mkRegex)
average :: (Fractional a, Real b) => [b] -> a
average xs = realToFrac (sum xs) / genericLength xs
expected :: Fractional a => a
expected = 90
main :: IO ()
main = do
output <- readProcess "stack" ["haddock"] ""
if average (match output) >= expected
then exitSuccess
else putStr output >> exitFailure
match :: String -> [Int]
match = fmap read . concat . catMaybes . fmap (matchRegex pat) . lines
where
pat = mkRegex "^ *([0-9]*)%"
|
cackharot/heub
|
test/Haddock.hs
|
mit
| 676 | 0 | 11 | 135 | 251 | 134 | 117 | 19 | 2 |
-----------------------------------------------------------------------------
--
-- Module : Language.PureScript.Exhaustive
-- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess
-- License : MIT (http://opensource.org/licenses/MIT)
--
-- Maintainer : Phil Freeman <[email protected]>
-- Stability : experimental
-- Portability :
--
-- |
-- | Module for exhaustivity checking over pattern matching definitions
-- | The algorithm analyses the clauses of a definition one by one from top
-- | to bottom, where in each step it has the cases already missing (uncovered),
-- | and it generates the new set of missing cases.
--
-----------------------------------------------------------------------------
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.PureScript.Linter.Exhaustive
( checkExhaustive
, checkExhaustiveModule
) where
import Prelude ()
import Prelude.Compat
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.List (foldl', sortBy, nub)
import Data.Function (on)
import Control.Monad (unless)
import Control.Applicative
import Control.Arrow (first, second)
import Control.Monad.Writer.Class
import Language.PureScript.Crash
import Language.PureScript.AST.Binders
import Language.PureScript.AST.Declarations
import Language.PureScript.Environment
import Language.PureScript.Names as P
import Language.PureScript.Kinds
import Language.PureScript.Types as P
import Language.PureScript.Errors
-- | There are two modes of failure for the redudancy check:
--
-- 1. Exhaustivity was incomeplete due to too many cases, so we couldn't determine redundancy.
-- 2. We didn't attempt to determine redundancy for a binder, e.g. an integer binder.
--
-- We want to warn the user in the first case.
data RedudancyError = Incomplete | Unknown
-- |
-- Qualifies a propername from a given qualified propername and a default module name
--
qualifyName :: a -> ModuleName -> Qualified a -> Qualified a
qualifyName n defmn qn = Qualified (Just mn) n
where
(mn, _) = qualify defmn qn
-- |
-- Given an environment and a datatype or newtype name,
-- this function returns the associated data constructors if it is the case of a datatype
-- where: - ProperName is the name of the constructor (for example, "Nothing" in Maybe)
-- - [Type] is the list of arguments, if it has (for example, "Just" has [TypeVar "a"])
--
getConstructors :: Environment -> ModuleName -> Qualified ProperName -> [(ProperName, [Type])]
getConstructors env defmn n = extractConstructors lnte
where
qpn :: Qualified ProperName
qpn = getConsDataName n
getConsDataName :: Qualified ProperName -> Qualified ProperName
getConsDataName con = qualifyName nm defmn con
where
nm = case getConsInfo con of
Nothing -> error $ "Constructor " ++ showQualified runProperName con ++ " not in the scope of the current environment in getConsDataName."
Just (_, pm, _, _) -> pm
getConsInfo :: Qualified ProperName -> Maybe (DataDeclType, ProperName, Type, [Ident])
getConsInfo con = M.lookup con dce
where
dce :: M.Map (Qualified ProperName) (DataDeclType, ProperName, Type, [Ident])
dce = dataConstructors env
lnte :: Maybe (Kind, TypeKind)
lnte = M.lookup qpn (types env)
extractConstructors :: Maybe (Kind, TypeKind) -> [(ProperName, [Type])]
extractConstructors (Just (_, DataType _ pt)) = pt
extractConstructors _ = internalError "Data name not in the scope of the current environment in extractConstructors"
-- |
-- Replicates a wildcard binder
--
initialize :: Int -> [Binder]
initialize l = replicate l NullBinder
-- |
-- Applies a function over two lists of tuples that may lack elements
--
genericMerge :: Ord a =>
(a -> Maybe b -> Maybe c -> d) ->
[(a, b)] ->
[(a, c)] ->
[d]
genericMerge _ [] [] = []
genericMerge f bs [] = map (\(s, b) -> f s (Just b) Nothing) bs
genericMerge f [] bs = map (\(s, b) -> f s Nothing (Just b)) bs
genericMerge f bsl@((s, b):bs) bsr@((s', b'):bs')
| s < s' = f s (Just b) Nothing : genericMerge f bs bsr
| s > s' = f s' Nothing (Just b') : genericMerge f bsl bs'
| otherwise = f s (Just b) (Just b') : genericMerge f bs bs'
-- |
-- Find the uncovered set between two binders:
-- the first binder is the case we are trying to cover, the second one is the matching binder
--
missingCasesSingle :: Environment -> ModuleName -> Binder -> Binder -> ([Binder], Either RedudancyError Bool)
missingCasesSingle _ _ _ NullBinder = ([], return True)
missingCasesSingle _ _ _ (VarBinder _) = ([], return True)
missingCasesSingle env mn (VarBinder _) b = missingCasesSingle env mn NullBinder b
missingCasesSingle env mn br (NamedBinder _ bl) = missingCasesSingle env mn br bl
missingCasesSingle env mn NullBinder cb@(ConstructorBinder con _) =
(concatMap (\cp -> fst $ missingCasesSingle env mn cp cb) allPatterns, return True)
where
allPatterns = map (\(p, t) -> ConstructorBinder (qualifyName p mn con) (initialize $ length t))
$ getConstructors env mn con
missingCasesSingle env mn cb@(ConstructorBinder con bs) (ConstructorBinder con' bs')
| con == con' = let (bs'', pr) = missingCasesMultiple env mn bs bs' in (map (ConstructorBinder con) bs'', pr)
| otherwise = ([cb], return False)
missingCasesSingle env mn NullBinder (ObjectBinder bs) =
(map (ObjectBinder . zip (map fst bs)) allMisses, pr)
where
(allMisses, pr) = missingCasesMultiple env mn (initialize $ length bs) (map snd bs)
missingCasesSingle env mn (ObjectBinder bs) (ObjectBinder bs') =
(map (ObjectBinder . zip sortedNames) allMisses, pr)
where
(allMisses, pr) = uncurry (missingCasesMultiple env mn) (unzip binders)
sortNames = sortBy (compare `on` fst)
(sbs, sbs') = (sortNames bs, sortNames bs')
compB :: a -> Maybe a -> Maybe a -> (a, a)
compB e b b' = (fm b, fm b')
where
fm = fromMaybe e
compBS :: Eq a => b -> a -> Maybe b -> Maybe b -> (a, (b, b))
compBS e s b b' = (s, compB e b b')
(sortedNames, binders) = unzip $ genericMerge (compBS NullBinder) sbs sbs'
missingCasesSingle _ _ NullBinder (BooleanBinder b) = ([BooleanBinder $ not b], return True)
missingCasesSingle _ _ (BooleanBinder bl) (BooleanBinder br)
| bl == br = ([], return True)
| otherwise = ([BooleanBinder bl], return False)
missingCasesSingle env mn b (PositionedBinder _ _ cb) = missingCasesSingle env mn b cb
missingCasesSingle env mn b (TypedBinder _ cb) = missingCasesSingle env mn b cb
missingCasesSingle _ _ b _ = ([b], Left Unknown)
-- |
-- Returns the uncovered set of binders
-- the first argument is the list of uncovered binders at step i
-- the second argument is the (i+1)th clause of a pattern matching definition
--
-- The idea of the algorithm is as follows:
-- it processes each binder of the two lists (say, `x` and `y`) one by one
-- at each step two cases arises:
-- - there are no missing cases between `x` and `y`: this is very straightforward, it continues with the remaining cases
-- but keeps the uncovered binder in its position.
-- - there are missing cases, let us call it the set `U`: on the one hand, we mix each new uncovered case in `U`
-- with the current tail of uncovered set. On the other hand, it continues with the remaining cases: here we
-- can use `x` (but it will generate overlapping cases), or `y`, which will generate non-overlapping cases.
--
-- As an example, consider:
--
-- data N = Z | S N
-- f Z Z = Z --> {[S _, _], [Z, S _]} which are the right non-overlapping cases (GHC uses this).
--
-- if we use `x` instead of `y` (in this case, `y` stands for `Z` and `x` for `_`) we obtain:
-- f Z Z = Z --> {[S _, _], [_, S _]} you can see that both cases overlaps each other.
--
-- Up to now, we've decided to use `x` just because we expect to generate uncovered cases which might be
-- redundant or not, but uncovered at least. If we use `y` instead, we'll need to have a redundancy checker
-- (which ought to be available soon), or increase the complexity of the algorithm.
--
missingCasesMultiple :: Environment -> ModuleName -> [Binder] -> [Binder] -> ([[Binder]], Either RedudancyError Bool)
missingCasesMultiple env mn = go
where
go [] [] = ([], pure True)
go (x:xs) (y:ys) = (map (: xs) miss1 ++ map (x :) miss2, liftA2 (&&) pr1 pr2)
where
(miss1, pr1) = missingCasesSingle env mn x y
(miss2, pr2) = go xs ys
go _ _ = internalError "Argument lengths did not match in missingCasesMultiple."
-- |
-- Guard handling
--
-- We say a guard is exhaustive iff it has an `otherwise` (or `true`) expression.
-- Example:
-- f x | x < 0 = 0
-- | otherwise = 1
-- is exhaustive, whereas `f x | x < 0` is not
--
-- The function below say whether or not a guard has an `otherwise` expression
-- It is considered that `otherwise` is defined in Prelude
--
isExhaustiveGuard :: Either [(Guard, Expr)] Expr -> Bool
isExhaustiveGuard (Left gs) = not . null $ filter (\(g, _) -> isOtherwise g) gs
where
isOtherwise :: Expr -> Bool
isOtherwise (TypedValue _ (BooleanLiteral True) _) = True
isOtherwise (TypedValue _ (Var (Qualified (Just (ModuleName [ProperName "Prelude"])) (Ident "otherwise"))) _) = True
isOtherwise _ = False
isExhaustiveGuard (Right _) = True
-- |
-- Returns the uncovered set of case alternatives
--
missingCases :: Environment -> ModuleName -> [Binder] -> CaseAlternative -> ([[Binder]], Either RedudancyError Bool)
missingCases env mn uncovered ca = missingCasesMultiple env mn uncovered (caseAlternativeBinders ca)
missingAlternative :: Environment -> ModuleName -> CaseAlternative -> [Binder] -> ([[Binder]], Either RedudancyError Bool)
missingAlternative env mn ca uncovered
| isExhaustiveGuard (caseAlternativeResult ca) = mcases
| otherwise = ([uncovered], snd mcases)
where
mcases = missingCases env mn uncovered ca
-- |
-- Main exhaustivity checking function
-- Starting with the set `uncovered = { _ }` (nothing covered, one `_` for each function argument),
-- it partitions that set with the new uncovered cases, until it consumes the whole set of clauses.
-- Then, returns the uncovered set of case alternatives.
--
checkExhaustive :: forall m. (MonadWriter MultipleErrors m) => Environment -> ModuleName -> Int -> [CaseAlternative] -> m ()
checkExhaustive env mn numArgs cas = makeResult . first nub $ foldl' step ([initialize numArgs], (pure True, [])) cas
where
step :: ([[Binder]], (Either RedudancyError Bool, [[Binder]])) -> CaseAlternative -> ([[Binder]], (Either RedudancyError Bool, [[Binder]]))
step (uncovered, (nec, redundant)) ca =
let (missed, pr) = unzip (map (missingAlternative env mn ca) uncovered)
(missed', approx) = splitAt 10000 (nub (concat missed))
cond = liftA2 (&&) (or <$> sequenceA pr) nec
in (missed', ( if null approx
then cond
else Left Incomplete
, if either (const True) id cond
then redundant
else caseAlternativeBinders ca : redundant
)
)
makeResult :: ([[Binder]], (Either RedudancyError Bool, [[Binder]])) -> m ()
makeResult (bss, (rr, bss')) =
do unless (null bss) tellExhaustive
unless (null bss') tellRedundant
case rr of
Left Incomplete -> tellIncomplete
_ -> return ()
where
tellExhaustive = tell . errorMessage . uncurry NotExhaustivePattern . second null . splitAt 5 $ bss
tellRedundant = tell . errorMessage . uncurry OverlappingPattern . second null . splitAt 5 $ bss'
tellIncomplete = tell . errorMessage $ IncompleteExhaustivityCheck
-- |
-- Exhaustivity checking over a list of declarations
--
checkExhaustiveDecls :: forall m. (Applicative m, MonadWriter MultipleErrors m) => Environment -> ModuleName -> [Declaration] -> m ()
checkExhaustiveDecls env mn = mapM_ onDecl
where
onDecl :: Declaration -> m ()
onDecl (BindingGroupDeclaration bs) = mapM_ (onDecl . convert) bs
where
convert :: (Ident, NameKind, Expr) -> Declaration
convert (name, nk, e) = ValueDeclaration name nk [] (Right e)
onDecl (ValueDeclaration name _ _ (Right e)) = censor (addHint (ErrorInValueDeclaration name)) (onExpr e)
onDecl (PositionedDeclaration pos _ dec) = censor (addHint (PositionedError pos)) (onDecl dec)
onDecl _ = return ()
onExpr :: Expr -> m ()
onExpr (UnaryMinus e) = onExpr e
onExpr (ArrayLiteral es) = mapM_ onExpr es
onExpr (ObjectLiteral es) = mapM_ (onExpr . snd) es
onExpr (TypeClassDictionaryConstructorApp _ e) = onExpr e
onExpr (Accessor _ e) = onExpr e
onExpr (ObjectUpdate o es) = onExpr o >> mapM_ (onExpr . snd) es
onExpr (Abs _ e) = onExpr e
onExpr (App e1 e2) = onExpr e1 >> onExpr e2
onExpr (IfThenElse e1 e2 e3) = onExpr e1 >> onExpr e2 >> onExpr e3
onExpr (Case es cas) = checkExhaustive env mn (length es) cas >> mapM_ onExpr es >> mapM_ onCaseAlternative cas
onExpr (TypedValue _ e _) = onExpr e
onExpr (Let ds e) = mapM_ onDecl ds >> onExpr e
onExpr (PositionedValue pos _ e) = censor (addHint (PositionedError pos)) (onExpr e)
onExpr _ = return ()
onCaseAlternative :: CaseAlternative -> m ()
onCaseAlternative (CaseAlternative _ (Left es)) = mapM_ (\(e, g) -> onExpr e >> onExpr g) es
onCaseAlternative (CaseAlternative _ (Right e)) = onExpr e
-- |
-- Exhaustivity checking over a single module
--
checkExhaustiveModule :: forall m. (Applicative m, MonadWriter MultipleErrors m) => Environment -> Module -> m ()
checkExhaustiveModule env (Module _ _ mn ds _) = censor (addHint (ErrorInModule mn)) $ checkExhaustiveDecls env mn ds
|
michaelficarra/purescript
|
src/Language/PureScript/Linter/Exhaustive.hs
|
mit
| 13,649 | 0 | 19 | 2,729 | 3,895 | 2,069 | 1,826 | 165 | 18 |
-- | Курс функционального программирования (Осень'2015).
--
-- Пример полноценной программы на языке Haskell.
-- Программа моделирует карточную игру "Бура" по
-- упрощённым правилам.
--
import System.Random
-- | Количество очков, которое необходимо набрать для победы
winScore :: Int
winScore = 31
-- | Отладочный режим?
-- (влияет на вывод отладочной информации)
isDebug :: Bool
isDebug = False
-- Определения типов --------------------------------------------------------------------
-- | Все масти карт
data Suit = Clubs -- ^ трефы / крести
| Diamonds -- ^ бубны
| Hearts -- ^ черви
| Spades -- ^ пики
deriving (Show, Eq)
-- | Все значения карт
data Rank = R6 | R7 | R8 | R9 | R10 | Jack | Queen | King | Ace deriving (Show, Eq)
-- | Карта задаётся мастью и значением
data Card = Card {
suit :: Suit,
rank :: Rank }
deriving Show
-- | Колода карт есть список карт
type Deck = [ Card ]
-- | Описание состояния игрового процесса
data GameState = GameState {
activePlayer :: ActivePlayer, -- ^ игрок, соверщающий действия на данном этапе
dealer :: ActivePlayer, -- ^ вистующий игрок
humanDeck :: Deck, -- ^ карты на руках у человека
computerDeck :: Deck, -- ^ карты на руках у компьютера
restDeck :: Deck, -- ^ оставшиеся карты
humanTricks :: Deck, -- ^ взятки человека
computerTricks :: Deck, -- ^ взятки компьютера
trump :: Suit, -- ^ козырная масть
playCard :: [Card] -- ^ текущая разыгрываемая карта: [] - нет карты, [c] - какая-то карта
}
-- | Перечисление возможных игроков
data ActivePlayer = Human | Computer
-- | Перечисление состояний победы (как на отдельном ходе, так и во всей игре):
-- ещё никто не победил, победил человек, победил компьютер
data WhoIsWinner = Nobody | HumanWin | ComputerWin
-- | Ход игрока: номер карты из карт на руках
type Move = Int
-- Чистые функции -----------------------------------------------------------------------
-- | Начальная настройка игрового состояния
setup :: Deck -> GameState
setup deck =
let humanDeck = take 3 deck -- первые три карты -- человеку
computerDeck = take 3 (drop 3 deck) -- следующие три карты -- компьютеру
restDeck = drop 6 deck -- оставшиеся карты
in GameState Human Human humanDeck computerDeck restDeck [] [] (suit (head restDeck)) []
-- | Сделать ход (т.е. применить ход к игровому состоянию).
-- Вычисляется новое игровое состояние и определяется,
-- кто победил в результате этого хода.
applyMove :: Move -> GameState -> (GameState, WhoIsWinner)
applyMove move gs =
-- рассмотрим пару (вистующий игрок, активный игрок) у текущего состояния
case (dealer gs, activePlayer gs) of
(Human, Human) ->
-- человек ходит первым
let (c,cs) = extractCard (humanDeck gs) move -- вытащить карту с руки человека
(rc:rs) = restDeck gs -- пара: карта из колоды, оставшаяся колода
-- сформировать новое состояние игры:
in (gs { activePlayer = Computer, -- теперь должен действовать компьютер
playCard = [c], -- выложена карта человека
restDeck = rs, -- из колоды извлекается карта...
humanDeck = rc:cs }, -- ...и помещается в руку человека
Nobody)
(Human, Computer) ->
-- компьютер отвечает на карту человека
let (compCard,cs) = extractCard (computerDeck gs) move -- вытащить карту с руки компьютера
[humanCard] = playCard gs -- текущая выложенная карта
(rc:rs) = restDeck gs -- пара: карта из колоды, оставшаяся колода
(gs', wt) = analyzeTrick humanCard compCard -- определить результат боя (карта побита компьютером или нет)
-- доформироать новое состояние игры:
in (gs' { restDeck = rs, -- из колоды извлекается карта...
computerDeck = rc:cs }, -- ...и помещается в руку компьютера
wt)
(Computer, Computer) ->
-- компьютер ходит первым
-- (комментарии аналогичны вышеприведённым)
let (c,cs) = extractCard (computerDeck gs) move
(rc:rs) = restDeck gs
in (gs { activePlayer = Human, playCard = [c], computerDeck = rc:cs, restDeck = rs }, Nobody)
(Computer, Human) ->
-- человек отвечает на карту компьютера
-- (комментарии аналогичны вышеприведённым)
let (humanCard,cs) = extractCard (humanDeck gs) move
[compCard] = playCard gs
(rc:rs) = restDeck gs
(gs', wt) = analyzeTrick humanCard compCard
in (gs' { humanDeck = rc:cs, restDeck = rs }, wt)
where
-- ^ извлечь карту номер i из колоды; вернуть извлечённую карту и оставшуюся колоду
extractCard cs i = (thisCard, before ++ after)
where
before = take i cs
(thisCard:after) = drop i cs
-- ^ бьёт ли карта c1 карту c2 с учётом козырной масти (trump)
isGreat trump c1 c2 =
if suit c1 == trump then
-- первая карта козырная
if suit c2 == trump then
-- обе карты козырные, надо сравнить значения
rankCompare
else
-- вторая -- не козырная, поэтому первая бьёт вторую
True
else
-- первая карта не козырная
if suit c2 == trump then
-- а вторая -- козырная, поэтому бъёт первую
False
else
-- обе карты не козырные: сравнение по значению карт
rankCompare
where
-- сравнение только по значению карт
rankCompare = rankScore (rank c1) > rankScore (rank c2)
-- ^ рассмотреть карты и определить, кто берёт взятку; вычислить новое состояние игры
analyzeTrick humanCard compCard =
if isGreat (trump gs) humanCard compCard then
-- взятку берёт человек
let ht = humanTricks gs
in (gs { activePlayer = Human, -- поэтому ход переходит к нему
dealer = Human,
playCard = [], -- на столе ничего не остаётся
humanTricks = humanCard:compCard:ht }, -- и побитые карты переходят во взятки человека
HumanWin)
else
-- взятку берёт компьютер
-- (комментарии аналогичны)
let ct = computerTricks gs
in (gs { activePlayer = Computer, dealer = Computer, playCard = [], computerTricks = humanCard:compCard:ct }, ComputerWin)
-- | Определить, кто победитель по текущему состоянию игры
whoIsWinner :: GameState -> WhoIsWinner
whoIsWinner gs =
-- посчитать взятые очки и определить победителя
let humanScore = deckScore (humanTricks gs)
computerScore = deckScore (computerTricks gs)
in
if humanScore > computerScore then
if humanScore >= winScore then
HumanWin
else
Nobody
else
if computerScore >= winScore then
ComputerWin
else
Nobody
-- | Вычислить стоимость набора карт
deckScore :: Deck -> Int
deckScore [] = 0
deckScore (c:cs) = rankScore (rank c) + deckScore cs
-- | Стоимости карт
rankScore :: Rank -> Int
rankScore R6 = 6
rankScore R7 = 7
rankScore R8 = 8
rankScore R9 = 9
rankScore R10 = 10
rankScore Jack = 2
rankScore Queen = 3
rankScore King = 4
rankScore Ace = 11
-- | Вычислить ход компьютера.
-- Программирование AI является нетривиальной задачей, выходящей
-- за рамки данного курса, поэтому тут предложена простейшая
-- реализация: компьютер всегда выкладывает первую карту с руки
calcComputerMove :: GameState -> Move
calcComputerMove _gs = 0
-- | Сформировать строковое представление игры
showGameState :: GameState -> String
showGameState gs =
"Козырь: " ++ showSuit (trump gs) ++
",\nКарты на руках: " ++ showDeck (humanDeck gs) ++
(if isDebug then (",\nКарты на руках компьютера: " ++ showDeck (computerDeck gs)) else "") ++
",\nВзятые карты игрока: " ++ showDeck (humanTricks gs) ++ " (" ++ show (deckScore (humanTricks gs)) ++ " очков)" ++
",\nВзятые карты компьютера: " ++ showDeck (computerTricks gs) ++ " (" ++ show (deckScore (computerTricks gs)) ++ " очков)" ++
",\nВ колоде осталось карт: " ++ show (length (restDeck gs))
-- | Сформировать строковое представление списка карт
showDeck :: Deck -> String
showDeck [] = "пусто"
showDeck [c] = showCard c
showDeck (c:cs) = showCard c ++ ", " ++ showDeck cs
-- | Сформировать строковое представление карты
showCard :: Card -> String
showCard c = showRank (rank c) ++ "/" ++ showSuit (suit c)
-- | Сформировать строковое представление масти
showSuit Clubs = "трефы"
showSuit Diamonds = "бубны"
showSuit Hearts = "черви"
showSuit Spades = "пики"
-- | Сформировать строковое представление значения
showRank R6 = "6"
showRank R7 = "7"
showRank R8 = "8"
showRank R9 = "9"
showRank R10 = "10"
showRank Jack = "Валет"
showRank Queen = "Дама"
showRank King = "Король"
showRank Ace = "Туз"
-- Функции с эффектами -----------------------------------------------
-- | Основной игровой цикл:
-- - запрашивает ход у игрока,
-- - вычисляет новое состояние игры,
-- - если игра закончена, завершает работу,
-- - иначе повторить
gameLoop :: GameState -> IO ()
gameLoop state = do
m <- inputMove state
let (newState, whoTrick) = applyMove m state
case whoTrick of
ComputerWin -> putStrLn "Взятку забрал комьютер"
HumanWin -> putStrLn "Взятку забрал человек"
Nobody -> return ()
case whoIsWinner newState of
Nobody -> do
gameLoop newState
HumanWin -> do
putStrLn "Вы выиграли!"
ComputerWin -> do
putStrLn "Вы проиграли! :("
-- | Ввести ход от активного игрока
inputMove :: GameState -> IO Move
inputMove gs = do
case activePlayer gs of
Human -> do
putStrLn ""
putStrLn (showGameState gs)
putStr "Какой картой будете ходить? "
cardNumberStr <- getLine
let cardNumber = read cardNumberStr
if cardNumber < 1 || cardNumber > 3 then do
putStrLn "Неправильный ввод, введите число от 1 до 3"
inputMove gs
else
return (cardNumber - 1) -- "внутри" игры карты пронумерованы от 0 до 2
Computer -> do
let cm = calcComputerMove gs
putStrLn ("Компьютер походил картой: " ++ showCard (head (computerDeck gs)))
return cm
-- | Перемешать колоду.
-- Перемешивание осуществляется так: взять первую карту и поменять её
-- с другой произвольной из колоды. Затем повторить со следующей и т.д.
shuffle :: Deck -> IO Deck
shuffle deck = do
g <- newStdGen
let r = randoms g
return (shuffle' deck r)
where
shuffle' [] _ = []
shuffle' [d] _ = [d]
shuffle' (d:dk) (r:rs) =
let r' = mod r (length dk)
dkb = take r' dk
(d':dka) = drop r' dk
in d' : shuffle' (dkb ++ d : dka) rs
main = do
-- сформировать начальное состояние колоды
let initDeck = [ Card s r | s <- [Clubs, Diamonds, Hearts, Spades], r <- [R6, R7, R8, R9, R10, Jack, Queen, King, Ace] ]
-- перемешать её
deck <- shuffle initDeck
-- сформировать начальное состояние игры
let initialState = setup deck
-- запустить игровой процесс
gameLoop initialState
|
dmalkr/fp-course-2015
|
game.hs
|
mit
| 15,426 | 0 | 24 | 3,877 | 2,392 | 1,293 | 1,099 | 188 | 8 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE DeriveDataTypeable #-}
-- | This app transformer equips an application with the ability to have
-- multiple seats. WARNING: We're not doing anything special here with regard
-- to security. Every user's data is visible.
module Blaze.React.Examples.MultiUser
( withMultiUser
) where
import Blaze.React
import Control.Lens (makeLenses, at, (^.), (.=), use, non, view)
import Data.Hashable (Hashable)
import qualified Data.HashMap.Strict as HMS
import Data.Monoid ((<>))
import qualified Data.Text as T
import Data.Typeable (Typeable)
import qualified Text.Blaze.Event as E
import qualified Text.Blaze.Event.Keycode as Keycode
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
newtype Username = Username { unUsername :: T.Text }
deriving (Eq, Hashable, Show, Read, Typeable, Ord)
data MUState innerState = MUState
{ _musUserStates :: !(HMS.HashMap Username innerState)
, _musActiveUser :: !(Maybe Username)
, _musUsernameField :: !T.Text
} deriving (Show)
type MUAction innerAction = WithWindowActions (MUAction' innerAction)
data MUAction' innerAction
= SignInA
| SignOutA
| UpdateUsernameFieldA T.Text
| InnerA (WithWindowActions innerAction)
deriving (Eq, Ord, Read, Show, Typeable)
makeLenses ''MUState
initialMUState :: MUState s
initialMUState = MUState
{ _musUserStates = HMS.empty
, _musActiveUser = Nothing
, _musUsernameField = ""
}
applyMUAction
:: (Eq s)
=> s
-> ((WithWindowActions a) -> Transition s (WithWindowActions a))
-> MUAction a
-> Transition (MUState s) (MUAction a)
applyMUAction initialInnerState applyInnerAction action =
runTransitionM $ case action of
-- Pass path changes along to the inner app
PathChangedTo path -> mkTransitionM $
applyMUAction initialInnerState applyInnerAction $
AppAction $ InnerA $ PathChangedTo path
AppAction SignInA -> do
username <- use musUsernameField
musActiveUser .= case username of
"" -> Nothing
x -> Just $ Username x
musUsernameField .= ""
AppAction SignOutA ->
musActiveUser .= Nothing
AppAction (UpdateUsernameFieldA text) ->
musUsernameField .= text
AppAction (InnerA innerAction) ->
use musActiveUser >>= \case
Nothing -> return ()
Just userId ->
-- NOTE (AS): The use of 'non' here introduces the (Eq s)
-- constraint above. I don't think this is necessary.
zoomTransition
(AppAction . InnerA)
(musUserStates . at userId . non initialInnerState)
(mkTransitionM $ applyInnerAction innerAction)
renderMUState
:: (Show a, Show s, Eq s)
=> s
-> (s -> WindowState (WithWindowActions a))
-> MUState s
-> WindowState (MUAction a)
renderMUState initialInnerState renderInnerState state =
case state ^. musActiveUser of
Nothing -> WindowState
{ _wsPath = ""
, _wsBody = renderNotSignedIn state
}
Just username ->
let innerState = state ^. musUserStates . at username . non initialInnerState
WindowState innerBody innerPath = renderInnerState innerState
in WindowState
{ _wsPath = innerPath
, _wsBody = renderSignedIn innerBody username
}
renderSignedIn
:: H.Html (WithWindowActions a)
-> Username
-> H.Html (MUAction a)
renderSignedIn innerBody username = do
H.div H.! A.class_ "multiuser-bar" $ do
H.span $ "Logged in as " <> H.toHtml (unUsername username) <> ". "
H.span H.! E.onClick' (AppAction SignOutA) $ "Sign out"
E.mapActions (AppAction . InnerA) innerBody
renderNotSignedIn :: MUState s -> H.Html (MUAction a)
renderNotSignedIn state =
H.div H.! A.class_ "multiuser-signin" $ do
H.p "Not logged in. Please specify username:"
H.input H.! A.autofocus True
H.! A.value (H.toValue $ view musUsernameField state)
H.! E.onValueChange (AppAction . UpdateUsernameFieldA)
H.! E.onKeyDown [Keycode.enter] (AppAction SignInA)
withMultiUser
:: (Show a, Show s, Eq s)
=> App s (WithWindowActions a)
-> App (MUState s) (MUAction a)
withMultiUser innerApp = App
{ appInitialState = initialMUState
, appInitialRequests = fmap (AppAction . InnerA) <$> appInitialRequests innerApp
, appApplyAction = applyMUAction (appInitialState innerApp) (appApplyAction innerApp)
, appRender = renderMUState (appInitialState innerApp) (appRender innerApp)
}
|
LumiGuide/blaze-react
|
src/Blaze/React/Examples/MultiUser.hs
|
mit
| 4,919 | 0 | 17 | 1,278 | 1,252 | 660 | 592 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
module Data.Store.StreamingSpec where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (race, concurrently)
import Control.Concurrent.MVar
import Control.Exception (try)
import Control.Monad (void, (<=<), forM_)
import Control.Monad.Trans.Free (runFreeT, FreeF(..))
import Control.Monad.Trans.Free.Church (fromFT)
import Control.Monad.Trans.Resource
import qualified Data.ByteString as BS
import Data.Conduit ((=$=), ($$))
import qualified Data.Conduit.List as C
import Data.List (unfoldr)
import Data.Monoid
import Data.Store.Internal
import Data.Store.Streaming
import Data.Store.Streaming.Internal
import Data.Streaming.Network (runTCPServer, runTCPClient, clientSettingsTCP, serverSettingsTCP, setAfterBind)
import Data.Streaming.Network.Internal (AppData(..))
import Data.Void (absurd, Void)
import Network.Socket (Socket(..), socketPort)
import Network.Socket.ByteString (send)
import qualified System.IO.ByteBuffer as BB
import System.Posix.Types (Fd(..))
import Test.Hspec
import Test.Hspec.SmallCheck
import Test.SmallCheck
spec :: Spec
spec = do
describe "conduitEncode and conduitDecode" $ do
it "Roundtrips ([Int])." $ property roundtrip
it "Roundtrips ([Int]), with chunked transfer." $ property roundtripChunked
it "Throws an Exception on incomplete messages." conduitIncomplete
it "Throws an Exception on excess input." $ property conduitExcess
describe "peekMessage" $ do
describe "ByteString" $ do
it "demands more input when needed." $ property (askMoreBS (headerLength + 1))
it "demands more input on incomplete message magic." $ property (askMoreBS 1)
it "demands more input on incomplete SizeTag." $ property (askMoreBS (headerLength - 1))
it "successfully decodes valid input." $ property canPeekBS
describe "decodeMessage" $ do
describe "ByteString" $ do
it "Throws an Exception on incomplete messages." decodeIncomplete
it "Throws an Exception on messages that are shorter than indicated." decodeTooShort
#ifndef mingw32_HOST_OS
describe "Socket" $ do
it "Decodes data trickling through a socket." $ property decodeTricklingMessageFd
#endif
roundtrip :: [Int] -> Property IO
roundtrip xs = monadic $ do
xs' <- runResourceT $ C.sourceList xs
=$= C.map Message
=$= conduitEncode
=$= conduitDecode Nothing
=$= C.map fromMessage
$$ C.consume
return $ xs' == xs
roundtripChunked :: [Int] -> Property IO
roundtripChunked input = monadic $ do
let (xs, chunkLengths) = splitAt (length input `div` 2) input
bs <- C.sourceList xs
=$= C.map Message
=$= conduitEncode
$$ C.fold (<>) mempty
let chunks = unfoldr takeChunk (bs, chunkLengths)
xs' <- runResourceT $ C.sourceList chunks
=$= conduitDecode (Just 10)
=$= C.map fromMessage
$$ C.consume
return $ xs' == xs
where
takeChunk (x, _) | BS.null x = Nothing
takeChunk (x, []) = Just (x, (BS.empty, []))
takeChunk (x, l:ls) =
let (chunk, rest) = BS.splitAt l x
in Just (chunk, (rest, ls))
conduitIncomplete :: Expectation
conduitIncomplete =
(runResourceT (C.sourceList [incompleteInput]
=$= conduitDecode (Just 10)
$$ C.consume)
:: IO [Message Integer]) `shouldThrow` \PeekException{} -> True
conduitExcess :: [Int] -> Property IO
conduitExcess xs = monadic $ do
bs <- C.sourceList xs
=$= C.map Message
=$= conduitEncode
$$ C.fold (<>) mempty
res <- try (runResourceT (C.sourceList [bs `BS.append` "excess bytes"]
=$= conduitDecode (Just 10)
$$ C.consume) :: IO [Message Int])
case res of
Right _ -> return False
Left (PeekException _ _) -> return True
-- splits an encoded message after n bytes. Feeds the first part to
-- peekResult, expecting it to require more input. Then, feeds the
-- second part and checks if the decoded result is the original
-- message.
askMoreBS :: Int -> Integer -> Property IO
askMoreBS n x = monadic $ BB.with (Just 10) $ \ bb -> do
let bs = encodeMessage (Message x)
(start, end) = BS.splitAt n $ bs
BB.copyByteString bb start
peekResult <- runFreeT (fromFT (peekMessageBS bb))
case peekResult of
Free cont ->
runFreeT (cont end) >>= \case
Pure (Message x') -> return $ x' == x
Free _ -> return False
Pure _ -> return False
canPeekBS :: Integer -> Property IO
canPeekBS x = monadic $ BB.with (Just 10) $ \ bb -> do
let bs = encodeMessage (Message x)
BB.copyByteString bb bs
peekResult <- runFreeT (fromFT (peekMessageBS bb))
case peekResult of
Free _ -> return False
Pure (Message x') -> return $ x' == x
#ifndef mingw32_HOST_OS
socketFd :: Socket -> Fd
socketFd (MkSocket fd _ _ _ _) = Fd fd
withServer :: (Socket -> Socket -> IO a) -> IO a
withServer cont = do
sock1Var :: MVar Socket <- newEmptyMVar
sock2Var :: MVar Socket <- newEmptyMVar
portVar :: MVar Int <- newEmptyMVar
doneVar :: MVar Void <- newEmptyMVar
let adSocket ad = case appRawSocket' ad of
Nothing -> error "withServer.adSocket: no raw socket in AppData"
Just sock -> sock
let ss = setAfterBind
(putMVar portVar . fromIntegral <=< socketPort)
(serverSettingsTCP 0 "127.0.0.1")
x <- fmap (either (either absurd absurd) id) $ race
(race
(runTCPServer ss $ \ad -> do
putMVar sock1Var (adSocket ad)
void (readMVar doneVar))
(do port <- takeMVar portVar
runTCPClient (clientSettingsTCP port "127.0.0.1") $ \ad -> do
putMVar sock2Var (adSocket ad)
readMVar doneVar))
(do sock1 <- takeMVar sock1Var
sock2 <- takeMVar sock2Var
cont sock1 sock2)
putMVar doneVar (error "withServer: impossible: read from doneVar")
return x
decodeTricklingMessageFd :: Integer -> Property IO
decodeTricklingMessageFd v = monadic $ do
let bs = encodeMessage (Message v)
BB.with Nothing $ \bb ->
withServer $ \sock1 sock2 -> do
let generateChunks :: [Int] -> BS.ByteString -> [BS.ByteString]
generateChunks xs0 bs_ = case xs0 of
[] -> generateChunks [1,3,10] bs_
x : xs -> if BS.null bs_
then []
else BS.take x bs_ : generateChunks xs (BS.drop x bs_)
let chunks = generateChunks [] bs
((), Message v') <- concurrently
(forM_ chunks $ \chunk -> do
void (send sock1 chunk)
threadDelay (10 * 1000))
(decodeMessageFd bb (socketFd sock2))
return (v == v')
#endif
decodeIncomplete :: IO ()
decodeIncomplete = BB.with (Just 0) $ \ bb -> do
BB.copyByteString bb (BS.take 1 incompleteInput)
(decodeMessageBS bb (return Nothing) :: IO (Maybe (Message Integer)))
`shouldThrow` \PeekException{} -> True
incompleteInput :: BS.ByteString
incompleteInput =
let bs = encodeMessage (Message (42 :: Integer))
in BS.take (BS.length bs - 1) bs
decodeTooShort :: IO ()
decodeTooShort = BB.with Nothing $ \bb -> do
BB.copyByteString bb (encodeMessageTooShort . Message $ (1 :: Int))
(decodeMessageBS bb (return Nothing) :: IO (Maybe (Message Int)))
`shouldThrow` \PeekException{} -> True
encodeMessageTooShort :: Message Int -> BS.ByteString
encodeMessageTooShort msg =
BS.take (BS.length encoded - (getSize (0 :: Int))) encoded
where
encoded = encodeMessage msg
|
fpco/store
|
store-streaming/test/Data/Store/StreamingSpec.hs
|
mit
| 7,727 | 0 | 25 | 1,896 | 2,505 | 1,258 | 1,247 | -1 | -1 |
module Wrapper where
import Data.Char
import System.Random
import Cards
-- The interface to the students' implementation.
data Interface = Interface
{ iEmpty :: Hand
, iFullDeck :: Hand
, iValue :: Hand -> Integer
, iGameOver :: Hand -> Bool
, iWinner :: Hand -> Hand -> Player
, iDraw :: Hand -> Hand -> (Hand, Hand)
, iPlayBank :: Hand -> Hand
, iShuffle :: StdGen -> Hand -> Hand
}
-- A type of players.
data Player = Guest | Bank
deriving (Show, Eq)
-- Runs a game given an implementation of the interface.
runGame :: Interface -> IO ()
runGame i = do
putStrLn "Welcome to the game."
g <- newStdGen
gameLoop i (iShuffle i g (iFullDeck i)) (iEmpty i)
-- Play until the guest player is bust or chooses to stop.
gameLoop :: Interface -> Hand -> Hand -> IO ()
gameLoop i deck guest = do
putStrLn ("Your current score: " ++ show (iValue i guest))
if iGameOver i guest then do
finish i deck guest
else do
putStrLn "Draw another card? [y]"
yn <- getLine
if null yn || not (map toLower yn == "n") then do
let (deck', guest') = iDraw i deck guest
gameLoop i deck' guest'
else
finish i deck guest
-- Display the bank's final score and the winner.
finish :: Interface -> Hand -> Hand -> IO ()
finish i deck guest = do
putStrLn ("The bank's final score: " ++ show (iValue i bank))
putStrLn ("Winner: " ++ show (iWinner i guest bank))
where
bank = iPlayBank i deck
|
tdeekens/tda452-code
|
Lab-2/Wrapper.hs
|
mit
| 1,472 | 0 | 16 | 377 | 475 | 243 | 232 | 37 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Main
( main
) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Either (EitherT)
import Data.Aeson (FromJSON, ToJSON)
import Data.Text (Text)
import GHC.Generics (Generic)
import Network.Wai (Application)
import Network.Wai.Handler.Warp (run)
import Servant
data Comment =
Comment { author :: !Text
, text :: !Text
}
deriving (Generic, Show)
instance FromJSON Comment
instance ToJSON Comment
type API = "api" :> "comments" :> Get '[JSON] [Comment]
:<|> "api" :> "comments" :> ReqBody '[JSON] Comment
:> Post '[JSON] [Comment]
:<|> Raw
api :: Proxy API
api = Proxy
getComments :: EitherT ServantErr IO [Comment]
getComments = do
liftIO $ putStrLn "Fetching comments ..."
return [ Comment { author = "Sigge Pigg"
, text = "A little meow" }
, Comment { author = "Frasse Tass"
, text = "Just *another* meow" }
]
postComment :: Comment -> EitherT ServantErr IO [Comment]
postComment comment = do
liftIO $ putStrLn ("Got " ++ (show comment))
return []
server :: Server API
server = getComments
:<|> postComment
:<|> serveDirectory "static"
app :: Application
app = serve api server
main :: IO ()
main = run 8081 app
|
kosmoskatten/react-play
|
src/Main.hs
|
mit
| 1,521 | 0 | 14 | 427 | 414 | 229 | 185 | 50 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Stackage.Prelude
( module X
, module Stackage.Prelude
) where
import ClassyPrelude.Conduit as X
import Control.Monad.Catch as X (throwM)
import Data.Conduit.Process as X
import qualified Data.Map as Map
import Distribution.Package as X (PackageIdentifier (..))
import Distribution.PackageDescription as X (FlagName, GenericPackageDescription)
import Distribution.Version as X (Version, VersionRange)
import Distribution.Version as X (withinRange, versionNumbers, mkVersion)
import Distribution.Types.PackageName as X (PackageName, mkPackageName, unPackageName)
import qualified Distribution.Version as C
import System.FilePath as FP
import System.Directory as D
import Stackage.Types as X
-- | There seems to be a bug in Cabal where serializing and deserializing
-- version ranges winds up with different representations. So we have a
-- super-simplifier to deal with that.
simplifyVersionRange :: VersionRange -> VersionRange
simplifyVersionRange vr =
fromMaybe (assert False vr') $ simpleParse $ display vr'
where
vr' = C.simplifyVersionRange vr
-- | Topologically sort so that items with dependencies occur after those
-- dependencies.
topologicalSort :: (Ord key, Show key, MonadThrow m, Typeable key)
=> (value -> finalValue)
-> (value -> Set key) -- ^ deps
-> Map key value
-> m (Vector (key, finalValue))
topologicalSort toFinal toDeps =
loop id . mapWithKey removeSelfDeps . fmap (toDeps &&& toFinal)
where
removeSelfDeps k (deps, final) = (deleteSet k deps, final)
loop front toProcess | null toProcess = return $ pack $ front []
loop front toProcess
| null noDeps = throwM $ NoEmptyDeps (map fst toProcess')
| otherwise = loop (front . noDeps') (mapFromList hasDeps)
where
toProcess' = fmap (first removeUnavailable) toProcess
allKeys = Map.keysSet toProcess
removeUnavailable = asSet . setFromList . filter (`member` allKeys) . setToList
(noDeps, hasDeps) = partition (null . fst . snd) $ mapToList toProcess'
noDeps' = (map (second snd) noDeps ++)
data TopologicalSortException key = NoEmptyDeps (Map key (Set key))
deriving (Show, Typeable)
instance (Show key, Typeable key) => Exception (TopologicalSortException key)
copyDir :: FilePath -> FilePath -> IO ()
copyDir src dest =
runConduitRes $ sourceDirectoryDeep False src .| mapM_C go
where
src' = fromString src </> ""
go fp = forM_ (stripDirPrefix src' fp) $ \suffix -> do
let dest' = dest </> suffix
liftIO $ createDirectoryIfMissing True $ takeDirectory dest'
runConduit $ sourceFile fp .| sinkFile dest'
data Target = TargetNightly !Day
| TargetLts !Int !Int
deriving Show
targetSlug :: Target -> Text
targetSlug (TargetNightly day) = "nightly-" ++ tshow day
targetSlug (TargetLts x y) = concat ["lts-", tshow x, ".", tshow y]
stripDirPrefix :: FilePath -> FilePath -> Maybe FilePath
stripDirPrefix pref path = stripPrefix (FP.addTrailingPathSeparator pref) path
|
fpco/stackage-curator
|
src/Stackage/Prelude.hs
|
mit
| 3,525 | 0 | 14 | 931 | 896 | 483 | 413 | 67 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Text.BlogLiterately.LaTeX
-- Copyright : (c) 2012 Brent Yorgey
-- License : GPL (see LICENSE)
-- Maintainer : Brent Yorgey <[email protected]>
--
-- Utilities for working with embedded LaTeX.
--
-----------------------------------------------------------------------------
module Text.BlogLiterately.LaTeX
(
wpTeXify
) where
import Data.List ( isPrefixOf )
import Text.Pandoc
-- | WordPress can render LaTeX, but expects it in a special non-standard
-- format (@\$latex foo\$@). The @wpTeXify@ function formats LaTeX code
-- using this format so that it can be processed by WordPress.
wpTeXify :: Pandoc -> Pandoc
wpTeXify = bottomUp formatDisplayTex . bottomUp formatInlineTex
where formatInlineTex :: [Inline] -> [Inline]
formatInlineTex (Math InlineMath tex : is)
= (Str $ "$latex " ++ unPrefix "latex" tex ++ "$") : is
formatInlineTex is = is
formatDisplayTex :: [Block] -> [Block]
formatDisplayTex (Para [Math DisplayMath tex] : bs)
= RawBlock "html" "<p><div style=\"text-align: center\">"
: Plain [Str $ "$latex " ++ "\\displaystyle " ++ unPrefix "latex" tex ++ "$"]
: RawBlock "html" "</div></p>"
: bs
formatDisplayTex bs = bs
unPrefix pre s
| pre `isPrefixOf` s = drop (length pre) s
| otherwise = s
|
jwiegley/BlogLiterately
|
src/Text/BlogLiterately/LaTeX.hs
|
gpl-3.0
| 1,476 | 0 | 15 | 355 | 273 | 147 | 126 | 21 | 3 |
-- |
-- Module : Graphics.Text.Annotation
-- Copyright : (c) Justus Sagemüller 2015
-- License : GPL v3
--
-- Maintainer : (@) sagemueller $ geo.uni-koeln.de
-- Stability : experimental
-- Portability : requires GHC>6 extensions
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Graphics.Text.Annotation where
import Graphics.Dynamic.Plot.Colour
import Graphics.Dynamic.Plot.Internal.Types
import qualified Prelude
import Diagrams.Prelude ((^&), (&), _x, _y, (|||), (===))
import qualified Diagrams.Prelude as Dia
import qualified Diagrams.TwoD.Size as Dia
import qualified Diagrams.TwoD.Types as DiaTypes
import qualified Diagrams.TwoD.Text as DiaTxt
import Diagrams.BoundingBox (BoundingBox)
import qualified Diagrams.BoundingBox as DiaBB
import qualified Diagrams.Backend.Cairo as Cairo
import qualified Diagrams.Backend.Cairo.Text as CairoTxt
import Control.Monad.Trans (liftIO)
import qualified Control.Category.Hask as Hask
import Control.Category.Constrained.Prelude hiding ((^))
import Control.Arrow.Constrained hiding ((|||))
import Control.Monad.Constrained
import Control.Lens hiding ((...), (<.>))
import Control.Lens.TH
import Data.List (foldl', sort, intercalate, isPrefixOf, isInfixOf, find, zip4)
import qualified Data.Vector as Arr
import Data.Maybe
import Data.Semigroup
import Data.Foldable (fold, foldMap)
import Data.Function (on)
import Data.VectorSpace
import Data.Basis
import Data.AffineSpace
import Data.Manifold.PseudoAffine
import Data.Manifold.TreeCover
import qualified Data.Map.Lazy as Map
import Data.Tagged
import Text.Printf
prettyFloatShow :: Int -> Double -> String
prettyFloatShow _ 0 = "0"
prettyFloatShow preci x
| preci >= 0, preci < 4 = show $ round x
| preci < 0, preci > -2 = printf "%.1f" x
| otherwise = case ceiling (0.01 + lg (abs x/10^^(preci+1))) + preci of
0 | preci < 0 -> printf "%.*f"
(-preci)
x
expn | expn>preci -> printf "%.*f×₁₀%s"
(expn-preci)
(x/10^^expn)
(showExponentAsSuperscript expn)
| otherwise -> printf "%i×₁₀%s"
(round $ x/10^^expn :: Int)
(showExponentAsSuperscript expn)
showExponentAsSuperscript :: Int -> String
showExponentAsSuperscript = map sup . show
where sup ch = case lookup ch $ zip "0123456789-"
"⁰¹²³⁴⁵⁶⁷⁸⁹⁻" of
Just ch -> ch
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . reads
data Annotation = Annotation {
getAnnotation :: AnnotationObj
, placement :: AnnotationPlace
, isOptional :: Bool
}
data AnnotationObj = TextAnnotation TextObj TextAlignment
data AnnotationPlace = ExactPlace R2
data TextObj = PlainText String
fromPlaintextObj :: TextObj -> String
fromPlaintextObj (PlainText t) = t
data TextAlignment = TextAlignment { hAlign, vAlign :: Alignment } -- , blockSpread :: Bool }
data Alignment = AlignBottom | AlignMid | AlignTop
type TxtStyle = Dia.Style Dia.V2 R
data DiagramTK = DiagramTK { textTools :: TextTK, viewScope :: GraphWindowSpecR2 }
data TextTK = TextTK { txtCairoStyle :: TxtStyle
, txtSize, xAspect, padding, extraTopPad :: R }
defaultTxtStyle :: TxtStyle
defaultTxtStyle = mempty & Dia.fontSizeO 9
& Dia.fc Dia.grey
& Dia.lc Dia.grey
prerenderAnnotation :: DiagramTK -> Annotation -> IO PlainGraphicsR2
prerenderAnnotation (DiagramTK{ textTools = TextTK{..}, viewScope = GraphWindowSpecR2{..} })
(Annotation{..})
| TextAnnotation (PlainText str) (TextAlignment{..}) <- getAnnotation
, ExactPlace p₀ <- placement = do
let dtxAlign = DiaTxt.BoxAlignedText
(case hAlign of {AlignBottom -> 0; AlignMid -> 0.5; AlignTop -> 1})
(case vAlign of {AlignBottom -> 0; AlignMid -> 0.5; AlignTop -> 1})
rnTextLines <- mapM (CairoTxt.textVisualBoundedIO txtCairoStyle
. DiaTxt.Text mempty dtxAlign )
$ lines str
let lineWidths = map ((/6 {- Magic number ??? -}) .
Dia.width) rnTextLines
nLines = length lineWidths
lineHeight = 1 + extraTopPad + 2*padding
ζx = ζy * xAspect
ζy = txtSize -- / lineHeight
width = (maximum $ 0 : lineWidths) + 2*padding
height = fromIntegral nLines * lineHeight
y₀ = case vAlign of
AlignBottom -> padding
AlignMid -> 0
AlignTop -> - padding
fullText = mconcat $ zipWith3 ( \n w ->
let y = n' * lineHeight
n' = n - case vAlign of
AlignTop -> 0
AlignMid -> fromIntegral nLines / 2
AlignBottom -> fromIntegral nLines
in (Dia.translate $ Dia.r2 (case hAlign of
AlignBottom -> ( padding, y₀-y )
AlignMid -> ( 0 , y₀-y )
AlignTop -> (-padding, y₀-y )
) ) ) [0..] lineWidths rnTextLines
p = px ^& py
where px = max l' . min r' $ p₀^._x
py = max b' . min t' $ p₀^._y
(l', r') = case hAlign of
AlignBottom -> (lBound , rBound - w )
AlignMid -> (lBound + w/2, rBound - w/2)
AlignTop -> (lBound + w , rBound )
(b', t') = case vAlign of
AlignBottom -> (bBound' , tBound - 2*h )
AlignMid -> (bBound' + h/2, tBound - 3*h/2)
AlignTop -> (bBound' + h , tBound - h )
w = ζx * width; h = 1.5 * ζy * height
bBound' = bBound + lineHeight*ζy
return . Dia.translate p . Dia.scaleX ζx . Dia.scaleY ζy
$ Dia.lc Dia.grey fullText
lg :: Floating a => a -> a
lg = logBase 10
data LegendEntry = LegendEntry {
_plotObjectTitle :: TextObj
, _plotObjRepresentativeColour :: Maybe PColour
, _customLegendObject :: Option ()
}
makeLenses ''LegendEntry
instance HasColour LegendEntry where
asAColourWith sch = asAColourWith sch . _plotObjRepresentativeColour
prerenderLegend :: TextTK -> ColourScheme -> LegendDisplayConfig
-> [LegendEntry] -> IO (Maybe PlainGraphicsR2)
prerenderLegend _ _ _ [] = return mempty
prerenderLegend TextTK{..} cscm layoutSpec l = do
let bgColour = cscm neutral
lRends <- forM l `id`\legEntry -> do
txtR <- CairoTxt.textVisualBoundedIO txtCairoStyle
$ DiaTxt.Text mempty (DiaTxt.BoxAlignedText 0 0.5)
(fromPlaintextObj $ legEntry^.plotObjectTitle)
let h = Dia.height txtR
return $ Dia.hsep 5 [ Dia.rect h h & Dia.fcA
(asAColourWith cscm legEntry)
, txtR
] & Dia.centerXY
& Dia.frame 2
& Dia.alignL
let szSpec = Dia.getSpec (layoutSpec ^. legendPrerenderSize)
hLine = maximum $ Dia.height <$> lRends
nLines = case szSpec of
DiaTypes.V2 _ Nothing -> length l
DiaTypes.V2 _ (Just hMax) -> max 1 . floor $ hMax / hLine
lRends2D = Dia.hsep (txtSize*2) $ Dia.vcat <$> takes nLines lRends
w = case szSpec of
DiaTypes.V2 Nothing _ -> Dia.width lRends2D
DiaTypes.V2 (Just wM) _ -> wM
h = Dia.height lRends2D
return . pure
$ ( lRends2D & Dia.centerXY & Dia.translate (3^&3) )
<> ( Dia.rect (w+1) (h+1) & Dia.fcA (cscm $ paler grey) )
where takes :: Int -> [a] -> [[a]]
takes n [] = []
takes n l = case splitAt n l of
(h,r) -> h : takes n r
|
leftaroundabout/dynamic-plot
|
Graphics/Text/Annotation.hs
|
gpl-3.0
| 9,604 | 14 | 25 | 3,656 | 2,391 | 1,301 | 1,090 | 185 | 15 |
module Main where
import Test.Tasty
-- library tests
import Test.Gophermap
-- server executable tests
import Test.FileTypeDetection
import Test.Integration
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "tests"
[ gophermapTests
, fileTypeDetectionTests
, integrationTests
]
|
sternenseemann/spacecookie
|
test/Main.hs
|
gpl-3.0
| 315 | 0 | 6 | 53 | 68 | 40 | 28 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
-- STDLIB
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.List (foldl')
import System.Environment (getArgs)
import qualified Data.Map as M
-- SITE PACKAGES
import Control.Monad.CryptoRandom (CRandom(..))
import Crypto.Random (SystemRandom, newGenIO)
import Math.Algebra.Field.Base (Fp, F97)
import Math.Common.IntegerAsType (IntegerAsType)
-- CRITERION
import Criterion.Config
import Criterion.Main
import Criterion.Types
-- LOCAL
import Data.ExpressionTypes (Expr(..))
import Data.FieldTypes (Field(..))
import Data.LinearExpression (VariableName, VarMapping)
import Data.RAE.Encoder (exprToRAC, exprToDRAC)
import Data.RAE.Evaluation (runRAC, runDRAC)
import Math.FiniteFields.F2Pow256 (F2Pow256)
import qualified Math.Polynomials as P
instance IntegerAsType n => Field (Fp n) where
invert n =
case n of
0 -> error "0 is not invertible"
n' -> 1 / n'
zero = fromInteger 0
one = fromInteger 1
instance IntegerAsType n => CRandom (Fp n) where
crandom g =
case crandom g of
Left err -> Left err
Right (a, g') -> Right (fromIntegral (a :: Int), g')
evalDirect :: (CRandom el, Field el, Show el)
=> SystemRandom -> VarMapping el -> Expr el -> el
evalDirect g varMap expr =
let (_, drac) = exprToDRAC g expr
out = fromJust . fst $ runDRAC varMap drac
in out `seq` out
evalViaRAC :: (CRandom el, Field el, Show el)
=> SystemRandom -> VarMapping el -> Expr el -> el
evalViaRAC g varMap expr =
let (_, rac, oac) = exprToRAC g expr
in case runRAC rac oac varMap of
Left s -> error s
Right out -> out `seq` out
_TVM_F97_ :: Map VariableName F97
_TVM_F97_ = M.fromList [("x", 17), ("y", 23)]
_TVM_F2Pow256_ :: Map VariableName F2Pow256
_TVM_F2Pow256_ = M.fromList [("x", 2^256-1), ("y", 1234)]
_X_ :: Field e => Expr e
_X_ = Var "x"
_Y_ :: Field e => Expr e
_Y_ = Var "y"
main =
do g <- (newGenIO :: IO SystemRandom)
(cfg, _) <- parseArgs defaultConfig defaultOptions =<< getArgs
defaultMain
[ bgroup "DRAC direct F97"
[ bench "x ^ 1" $ whnf (evalD97 g) (_X_ ^ 1)
, bench "x ^ 10" $ whnf (evalD97 g) (_X_ ^ 10)
, bench "x ^ 100" $ whnf (evalD97 g) (_X_ ^ 100)
, bench "x ^ 1000" $ whnf (evalD97 g) (_X_ ^ 1000)
, bench "x * 1" $ whnf (evalD97 g) (addNx 1)
, bench "x * 10" $ whnf (evalD97 g) (addNx 10)
, bench "x * 100" $ whnf (evalD97 g) (addNx 100)
, bench "x * 1000" $ whnf (evalD97 g) (addNx 1000)
, bench "x * 10000"$ whnf (evalD97 g) (addNx 10000)
]
, bgroup "DRAC direct F2Pow256"
[ bench "x ^ 1" $ whnf (evalDF2e256 g) (_X_ ^ 1)
, bench "x ^ 10" $ whnf (evalDF2e256 g) (_X_ ^ 10)
, bench "x ^ 100" $ whnf (evalDF2e256 g) (_X_ ^ 100)
, bench "x ^ 1000" $ whnf (evalDF2e256 g) (_X_ ^ 1000)
, bench "x * 1" $ whnf (evalDF2e256 g) (addNx 1)
, bench "x * 10" $ whnf (evalDF2e256 g) (addNx 10)
, bench "x * 100" $ whnf (evalDF2e256 g) (addNx 100)
, bench "x * 1000" $ whnf (evalDF2e256 g) (addNx 1000)
, bench "x * 10000"$ whnf (evalDF2e256 g) (addNx 10000)
]
, bgroup "DRAC via RAC F97"
[ bench "x ^ 1" $ whnf (evalRAC97 g) (_X_ ^ 1)
, bench "x ^ 10" $ whnf (evalRAC97 g) (_X_ ^ 10)
, bench "x ^ 100" $ whnf (evalRAC97 g) (_X_ ^ 100)
, bench "x ^ 1000" $ whnf (evalRAC97 g) (_X_ ^ 1000)
, bench "x * 1" $ whnf (evalRAC97 g) (addNx 1)
, bench "x * 10" $ whnf (evalRAC97 g) (addNx 10)
, bench "x * 100" $ whnf (evalRAC97 g) (addNx 100)
, bench "x * 1000" $ whnf (evalRAC97 g) (addNx 1000)
, bench "x * 10000"$ whnf (evalRAC97 g) (addNx 10000)
]
, bgroup "DRAC via RAC F2Pow256"
[ bench "x ^ 1" $ whnf (evalRACF2e256 g) (_X_ ^ 1)
, bench "x ^ 10" $ whnf (evalRACF2e256 g) (_X_ ^ 10)
, bench "x ^ 100" $ whnf (evalRACF2e256 g) (_X_ ^ 100)
, bench "x ^ 1000" $ whnf (evalRACF2e256 g) (_X_ ^ 1000)
, bench "x * 1" $ whnf (evalRACF2e256 g) (addNx 1)
, bench "x * 10" $ whnf (evalRACF2e256 g) (addNx 10)
, bench "x * 100" $ whnf (evalRACF2e256 g) (addNx 100)
, bench "x * 1000" $ whnf (evalRACF2e256 g) (addNx 1000)
, bench "x * 10000"$ whnf (evalRACF2e256 g) (addNx 10000)
]
, bgroup "Horner Poly Building F97"
[ bench "1..100" $whnf hornerF97 $ replicate 100 17
, bench "1..1000" $whnf hornerF97 $ replicate 1000 17
, bench "1..10000" $whnf hornerF97 $ replicate 10000 17
, bench "1..100000" $whnf hornerF97 $ replicate 100000 17
]
, bgroup "Horner Poly Building F2Pow256"
[ bench "1..100" $whnf hornerF2P $ replicate 100 someF2PElem
, bench "1..1000" $whnf hornerF2P $ replicate 1000 someF2PElem
, bench "1..10000" $whnf hornerF2P $ replicate 10000 someF2PElem
, bench "1..100000" $whnf hornerF2P $ replicate 100000 someF2PElem
]
]
where evalD97 g = evalDirect g _TVM_F97_
evalDF2e256 g = evalDirect g _TVM_F2Pow256_
evalRAC97 g = evalViaRAC g _TVM_F97_
evalRACF2e256 g = evalViaRAC g _TVM_F2Pow256_
addNx n = foldl' (+) 0 $ take n $ repeat _X_
hornerF97 = P.horner (17 :: F97)
hornerF2P = P.horner someF2PElem
someF2PElem :: F2Pow256
someF2PElem = read "[1 0 1 1 0 0 1 0 1]"
|
weissi/diplomarbeit
|
bench/BenchRAE.hs
|
gpl-3.0
| 5,862 | 0 | 14 | 1,912 | 2,083 | 1,057 | 1,026 | 117 | 2 |
module NumberTheory.Permutations.CycManip
where
import Data.List
{- Replaces part of a list with a specific element in a list. If the
list has multiple arguments, the elements of the list are substituted. -}
replacePart :: Eq a => Int -> [a] -> [a] -> [a]
replacePart n x l = take (n-1) l ++ x ++ drop n l
{- Replaces multiple consecutive parts of a list specified in the ordered pair of the first argument, substituting the elements
of another list -}
replaceParts :: (Eq a) => (Int, Int) -> [a] -> [a] -> [a]
replaceParts (start, end) l1 l2
| start >= end = error "Start index too large."
| start <= 0 || end <= 0 = error "Non-positive argument."
| end > length l1 = error "End index too large."
| otherwise = take (start-1) l1 ++ l2 ++ drop end l1
multiint, multiuni :: Eq a => [[a]] -> [a]
multiint = foldl1 union
multiuni = foldl1 intersect
type Perm = [[Int]]
cycleprodQ :: Perm -> Bool
cycleprodQ xs = nub (concat xs) == concat xs
rotateList l n
| n >= 0 && ln > n = (drop n l) ++ (take n l)
| otherwise = rotateList l (mod n ln)
where ln = length l
cycleRotate l (n,nn)
| n > length l = error "Part length excessively large! "
| otherwise = replacePart n [rotateList (l !! (n - 1)) nn] l
cycleDecompose l n
| n > length l = error "Part length excessively large!"
| otherwise = replacePart n decomposed l
where decomposed = decomposeCycle (l !! (n-1))
decomposeCycle (l0:ls) = map (\x -> [l0,x]) ls
cycleCompose :: Perm -> (Int,Int) -> Perm
cycleCompose l (start,end)
| start >= end = error "Start position can't go before end position!"
| end > length l = error "End position can't exceed length of list!"
| any (/=2) (map length cycles_to_compose)
= error "Composed cycles must be of length 2!"
| length (multiint cycles_to_compose) /= 1
= error "Cycles must pairwise share exactly one element!"
| otherwise = replaceParts (start, end) l
[(nub (concat cycles_to_compose))]
where cycles_to_compose = [ l !! n | n <- [(start-1)..(end-1)]]
involuteCancel :: Perm -> Int -> Perm
involuteCancel l n
| n > (length l) - 1 = error "Position can't exceed length of list!"
| (l !! (n - 1)) /= (l !! n) = error "No involution here to cancel!"
| otherwise = replaceParts (n, n + 1) l []
cycleCommute :: Perm -> Int -> Perm
cycleCommute l n
| n > (length l) - 1 = error "Position can't exceed length of list!"
| intersect (l !! (n-1)) (l !! n) /= [] =
error "Cycle at position not pairwise disjoint with its neighbour!"
| otherwise = replaceParts (n, n + 1) l [(l !! n), (l !! (n-1))]
cycleManip :: String -> Perm -> Perm
cycleManip cmds l = foldr cM l (words cmds)
where cM command perm
= case command
of ('k':':':xs) -> cycleDecompose perm (read xs)
('r':':':xs) -> cycleRotate perm (read2 xs)
('i':':':xs) -> involuteCancel perm (read xs)
('p':':':xs) -> cycleCompose perm (read2 xs)
('c':':':xs) -> cycleCommute perm (read xs)
_ -> error "Improper syntax: Unsupported command."
read2 :: String -> (Int,Int)
read2 str = let (n1,s) = (\st -> break (==',') st) str
(',':n2) = s
in (read n1, read n2)
|
mathlover2/number-theory
|
NumberTheory/Permutations/CycManip.hs
|
gpl-3.0
| 3,308 | 0 | 13 | 874 | 1,311 | 664 | 647 | 64 | 6 |
module RewriteRules (simplify, dedual, unexpt,
prop_simplify_idempotent,
prop_dedual_onlyNegativeAtoms,
prop_unexpt_inExponentialLattice1,
prop_unexpt_inExponentialLattice2)
where
import Test.QuickCheck
import Arbitrary
import Syntax
import Parser
import Rewrite
l --@ r = (tt l, tt r)
dedual_rules = [
"a^^" --@ "a",
"(a * b)^" --@ "a^ $ b^",
"(a $ b)^" --@ "a^ * b^",
"(a & b)^" --@ "a^ + b^",
"(a + b)^" --@ "a^ & b^",
"(a -@ b)^" --@ "a * b^",
"(!a)^" --@ "?(a^)",
"(?a)^" --@ "!(a^)",
"1^" --@ "%",
"0^" --@ "#",
"#^" --@ "0",
"%^" --@ "1"
]
unexpt_rules = [
"!!a" --@ "!a",
"??a" --@ "?a",
"!?!?a" --@ "!?a",
"?!?!a" --@ "?!a",
"!?1" --@ "1",
"?!%" --@ "%"
]
unit_rules = [
"!#" --@ "1",
"?0" --@ "%",
"a * 1" --@ "a",
"a $ %" --@ "a",
"a + 0" --@ "a",
"a & #" --@ "a",
"a * 0" --@ "0",
"a $ #" --@ "#"
]
distrib_rules = [
"a * (b + c)" --@ "(a * b) + (a * c)",
"a $ (b & c)" --@ "(a $ b) & (a $ c)",
"a * (b & c)" --@ "(a * b) & (a * c)",
"a $ (b + c)" --@ "(a $ b) + (a $ c)"
]
unexpt_aux_rules = [
"!(a & b)" --@ "!a * !b",
"?(a + b)" --@ "?a $ ?b"
]
dedual :: Term -> Term
dedual = rewrite' dedual_rules
unexpt :: Term -> Term
unexpt = rewrite' unexpt_rules
simplify :: Term -> Term
simplify = rewrite' $ concat [dedual_rules, unexpt_rules, unit_rules]
reduce :: Term -> Term
reduce = rewrite' $ concat [distrib_rules, unexpt_aux_rules]
-- Second order idempotence predicate
prop_idempotent :: Eq a => (a -> a) -> a -> Bool
prop_idempotent f x = f (f x) == f x
prop_simplify_idempotent :: Term -> Bool
prop_dedual_idempotent :: Term -> Bool
prop_unexpt_idempotent :: Term -> Bool
prop_simplify_idempotent = prop_idempotent simplify
prop_dedual_idempotent = prop_idempotent dedual
prop_unexpt_idempotent = prop_idempotent unexpt
prop_dedual_onlyNegativeAtoms :: Term -> Bool
prop_dedual_onlyNegativeAtoms x = check (dedual x)
where check (Not (Atom _)) = True
check (Not _) = False
check (l :*: r) = check l && check r
check (l :$: r) = check l && check r
check (l :-@: r) = check l && check r
check (l :&: r) = check l && check r
check (l :+: r) = check l && check r
check (OfCourse a) = check a
check (WhyNot a) = check a
check _ = True
prop_unexpt_inExponentialLattice1 :: Term -> Bool
prop_unexpt_inExponentialLattice2 :: Term -> Property
prop_unexpt_inExponentialLattice1 x = lattice (unexpt x)
-- This is a weakened version of the prop above,
-- that makes counter examples easier to find for quickCheck
prop_unexpt_inExponentialLattice2 x =
forAllShrink exponentOnlyTerm shrink $ \t -> lattice (unexpt t)
lattice :: Term -> Bool
lattice (OfCourse (WhyNot (OfCourse a))) = latticeNoExp a
lattice (WhyNot (OfCourse (WhyNot a))) = latticeNoExp a
lattice (OfCourse (WhyNot a)) = latticeNoExp a
lattice (WhyNot (OfCourse a)) = latticeNoExp a
lattice (OfCourse a) = latticeNoExp a
lattice (WhyNot a) = latticeNoExp a
lattice (l :*: r) = lattice l && lattice r
lattice (l :$: r) = lattice l && lattice r
lattice (l :-@: r) = lattice l && lattice r
lattice (l :&: r) = lattice l && lattice r
lattice (l :+: r) = lattice l && lattice r
lattice (Not a) = lattice a
lattice _ = True
latticeNoExp (OfCourse _) = False
latticeNoExp (WhyNot _) = False
latticeNoExp t = lattice t
(--@) :: String -> String -> (Term, Term)
dedual_rules :: [Rule]
unexpt_rules :: [Rule]
|
andykitchen/linear-logic
|
RewriteRules.hs
|
gpl-3.0
| 3,576 | 0 | 11 | 901 | 1,182 | 618 | 564 | 101 | 10 |
module Gis.Saga.Node (getAllRoutes)
where
import qualified Data.Map as M
import Gis.Saga.Types
-- | find all possible edges between Nodes
findEdges :: NodeMap -> [((String,String),[String])]
findEdges nds =
[((fromNme,toNme),[o]) | (fromNme, (_, fromOuts)) <- M.toList nds
, (toNme, (toIns, _)) <- M.toList nds
, o <- fromOuts
, i <- toIns
, o == i
]
-- | Get all possible routes for some nodes
getAllRoutes :: NodeMap -> [((String,String),[String])]
getAllRoutes = concat . findRoutes . findEdges
-- | finds all possible routes
findRoutes :: [((String,String),[String])] -> [[((String,String),[String])]]
findRoutes [] = []
findRoutes edgs = edgs : edgs' : findRoutes edgs'
where
edgs' = chainEdges edgs
chainEdges :: [((String,String),[String])] -> [((String,String),[String])]
chainEdges edges =
[((srcF,dstT), srcCmds ++ dstCmds) | ((srcF,srcT),srcCmds) <- edges
, ((dstF,dstT),dstCmds) <- edges
, srcT == dstF
]
|
michelk/bindings-saga-cmd.hs
|
src/Gis/Saga/Node.hs
|
gpl-3.0
| 1,181 | 0 | 11 | 394 | 405 | 242 | 163 | 21 | 1 |
import Data.Unsafe.Global
myGlobalVar = newGlobal 2
incMyGlob = modifyIORef myGlobalVar (+1)
main = do
incMyGlob
incMyGlob
myGlobVar' <- readIORef myGlobalVar
print myGlobVar'
|
xpika/global
|
example.hs
|
gpl-3.0
| 206 | 0 | 8 | 52 | 56 | 27 | 29 | 8 | 1 |
module Lambia.Unlambda () where
import Prelude hiding (lookup)
import Lambia.Types hiding (simple,apply)
import qualified Lambia.Types as T (simple,apply)
simple :: Int -> Unlambda -> (Bool, Unlambda)
simple n l = s l n where
s :: Unlambda -> Int -> (Bool, Unlambda)
s e 0
| size e == size l = (True,e)
| size e < size l = (True,snd $ simple n e)
| otherwise = (False,l)
s e x = case repl e of
(False,_) -> s e 0
(True,e') -> s e' (x-1)
size :: Unlambda -> Int
size (Au x y) = size x + size y
size _ = 1
apply :: Unlambda -> (Unlambda, [Unlambda])
apply i = a i [] where
a x xs = case repl x of
(True, x') -> a x' (x:xs)
(False, _) -> (x,xs)
repl :: Unlambda -> (Bool, Unlambda)
repl (Au Iu x) = (True, snd $ repl x)
repl (Au (Au Ku x) y) = (True, snd $ repl x)
repl (Au (Au (Au Su x) y) z) = (True, Au (Au x z) (Au y z))
repl (Au x y) = case repl x of
(True, x') -> (True, Au x' y)
(False, _) -> case repl y of
(True, y') -> (True, Au x y')
(False, _) -> (False, Au x y)
repl x = (False, x)
instance Store Unlambda where
simple = simple
apply = apply
fromSyn = sToU
|
phi16/Lambia
|
src/Lambia/Unlambda.hs
|
gpl-3.0
| 1,134 | 0 | 12 | 304 | 667 | 357 | 310 | 36 | 4 |
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : HEP.Automation.MadGraph.Machine
-- Copyright : (c) 2011-2013,2015 Ian-Woo Kim
--
-- License : GPL-3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module HEP.Automation.MadGraph.Card where
import Control.Applicative
import Data.Hashable
import Text.StringTemplate
import Text.StringTemplate.Helpers
import System.FilePath ((</>))
--
import HEP.Automation.MadGraph.Type
-- |
runCard4CutMatch :: CutType -> MatchType -> String
runCard4CutMatch NoCut NoMatch = "run_card_NoCut_NoMatch.dat"
runCard4CutMatch DefCut NoMatch = "run_card_DefCut_NoMatch.dat"
runCard4CutMatch DefCut MLM = "run_card_DefCut_MLM.dat"
runCard4CutMatch KCut MLM = "run_card_KCut_MLM.dat"
runCard4CutMatch _ _ = error "cut mlm does not match"
-- |
pythiaCardMatch :: MatchType -> String
pythiaCardMatch NoMatch = "pythia_card_default.dat"
pythiaCardMatch MLM = "pythia_card_MLM.dat"
-- |
pgsCardMachine :: MachineType -> String
pgsCardMachine TeVatron = "pgs_card_TEV.dat.st"
pgsCardMachine (LHC7 LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (LHC7 ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (LHC7 CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (LHC7 _) = undefined
pgsCardMachine (LHC8 LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (LHC8 ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (LHC8 CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (LHC8 _) = undefined
pgsCardMachine (LHC10 LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (LHC10 ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (LHC10 CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (LHC10 _) = undefined
pgsCardMachine (LHC13 LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (LHC13 ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (LHC13 CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (LHC13 _) = undefined
pgsCardMachine (LHC14 LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (LHC14 ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (LHC14 CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (LHC14 _) = undefined
pgsCardMachine (Parton _ LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (Parton _ Tevatron) = "pgs_card_TEV.dat.st"
pgsCardMachine (Parton _ ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (Parton _ CMS) = "pgs_card_CMS.dat.st"
pgsCardMachine (PolParton _ _ LHC) = "pgs_card_LHC.dat.st"
pgsCardMachine (PolParton _ _ Tevatron) = "pgs_card_TEV.dat.st"
pgsCardMachine (PolParton _ _ ATLAS) = "pgs_card_ATLAS.dat.st"
pgsCardMachine (PolParton _ _ CMS) = "pgs_card_CMS.dat.st"
-- |
runCardSetup :: FilePath
-> MachineType
-> CutType
-> MatchType
-> RGRunType
-> Double
-> Int -- ^ number of events
-> HashSalt
-> Int -- ^ set number
-> IO String
runCardSetup tpath machine ctype mtype rgtype scale numevt hsalt setnum = do
let (beamtyp1,beamtyp2,beamenergy,beampol1,beampol2) = case machine of
TeVatron -> ("1","-1","980","0","0")
LHC7 _ -> ("1","1","3500","0","0")
LHC8 _ -> ("1","1","4000","0","0")
LHC10 _ -> ("1","1","5000","0","0")
LHC13 _ -> ("1","1","6500","0","0")
LHC14 _ -> ("1","1","7000","0","0")
Parton be _ -> ("0","0", show be,"0","0")
PolParton be ipol _ -> ( "0","0", show be
, (show . rhpol_percent . particle1pol) ipol
, (show . rhpol_percent . particle2pol) ipol )
isFixedRG = case rgtype of
Fixed -> "T"
Auto -> "F"
numevtfinal = if numevt > 100000 then 100000 else numevt
iseed = case unHashSalt hsalt of
Nothing -> show (setnum + 1)
Just hs -> show (hashWithSalt hs setnum `mod` 1000 + 1005)
templates <- directoryGroup tpath
return $ (renderTemplateGroup
templates
[ ("numevt" , show numevtfinal )
, ("iseed" , iseed )
, ("beamTypeOne" , beamtyp1 )
, ("beamTypeTwo" , beamtyp2 )
, ("beamEnergy" , beamenergy )
, ("beamPolOne" , beampol1)
, ("beamPolTwo" , beampol2)
, ("isFixedRG" , isFixedRG )
, ("rgScale" , show scale )
, ("facScale" , show scale ) ]
(runCard4CutMatch ctype mtype) ) ++ "\n\n\n"
-- |
pythiaCardSetup :: FilePath -> MatchType -> PYTHIAType -> IO (Maybe String)
pythiaCardSetup tpath mtype ptype = do
templates <- directoryGroup tpath
let tfile = pythiaCardMatch mtype
case ptype of
NoPYTHIA -> return Nothing
RunPYTHIA8 -> return Nothing
RunPYTHIA -> do
let str = renderTemplateGroup templates [ ("ISR","1"), ("FSR","1") ] tfile ++ "\n\n\n"
return (Just str)
RunPYTHIA6Detail isr fsr -> do
let f True = "1"
f False = "0"
flagset = [ ("ISR", f isr), ("FSR", f fsr) ]
str = renderTemplateGroup templates flagset tfile ++ "\n\n\n"
return (Just str)
-- |
pgsCardSetup :: FilePath -- ^ template path
-> MachineType -- ^ machine type
-> PGSType -- ^ pgs work type
-> IO (Maybe String) -- ^ pgs card string
pgsCardSetup tpath machine NoPGS = return Nothing
pgsCardSetup tpath machine (RunPGS (jetalgo,tau)) = do
tmplstr <- (++ "\n\n\n") <$> readFile (tpath </> pgsCardMachine machine)
let addnotau = case tau of
-- NoTau -> "notau"
WithTau -> ""
let str = case jetalgo of
Cone conesize -> render1 [ ("jetalgo", "cone"++addnotau)
, ("conesize", show conesize) ] tmplstr
KTJet conesize -> render1 [ ("jetalgo", "ktjet"++addnotau)
, ("conesize", show conesize) ] tmplstr
AntiKTJet conesize -> render1 [ ("jetalgo", "antikt"++addnotau)
, ("conesize", show conesize) ] tmplstr
return (Just str)
|
wavewave/madgraph-auto
|
src/HEP/Automation/MadGraph/Card.hs
|
gpl-3.0
| 6,389 | 0 | 18 | 1,767 | 1,641 | 874 | 767 | 123 | 11 |
{-# LANGUAGE OverloadedStrings #-}
module Coala.Input.SingleFile
( SingleFile (SingleFile)
, singleFile
, file
, settings
) where
import Coala ( Filename (Filename), FileRef )
import qualified Coala as C (filename)
import Coala.Input ( Settings, emptySettings )
import Data.Text ( Text )
import Data.Text.Encoding ( encodeUtf8 )
import Data.ByteString.Lazy ( ByteString )
import Data.Maybe ( fromJust )
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Data.Aeson ( (.:), decode, Object )
import Data.Aeson.Types ( parseMaybe )
data SingleFile = SingleFile { filename :: Filename -- ^ Source filename
, file :: [Text] -- ^ Lines of source file
, settings :: Settings -- ^ Settings
} deriving ( Eq, Show )
instance FileRef SingleFile where
filename = filename
singleFile :: (ByteString -> Maybe SingleFile)
singleFile content = do o <- decode content :: Maybe Object
flip parseMaybe o $ \obj -> do
fn <- obj .: "filename"
t <- obj .: "file"
s <- obj .: "settings"
return $ SingleFile (Filename fn) t s
|
maweki/coalaHs
|
src/Coala/Input/SingleFile.hs
|
gpl-3.0
| 1,281 | 0 | 14 | 419 | 319 | 188 | 131 | 33 | 1 |
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Orphans () where
import Data.Default (Default, def)
import qualified Data.Strict.Maybe as Strict
import Data.Vector.Unboxed (Unbox)
import Data.Vector.Unboxed.Deriving (derivingUnbox)
deriving instance Foldable Strict.Maybe
deriving instance Traversable Strict.Maybe
instance Applicative Strict.Maybe where
pure = Strict.Just
(<*>) Strict.Nothing _ = Strict.Nothing
(<*>) _ Strict.Nothing = Strict.Nothing
(<*>) (Strict.Just f) (Strict.Just x) = Strict.Just $ f x
derivingUnbox "Maybe"
[t| forall a. (Default a, Unbox a) => Maybe a -> (Bool, a) |]
[| maybe (False, def) (\ x -> (True, x)) |]
[| \ (b, x) -> if b then Just x else Nothing |]
|
davidspies/regret-solver
|
game/src/Orphans.hs
|
gpl-3.0
| 982 | 0 | 9 | 180 | 188 | 114 | 74 | 24 | 0 |
{-# LANGUAGE RankNTypes #-}
module Language.Mulang.Parsers.Prolog (pl, parseProlog) where
import Text.Parsec
import Text.Parsec.Expr
import Text.Parsec.Numbers
import Language.Mulang.Ast
import Language.Mulang.Builder (compact)
import Language.Mulang.Parsers
import Data.Maybe (fromMaybe)
import Data.Char (isUpper, isSpace)
import Data.List (dropWhileEnd)
import Control.Fallible
type ParsecParser a = forall x . Parsec String x a
pl :: Parser
pl = orFail . parseProlog'
parseProlog :: EitherParser
parseProlog = orLeft . parseProlog'
parseProlog' = fmap compact . parse program "" . trim . stripComments
trim :: String -> String
trim = dropWhile isSpace . dropWhileEnd isSpace
stripComments :: String -> String
stripComments ('%' : code) = stripComments $ dropSingleLineComment code
stripComments ('/' : '*' : code) = stripComments $ dropMultiLineComment code
stripComments (c : ode) = c : stripComments ode
stripComments "" = ""
dropSingleLineComment :: String -> String
dropSingleLineComment ('\n' : code) = code
dropSingleLineComment (_ : code) = dropSingleLineComment code
dropSingleLineComment "" = ""
dropMultiLineComment :: String -> String
dropMultiLineComment ('*' : '/' : code) = code
dropMultiLineComment (_ : code) = dropMultiLineComment code
dropMultiLineComment "" = ""
program :: ParsecParser [Expression]
program = many predicate
pattern :: ParsecParser Pattern
pattern = buildExpressionParser optable (term <* spaces)
where
optable = [ [ Infix (op "^") AssocLeft ],
[ Infix (op "*") AssocLeft ],
[ Infix (op "/") AssocLeft ],
[ Infix (op "+") AssocLeft ],
[ Infix (op "-") AssocLeft ] ]
term = try number <|> wildcard <|> tuple <|> (fmap otherToPattern phead)
otherToPattern (name, []) | isUpper . head $ name = VariablePattern name
| otherwise = LiteralPattern name
otherToPattern ("abs", [p]) = ApplicationPattern "abs" [p]
otherToPattern ("mod", [p1, p2]) = ApplicationPattern "mod" [p1, p2]
otherToPattern ("div", [p1, p2]) = ApplicationPattern "div" [p1, p2]
otherToPattern ("rem", [p1, p2]) = ApplicationPattern "rem" [p1, p2]
otherToPattern ("round", [p1]) = ApplicationPattern "round" [p1]
otherToPattern (name, args) = FunctorPattern name args
op :: String -> ParsecParser (Pattern -> Pattern -> Pattern)
op symbol = string symbol <* spaces >> return (\x y -> ApplicationPattern symbol [x, y])
tuple :: ParsecParser Pattern
tuple = fmap compact patternsList
where compact [p] = p
compact ps = TuplePattern ps
wildcard :: ParsecParser Pattern
wildcard = string "_" >> return WildcardPattern
number :: ParsecParser Pattern
number = fmap (LiteralPattern . show) parseFloat
fact :: ParsecParser Expression
fact = do
(name, args) <- phead
end
return $ Fact name args
rule :: ParsecParser Expression
rule = do
(name, args) <- phead
def
consults <- body
end
return $ Rule name args consults
phead :: ParsecParser (Identifier, [Pattern])
phead = do
name <- identifier
args <- optionMaybe patternsList
spaces
return (name, fromMaybe [] args)
forall :: ParsecParser Expression
forall = do
string "forall"
startTuple
c1 <- consult
separator
c2 <- consult
endTuple
return $ Forall c1 c2
findall :: ParsecParser Expression
findall = do
string "findall"
startTuple
c1 <- consult
separator
c2 <- consult
separator
c3 <- consult
endTuple
return $ Findall c1 c2 c3
cut :: ParsecParser Expression
cut = do
bang
return $ Exist "!" []
pnot :: ParsecParser Expression
pnot = do
c <- operator <|> functor
return $ Not c
where
functor = string "not" >> startTuple >> consult <* endTuple
operator = negation >> consult
exist :: ParsecParser Expression
exist = fmap (\(name, args) -> Exist name args) phead
body :: ParsecParser [Expression]
body = sepBy1 consult separator
inlineBody :: ParsecParser Expression
inlineBody = do
startTuple
queries <- body
endTuple
return $ Sequence queries
pinfix :: ParsecParser Expression
pinfix = do
p1 <- pattern
spaces
operator <- choice . map try . map string $ ["is", "|", ">=", "=<", "\\=", ">", "<", "=:=", "==", "=\\=", ":=", "=..", "=@=", "\\\\=@=", "="]
spaces
p2 <- pattern
return $ Exist operator [p1, p2]
consult :: ParsecParser Expression
consult = choice [try findall, try forall, try pnot, try pinfix, inlineBody, cut, exist]
predicate :: ParsecParser Expression
predicate = try fact <|> rule
patternsList :: ParsecParser [Pattern]
patternsList = startTuple >> sepBy1 pattern separator <* endTuple
bang = string "!" >> spaces
negation = string "\\+" >> spaces
identifier = many1 letter
def = string ":-" >> spaces
startTuple = lparen >> spaces
endTuple = rparen >> spaces
separator = (char ',' <|> char ';') >> spaces
end = char '.' >> spaces
lparen = char '('
rparen = char ')'
|
mumuki/mulang
|
src/Language/Mulang/Parsers/Prolog.hs
|
gpl-3.0
| 5,026 | 139 | 15 | 1,098 | 1,644 | 884 | 760 | 143 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.