code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-|
Module : Idris.Elab.Term
Description : Code to elaborate terms.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE LambdaCase, PatternGuards, ViewPatterns #-}
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
module Idris.Elab.Term where
import Idris.AbsSyntax
import Idris.Core.CaseTree (SC'(STerm), findCalls)
import Idris.Core.Elaborate hiding (Tactic(..))
import Idris.Core.Evaluate
import Idris.Core.ProofTerm (getProofTerm)
import Idris.Core.TT
import Idris.Core.Typecheck (check, converts, isType, recheck)
import Idris.Core.Unify
import Idris.Core.WHNF (whnf)
import Idris.Coverage (genClauses, recoverableCoverage)
import Idris.Delaborate
import Idris.Elab.Quasiquote (extractUnquotes)
import Idris.Elab.Rewrite
import Idris.Elab.Utils
import Idris.Error
import Idris.ErrReverse (errReverse)
import Idris.Options
import Idris.ProofSearch
import Idris.Reflection
import Idris.Termination (buildSCG, checkDeclTotality, checkPositive)
import Control.Monad
import Control.Monad.State.Strict
import Data.Foldable (for_)
import Data.List
import qualified Data.Map as M
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import qualified Data.Set as S
import Debug.Trace
data ElabMode = ETyDecl | ETransLHS | ELHS | EImpossible | ERHS
deriving Eq
data ElabResult = ElabResult {
-- | The term resulting from elaboration
resultTerm :: Term
-- | Information about new metavariables
, resultMetavars :: [(Name, (Int, Maybe Name, Type, [Name]))]
-- | Deferred declarations as the meaning of case blocks
, resultCaseDecls :: [PDecl]
-- | The potentially extended context from new definitions
, resultContext :: Context
-- | Meta-info about the new type declarations
, resultTyDecls :: [RDeclInstructions]
-- | Saved highlights from elaboration
, resultHighlighting :: S.Set (FC', OutputAnnotation)
-- | The new global name counter
, resultName :: Int
}
-- | Using the elaborator, convert a term in raw syntax to a fully
-- elaborated, typechecked term.
--
-- If building a pattern match, we convert undeclared variables from
-- holes to pattern bindings.
--
-- Also find deferred names in the term and their types
build :: IState
-> ElabInfo
-> ElabMode
-> FnOpts
-> Name
-> PTerm
-> ElabD ElabResult
build ist info emode opts fn tm
= do elab ist info emode opts fn tm
let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
hs <- get_holes
ivs <- get_implementations
ptm <- get_term
-- Resolve remaining interfaces. Two passes - first to get the
-- default Num implementations, second to clean up the rest
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
try (resolveTC' True True 10 g fn ist)
(movelast n)) ivs
ivs <- get_implementations
hs <- get_holes
when (not pattern) $
mapM_ (\n -> when (n `elem` hs) $
do focus n
g <- goal
ptm <- get_term
resolveTC' True True 10 g fn ist) ivs
when (not pattern) $ solveAutos ist fn False
tm <- get_term
ctxt <- get_context
probs <- get_probs
u <- getUnifyLog
hs <- get_holes
when (not pattern) $
traceWhen u ("Remaining holes:\n" ++ show hs ++ "\n" ++
"Remaining problems:\n" ++ qshow probs) $
do unify_all; matchProblems True; unifyProblems
when (not pattern) $ solveAutos ist fn True
probs <- get_probs
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> traceWhen u ("Final problems:\n" ++ qshow probs ++ "\nin\n" ++ show tm) $
if inf then return ()
else lift (Error e)
when tydecl (do mkPat
update_term liftPats
update_term orderPats)
EState is _ impls highlights _ _ <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
g_nextname <- get_global_nextname
if log /= ""
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
where pattern = emode == ELHS || emode == EImpossible
tydecl = emode == ETyDecl
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
-- | Build a term autogenerated as an interface method definition.
--
-- (Separate, so we don't go overboard resolving things that we don't
-- know about yet on the LHS of a pattern def)
buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name ->
[Name] -> -- Cached names in the PTerm, before adding PAlternatives
PTerm ->
ElabD ElabResult
buildTC ist info emode opts fn ns tm
= do let inf = case lookupCtxt fn (idris_tyinfodata ist) of
[TIPartial] -> True
_ -> False
-- set name supply to begin after highest index in tm
initNextNameFrom ns
elab ist info emode opts fn tm
probs <- get_probs
tm <- get_term
case probs of
[] -> return ()
((_,_,_,_,e,_,_):es) -> if inf then return ()
else lift (Error e)
dots <- get_dotterm
-- 'dots' are the PHidden things which have not been solved by
-- unification
when (not (null dots)) $
lift (Error (CantMatch (getInferTerm tm)))
EState is _ impls highlights _ _ <- getAux
tt <- get_term
ctxt <- get_context
let (tm, ds) = runState (collectDeferred (Just fn) (map fst is) ctxt tt) []
log <- getLog
g_nextname <- get_global_nextname
if (log /= "")
then trace log $ return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
else return (ElabResult tm ds (map snd is) ctxt impls highlights g_nextname)
-- | return whether arguments of the given constructor name can be
-- matched on. If they're polymorphic, no, unless the type has beed
-- made concrete by the time we get around to elaborating the
-- argument.
getUnmatchable :: Context -> Name -> [Bool]
getUnmatchable ctxt n | isDConName n ctxt && n /= inferCon
= case lookupTyExact n ctxt of
Nothing -> []
Just ty -> checkArgs [] [] ty
where checkArgs :: [Name] -> [[Name]] -> Type -> [Bool]
checkArgs env ns (Bind n (Pi _ _ t _) sc)
= let env' = case t of
TType _ -> n : env
_ -> env in
checkArgs env' (intersect env (refsIn t) : ns)
(instantiate (P Bound n t) sc)
checkArgs env ns t
= map (not . null) (reverse ns)
getUnmatchable ctxt n = []
data ElabCtxt = ElabCtxt { e_inarg :: Bool,
e_isfn :: Bool, -- ^ Function part of application
e_guarded :: Bool,
e_intype :: Bool,
e_qq :: Bool,
e_nomatching :: Bool -- ^ can't pattern match
}
initElabCtxt = ElabCtxt False False False False False False
goal_polymorphic :: ElabD Bool
goal_polymorphic =
do ty <- goal
case ty of
P _ n _ -> do env <- get_env
case lookupBinder n env of
Nothing -> return False
_ -> return True
_ -> return False
-- | Returns the set of declarations we need to add to complete the
-- definition (most likely case blocks to elaborate) as well as
-- declarations resulting from user tactic scripts (%runElab)
elab :: IState
-> ElabInfo
-> ElabMode
-> FnOpts
-> Name
-> PTerm
-> ElabD ()
elab ist info emode opts fn tm
= do let loglvl = opt_logLevel (idris_options ist)
when (loglvl > 5) $ unifyLog True
compute -- expand type synonyms, etc
elabE initElabCtxt (elabFC info) tm -- (in argument, guarded, in type, in qquote)
est <- getAux
sequence_ (get_delayed_elab est)
end_unify
when (pattern || intransform) $
-- convert remaining holes to pattern vars
do unify_all
matchProblems False -- only the ones we matched earlier
unifyProblems
mkPat
update_term liftPats
ptm <- get_term
when pattern $
-- Look for Rig1 (linear) pattern bindings
do let pnms = findLinear Rig1 ist [] ptm
update_term (setLinear pnms)
where
pattern = emode == ELHS || emode == EImpossible
eimpossible = emode == EImpossible
intransform = emode == ETransLHS
bindfree = emode == ETyDecl || emode == ELHS || emode == ETransLHS
|| emode == EImpossible
autoimpls = opt_autoimpls (idris_options ist)
get_delayed_elab est =
let ds = delayed_elab est in
map snd $ sortBy (\(p1, _) (p2, _) -> compare p1 p2) ds
tcgen = Dictionary `elem` opts
reflection = Reflection `elem` opts
isph arg = case getTm arg of
Placeholder -> (True, priority arg)
tm -> (False, priority arg)
mkPat = do hs <- get_holes
tm <- get_term
case hs of
(h: hs) -> do patvar h; mkPat
[] -> return ()
elabRec = elabE initElabCtxt Nothing
-- | elabE elaborates an expression, possibly wrapping implicit coercions
-- and forces/delays. If you make a recursive call in elab', it is
-- normally correct to call elabE - the ones that don't are `desugarings
-- typically
elabE :: ElabCtxt -> Maybe FC -> PTerm -> ElabD ()
elabE ina fc' t =
do solved <- get_recents
as <- get_autos
hs <- get_holes
-- If any of the autos use variables which have recently been solved,
-- have another go at solving them now.
mapM_ (\(a, (failc, ns)) ->
if any (\n -> n `elem` solved) ns && head hs /= a
then solveAuto ist fn False (a, failc)
else return ()) as
apt <- expandToArity t
itm <- if not pattern then insertImpLam ina apt else return apt
ct <- insertCoerce ina itm
t' <- insertLazy ina ct
g <- goal
tm <- get_term
ps <- get_probs
hs <- get_holes
--trace ("Elaborating " ++ show t' ++ " in " ++ show g
-- ++ "\n" ++ show tm
-- ++ "\nholes " ++ show hs
-- ++ "\nproblems " ++ show ps
-- ++ "\n-----------\n") $
--trace ("ELAB " ++ show t') $
env <- get_env
let fc = fileFC "Force"
handleError (forceErr t' env)
(elab' ina fc' t')
(elab' ina fc' (PApp fc (PRef fc [] (sUN "Force"))
[pimp (sUN "t") Placeholder True,
pimp (sUN "a") Placeholder True,
pexp ct]))
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Delayed" = notDelay orig
forceErr orig env (CantUnify _ (t,_) (t',_) _ _ _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t'),
ht == txt "Delayed" = notDelay orig
forceErr orig env (InfiniteUnify _ t _)
| (P _ (UN ht) _, _) <- unApply (normalise (tt_ctxt ist) env t),
ht == txt "Delayed" = notDelay orig
forceErr orig env (Elaborating _ _ _ t) = forceErr orig env t
forceErr orig env (ElaboratingArg _ _ _ t) = forceErr orig env t
forceErr orig env (At _ t) = forceErr orig env t
forceErr orig env t = False
notDelay t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = False
notDelay _ = True
elab' :: ElabCtxt -- ^ (in an argument, guarded, in a type, in a quasiquote)
-> Maybe FC -- ^ The closest FC in the syntax tree, if applicable
-> PTerm -- ^ The term to elaborate
-> ElabD ()
elab' ina fc (PNoImplicits t) = elab' ina fc t -- skip elabE step
elab' ina fc (PType fc') =
do apply RType []
solve
highlightSource fc' (AnnType "Type" "The type of types")
elab' ina fc (PUniverse fc' u) =
do unless (UniquenessTypes `elem` idris_language_extensions ist
|| e_qq ina) $
lift $ tfail $ At fc' (Msg "You must turn on the UniquenessTypes extension to use UniqueType or AnyType")
apply (RUType u) []
solve
highlightSource fc' (AnnType (show u) "The type of unique types")
-- elab' (_,_,inty) (PConstant c)
-- | constType c && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ina fc tm@(PConstant fc' c)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTypeConst c
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = do apply (RConstant c) []
solve
highlightSource fc' (AnnConst c)
elab' ina fc (PQuote r) = do fill r; solve
elab' ina _ (PTrue fc _) =
do compute
g <- goal
case g of
TType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
UType _ -> elab' ina (Just fc) (PRef fc [] unitTy)
_ -> elab' ina (Just fc) (PRef fc [] unitCon)
elab' ina fc (PResolveTC (FC "HACK" _ _)) -- for chasing parent interfaces
= do g <- goal; resolveTC False False 5 g fn elabRec ist
elab' ina fc (PResolveTC fc')
= do c <- getNameFrom (sMN 0 "__interface")
implementationArg c
-- Elaborate the equality type first homogeneously, then
-- heterogeneously as a fallback
elab' ina _ (PApp fc (PRef _ _ n) args)
| n == eqTy, [Placeholder, Placeholder, l, r] <- map getTm args
= try (do tyn <- getNameFrom (sMN 0 "aqty")
claim tyn RType
movelast tyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] tyn) True,
pimp (sUN "B") (PRef NoFC [] tyn) False,
pexp l, pexp r]))
(do atyn <- getNameFrom (sMN 0 "aqty")
btyn <- getNameFrom (sMN 0 "bqty")
claim atyn RType
movelast atyn
claim btyn RType
movelast btyn
elab' ina (Just fc) (PApp fc (PRef fc [] eqTy)
[pimp (sUN "A") (PRef NoFC [] atyn) True,
pimp (sUN "B") (PRef NoFC [] btyn) False,
pexp l, pexp r]))
elab' ina _ (PPair fc hls _ l r)
= do compute
g <- goal
let (tc, _) = unApply g
case g of
TType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairTy)
[pexp l,pexp r])
UType _ -> elab' ina (Just fc) (PApp fc (PRef fc hls upairTy)
[pexp l,pexp r])
_ -> case tc of
P _ n _ | n == upairTy
-> elab' ina (Just fc) (PApp fc (PRef fc hls upairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
_ -> elab' ina (Just fc) (PApp fc (PRef fc hls pairCon)
[pimp (sUN "A") Placeholder False,
pimp (sUN "B") Placeholder False,
pexp l, pexp r])
elab' ina _ (PDPair fc hls p l@(PRef nfc hl n) t r)
= case p of
IsType -> asType
IsTerm -> asValue
TypeOrTerm ->
do compute
g <- goal
case g of
TType _ -> asType
_ -> asValue
where asType = elab' ina (Just fc) (PApp fc (PRef NoFC hls sigmaTy)
[pexp t,
pexp (PLam fc n nfc Placeholder r)])
asValue = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina _ (PDPair fc hls p l t r) = elab' ina (Just fc) (PApp fc (PRef fc hls sigmaCon)
[pimp (sMN 0 "a") t False,
pimp (sMN 0 "P") Placeholder True,
pexp l, pexp r])
elab' ina fc (PAlternative ms (ExactlyOne delayok) as)
= do as_pruned <- doPrune as
-- Finish the mkUniqueNames job with the pruned set, rather than
-- the full set.
uns <- get_usedns
let as' = map (mkUniqueNames (uns ++ map snd ms) ms) as_pruned
~(h : hs) <- get_holes
ty <- goal
case as' of
[] -> do hds <- mapM showHd as
lift $ tfail $ NoValidAlts hds
[x] -> elab' ina fc x
-- If there's options, try now, and if that fails, postpone
-- to later.
_ -> handleError isAmbiguous
(do hds <- mapM showHd as'
tryAll (zip (map (elab' ina fc) as')
hds))
(do movelast h
delayElab 5 $ do
hs <- get_holes
when (h `elem` hs) $ do
focus h
as'' <- doPrune as'
case as'' of
[x] -> elab' ina fc x
_ -> do hds <- mapM showHd as''
tryAll' False (zip (map (elab' ina fc) as'')
hds))
where showHd (PApp _ (PRef _ _ (UN l)) [_, _, arg])
| l == txt "Delay" = showHd (getTm arg)
showHd (PApp _ (PRef _ _ n) _) = return n
showHd (PRef _ _ n) = return n
showHd (PApp _ h _) = showHd h
showHd (PHidden h) = showHd h
showHd x = getNameFrom (sMN 0 "_") -- We probably should do something better than this here
doPrune as =
do compute -- to get 'Delayed' if it's there
ty <- goal
ctxt <- get_context
env <- get_env
let ty' = unDelay ty
let (tc, _) = unApply ty'
return $ pruneByType eimpossible env tc ty' ist as
unDelay t | (P _ (UN l) _, [_, arg]) <- unApply t,
l == txt "Delayed" = unDelay arg
| otherwise = t
isAmbiguous (CantResolveAlts _) = delayok
isAmbiguous (Elaborating _ _ _ e) = isAmbiguous e
isAmbiguous (ElaboratingArg _ _ _ e) = isAmbiguous e
isAmbiguous (At _ e) = isAmbiguous e
isAmbiguous _ = False
elab' ina fc (PAlternative ms FirstSuccess as_in)
= do -- finish the mkUniqueNames job
uns <- get_usedns
let as = map (mkUniqueNames (uns ++ map snd ms) ms) as_in
trySeq as
where -- if none work, take the error from the first
trySeq (x : xs) = let e1 = elab' ina fc x in
try' e1 (trySeq' e1 xs) True
trySeq [] = fail "Nothing to try in sequence"
trySeq' deferr [] = do deferr; unifyProblems
trySeq' deferr (x : xs)
= try' (tryCatch (do elab' ina fc x
solveAutos ist fn False
unifyProblems)
(\_ -> trySeq' deferr []))
(trySeq' deferr xs) True
elab' ina fc (PAlternative ms TryImplicit (orig : alts)) = do
env <- get_env
compute
ty <- goal
let doelab = elab' ina fc orig
tryCatch doelab
(\err ->
if recoverableErr err
then -- trace ("NEED IMPLICIT! " ++ show orig ++ "\n" ++
-- show alts ++ "\n" ++
-- showQuick err) $
-- Prune the coercions so that only the ones
-- with the right type to fix the error will be tried!
case pruneAlts err alts env of
[] -> lift $ tfail err
alts' -> do
try' (elab' ina fc (PAlternative ms (ExactlyOne False) alts'))
(lift $ tfail err) -- take error from original if all fail
True
else lift $ tfail err)
where
recoverableErr (CantUnify _ _ _ _ _ _) = True
recoverableErr (TooManyArguments _) = False
recoverableErr (CantSolveGoal _ _) = False
recoverableErr (CantResolveAlts _) = False
recoverableErr (NoValidAlts _) = True
recoverableErr (ProofSearchFail (Msg _)) = True
recoverableErr (ProofSearchFail _) = False
recoverableErr (ElaboratingArg _ _ _ e) = recoverableErr e
recoverableErr (At _ e) = recoverableErr e
recoverableErr (ElabScriptDebug _ _ _) = False
recoverableErr _ = True
pruneAlts (CantUnify _ (inc, _) (outc, _) _ _ _) alts env
= case unApply (normalise (tt_ctxt ist) env inc) of
(P (TCon _ _) n _, _) -> filter (hasArg n env) alts
(Constant _, _) -> alts
_ -> filter isLend alts -- special case hack for 'Borrowed'
pruneAlts (ElaboratingArg _ _ _ e) alts env = pruneAlts e alts env
pruneAlts (At _ e) alts env = pruneAlts e alts env
pruneAlts (NoValidAlts as) alts env = alts
pruneAlts err alts _ = filter isLend alts
hasArg n env ap | isLend ap = True -- special case hack for 'Borrowed'
hasArg n env (PApp _ (PRef _ _ a) _)
= case lookupTyExact a (tt_ctxt ist) of
Just ty -> let args = map snd (getArgTys (normalise (tt_ctxt ist) env ty)) in
any (fnIs n) args
Nothing -> False
hasArg n env (PAlternative _ _ as) = any (hasArg n env) as
hasArg n _ tm = False
isLend (PApp _ (PRef _ _ l) _) = l == sNS (sUN "lend") ["Ownership"]
isLend _ = False
fnIs n ty = case unApply ty of
(P _ n' _, _) -> n == n'
_ -> False
elab' ina _ (PPatvar fc n) | bindfree
= do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
-- elab' (_, _, inty) (PRef fc f)
-- | isTConName f (tt_ctxt ist) && pattern && not reflection && not inty
-- = lift $ tfail (Msg "Typecase is not allowed")
elab' ec fc' tm@(PRef fc hls n)
| pattern && not reflection && not (e_qq ec) && not (e_intype ec)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ec) && e_nomatching ec
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| (pattern || intransform || (bindfree && bindable n)) && not (inparamBlock n) && not (e_qq ec)
= do ty <- goal
testImplicitWarning fc n ty
let ina = e_inarg ec
ctxt <- get_context
env <- get_env
-- If the name is defined, globally or locally, elaborate it
-- as a reference, otherwise it might end up as a pattern var.
let defined = case lookupTy n ctxt of
[] -> case lookupTyEnv n env of
Just _ -> True
_ -> False
_ -> True
-- this is to stop us resolving interfaces recursively
if (tcname n && ina && not intransform)
then erun fc $
do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False)
else if defined -- finally, ordinary PRef elaboration
then elabRef ec fc' fc hls n tm
else try (do apply (Var n) []
annot <- findHighlight n
solve
highlightSource fc annot)
(do patvar n
update_term liftPats
highlightSource fc (AnnBoundName n False))
where inparamBlock n = case lookupCtxtName n (inblock info) of
[] -> False
_ -> True
bindable (NS _ _) = False
bindable (MN _ _) = True
bindable n = implicitable n && autoimpls
elab' ina _ f@(PInferRef fc hls n) = elab' ina (Just fc) (PApp NoFC f [])
elab' ina fc' tm@(PRef fc hls n)
| pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName n (tt_ctxt ist)
= lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = elabRef ina fc' fc hls n tm
elab' ina _ (PLam _ _ _ _ PImpossible) = lift . tfail . Msg $ "Only pattern-matching lambdas can be impossible"
elab' ina _ (PLam fc n nfc Placeholder sc)
= do -- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
attack; intro (Just n);
addPSname n -- okay for proof search
-- trace ("------ intro " ++ show n ++ " ---- \n" ++ show ptm)
elabE (ina { e_inarg = True } ) (Just fc) sc; solve
highlightSource nfc (AnnBoundName n False)
elab' ec _ (PLam fc n nfc ty sc)
= do tyn <- getNameFrom (sMN 0 "lamty")
-- if n is a type constructor name, this makes no sense...
ctxt <- get_context
when (isTConName n ctxt) $
lift $ tfail (Msg $ "Can't use type constructor " ++ show n ++ " here")
checkPiGoal n
claim tyn RType
explicit tyn
attack
ptm <- get_term
hs <- get_holes
introTy (Var tyn) (Just n)
addPSname n -- okay for proof search
focus tyn
elabE (ec { e_inarg = True, e_intype = True }) (Just fc) ty
elabE (ec { e_inarg = True }) (Just fc) sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc Placeholder sc)
= do attack;
case pcount p of
RigW -> return ()
_ -> unless (LinearTypes `elem` idris_language_extensions ist
|| e_qq ina) $
lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a count")
arg n (pcount p) (is_scoped p) (sMN 0 "phTy")
addAutoBind p n
addPSname n -- okay for proof search
elabE (ina { e_inarg = True, e_intype = True }) fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina fc (PPi p n nfc ty sc)
= do attack; tyn <- getNameFrom (sMN 0 "piTy")
claim tyn RType
n' <- case n of
MN _ _ -> unique_hole n
_ -> return n
case pcount p of
RigW -> return ()
_ -> unless (LinearTypes `elem` idris_language_extensions ist
|| e_qq ina) $
lift $ tfail $ At nfc (Msg "You must turn on the LinearTypes extension to use a linear argument")
forall n' (pcount p) (is_scoped p) (Var tyn)
addAutoBind p n'
addPSname n' -- okay for proof search
focus tyn
let ec' = ina { e_inarg = True, e_intype = True }
elabE ec' fc ty
elabE ec' fc sc
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ tm@(PLet fc rig n nfc ty val sc)
= do attack
ivs <- get_implementations
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
explicit valn
letbind n rig (Var tyn) (Var valn)
addPSname n
case ty of
Placeholder -> return ()
_ -> do focus tyn
explicit tyn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) ty
focus valn
elabE (ina { e_inarg = True, e_intype = True })
(Just fc) val
ivs' <- get_implementations
env <- get_env
elabE (ina { e_inarg = True }) (Just fc) sc
when (not (pattern || intransform)) $
mapM_ (\n -> do focus n
g <- goal
hs <- get_holes
if all (\n -> n == tyn || not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC True False 10 g fn elabRec ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
-- HACK: If the name leaks into its type, it may leak out of
-- scope outside, so substitute in the outer scope.
expandLet n (case lookupBinder n env of
Just (Let rig t v) -> v
other -> error ("Value not a let binding: " ++ show other))
solve
highlightSource nfc (AnnBoundName n False)
elab' ina _ (PGoal fc r n sc) = do
rty <- goal
attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letbind n RigW (Var tyn) (Var valn)
focus valn
elabE (ina { e_inarg = True, e_intype = True }) (Just fc) (PApp fc r [pexp (delab ist rty)])
env <- get_env
computeLet n
elabE (ina { e_inarg = True }) (Just fc) sc
solve
-- elab' ina fc (PLet n Placeholder
-- (PApp fc r [pexp (delab ist rty)]) sc)
elab' ina _ tm@(PApp fc (PInferRef _ _ f) args) = do
rty <- goal
ds <- get_deferred
ctxt <- get_context
-- make a function type a -> b -> c -> ... -> rty for the
-- new function name
env <- get_env
argTys <- claimArgTys env args
fn <- getNameFrom (sMN 0 "inf_fn")
let fty = fnTy argTys rty
-- trace (show (ptm, map fst argTys)) $ focus fn
-- build and defer the function application
attack; deferType (mkN f) fty (map fst argTys); solve
-- elaborate the arguments, to unify their types. They all have to
-- be explicit.
mapM_ elabIArg (zip argTys args)
where claimArgTys env [] = return []
claimArgTys env (arg : xs) | Just n <- localVar env (getTm arg)
= do nty <- get_type (Var n)
ans <- claimArgTys env xs
return ((n, (False, forget nty)) : ans)
claimArgTys env (_ : xs)
= do an <- getNameFrom (sMN 0 "inf_argTy")
aval <- getNameFrom (sMN 0 "inf_arg")
claim an RType
claim aval (Var an)
ans <- claimArgTys env xs
return ((aval, (True, (Var an))) : ans)
fnTy [] ret = forget ret
fnTy ((x, (_, xt)) : xs) ret = RBind x (Pi RigW Nothing xt RType) (fnTy xs ret)
localVar env (PRef _ _ x)
= case lookupBinder x env of
Just _ -> Just x
_ -> Nothing
localVar env _ = Nothing
elabIArg ((n, (True, ty)), def) =
do focus n; elabE ina (Just fc) (getTm def)
elabIArg _ = return () -- already done, just a name
mkN n@(NS _ _) = n
mkN n@(SN _) = n
mkN n = case namespace info of
xs@(_:_) -> sNS n xs
_ -> n
elab' ina _ (PMatchApp fc fn)
= do (fn', imps) <- case lookupCtxtName fn (idris_implicits ist) of
[(n, args)] -> return (n, map (const True) args)
_ -> lift $ tfail (NoSuchVariable fn)
ns <- match_apply (Var fn') (map (\x -> (x,0)) imps)
solve
-- if f is local, just do a simple_app
-- FIXME: Anyone feel like refactoring this mess? - EB
elab' ina topfc tm@(PApp fc (PRef ffc hls f) args_in)
| pattern && not reflection && not (e_qq ina) && e_nomatching ina
= lift $ tfail $ Msg ("Attempting concrete match on polymorphic argument: " ++ show tm)
| otherwise = implicitApp $
do env <- get_env
ty <- goal
fty <- get_type (Var f)
ctxt <- get_context
let dataCon = isDConName f ctxt
annot <- findHighlight f
knowns_m <- mapM getKnownImplicit args_in
let knowns = mapMaybe id knowns_m
args <- insertScopedImps fc f knowns (normalise ctxt env fty) args_in
let unmatchableArgs = if pattern
then getUnmatchable (tt_ctxt ist) f
else []
-- trace ("BEFORE " ++ show f ++ ": " ++ show ty) $
when (pattern && not reflection && not (e_qq ina) && not (e_intype ina)
&& isTConName f (tt_ctxt ist)) $
lift $ tfail $ Msg ("No explicit types on left hand side: " ++ show tm)
-- trace (show (f, args_in, args)) $
if (f `elem` map fstEnv env && length args == 1 && length args_in == 1)
then -- simple app, as below
do simple_app False
(elabE (ina { e_isfn = True }) (Just fc) (PRef ffc hls f))
(elabE (ina { e_inarg = True,
e_guarded = dataCon }) (Just fc) (getTm (head args)))
(show tm)
solve
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
return []
else
do ivs <- get_implementations
ps <- get_probs
-- HACK: we shouldn't resolve interfaces if we're defining an implementation
-- function or default definition.
let isinf = f == inferCon || tcname f
-- if f is an interface, we need to know its arguments so that
-- we can unify with them
case lookupCtxt f (idris_interfaces ist) of
[] -> return ()
_ -> do mapM_ setInjective (map getTm args)
-- maybe more things are solvable now
unifyProblems
-- trace ("args is " ++ show args) $ return ()
ns <- apply (Var f) (map isph args)
-- trace ("ns is " ++ show ns) $ return ()
-- mark any interface arguments as injective
-- when (not pattern) $
mapM_ checkIfInjective (map snd ns)
unifyProblems -- try again with the new information,
-- to help with disambiguation
ulog <- getUnifyLog
annot <- findHighlight f
mapM (uncurry highlightSource) $
(ffc, annot) : map (\f -> (f, annot)) hls
elabArgs ist (ina { e_inarg = e_inarg ina || not isinf,
e_guarded = dataCon })
[] fc False f
(zip ns (unmatchableArgs ++ repeat False))
(f == sUN "Force")
(map (\x -> getTm x) args) -- TODO: remove this False arg
imp <- if (e_isfn ina) then
do guess <- get_guess
env <- get_env
case safeForgetEnv (map fstEnv env) guess of
Nothing ->
return []
Just rguess -> do
gty <- get_type rguess
let ty_n = normalise ctxt env gty
return $ getReqImps ty_n
else return []
-- Now we find out how many implicits we needed at the
-- end of the application by looking at the goal again
-- - Have another go, but this time add the
-- implicits (can't think of a better way than this...)
case imp of
rs@(_:_) | not pattern -> return rs -- quit, try again
_ -> do solve
hs <- get_holes
ivs' <- get_implementations
-- Attempt to resolve any interfaces which have 'complete' types,
-- i.e. no holes in them
when (not pattern || (e_inarg ina && not tcgen)) $
mapM_ (\n -> do focus n
g <- goal
env <- get_env
hs <- get_holes
if all (\n -> not (n `elem` hs)) (freeNames g)
then handleError (tcRecoverable emode)
(resolveTC False False 10 g fn elabRec ist)
(movelast n)
else movelast n)
(ivs' \\ ivs)
return []
where
-- Run the elaborator, which returns how many implicit
-- args were needed, then run it again with those args. We need
-- this because we have to elaborate the whole application to
-- find out whether any computations have caused more implicits
-- to be needed.
implicitApp :: ElabD [ImplicitInfo] -> ElabD ()
implicitApp elab
| pattern || intransform = do elab; return ()
| otherwise
= do s <- get
imps <- elab
case imps of
[] -> return ()
es -> do put s
elab' ina topfc (PAppImpl tm es)
getKnownImplicit imp
| UnknownImp `elem` argopts imp
= return Nothing -- lift $ tfail $ UnknownImplicit (pname imp) f
| otherwise = return (Just (pname imp))
getReqImps (Bind x (Pi _ (Just i) ty _) sc)
= i : getReqImps sc
getReqImps _ = []
checkIfInjective n = do
env <- get_env
case lookupBinder n env of
Nothing -> return ()
Just b ->
case unApply (normalise (tt_ctxt ist) env (binderTy b)) of
(P _ c _, args) ->
case lookupCtxtExact c (idris_interfaces ist) of
Nothing -> return ()
Just ci -> -- interface, set as injective
do mapM_ setinjArg (getDets 0 (interface_determiners ci) args)
-- maybe we can solve more things now...
ulog <- getUnifyLog
probs <- get_probs
inj <- get_inj
traceWhen ulog ("Injective now " ++ show args ++ "\nAll: " ++ show inj
++ "\nProblems: " ++ qshow probs) $
unifyProblems
probs <- get_probs
traceWhen ulog (qshow probs) $ return ()
_ -> return ()
setinjArg (P _ n _) = setinj n
setinjArg _ = return ()
getDets i ds [] = []
getDets i ds (a : as) | i `elem` ds = a : getDets (i + 1) ds as
| otherwise = getDets (i + 1) ds as
setInjective (PRef _ _ n) = setinj n
setInjective (PApp _ (PRef _ _ n) _) = setinj n
setInjective _ = return ()
elab' ina _ tm@(PApp fc f [arg]) =
erun fc $
do simple_app (not $ headRef f)
(elabE (ina { e_isfn = True }) (Just fc) f)
(elabE (ina { e_inarg = True }) (Just fc) (getTm arg))
(show tm)
solve
where headRef (PRef _ _ _) = True
headRef (PApp _ f _) = headRef f
headRef (PAlternative _ _ as) = all headRef as
headRef _ = False
elab' ina fc (PAppImpl f es) = do appImpl (reverse es) -- not that we look...
solve
where appImpl [] = elab' (ina { e_isfn = False }) fc f -- e_isfn not set, so no recursive expansion of implicits
appImpl (e : es) = simple_app False
(appImpl es)
(elab' ina fc Placeholder)
(show f)
elab' ina fc Placeholder
= do ~(h : hs) <- get_holes
movelast h
elab' ina fc (PMetavar nfc n) =
do ptm <- get_term
-- When building the metavar application, leave out the unique
-- names which have been used elsewhere in the term, since we
-- won't be able to use them in the resulting application.
env <- get_env
let unique_used = getUniqueUsed (tt_ctxt ist) ptm
let lin_used = getLinearUsed (tt_ctxt ist) ptm
let n' = metavarName (namespace info) n
attack
psns <- getPSnames
n' <- defer unique_used lin_used n'
solve
highlightSource nfc (AnnName n' (Just MetavarOutput) Nothing Nothing)
elab' ina fc (PProof ts) = do compute; mapM_ (runTac True ist (elabFC info) fn) ts
elab' ina fc (PTactics ts)
| not pattern = do mapM_ (runTac False ist fc fn) ts
| otherwise = elab' ina fc Placeholder
elab' ina fc (PElabError e) = lift $ tfail e
elab' ina mfc (PRewrite fc substfn rule sc newg)
= elabRewrite (elab' ina mfc) ist fc substfn rule sc newg
-- A common error case if trying to typecheck an autogenerated case block
elab' ina _ c@(PCase fc Placeholder opts)
= lift $ tfail (Msg "No expression for the case to inspect.\nYou need to replace the _ with an expression.")
elab' ina _ c@(PCase fc scr opts)
= do attack
tyn <- getNameFrom (sMN 0 "scty")
claim tyn RType
valn <- getNameFrom (sMN 0 "scval")
scvn <- getNameFrom (sMN 0 "scvar")
claim valn (Var tyn)
env <- get_env
let scrnames = allNamesIn scr
letbind scvn (letrig scrnames env) (Var tyn) (Var valn)
-- Start filling in the scrutinee type, if we can work one
-- out from the case options
let scrTy = getScrType (map fst opts)
case scrTy of
Nothing -> return ()
Just ty -> do focus tyn
elabE ina (Just fc) ty
focus valn
elabE (ina { e_inarg = True }) (Just fc) scr
-- Solve any remaining implicits - we need to solve as many
-- as possible before making the 'case' type
unifyProblems
matchProblems True
args <- get_env
envU <- mapM (getKind args) args
-- Drop the unique arguments used in the term already
-- and in the scrutinee (since it's
-- not valid to use them again anyway)
--
-- Also drop unique arguments which don't appear explicitly
-- in either case branch so they don't count as used
-- unnecessarily (can only do this for unique things, since we
-- assume they don't appear implicitly in types)
ptm <- get_term
let inOpts = (filter (/= scvn) (map fstEnv args)) \\ (concatMap (\x -> allNamesIn (snd x)) opts)
let argsDropped = filter (\t -> isUnique envU t || isNotLift args t)
(nub $ scrnames ++ inApp ptm ++
inOpts)
let lin_used = getLinearUsed (tt_ctxt ist) ptm
let args' = filter (\(n, _, _) -> n `notElem` argsDropped) args
-- trace (show lin_used ++ "\n" ++ show args ++ "\n" ++ show ptm) attack
attack
cname' <- defer argsDropped lin_used (mkN (mkCaseName fc fn))
solve
-- if the scrutinee is one of the 'args' in env, we should
-- inspect it directly, rather than adding it as a new argument
let newdef = PClauses fc [] cname'
(caseBlock fc cname' scr
(map (isScr scr) (reverse args')) opts)
-- elaborate case
updateAux (\e -> e { case_decls = (cname', newdef) : case_decls e } )
-- if we haven't got the type yet, hopefully we'll get it later!
movelast tyn
solve
where mkCaseName fc (NS n ns) = NS (mkCaseName fc n) ns
mkCaseName fc n = SN (CaseN (FC' fc) n)
-- mkCaseName (UN x) = UN (x ++ "_case")
-- mkCaseName (MN i x) = MN i (x ++ "_case")
mkN n@(NS _ _) = n
mkN n = case namespace info of
xs@(_:_) -> sNS n xs
_ -> n
-- If any variables in the scrutinee are in the environment with
-- multiplicity other than RigW, let bind the scrutinee variable
-- with the smallest multiplicity
letrig ns [] = RigW
letrig ns env = letrig' Rig1 ns env
letrig' def ns [] = def
letrig' def ns ((n, r, _) : env)
| n `elem` ns = letrig' (rigMult def r) ns env
| otherwise = letrig' def ns env
getScrType [] = Nothing
getScrType (f : os) = maybe (getScrType os) Just (getAppType f)
getAppType (PRef _ _ n) =
case lookupTyName n (tt_ctxt ist) of
[(n', ty)] | isDConName n' (tt_ctxt ist) ->
case unApply (getRetTy ty) of
(P _ tyn _, args) ->
Just (PApp fc (PRef fc [] tyn)
(map pexp (map (const Placeholder) args)))
_ -> Nothing
_ -> Nothing -- ambiguity is no help to us!
getAppType (PApp _ t as) = getAppType t
getAppType _ = Nothing
inApp (P _ n _) = [n]
inApp (App _ f a) = inApp f ++ inApp a
inApp (Bind n (Let _ _ v) sc) = inApp v ++ inApp sc
inApp (Bind n (Guess _ v) sc) = inApp v ++ inApp sc
inApp (Bind n b sc) = inApp sc
inApp _ = []
isUnique envk n = case lookup n envk of
Just u -> u
_ -> False
getKind env (n, _, _)
= case lookupBinder n env of
Nothing -> return (n, False) -- can't happen, actually...
Just b ->
do ty <- get_type (forget (binderTy b))
case ty of
UType UniqueType -> return (n, True)
UType AllTypes -> return (n, True)
_ -> return (n, False)
isNotLift env n
= case lookupBinder n env of
Just ty ->
case unApply (binderTy ty) of
(P _ n _, _) -> n `elem` noCaseLift info
_ -> False
_ -> False
elab' ina fc (PUnifyLog t) = do unifyLog True
elab' ina fc t
unifyLog False
elab' ina fc (PQuasiquote t goalt)
= do -- First extract the unquoted subterms, replacing them with fresh
-- names in the quasiquoted term. Claim their reflections to be
-- an inferred type (to support polytypic quasiquotes).
finalTy <- goal
(t, unq) <- extractUnquotes 0 t
let unquoteNames = map fst unq
mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames
-- Save the old state - we need a fresh proof state to avoid
-- capturing lexically available variables in the quoted term.
ctxt <- get_context
datatypes <- get_datatypes
g_nextname <- get_global_nextname
saveState
updatePS (const .
newProof (sMN 0 "q") (constraintNS info) ctxt datatypes g_nextname $
P Ref (reflm "TT") Erased)
-- Re-add the unquotes, letting Idris infer the (fictional)
-- types. Here, they represent the real type rather than the type
-- of their reflection.
mapM_ (\n -> do ty <- getNameFrom (sMN 0 "unqTy")
claim ty RType
movelast ty
claim n (Var ty)
movelast n)
unquoteNames
-- Determine whether there's an explicit goal type, and act accordingly
-- Establish holes for the type and value of the term to be
-- quasiquoted
qTy <- getNameFrom (sMN 0 "qquoteTy")
claim qTy RType
movelast qTy
qTm <- getNameFrom (sMN 0 "qquoteTm")
claim qTm (Var qTy)
-- Let-bind the result of elaborating the contained term, so that
-- the hole doesn't disappear
nTm <- getNameFrom (sMN 0 "quotedTerm")
letbind nTm RigW (Var qTy) (Var qTm)
-- Fill out the goal type, if relevant
case goalt of
Nothing -> return ()
Just gTy -> do focus qTy
elabE (ina { e_qq = True }) fc gTy
-- Elaborate the quasiquoted term into the hole
focus qTm
elabE (ina { e_qq = True }) fc t
end_unify
-- We now have an elaborated term. Reflect it and solve the
-- original goal in the original proof state, preserving highlighting
env <- get_env
EState _ _ _ hs _ _ <- getAux
loadState
updateAux (\aux -> aux { highlighting = hs })
let quoted = fmap (explicitNames . binderVal) $ lookupBinder nTm env
isRaw = case unApply (normaliseAll ctxt env finalTy) of
(P _ n _, []) | n == reflm "Raw" -> True
_ -> False
case quoted of
Just q -> do ctxt <- get_context
(q', _, _) <- lift $ recheck (constraintNS info) ctxt [(uq, RigW, Lam RigW Erased) | uq <- unquoteNames] (forget q) q
if pattern
then if isRaw
then reflectRawQuotePattern unquoteNames (forget q')
else reflectTTQuotePattern unquoteNames q'
else do if isRaw
then -- we forget q' instead of using q to ensure rechecking
fill $ reflectRawQuote unquoteNames (forget q')
else fill $ reflectTTQuote unquoteNames q'
solve
Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote"
-- Finally fill in the terms or patterns from the unquotes. This
-- happens last so that their holes still exist while elaborating
-- the main quotation.
mapM_ elabUnquote unq
where elabUnquote (n, tm)
= do focus n
elabE (ina { e_qq = False }) fc tm
elab' ina fc (PUnquote t) = fail "Found unquote outside of quasiquote"
elab' ina fc (PQuoteName n False nfc) =
do fill $ reflectName n
solve
elab' ina fc (PQuoteName n True nfc) =
do ctxt <- get_context
env <- get_env
case lookupBinder n env of
Just _ -> do fill $ reflectName n
solve
highlightSource nfc (AnnBoundName n False)
Nothing ->
case lookupNameDef n ctxt of
[(n', _)] -> do fill $ reflectName n'
solve
highlightSource nfc (AnnName n' Nothing Nothing Nothing)
[] -> lift . tfail . NoSuchVariable $ n
more -> lift . tfail . CantResolveAlts $ map fst more
elab' ina fc (PAs _ n t) = lift . tfail . Msg $ "@-pattern not allowed here"
elab' ina fc (PHidden t)
| reflection = elab' ina fc t
| otherwise
= do ~(h : hs) <- get_holes
-- Dotting a hole means that either the hole or any outer
-- hole (a hole outside any occurrence of it)
-- must be solvable by unification as well as being filled
-- in directly.
-- Delay dotted things to the end, then when we elaborate them
-- we can check the result against what was inferred
movelast h
~(h' : hs) <- get_holes
-- If we're at the end anyway, do it now
if h == h' then elabHidden h
else delayElab 10 $ elabHidden h
where
elabHidden h = do hs <- get_holes
when (h `elem` hs) $ do
focus h
dotterm
elab' ina fc t
elab' ina fc (PRunElab fc' tm ns) =
do unless (ElabReflection `elem` idris_language_extensions ist) $
lift $ tfail $ At fc' (Msg "You must turn on the ElabReflection extension to use %runElab")
attack
let elabName = sNS (sUN "Elab") ["Elab", "Reflection", "Language"]
n <- getNameFrom (sMN 0 "tacticScript")
let scriptTy = RApp (Var elabName) (Var unitTy)
claim n scriptTy
focus n
elabUnit <- goal
attack -- to get an extra hole
elab' ina (Just fc') tm
script <- get_guess
fullyElaborated script
solve -- eliminate the hole. Because there are no references, the script is only in the binding
ctxt <- get_context
env <- get_env
(scriptTm, scriptTy) <- lift $ check ctxt [] (forget script)
lift $ converts ctxt env elabUnit scriptTy
env <- get_env
runElabAction info ist (maybe fc' id fc) env script ns
solve
elab' ina fc (PConstSugar constFC tm) =
-- Here we elaborate the contained term, then calculate
-- highlighting for constFC. The highlighting is the
-- highlighting for the outermost constructor of the result of
-- evaluating the elaborated term, if one exists (it always
-- should, but better to fail gracefully for something silly
-- like highlighting info). This is how implicit applications of
-- fromInteger get highlighted.
do saveState -- so we don't pollute the elaborated term
n <- getNameFrom (sMN 0 "cstI")
n' <- getNameFrom (sMN 0 "cstIhole")
g <- forget <$> goal
claim n' g
movelast n'
-- In order to intercept the elaborated value, we need to
-- let-bind it.
attack
letbind n RigW g (Var n')
focus n'
elab' ina fc tm
env <- get_env
ctxt <- get_context
let v = fmap (normaliseAll ctxt env . finalise . binderVal)
(lookupBinder n env)
loadState -- we have the highlighting - re-elaborate the value
elab' ina fc tm
case v of
Just val -> highlightConst constFC val
Nothing -> return ()
where highlightConst fc (P _ n _) =
highlightSource fc (AnnName n Nothing Nothing Nothing)
highlightConst fc (App _ f _) =
highlightConst fc f
highlightConst fc (Constant c) =
highlightSource fc (AnnConst c)
highlightConst _ _ = return ()
elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x
-- delay elaboration of 't', with priority 'pri' until after everything
-- else is done.
-- The delayed things with lower numbered priority will be elaborated
-- first. (In practice, this means delayed alternatives, then PHidden
-- things.)
delayElab pri t
= updateAux (\e -> e { delayed_elab = delayed_elab e ++ [(pri, t)] })
-- If the variable in the environment is the scrutinee of the case,
-- and has multiplicity W, keep it available
isScr :: PTerm -> (Name, RigCount, Binder Term) -> (Name, (Bool, Binder Term))
isScr (PRef _ _ n) (n', RigW, b) = (n', (n == n', b))
isScr _ (n', _, b) = (n', (False, b))
caseBlock :: FC -> Name
-> PTerm -- original scrutinee
-> [(Name, (Bool, Binder Term))] -> [(PTerm, PTerm)] -> [PClause]
caseBlock fc n scr env opts
= let args' = findScr env
args = map mkarg (map getNmScr args') in
map (mkClause args) opts
where -- Find the variable we want as the scrutinee and mark it as
-- 'True'. If the scrutinee is available in the environment,
-- match on that otherwise match on the new argument we're adding.
findScr ((n, (True, t)) : xs)
= (n, (True, t)) : scrName n xs
findScr [(n, (_, t))] = [(n, (True, t))]
findScr (x : xs) = x : findScr xs
-- [] can't happen since scrutinee is in the environment!
findScr [] = error "The impossible happened - the scrutinee was not in the environment"
-- To make sure top level pattern name remains in scope, put
-- it at the end of the environment
scrName n [] = []
scrName n [(_, t)] = [(n, t)]
scrName n (x : xs) = x : scrName n xs
getNmScr (n, (s, _)) = (n, s)
mkarg (n, s) = (PRef fc [] n, s)
-- may be shadowed names in the new pattern - so replace the
-- old ones with an _
-- Also, names which don't appear on the rhs should not be
-- fixed on the lhs, or this restricts the kind of matching
-- we can do to non-dependent types.
mkClause args (l, r)
= let args' = map (shadowed (allNamesIn l)) args
args'' = map (implicitable (allNamesIn r ++
keepscrName scr)) args'
lhs = PApp (getFC fc l) (PRef NoFC [] n)
(map (mkLHSarg l) args'') in
PClause (getFC fc l) n lhs [] r []
-- Keep scrutinee available if it's just a name (this makes
-- the names in scope look better when looking at a hole on
-- the rhs of a case)
keepscrName (PRef _ _ n) = [n]
keepscrName _ = []
mkLHSarg l (tm, True) = pexp l
mkLHSarg l (tm, False) = pexp tm
shadowed new (PRef _ _ n, s) | n `elem` new = (Placeholder, s)
shadowed new t = t
implicitable rhs (PRef _ _ n, s) | n `notElem` rhs = (Placeholder, s)
implicitable rhs t = t
getFC d (PApp fc _ _) = fc
getFC d (PRef fc _ _) = fc
getFC d (PAlternative _ _ (x:_)) = getFC d x
getFC d x = d
-- Fail if a term is not yet fully elaborated (e.g. if it contains
-- case block functions that don't yet exist)
fullyElaborated :: Term -> ElabD ()
fullyElaborated (P _ n _) =
do estate <- getAux
case lookup n (case_decls estate) of
Nothing -> return ()
Just _ -> lift . tfail $ ElabScriptStaging n
fullyElaborated (Bind n b body) = fullyElaborated body >> for_ b fullyElaborated
fullyElaborated (App _ l r) = fullyElaborated l >> fullyElaborated r
fullyElaborated (Proj t _) = fullyElaborated t
fullyElaborated _ = return ()
-- If the goal type is a "Lazy", then try elaborating via 'Delay'
-- first. We need to do this brute force approach, rather than anything
-- more precise, since there may be various other ambiguities to resolve
-- first.
insertLazy :: ElabCtxt -> PTerm -> ElabD PTerm
insertLazy ina t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Delay" = return t
insertLazy ina t@(PApp _ (PRef _ _ (UN l)) _) | l == txt "Force" = return t
insertLazy ina (PCoerced t) = return t
-- Don't add a delay to top level pattern variables, since they
-- can be forced on the rhs if needed
insertLazy ina t@(PPatvar _ _) | pattern && not (e_guarded ina) = return t
insertLazy ina t =
do ty <- goal
env <- get_env
let (tyh, _) = unApply (normalise (tt_ctxt ist) env ty)
let tries = [mkDelay env t, t]
case tyh of
P _ (UN l) _ | l == txt "Delayed"
-> return (PAlternative [] FirstSuccess tries)
_ -> return t
where
mkDelay env (PAlternative ms b xs) = PAlternative ms b (map (mkDelay env) xs)
mkDelay env t
= let fc = fileFC "Delay" in
addImplBound ist (map fstEnv env) (PApp fc (PRef fc [] (sUN "Delay"))
[pexp t])
-- Don't put implicit coercions around applications which are marked
-- as '%noImplicit', or around case blocks, otherwise we get exponential
-- blowup especially where there are errors deep in large expressions.
notImplicitable (PApp _ f _) = notImplicitable f
-- TMP HACK no coercing on bind (make this configurable)
notImplicitable (PRef _ _ n)
| [opts] <- lookupCtxt n (idris_flags ist)
= NoImplicit `elem` opts
notImplicitable (PAlternative _ _ as) = any notImplicitable as
-- case is tricky enough without implicit coercions! If they are needed,
-- they can go in the branches separately.
notImplicitable (PCase _ _ _) = True
notImplicitable _ = False
-- Elaboration works more smoothly if we expand function applications
-- to their full arity and elaborate it all at once (better error messages
-- in particular)
expandToArity tm@(PApp fc f a) = do
env <- get_env
case fullApp tm of
-- if f is global, leave it alone because we've already
-- expanded it to the right arity
PApp fc ftm@(PRef _ _ f) args | Just aty <- lookupBinder f env ->
do let a = length (getArgTys (normalise (tt_ctxt ist) env (binderTy aty)))
return (mkPApp fc a ftm args)
_ -> return tm
expandToArity t = return t
fullApp (PApp _ (PApp fc f args) xs) = fullApp (PApp fc f (args ++ xs))
fullApp x = x
-- See if the name is listed as an implicit. If it is, return it, and
-- drop it from the rest of the list
findImplicit :: Name -> [PArg] -> (Maybe PArg, [PArg])
findImplicit n [] = (Nothing, [])
findImplicit n (i@(PImp _ _ _ n' _) : args)
| n == n' = (Just i, args)
findImplicit n (i@(PTacImplicit _ _ n' _ _) : args)
| n == n' = (Just i, args)
findImplicit n (x : xs) = let (arg, rest) = findImplicit n xs in
(arg, x : rest)
insertScopedImps :: FC -> Name -> [Name] -> Type -> [PArg] -> ElabD [PArg]
insertScopedImps fc f knowns ty xs =
do mapM_ (checkKnownImplicit (map fst (getArgTys ty) ++ knowns)) xs
doInsert ty xs
where
doInsert ty@(Bind n (Pi _ im@(Just i) _ _) sc) xs
| (Just arg, xs') <- findImplicit n xs,
not (toplevel_imp i)
= liftM (arg :) (doInsert sc xs')
| tcimplementation i && not (toplevel_imp i)
= liftM (pimp n (PResolveTC fc) True :) (doInsert sc xs)
| not (toplevel_imp i)
= liftM (pimp n Placeholder True :) (doInsert sc xs)
doInsert (Bind n (Pi _ _ _ _) sc) (x : xs)
= liftM (x :) (doInsert sc xs)
doInsert ty xs = return xs
-- Any implicit in the application needs to have the name of a
-- scoped implicit or a top level implicit, otherwise report an error
checkKnownImplicit ns imp@(PImp{})
| pname imp `elem` ns = return ()
| otherwise = lift $ tfail $ At fc $ UnknownImplicit (pname imp) f
checkKnownImplicit ns _ = return ()
insertImpLam ina t =
do ty <- goal
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
addLam ty' t
where
-- just one level at a time
addLam goal@(Bind n (Pi _ (Just _) _ _) sc) t =
do impn <- unique_hole n -- (sMN 0 "scoped_imp")
return (PLam emptyFC impn NoFC Placeholder t)
addLam _ t = return t
insertCoerce ina t@(PCase _ _ _) = return t
insertCoerce ina t | notImplicitable t = return t
insertCoerce ina t =
do ty <- goal
-- Check for possible coercions to get to the goal
-- and add them as 'alternatives'
env <- get_env
let ty' = normalise (tt_ctxt ist) env ty
let cs = getCoercionsTo ist ty'
let t' = case (t, cs) of
(PCoerced tm, _) -> tm
(_, []) -> t
(_, cs) -> PAlternative [] TryImplicit
(t : map (mkCoerce env t) cs)
return t'
where
mkCoerce env (PAlternative ms aty tms) n
= PAlternative ms aty (map (\t -> mkCoerce env t n) tms)
mkCoerce env t n = let fc = maybe (fileFC "Coercion") id (highestFC t) in
addImplBound ist (map fstEnv env)
(PApp fc (PRef fc [] n) [pexp (PCoerced t)])
elabRef :: ElabCtxt -> Maybe FC -> FC -> [FC] -> Name -> PTerm -> ElabD ()
elabRef ina fc' fc hls n tm =
do fty <- get_type (Var n) -- check for implicits
ctxt <- get_context
env <- get_env
a' <- insertScopedImps fc n [] (normalise ctxt env fty) []
if null a'
then erun fc $
do apply (Var n) []
hilite <- findHighlight n
solve
mapM_ (uncurry highlightSource) $
(fc, hilite) : map (\f -> (f, hilite)) hls
else elab' ina fc' (PApp fc tm [])
-- | Elaborate the arguments to a function
elabArgs :: IState -- ^ The current Idris state
-> ElabCtxt -- ^ (in an argument, guarded, in a type, in a qquote)
-> [Bool]
-> FC -- ^ Source location
-> Bool
-> Name -- ^ Name of the function being applied
-> [((Name, Name), Bool)] -- ^ (Argument Name, Hole Name, unmatchable)
-> Bool -- ^ under a 'force'
-> [PTerm] -- ^ argument
-> ElabD ()
elabArgs ist ina failed fc retry f [] force _ = return ()
elabArgs ist ina failed fc r f (((argName, holeName), unm):ns) force (t : args)
= do hs <- get_holes
if holeName `elem` hs then
do focus holeName
case t of
Placeholder -> do movelast holeName
elabArgs ist ina failed fc r f ns force args
_ -> elabArg t
else elabArgs ist ina failed fc r f ns force args
where elabArg t =
do -- solveAutos ist fn False
now_elaborating fc f argName
wrapErr f argName $ do
hs <- get_holes
tm <- get_term
-- No coercing under an explicit Force (or it can Force/Delay
-- recursively!)
let elab = if force then elab' else elabE
failed' <- -- trace (show (n, t, hs, tm)) $
-- traceWhen (not (null cs)) (show ty ++ "\n" ++ showImp True t) $
do focus holeName;
g <- goal
-- Can't pattern match on polymorphic goals
poly <- goal_polymorphic
ulog <- getUnifyLog
traceWhen ulog ("Elaborating argument " ++ show (argName, holeName, g)) $
elab (ina { e_nomatching = unm && poly }) (Just fc) t
return failed
done_elaborating_arg f argName
elabArgs ist ina failed fc r f ns force args
wrapErr f argName action =
do elabState <- get
while <- elaborating_app
let while' = map (\(x, y, z)-> (y, z)) while
(result, newState) <- case runStateT action elabState of
OK (res, newState) -> return (res, newState)
Error e -> do done_elaborating_arg f argName
lift (tfail (elaboratingArgErr while' e))
put newState
return result
elabArgs _ _ _ _ _ _ (((arg, hole), _) : _) _ [] =
fail $ "Can't elaborate these args: " ++ show arg ++ " " ++ show hole
addAutoBind :: Plicity -> Name -> ElabD ()
addAutoBind (Imp _ _ _ _ False _) n
= updateAux (\est -> est { auto_binds = n : auto_binds est })
addAutoBind _ _ = return ()
testImplicitWarning :: FC -> Name -> Type -> ElabD ()
testImplicitWarning fc n goal
| implicitable n && emode == ETyDecl
= do env <- get_env
est <- getAux
when (n `elem` auto_binds est) $
tryUnify env (lookupTyName n (tt_ctxt ist))
| otherwise = return ()
where
tryUnify env [] = return ()
tryUnify env ((nm, ty) : ts)
= do inj <- get_inj
hs <- get_holes
case unify (tt_ctxt ist) env (ty, Nothing) (goal, Nothing)
inj hs [] [] of
OK _ ->
updateAux (\est -> est { implicit_warnings =
(fc, nm) : implicit_warnings est })
_ -> tryUnify env ts
-- For every alternative, look at the function at the head. Automatically resolve
-- any nested alternatives where that function is also at the head
pruneAlt :: [PTerm] -> [PTerm]
pruneAlt xs = map prune xs
where
prune (PApp fc1 (PRef fc2 hls f) as)
= PApp fc1 (PRef fc2 hls f) (fmap (fmap (choose f)) as)
prune t = t
choose f (PAlternative ms a as)
= let as' = fmap (choose f) as
fs = filter (headIs f) as' in
case fs of
[a] -> a
_ -> PAlternative ms a as'
choose f (PApp fc f' as) = PApp fc (choose f f') (fmap (fmap (choose f)) as)
choose f t = t
headIs f (PApp _ (PRef _ _ f') _) = f == f'
headIs f (PApp _ f' _) = headIs f f'
headIs f _ = True -- keep if it's not an application
-- | Use the local elab context to work out the highlighting for a name
findHighlight :: Name -> ElabD OutputAnnotation
findHighlight n = do ctxt <- get_context
env <- get_env
case lookupBinder n env of
Just _ -> return $ AnnBoundName n False
Nothing -> case lookupTyExact n ctxt of
Just _ -> return $ AnnName n Nothing Nothing Nothing
Nothing -> lift . tfail . InternalMsg $
"Can't find name " ++ show n
-- Try again to solve auto implicits
solveAuto :: IState -> Name -> Bool -> (Name, [FailContext]) -> ElabD ()
solveAuto ist fn ambigok (n, failc)
= do hs <- get_holes
when (not (null hs)) $ do
env <- get_env
g <- goal
handleError cantsolve (when (n `elem` hs) $ do
focus n
isg <- is_guess -- if it's a guess, we're working on it recursively, so stop
when (not isg) $
proofSearch' ist True ambigok 100 True Nothing fn [] [])
(lift $ Error (addLoc failc
(CantSolveGoal g (map (\(n, _, b) -> (n, binderTy b)) env))))
return ()
where addLoc (FailContext fc f x : prev) err
= At fc (ElaboratingArg f x
(map (\(FailContext _ f' x') -> (f', x')) prev) err)
addLoc _ err = err
cantsolve (CantSolveGoal _ _) = True
cantsolve (InternalMsg _) = True
cantsolve (At _ e) = cantsolve e
cantsolve (Elaborating _ _ _ e) = cantsolve e
cantsolve (ElaboratingArg _ _ _ e) = cantsolve e
cantsolve _ = False
solveAutos :: IState -> Name -> Bool -> ElabD ()
solveAutos ist fn ambigok
= do autos <- get_autos
mapM_ (solveAuto ist fn ambigok) (map (\(n, (fc, _)) -> (n, fc)) autos)
-- Return true if the given error suggests an interface failure is
-- recoverable
tcRecoverable :: ElabMode -> Err -> Bool
tcRecoverable ERHS (CantResolve f g _) = f
tcRecoverable ETyDecl (CantResolve f g _) = f
tcRecoverable e (ElaboratingArg _ _ _ err) = tcRecoverable e err
tcRecoverable e (At _ err) = tcRecoverable e err
tcRecoverable _ _ = True
trivial' ist
= trivial (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
trivialHoles' psn h ist
= trivialHoles psn h (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
proofSearch' ist rec ambigok depth prv top n psns hints
= do unifyProblems
proofSearch rec prv ambigok (not prv) depth
(elab ist toplevel ERHS [] (sMN 0 "tac")) top n psns hints ist
resolveTC' di mv depth tm n ist
= resolveTC di mv depth tm n (elab ist toplevel ERHS [] (sMN 0 "tac")) ist
collectDeferred :: Maybe Name -> [Name] -> Context ->
Term -> State [(Name, (Int, Maybe Name, Type, [Name]))] Term
collectDeferred top casenames ctxt tm = cd [] tm
where
cd env (Bind n (GHole i psns t) app) =
do ds <- get
t' <- collectDeferred top casenames ctxt t
when (not (n `elem` map fst ds)) $ put (ds ++ [(n, (i, top, t', psns))])
cd env app
cd env (Bind n b t)
= do b' <- cdb b
t' <- cd ((n, b) : env) t
return (Bind n b' t')
where
cdb (Let rig t v) = liftM2 (Let rig) (cd env t) (cd env v)
cdb (Guess t v) = liftM2 Guess (cd env t) (cd env v)
cdb b = do ty' <- cd env (binderTy b)
return (b { binderTy = ty' })
cd env (App s f a) = liftM2 (App s) (cd env f)
(cd env a)
cd env t = return t
-- | Compute the appropriate name for a top-level metavariable
metavarName :: [String] -> Name -> Name
metavarName _ n@(NS _ _) = n
metavarName (ns@(_:_)) n = sNS n ns
metavarName _ n = n
runElabAction :: ElabInfo -> IState -> FC -> Env -> Term -> [String] -> ElabD Term
runElabAction info ist fc env tm ns = do tm' <- eval tm
runTacTm tm'
where
eval tm = do ctxt <- get_context
return $ normaliseAll ctxt env (finalise tm)
returnUnit = return $ P (DCon 0 0 False) unitCon (P (TCon 0 0) unitTy Erased)
patvars :: [(Name, Term)] -> Term -> ([(Name, Term)], Term)
patvars ns (Bind n (PVar _ t) sc) = patvars ((n, t) : ns) (instantiate (P Bound n t) sc)
patvars ns tm = (ns, tm)
pullVars :: (Term, Term) -> ([(Name, Term)], Term, Term)
pullVars (lhs, rhs) = (fst (patvars [] lhs), snd (patvars [] lhs), snd (patvars [] rhs)) -- TODO alpha-convert rhs
requireError :: Err -> ElabD a -> ElabD ()
requireError orErr elab =
do state <- get
case runStateT elab state of
OK (_, state') -> lift (tfail orErr)
Error e -> return ()
-- create a fake TT term for the LHS of an impossible case
fakeTT :: Raw -> Term
fakeTT (Var n) =
case lookupNameDef n (tt_ctxt ist) of
[(n', TyDecl nt _)] -> P nt n' Erased
_ -> P Ref n Erased
fakeTT (RBind n b body) = Bind n (fmap fakeTT b) (fakeTT body)
fakeTT (RApp f a) = App Complete (fakeTT f) (fakeTT a)
fakeTT RType = TType (UVar [] (-1))
fakeTT (RUType u) = UType u
fakeTT (RConstant c) = Constant c
defineFunction :: RFunDefn Raw -> ElabD ()
defineFunction (RDefineFun n clauses) =
do ctxt <- get_context
ty <- maybe (fail "no type decl") return $ lookupTyExact n ctxt
let info = CaseInfo True True False -- TODO document and figure out
clauses' <- forM clauses (\case
RMkFunClause lhs rhs ->
do (lhs', lty) <- lift $ check ctxt [] lhs
(rhs', rty) <- lift $ check ctxt [] rhs
lift $ converts ctxt [] lty rty
return $ Right (lhs', rhs')
RMkImpossibleClause lhs ->
do requireError (Msg "Not an impossible case") . lift $
check ctxt [] lhs
return $ Left (fakeTT lhs))
let clauses'' = map (\case Right c -> pullVars c
Left lhs -> let (ns, lhs') = patvars [] lhs
in (ns, lhs', Impossible))
clauses'
let clauses''' = map (\(ns, lhs, rhs) -> (map fst ns, lhs, rhs)) clauses''
let argtys = map (\x -> (x, isCanonical x ctxt))
(map snd (getArgTys (normalise ctxt [] ty)))
ctxt'<- lift $
addCasedef n (const [])
info False (STerm Erased)
True False -- TODO what are these?
argtys [] -- TODO inaccessible types
clauses'
clauses'''
clauses'''
ty
ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = RClausesInstrs n clauses'' : new_tyDecls e}
return ()
checkClosed :: Raw -> Elab' aux (Term, Type)
checkClosed tm = do ctxt <- get_context
(val, ty) <- lift $ check ctxt [] tm
return $! (finalise val, finalise ty)
-- | Add another argument to a Pi
mkPi :: RFunArg -> Raw -> Raw
mkPi arg rTy = RBind (argName arg) (Pi RigW Nothing (argTy arg) (RUType AllTypes)) rTy
mustBeType ctxt tm ty =
case normaliseAll ctxt [] (finalise ty) of
UType _ -> return ()
TType _ -> return ()
ty' -> lift . tfail . InternalMsg $
show tm ++ " is not a type: it's " ++ show ty'
mustNotBeDefined ctxt n =
case lookupDefExact n ctxt of
Just _ -> lift . tfail . InternalMsg $
show n ++ " is already defined."
Nothing -> return ()
-- | Prepare a constructor to be added to a datatype being defined here
prepareConstructor :: Name -> RConstructorDefn -> ElabD (Name, [PArg], Type)
prepareConstructor tyn (RConstructor cn args resTy) =
do ctxt <- get_context
-- ensure the constructor name is not qualified, and
-- construct a qualified one
notQualified cn
let qcn = qualify cn
-- ensure that the constructor name is not defined already
mustNotBeDefined ctxt qcn
-- construct the actual type for the constructor
let cty = foldr mkPi resTy args
(checkedTy, ctyTy) <- lift $ check ctxt [] cty
mustBeType ctxt checkedTy ctyTy
-- ensure that the constructor builds the right family
case unApply (getRetTy (normaliseAll ctxt [] (finalise checkedTy))) of
(P _ n _, _) | n == tyn -> return ()
t -> lift . tfail . Msg $ "The constructor " ++ show cn ++
" doesn't construct " ++ show tyn ++
" (return type is " ++ show t ++ ")"
-- add temporary type declaration for constructor (so it can
-- occur in later constructor types)
set_context (addTyDecl qcn (DCon 0 0 False) checkedTy ctxt)
-- Save the implicits for high-level Idris
let impls = map rFunArgToPArg args
return (qcn, impls, checkedTy)
where
notQualified (NS _ _) = lift . tfail . Msg $ "Constructor names may not be qualified"
notQualified _ = return ()
qualify n = case tyn of
(NS _ ns) -> NS n ns
_ -> n
getRetTy :: Type -> Type
getRetTy (Bind _ (Pi _ _ _ _) sc) = getRetTy sc
getRetTy ty = ty
elabScriptStuck :: Term -> ElabD a
elabScriptStuck x = lift . tfail $ ElabScriptStuck x
-- Should be dependent
tacTmArgs :: Int -> Term -> [Term] -> ElabD [Term]
tacTmArgs l t args | length args == l = return args
| otherwise = elabScriptStuck t -- Probably should be an argument size mismatch internal error
-- | Do a step in the reflected elaborator monad. The input is the
-- step, the output is the (reflected) term returned.
runTacTm :: Term -> ElabD Term
runTacTm tac@(unApply -> (P _ n _, args))
| n == tacN "Prim__Solve"
= do ~[] <- tacTmArgs 0 tac args -- patterns are irrefutable because `tacTmArgs` returns lists of exactly the size given to it as first argument
solve
returnUnit
| n == tacN "Prim__Goal"
= do ~[] <- tacTmArgs 0 tac args
hs <- get_holes
case hs of
(h : _) -> do t <- goal
fmap fst . checkClosed $
rawPair (Var (reflm "TTName"), Var (reflm "TT"))
(reflectName h, reflect t)
[] -> lift . tfail . Msg $
"Elaboration is complete. There are no goals."
| n == tacN "Prim__Holes"
= do ~[] <- tacTmArgs 0 tac args
hs <- get_holes
fmap fst . checkClosed $
mkList (Var $ reflm "TTName") (map reflectName hs)
| n == tacN "Prim__Guess"
= do ~[] <- tacTmArgs 0 tac args
g <- get_guess
fmap fst . checkClosed $ reflect g
| n == tacN "Prim__LookupTy"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
ctxt <- get_context
let getNameTypeAndType = \case Function ty _ -> (Ref, ty)
TyDecl nt ty -> (nt, ty)
Operator ty _ _ -> (Ref, ty)
CaseOp _ ty _ _ _ _ -> (Ref, ty)
-- Idris tuples nest to the right
reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [Var (reflm "NameType"), Var (reflm "TT")]
, x
, raw_apply (Var pairCon) [ Var (reflm "NameType"), Var (reflm "TT")
, y, z]]
let defs = [ reflectTriple (reflectName n, reflectNameType nt, reflect ty)
| (n, def) <- lookupNameDef n' ctxt
, let (nt, ty) = getNameTypeAndType def ]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [ Var (reflm "NameType")
, Var (reflm "TT")]])
defs
| n == tacN "Prim__LookupDatatype"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
datatypes <- get_datatypes
ctxt <- get_context
fmap fst . checkClosed $
rawList (Var (tacN "Datatype"))
(map reflectDatatype (buildDatatypes ist n'))
| n == tacN "Prim__LookupFunDefn"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
fmap fst . checkClosed $
rawList (RApp (Var $ tacN "FunDefn") (Var $ reflm "TT"))
(map reflectFunDefn (buildFunDefns ist n'))
| n == tacN "Prim__LookupArgs"
= do ~[name] <- tacTmArgs 1 tac args
n' <- reifyTTName name
let listTy = Var (sNS (sUN "List") ["List", "Prelude"])
listFunArg = RApp listTy (Var (tacN "FunArg"))
-- Idris tuples nest to the right
let reflectTriple (x, y, z) =
raw_apply (Var pairCon) [ Var (reflm "TTName")
, raw_apply (Var pairTy) [listFunArg, Var (reflm "Raw")]
, x
, raw_apply (Var pairCon) [listFunArg, Var (reflm "Raw")
, y, z]]
let out =
[ reflectTriple (reflectName fn, reflectList (Var (tacN "FunArg")) (map reflectArg args), reflectRaw res)
| (fn, pargs) <- lookupCtxtName n' (idris_implicits ist)
, (args, res) <- getArgs pargs . forget <$>
maybeToList (lookupTyExact fn (tt_ctxt ist))
]
fmap fst . checkClosed $
rawList (raw_apply (Var pairTy) [Var (reflm "TTName")
, raw_apply (Var pairTy) [ RApp listTy
(Var (tacN "FunArg"))
, Var (reflm "Raw")]])
out
| n == tacN "Prim__SourceLocation"
= do ~[] <- tacTmArgs 0 tac args
fmap fst . checkClosed $
reflectFC fc
| n == tacN "Prim__Namespace"
= do ~[] <- tacTmArgs 0 tac args
fmap fst . checkClosed $
rawList (RConstant StrType) (map (RConstant . Str) ns)
| n == tacN "Prim__Env"
= do ~[] <- tacTmArgs 0 tac args
env <- get_env
fmap fst . checkClosed $ reflectEnv env
| n == tacN "Prim__Fail"
= do ~[_a, errs] <- tacTmArgs 2 tac args
errs' <- eval errs
parts <- reifyReportParts errs'
lift . tfail $ ReflectionError [parts] (Msg "")
| n == tacN "Prim__PureElab"
= do ~[_a, tm] <- tacTmArgs 2 tac args
return tm
| n == tacN "Prim__BindElab"
= do ~[_a, _b, first, andThen] <- tacTmArgs 4 tac args
first' <- eval first
res <- eval =<< runTacTm first'
next <- eval (App Complete andThen res)
runTacTm next
| n == tacN "Prim__Try"
= do ~[_a, first, alt] <- tacTmArgs 3 tac args
first' <- eval first
alt' <- eval alt
try' (runTacTm first') (runTacTm alt') True
| n == tacN "Prim__TryCatch"
= do ~[_a, first, f] <- tacTmArgs 3 tac args
first' <- eval first
f' <- eval f
tryCatch (runTacTm first') $ \err ->
do (err', _) <- checkClosed (reflectErr err)
f' <- eval (App Complete f err')
runTacTm f'
| n == tacN "Prim__Fill"
= do ~[raw] <- tacTmArgs 1 tac args
raw' <- reifyRaw =<< eval raw
apply raw' []
returnUnit
| n == tacN "Prim__Apply" || n == tacN "Prim__MatchApply"
= do ~[raw, argSpec] <- tacTmArgs 2 tac args
raw' <- reifyRaw =<< eval raw
argSpec' <- map (\b -> (b, 0)) <$> reifyList reifyBool argSpec
let op = if n == tacN "Prim__Apply"
then apply
else match_apply
ns <- op raw' argSpec'
fmap fst . checkClosed $
rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TTName"))
[ rawPair (Var $ reflm "TTName", Var $ reflm "TTName")
(reflectName n1, reflectName n2)
| (n1, n2) <- ns
]
| n == tacN "Prim__Gensym"
= do ~[hint] <- tacTmArgs 1 tac args
hintStr <- eval hint
case hintStr of
Constant (Str h) -> do
n <- getNameFrom (sMN 0 h)
fmap fst $ get_type_val (reflectName n)
_ -> fail "no hint"
| n == tacN "Prim__Claim"
= do ~[n, ty] <- tacTmArgs 2 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
claim n' ty'
returnUnit
| n == tacN "Prim__Check"
= do ~[env', raw] <- tacTmArgs 2 tac args
env <- reifyEnv env'
raw' <- reifyRaw =<< eval raw
ctxt <- get_context
(tm, ty) <- lift $ check ctxt env raw'
fmap fst . checkClosed $
rawPair (Var (reflm "TT"), Var (reflm "TT"))
(reflect tm, reflect ty)
| n == tacN "Prim__Attack"
= do ~[] <- tacTmArgs 0 tac args
attack
returnUnit
| n == tacN "Prim__Rewrite"
= do ~[rule] <- tacTmArgs 1 tac args
r <- reifyRaw rule
rewrite r
returnUnit
| n == tacN "Prim__Focus"
= do ~[what] <- tacTmArgs 1 tac args
n' <- reifyTTName what
hs <- get_holes
if elem n' hs
then focus n' >> returnUnit
else lift . tfail . Msg $ "The name " ++ show n' ++ " does not denote a hole"
| n == tacN "Prim__Unfocus"
= do ~[what] <- tacTmArgs 1 tac args
n' <- reifyTTName what
movelast n'
returnUnit
| n == tacN "Prim__Intro"
= do ~[mn] <- tacTmArgs 1 tac args
n <- case fromTTMaybe mn of
Nothing -> return Nothing
Just name -> fmap Just $ reifyTTName name
intro n
returnUnit
| n == tacN "Prim__Forall"
= do ~[n, ty] <- tacTmArgs 2 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
forall n' RigW Nothing ty'
returnUnit
| n == tacN "Prim__PatVar"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
patvar' n'
returnUnit
| n == tacN "Prim__PatBind"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
patbind n' RigW
returnUnit
| n == tacN "Prim__LetBind"
= do ~[n, ty, tm] <- tacTmArgs 3 tac args
n' <- reifyTTName n
ty' <- reifyRaw ty
tm' <- reifyRaw tm
letbind n' RigW ty' tm'
returnUnit
| n == tacN "Prim__Compute"
= do ~[] <- tacTmArgs 0 tac args; compute ; returnUnit
| n == tacN "Prim__Normalise"
= do ~[env, tm] <- tacTmArgs 2 tac args
env' <- reifyEnv env
tm' <- reifyTT tm
ctxt <- get_context
let out = normaliseAll ctxt env' (finalise tm')
fmap fst . checkClosed $ reflect out
| n == tacN "Prim__Whnf"
= do ~[tm] <- tacTmArgs 1 tac args
tm' <- reifyTT tm
ctxt <- get_context
fmap fst . checkClosed . reflect $ whnf ctxt [] tm'
| n == tacN "Prim__Converts"
= do ~[env, tm1, tm2] <- tacTmArgs 3 tac args
env' <- reifyEnv env
tm1' <- reifyTT tm1
tm2' <- reifyTT tm2
ctxt <- get_context
lift $ converts ctxt env' tm1' tm2'
returnUnit
| n == tacN "Prim__DeclareType"
= do ~[decl] <- tacTmArgs 1 tac args
(RDeclare n args res) <- reifyTyDecl decl
ctxt <- get_context
let rty = foldr mkPi res args
(checked, ty') <- lift $ check ctxt [] rty
mustBeType ctxt checked ty'
mustNotBeDefined ctxt n
let decl = TyDecl Ref checked
ctxt' = addCtxtDef n decl ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = (RTyDeclInstrs n fc (map rFunArgToPArg args) checked) :
new_tyDecls e }
returnUnit
| n == tacN "Prim__DefineFunction"
= do ~[decl] <- tacTmArgs 1 tac args
defn <- reifyFunDefn decl
defineFunction defn
returnUnit
| n == tacN "Prim__DeclareDatatype"
= do ~[decl] <- tacTmArgs 1 tac args
RDeclare n args resTy <- reifyTyDecl decl
ctxt <- get_context
let tcTy = foldr mkPi resTy args
(checked, ty') <- lift $ check ctxt [] tcTy
mustBeType ctxt checked ty'
mustNotBeDefined ctxt n
let ctxt' = addTyDecl n (TCon 0 0) checked ctxt
set_context ctxt'
updateAux $ \e -> e { new_tyDecls = RDatatypeDeclInstrs n (map rFunArgToPArg args) : new_tyDecls e }
returnUnit
| n == tacN "Prim__DefineDatatype"
= do ~[defn] <- tacTmArgs 1 tac args
RDefineDatatype n ctors <- reifyRDataDefn defn
ctxt <- get_context
tyconTy <- case lookupTyExact n ctxt of
Just t -> return t
Nothing -> lift . tfail . Msg $ "Type not previously declared"
datatypes <- get_datatypes
case lookupCtxtName n datatypes of
[] -> return ()
_ -> lift . tfail . Msg $ show n ++ " is already defined as a datatype."
-- Prepare the constructors
ctors' <- mapM (prepareConstructor n) ctors
ttag <- do ES (ps, aux) str prev <- get
let i = global_nextname ps
put $ ES (ps { global_nextname = global_nextname ps + 1 },
aux)
str
prev
return i
let ctxt' = addDatatype (Data n ttag tyconTy False (map (\(cn, _, cty) -> (cn, cty)) ctors')) ctxt
set_context ctxt'
-- the rest happens in a bit
updateAux $ \e -> e { new_tyDecls = RDatatypeDefnInstrs n tyconTy ctors' : new_tyDecls e }
returnUnit
| n == tacN "Prim__AddImplementation"
= do ~[cls, impl] <- tacTmArgs 2 tac args
interfaceName <- reifyTTName cls
implName <- reifyTTName impl
updateAux $ \e -> e { new_tyDecls = RAddImplementation interfaceName implName :
new_tyDecls e }
returnUnit
| n == tacN "Prim__IsTCName"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
case lookupCtxtExact n' (idris_interfaces ist) of
Just _ -> fmap fst . checkClosed $ Var (sNS (sUN "True") ["Bool", "Prelude"])
Nothing -> fmap fst . checkClosed $ Var (sNS (sUN "False") ["Bool", "Prelude"])
| n == tacN "Prim__ResolveTC"
= do ~[fn] <- tacTmArgs 1 tac args
g <- goal
fn <- reifyTTName fn
resolveTC' False True 100 g fn ist
returnUnit
| n == tacN "Prim__Search"
= do ~[depth, hints] <- tacTmArgs 2 tac args
d <- eval depth
hints' <- eval hints
case (d, unList hints') of
(Constant (I i), Just hs) ->
do actualHints <- mapM reifyTTName hs
unifyProblems
let psElab = elab ist toplevel ERHS [] (sMN 0 "tac")
proofSearch True True False False i psElab Nothing (sMN 0 "search ") [] actualHints ist
returnUnit
(Constant (I _), Nothing ) ->
lift . tfail . InternalMsg $ "Not a list: " ++ show hints'
(_, _) -> lift . tfail . InternalMsg $ "Can't reify int " ++ show d
| n == tacN "Prim__RecursiveElab"
= do ~[goal, script] <- tacTmArgs 2 tac args
goal' <- reifyRaw goal
ctxt <- get_context
script <- eval script
(goalTT, goalTy) <- lift $ check ctxt [] goal'
lift $ isType ctxt [] goalTy
recH <- getNameFrom (sMN 0 "recElabHole")
aux <- getAux
datatypes <- get_datatypes
env <- get_env
g_next <- get_global_nextname
(ctxt', ES (p, aux') _ _) <-
do (ES (current_p, _) _ _) <- get
lift $ runElab aux
(do runElabAction info ist fc [] script ns
ctxt' <- get_context
return ctxt')
((newProof recH (constraintNS info) ctxt datatypes g_next goalTT)
{ nextname = nextname current_p })
set_context ctxt'
let tm_out = getProofTerm (pterm p)
do (ES (prf, _) s e) <- get
let p' = prf { nextname = nextname p
, global_nextname = global_nextname p
}
put (ES (p', aux') s e)
env' <- get_env
(tm, ty, _) <- lift $ recheck (constraintNS info) ctxt' env (forget tm_out) tm_out
let (tm', ty') = (reflect tm, reflect ty)
fmap fst . checkClosed $
rawPair (Var $ reflm "TT", Var $ reflm "TT")
(tm', ty')
| n == tacN "Prim__Metavar"
= do ~[n] <- tacTmArgs 1 tac args
n' <- reifyTTName n
ctxt <- get_context
ptm <- get_term
-- See documentation above in the elab case for PMetavar
let unique_used = getUniqueUsed ctxt ptm
let lin_used = getLinearUsed ctxt ptm
let mvn = metavarName ns n'
attack
defer unique_used lin_used mvn
solve
returnUnit
| n == tacN "Prim__Fixity"
= do ~[op'] <- tacTmArgs 1 tac args
opTm <- eval op'
case opTm of
Constant (Str op) ->
let opChars = ":!#$%&*+./<=>?@\\^|-~"
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"]
fixities = idris_infixes ist
in if not (all (flip elem opChars) op) || elem op invalidOperators
then lift . tfail . Msg $ "'" ++ op ++ "' is not a valid operator name."
else case nub [f | Fix f someOp <- fixities, someOp == op] of
[] -> lift . tfail . Msg $ "No fixity found for operator '" ++ op ++ "'."
[f] -> fmap fst . checkClosed $ reflectFixity f
many -> lift . tfail . InternalMsg $ "Ambiguous fixity for '" ++ op ++ "'! Found " ++ show many
_ -> lift . tfail . Msg $ "Not a constant string for an operator name: " ++ show opTm
| n == tacN "Prim__Debug"
= do ~[ty, msg] <- tacTmArgs 2 tac args
msg' <- eval msg
parts <- reifyReportParts msg
debugElaborator parts
runTacTm x = elabScriptStuck x
-- Running tactics directly
-- if a tactic adds unification problems, return an error
runTac :: Bool -> IState -> Maybe FC -> Name -> PTactic -> ElabD ()
runTac autoSolve ist perhapsFC fn tac
= do env <- get_env
g <- goal
let tac' = fmap (addImplBound ist (map fstEnv env)) tac
if autoSolve
then runT tac'
else no_errors (runT tac')
(Just (CantSolveGoal g (map (\(n, _, b) -> (n, binderTy b)) env)))
where
runT (Intro []) = do g <- goal
attack; intro (bname g)
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Intro xs) = mapM_ (\x -> do attack; intro (Just x)) xs
runT Intros = do g <- goal
attack;
intro (bname g)
try' (runT Intros)
(return ()) True
where
bname (Bind n _ _) = Just n
bname _ = Nothing
runT (Exact tm) = do elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (MatchRefine fn)
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map (const True) a)) ns)
let tacs = map (\ (fn', imps) ->
(match_apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where envArgs n = do e <- get_env
case lookupBinder n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn [])
= do fnimps <-
case lookupCtxtName fn (idris_implicits ist) of
[] -> do a <- envArgs fn
return [(fn, a)]
ns -> return (map (\ (n, a) -> (n, map isImp a)) ns)
let tacs = map (\ (fn', imps) ->
(apply (Var fn') (map (\x -> (x, 0)) imps),
fn')) fnimps
tryAll tacs
when autoSolve solveAll
where isImp (PImp _ _ _ _ _) = True
isImp _ = False
envArgs n = do e <- get_env
case lookupBinder n e of
Just t -> return $ map (const False)
(getArgTys (binderTy t))
_ -> return []
runT (Refine fn imps) = do ns <- apply (Var fn) (map (\x -> (x,0)) imps)
when autoSolve solveAll
runT DoUnify = do unify_all
when autoSolve solveAll
runT (Claim n tm) = do tmHole <- getNameFrom (sMN 0 "newGoal")
claim tmHole RType
claim n (Var tmHole)
focus tmHole
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus n
runT (Equiv tm) -- let bind tm, then
= do attack
tyn <- getNameFrom (sMN 0 "ety")
claim tyn RType
valn <- getNameFrom (sMN 0 "eqval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "equiv_val")
letbind letn RigW (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
focus valn
when autoSolve solveAll
runT (Rewrite tm) -- to elaborate tm, let bind it, then rewrite by that
= do attack; -- (h:_) <- get_holes
tyn <- getNameFrom (sMN 0 "rty")
-- start_unify h
claim tyn RType
valn <- getNameFrom (sMN 0 "rval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "rewrite_rule")
letbind letn RigW (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
rewrite (Var letn)
when autoSolve solveAll
runT (LetTac n tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn RigW (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT (LetTacTy n ty tm)
= do attack
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- unique_hole n
letbind letn RigW (Var tyn) (Var valn)
focus tyn
elab ist toplevel ERHS [] (sMN 0 "tac") ty
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") tm
when autoSolve solveAll
runT Compute = compute
runT Trivial = do trivial' ist; when autoSolve solveAll
runT TCImplementation = runT (Exact (PResolveTC emptyFC))
runT (ProofSearch rec prover depth top psns hints)
= do proofSearch' ist rec False depth prover top fn psns hints
when autoSolve solveAll
runT (Focus n) = focus n
runT Unfocus = do hs <- get_holes
case hs of
[] -> return ()
(h : _) -> movelast h
runT Solve = solve
runT (Try l r) = do try' (runT l) (runT r) True
runT (TSeq l r) = do runT l; runT r
runT (ApplyTactic tm) = do tenv <- get_env -- store the environment
tgoal <- goal -- store the goal
attack -- let f : List (TTName, Binder TT) -> TT -> Tactic = tm in ...
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar RigW scriptTy (Var script)
focus script
elab ist toplevel ERHS [] (sMN 0 "tac") tm
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal and context
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (raw_apply (forget script')
[reflectEnv tenv, reflect tgoal])
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
listTy = Var (sNS (sUN "List") ["List", "Prelude"])
scriptTy = (RBind (sMN 0 "__pi_arg")
(Pi RigW Nothing (RApp listTy envTupleType) RType)
(RBind (sMN 1 "__pi_arg")
(Pi RigW Nothing (Var $ reflm "TT") RType) tacticTy))
runT (ByReflection tm) -- run the reflection function 'tm' on the
-- goal, then apply the resulting reflected Tactic
= do tgoal <- goal
attack
script <- getNameFrom (sMN 0 "script")
claim script scriptTy
scriptvar <- getNameFrom (sMN 0 "scriptvar" )
letbind scriptvar RigW scriptTy (Var script)
focus script
ptm <- get_term
env <- get_env
let denv = map (\(n, _, b) -> (n, binderTy b)) env
elab ist toplevel ERHS [] (sMN 0 "tac")
(PApp emptyFC tm [pexp (delabTy' ist [] denv tgoal True True True)])
(script', _) <- get_type_val (Var scriptvar)
-- now that we have the script apply
-- it to the reflected goal
restac <- getNameFrom (sMN 0 "restac")
claim restac tacticTy
focus restac
fill (forget script')
restac' <- get_guess
solve
-- normalise the result in order to
-- reify it
ctxt <- get_context
env <- get_env
let tactic = normalise ctxt env restac'
runReflected tactic
where tacticTy = Var (reflm "Tactic")
scriptTy = tacticTy
runT (Reflect v) = do attack -- let x = reflect v in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn RigW (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = normalise ctxt env value
runTac autoSolve ist perhapsFC fn (Exact $ PQuote (reflect value'))
runT (Fill v) = do attack -- let x = fill x in ...
tyn <- getNameFrom (sMN 0 "letty")
claim tyn RType
valn <- getNameFrom (sMN 0 "letval")
claim valn (Var tyn)
letn <- getNameFrom (sMN 0 "letvar")
letbind letn RigW (Var tyn) (Var valn)
focus valn
elab ist toplevel ERHS [] (sMN 0 "tac") v
(value, _) <- get_type_val (Var letn)
ctxt <- get_context
env <- get_env
let value' = normalise ctxt env value
rawValue <- reifyRaw value'
runTac autoSolve ist perhapsFC fn (Exact $ PQuote rawValue)
runT (GoalType n tac) = do g <- goal
case unApply g of
(P _ n' _, _) ->
if nsroot n' == sUN n
then runT tac
else fail "Wrong goal type"
_ -> fail "Wrong goal type"
runT ProofState = do g <- goal
return ()
runT Skip = return ()
runT (TFail err) = lift . tfail $ ReflectionError [err] (Msg "")
runT SourceFC =
case perhapsFC of
Nothing -> lift . tfail $ Msg "There is no source location available."
Just fc ->
do fill $ reflectFC fc
solve
runT Qed = lift . tfail $ Msg "The qed command is only valid in the interactive prover"
runT x = fail $ "Not implemented " ++ show x
runReflected t = do t' <- reify ist t
runTac autoSolve ist perhapsFC fn t'
elaboratingArgErr :: [(Name, Name)] -> Err -> Err
elaboratingArgErr [] err = err
elaboratingArgErr ((f,x):during) err = fromMaybe err (rewrite err)
where rewrite (ElaboratingArg _ _ _ _) = Nothing
rewrite (ProofSearchFail e) = fmap ProofSearchFail (rewrite e)
rewrite (At fc e) = fmap (At fc) (rewrite e)
rewrite err = Just (ElaboratingArg f x during err)
withErrorReflection :: Idris a -> Idris a
withErrorReflection x = idrisCatch x (\ e -> handle e >>= ierror)
where handle :: Err -> Idris Err
handle e@(ReflectionError _ _) = do logElab 3 "Skipping reflection of error reflection result"
return e -- Don't do meta-reflection of errors
handle e@(ReflectionFailed _ _) = do logElab 3 "Skipping reflection of reflection failure"
return e
-- At and Elaborating are just plumbing - error reflection shouldn't rewrite them
handle e@(At fc err) = do logElab 3 "Reflecting body of At"
err' <- handle err
return (At fc err')
handle e@(Elaborating what n ty err) = do logElab 3 "Reflecting body of Elaborating"
err' <- handle err
return (Elaborating what n ty err')
handle e@(ElaboratingArg f a prev err) = do logElab 3 "Reflecting body of ElaboratingArg"
hs <- getFnHandlers f a
err' <- if null hs
then handle err
else applyHandlers err hs
return (ElaboratingArg f a prev err')
-- ProofSearchFail is an internal detail - so don't expose it
handle (ProofSearchFail e) = handle e
-- TODO: argument-specific error handlers go here for ElaboratingArg
handle e = do ist <- getIState
logElab 2 "Starting error reflection"
logElab 5 (show e)
let handlers = idris_errorhandlers ist
applyHandlers e handlers
getFnHandlers :: Name -> Name -> Idris [Name]
getFnHandlers f arg = do ist <- getIState
let funHandlers = maybe M.empty id .
lookupCtxtExact f .
idris_function_errorhandlers $ ist
return . maybe [] S.toList . M.lookup arg $ funHandlers
applyHandlers e handlers =
do ist <- getIState
let err = fmap (errReverse ist) e
logElab 3 $ "Using reflection handlers " ++
concat (intersperse ", " (map show handlers))
let reports = map (\n -> RApp (Var n) (reflectErr err)) handlers
-- Typecheck error handlers - if this fails, most
-- likely something which is needed by it has not
-- been imported, so keep the original error.
handlers <- case mapM (check (tt_ctxt ist) []) reports of
Error _ -> return [] -- ierror $ ReflectionFailed "Type error while constructing reflected error" e
OK hs -> return hs
-- Normalize error handler terms to produce the new messages
-- Need to use 'normaliseAll' since we have to reduce private
-- names in error handlers too
ctxt <- getContext
let results = map (normaliseAll ctxt []) (map fst handlers)
logElab 3 $ "New error message info: " ++ concat (intersperse " and " (map show results))
-- For each handler term output, either discard it if it is Nothing or reify it the Haskell equivalent
let errorpartsTT = mapMaybe unList (mapMaybe fromTTMaybe results)
errorparts <- case mapM (mapM reifyReportPart) errorpartsTT of
Left err -> ierror err
Right ok -> return ok
return $ case errorparts of
[] -> e
parts -> ReflectionError errorparts e
solveAll = try (do solve; solveAll) (return ())
-- | Do the left-over work after creating declarations in reflected
-- elaborator scripts
processTacticDecls :: ElabInfo -> [RDeclInstructions] -> Idris ()
processTacticDecls info steps =
-- The order of steps is important: type declarations might
-- establish metavars that later function bodies resolve.
forM_ (reverse steps) $ \case
RTyDeclInstrs n fc impls ty ->
do logElab 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty
logElab 3 $ " It has impls " ++ show impls
updateIState $ \i -> i { idris_implicits =
addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
ds <- checkDef info fc (\_ e -> e) True [(n, (-1, Nothing, ty, []))]
addIBC (IBCDef n)
ctxt <- getContext
case lookupDef n ctxt of
(TyDecl _ _ : _) ->
-- If the function isn't defined at the end of the elab script,
-- then it must be added as a metavariable. This needs guarding
-- to prevent overwriting case defs with a metavar, if the case
-- defs come after the type decl in the same script!
let ds' = map (\(n, (i, top, t, ns)) -> (n, (i, top, t, ns, True, True))) ds
in addDeferred ds'
_ -> return ()
RDatatypeDeclInstrs n impls ->
do addIBC (IBCDef n)
updateIState $ \i -> i { idris_implicits = addDef n impls (idris_implicits i) }
addIBC (IBCImp n)
RDatatypeDefnInstrs tyn tyconTy ctors ->
do let cn (n, _, _) = n
cty (_, _, t) = t
addIBC (IBCDef tyn)
mapM_ (addIBC . IBCDef . cn) ctors
ctxt <- getContext
let params = findParams tyn (normalise ctxt [] tyconTy) (map cty ctors)
let typeInfo = TI (map cn ctors) False [] params [] False
-- implicit precondition to IBCData is that idris_datatypes on the IState is populated.
-- otherwise writing the IBC just fails silently!
updateIState $ \i -> i { idris_datatypes =
addDef tyn typeInfo (idris_datatypes i) }
addIBC (IBCData tyn)
ttag <- getName -- from AbsSyntax.hs, really returns a disambiguating Int
let metainf = DataMI params
addIBC (IBCMetaInformation tyn metainf)
updateContext (setMetaInformation tyn metainf)
for_ ctors $ \(cn, impls, _) ->
do updateIState $ \i -> i { idris_implicits = addDef cn impls (idris_implicits i) }
addIBC (IBCImp cn)
for_ ctors $ \(ctorN, _, _) ->
do totcheck (NoFC, ctorN)
ctxt <- tt_ctxt <$> getIState
case lookupTyExact ctorN ctxt of
Just cty -> do checkPositive (tyn : map cn ctors) (ctorN, cty)
return ()
Nothing -> return ()
case ctors of
[ctor] -> do setDetaggable (cn ctor); setDetaggable tyn
addIBC (IBCOpt (cn ctor)); addIBC (IBCOpt tyn)
_ -> return ()
-- TODO: inaccessible
RAddImplementation interfaceName implName ->
do -- The interface resolution machinery relies on a special
logElab 2 $ "Adding elab script implementation " ++ show implName ++
" for " ++ show interfaceName
addImplementation False True interfaceName implName
addIBC (IBCImplementation False True interfaceName implName)
RClausesInstrs n cs ->
do logElab 3 $ "Pattern-matching definition from tactics: " ++ show n
solveDeferred emptyFC n
let lhss = map (\(ns, lhs, _) -> (map fst ns, lhs)) cs
let fc = fileFC "elab_reflected"
pmissing <-
do ist <- getIState
possible <- genClauses fc n lhss
(map (\ (ns, lhs) ->
delab' ist lhs True True) lhss)
missing <- filterM (checkPossible n) possible
let undef = filter (noMatch ist (map snd lhss)) missing
return undef
let tot = if null pmissing
then Unchecked -- still need to check recursive calls
else Partial NotCovering -- missing cases implies not total
setTotality n tot
updateIState $ \i -> i { idris_patdefs =
addDef n (cs, pmissing) $ idris_patdefs i }
addIBC (IBCDef n)
ctxt <- getContext
case lookupDefExact n ctxt of
Just (CaseOp _ _ _ _ _ cd) ->
-- Here, we populate the call graph with a list of things
-- we refer to, so that if they aren't total, the whole
-- thing won't be.
let (scargs, sc) = cases_compiletime cd
calls = map fst $ findCalls sc scargs
in do logElab 2 $ "Called names in reflected elab: " ++ show calls
addCalls n calls
addIBC $ IBCCG n
Just _ -> return () -- TODO throw internal error
Nothing -> return ()
-- checkDeclTotality requires that the call graph be present
-- before calling it.
-- TODO: reduce code duplication with Idris.Elab.Clause
buildSCG (fc, n)
-- Actually run the totality checker. In the main clause
-- elaborator, this is deferred until after. Here, we run it
-- now to get totality information as early as possible.
tot' <- checkDeclTotality (fc, n)
setTotality n tot'
when (tot' /= Unchecked) $ addIBC (IBCTotal n tot')
where
-- TODO: see if the code duplication with Idris.Elab.Clause can be
-- reduced or eliminated.
-- These are always cases generated by genClauses
checkPossible :: Name -> PTerm -> Idris Bool
checkPossible fname lhs_in =
do ctxt <- getContext
ist <- getIState
let lhs = addImplPat ist lhs_in
let fc = fileFC "elab_reflected_totality"
case elaborate (constraintNS info) ctxt (idris_datatypes ist) (idris_name ist) (sMN 0 "refPatLHS") infP initEState
(erun fc (buildTC ist info EImpossible [] fname (allNamesIn lhs_in)
(infTerm lhs))) of
OK (ElabResult lhs' _ _ _ _ _ name', _) ->
do -- not recursively calling here, because we don't
-- want to run infinitely many times
let lhs_tm = orderPats (getInferTerm lhs')
updateIState $ \i -> i { idris_name = name' }
case recheck (constraintNS info) ctxt [] (forget lhs_tm) lhs_tm of
OK _ -> return True
err -> return False
-- if it's a recoverable error, the case may become possible
Error err -> return (recoverableCoverage ctxt err)
-- TODO: Attempt to reduce/eliminate code duplication with Idris.Elab.Clause
noMatch i cs tm = all (\x -> case matchClause i (delab' i x True True) tm of
Right _ -> False
Left _ -> True) cs
|
kojiromike/Idris-dev
|
src/Idris/Elab/Term.hs
|
bsd-3-clause
| 129,531
| 1,192
| 30
| 56,065
| 22,482
| 13,681
| 8,801
| 2,270
| 238
|
-- Thread pool and work stealing
--
-- Author: Patrick Maier
-----------------------------------------------------------------------------
module Control.Parallel.HdpH.Internal.Threadpool
( -- * thread pool monad
ThreadM, -- synonym: ThreadM m = ReaderT <State m> (SparkM m)
run, -- :: [DequeIO (Thread m)] -> ThreadM m a -> SparkM m a
forkThreadM, -- :: Int -> ThreadM m () ->
-- ThreadM m Control.Concurrent.ThreadId
liftSparkM, -- :: SparkM m a -> ThreadM m a
liftCommM, -- :: CommM a -> ThreadM m a
liftIO, -- :: IO a -> ThreadM m a
-- * thread pool ID (of scheduler's own pool)
poolID, -- :: ThreadM m Int
-- * putting threads into the scheduler's own pool
putThread, -- :: Thread m -> ThreadM m ()
putThreads, -- :: [Thread m] -> ThreadM m ()
-- * stealing threads (from scheduler's own pool, or from other pools)
stealThread, -- :: ThreadM m (Maybe (Thread m))
-- * statistics
readMaxThreadCtrs -- :: ThreadM m [Int]
) where
import Prelude hiding (error)
import Control.Concurrent (ThreadId)
import Control.Monad.Reader (ReaderT, runReaderT, ask)
import Control.Monad.Trans (lift)
import Control.Parallel.HdpH.Internal.Comm (CommM)
import Control.Parallel.HdpH.Internal.Data.Deque
(DequeIO, pushFrontIO, popFrontIO, popBackIO, maxLengthIO)
import Control.Parallel.HdpH.Internal.Location (error)
import Control.Parallel.HdpH.Internal.Misc (Forkable, fork, rotate)
import Control.Parallel.HdpH.Internal.Sparkpool (SparkM, wakeupSched)
import qualified Control.Parallel.HdpH.Internal.Sparkpool as Sparkpool
(liftCommM, liftIO)
import Control.Parallel.HdpH.Internal.Type.Par (Thread)
-----------------------------------------------------------------------------
-- thread pool monad
-- 'ThreadM' is a reader monad sitting on top of the 'SparkM' monad;
-- the parameter 'm' abstracts a monad (cf. module HdpH.Internal.Type.Par).
type ThreadM m = ReaderT (State m) (SparkM m)
-- thread pool state (mutable bits held in DequeIO)
type State m = [(Int, DequeIO (Thread m))] -- list of actual thread pools,
-- each with identifying Int
-- Eliminates the 'ThreadM' layer by executing the given 'action' (typically
-- a scheduler loop) on the given non-empty list of thread 'pools' (the first
-- of which is the scheduler's own pool).
-- NOTE: An empty list of pools is admitted but then 'action' must not call
-- 'putThread', 'putThreads', 'stealThread' or 'readMaxThreadCtrs'.
run :: [(Int, DequeIO (Thread m))] -> ThreadM m a -> SparkM m a
run pools action = runReaderT action pools
-- Execute the given 'ThreadM' action in a new thread, sharing the same
-- thread pools (but rotated by 'n' pools).
forkThreadM :: Int -> ThreadM m () -> ThreadM m ThreadId
forkThreadM n action = do
pools <- getPools
lift $ fork $ run (rotate n pools) action
-- Lifting lower layers.
liftSparkM :: SparkM m a -> ThreadM m a
liftSparkM = lift
liftCommM :: CommM a -> ThreadM m a
liftCommM = liftSparkM . Sparkpool.liftCommM
liftIO :: IO a -> ThreadM m a
liftIO = liftSparkM . Sparkpool.liftIO
-----------------------------------------------------------------------------
-- access to state
getPools :: ThreadM m [(Int, DequeIO (Thread m))]
getPools = do pools <- ask
case pools of
[] -> error "HdpH.Internal.Threadpool.getPools: no pools"
_ -> return pools
-----------------------------------------------------------------------------
-- access to thread pool
-- Return thread pool ID, that is ID of scheduler's own pool.
poolID :: ThreadM m Int
poolID = do
my_pool:_ <- getPools
return $ fst my_pool
-- Read the max size of each thread pool.
readMaxThreadCtrs :: ThreadM m [Int]
readMaxThreadCtrs = getPools >>= liftIO . mapM (maxLengthIO . snd)
-- Steal a thread from any thread pool, with own pool as highest priority;
-- threads from own pool are always taken from the front; threads from other
-- pools are stolen from the back of those pools.
-- Rationale: Preserve locality as much as possible for own threads; try
-- not to disturb locality for threads stolen from others.
stealThread :: ThreadM m (Maybe (Thread m))
stealThread = do
my_pool:other_pools <- getPools
maybe_thread <- liftIO $ popFrontIO $ snd my_pool
case maybe_thread of
Just _ -> return maybe_thread
Nothing -> steal other_pools
where
steal :: [(Int, DequeIO (Thread m))] -> ThreadM m (Maybe (Thread m))
steal [] = return Nothing
steal (pool:pools) = do
maybe_thread' <- liftIO $ popBackIO $ snd pool
case maybe_thread' of
Just _ -> return maybe_thread'
Nothing -> steal pools
-- Put the given thread at the front of the executing scheduler's own pool;
-- wake up 1 sleeping scheduler (if there is any).
putThread :: Thread m -> ThreadM m ()
putThread thread = do
my_pool:_ <- getPools
liftIO $ pushFrontIO (snd my_pool) thread
liftSparkM $ wakeupSched 1
-- Put the given threads at the front of the executing scheduler's own pool;
-- the last thread in the list will end up at the front of the pool;
-- wake up as many sleeping schedulers as threads added.
putThreads :: [Thread m] -> ThreadM m ()
putThreads threads = do
all_pools@(my_pool:_) <- getPools
liftIO $ mapM_ (pushFrontIO $ snd my_pool) threads
liftSparkM $ wakeupSched (min (length all_pools) (length threads))
|
bitemyapp/hdph-rs
|
src/Control/Parallel/HdpH/Internal/Threadpool.hs
|
bsd-3-clause
| 5,520
| 13
| 12
| 1,171
| 995
| 562
| 433
| 75
| 4
|
module Network.MQTT.SN.ParserSpec (spec) where
import Data.Attoparsec.ByteString
import qualified Data.ByteString as BS
import Data.Maybe (fromJust)
import Network.MQTT.SN.Packet
import Network.MQTT.SN.Parser
import Test.Hspec
shouldParseFully :: (Show a, Eq a) => Result a -> a -> Expectation
shouldParseFully r x = r `shouldSatisfy` fromJust . compareResults (Done BS.empty x)
spec :: Spec
spec = do
describe "parsePacket" $ do
it "parses packets with long length" $ do
parse parsePacket (BS.pack [0x01, 0x00, 0x05, 0x01, 0x00])
`shouldParseFully` SEARCHGW (SearchgwPacket 0)
it "parses long packet" $ do
parse parsePacket (BS.pack $ [0x01, 0x01, 0x02, 0x0c, 0x00, 0xab, 0xcd, 0xef, 0x01] ++ [1 .. 249])
`shouldParseFully` PUBLISH (PublishPacket 0x00 0xabcd 0xef01 (BS.pack [1 .. 249]))
|
rasendubi/arachne
|
test/Network/MQTT/SN/ParserSpec.hs
|
bsd-3-clause
| 885
| 0
| 19
| 204
| 295
| 165
| 130
| -1
| -1
|
--
-- Copyright (c) 2005 Lennart Augustsson
-- See LICENSE for licensing details.
--
module HCheck(htCheckEnv, htCheckType) where
import Data.List(union)
--import Control.Monad.Trans
import Control.Monad.Error()
import Control.Monad.State
import Data.IntMap(IntMap, insert, (!), empty)
import Data.Graph(stronglyConnComp, SCC(..))
import HTypes
-- import Debug.Trace
type KState = (Int, IntMap (Maybe HKind))
initState :: KState
initState = (0, empty)
type M a = StateT KState (Either String) a
type KEnv = [(HSymbol, HKind)]
newKVar :: M HKind
newKVar = do
(i, m) <- get
put (i+1, insert i Nothing m)
return $ KVar i
getVar :: Int -> M (Maybe HKind)
getVar i = do
(_, m) <- get
case m!i of
Just (KVar i') -> getVar i'
mk -> return mk
addMap :: Int -> HKind -> M ()
addMap i k = do
(n, m) <- get
put (n, insert i (Just k) m)
clearState :: M ()
clearState = put initState
htCheckType :: [(HSymbol, ([HSymbol], HType, HKind))] -> HType -> Either String ()
htCheckType its t = flip evalStateT initState $ do
let vs = getHTVars t
ks <- mapM (const newKVar) vs
let env = zip vs ks ++ [(i, k) | (i, (_, _, k)) <- its ]
iHKindStar env t
htCheckEnv :: [(HSymbol, ([HSymbol], HType, a))] -> Either String [(HSymbol, ([HSymbol], HType, HKind))]
htCheckEnv its =
let graph = [ (n, i, getHTCons t) | n@(i, (_, t, _)) <- its ]
order = stronglyConnComp graph
in case [ c | CyclicSCC c <- order ] of
c : _ -> Left $ "Recursive types are not allowed: " ++ unwords [ i | (i, _) <- c ]
[] -> flip evalStateT initState $ addKinds
where addKinds = do
env <- inferHKinds [] $ map (\ (AcyclicSCC n) -> n) order
let getK i = maybe (error $ "htCheck " ++ i) id $ lookup i env
return [ (i, (vs, t, getK i)) | (i, (vs, t, _)) <- its ]
inferHKinds :: KEnv -> [(HSymbol, ([HSymbol], HType, a))] -> M KEnv
inferHKinds env [] = return env
inferHKinds env ((i, (vs, t, _)) : its) = do
k <- inferHKind env vs t
inferHKinds ((i, k) : env) its
inferHKind :: KEnv -> [HSymbol] -> HType -> M HKind
inferHKind _ _ (HTAbstract _ k) = return k
inferHKind env vs t = do
clearState
ks <- mapM (const newKVar) vs
let env' = zip vs ks ++ env
k <- iHKind env' t
ground $ foldr KArrow k ks
iHKind :: KEnv -> HType -> M HKind
iHKind env (HTApp f a) = do
kf <- iHKind env f
ka <- iHKind env a
r <- newKVar
unifyK (KArrow ka r) kf
return r
iHKind env (HTVar v) = do
getVarHKind env v
iHKind env (HTCon c) = do
getConHKind env c
iHKind env (HTTuple ts) = do
mapM_ (iHKindStar env) ts
return KStar
iHKind env (HTArrow f a) = do
iHKindStar env f
iHKindStar env a
return KStar
iHKind env (HTUnion cs) = do
mapM_ (\ (_, ts) -> mapM_ (iHKindStar env) ts) cs
return KStar
iHKind _ (HTAbstract _ _) = error "iHKind HTAbstract"
iHKindStar :: KEnv -> HType -> M ()
iHKindStar env t = do
k <- iHKind env t
unifyK k KStar
unifyK :: HKind -> HKind -> M ()
unifyK k1 k2 = do
let follow k@(KVar i) = getVar i >>= return . maybe k id
follow k = return k
unify KStar KStar = return ()
unify (KArrow k11 k12) (KArrow k21 k22) = do unifyK k11 k21; unifyK k12 k22
unify (KVar i1) (KVar i2) | i1 == i2 = return ()
unify (KVar i) k = do occurs i k; addMap i k
unify k (KVar i) = do occurs i k; addMap i k
unify _ _ = lift $ Left $ "kind error: " ++ show (k1, k2)
occurs _ KStar = return ()
occurs i (KArrow f a) = do follow f >>= occurs i; follow a >>= occurs i
occurs i (KVar i') = if i == i' then lift $ Left "cyclic kind" else return ()
k1' <- follow k1
k2' <- follow k2
unify k1' k2'
getVarHKind :: KEnv -> HSymbol -> M HKind
getVarHKind env v =
case lookup v env of
Just k -> return k
Nothing -> lift $ Left $ "Undefined type variable " ++ v
getConHKind :: KEnv -> HSymbol -> M HKind
getConHKind env v =
case lookup v env of
Just k -> return k
Nothing -> lift $ Left $ "Undefined type " ++ v
ground :: HKind -> M HKind
ground KStar = return KStar
ground (KArrow k1 k2) = liftM2 KArrow (ground k1) (ground k2)
ground (KVar i) = do
mk <- getVar i
case mk of
Just k -> return k
Nothing -> return KStar
getHTCons :: HType -> [HSymbol]
getHTCons (HTApp f a) = getHTCons f `union` getHTCons a
getHTCons (HTVar _) = []
getHTCons (HTCon s) = [s]
getHTCons (HTTuple ts) = foldr union [] (map getHTCons ts)
getHTCons (HTArrow f a) = getHTCons f `union` getHTCons a
getHTCons (HTUnion alts) = foldr union [] [ getHTCons t | (_, ts) <- alts, t <- ts ]
getHTCons (HTAbstract _ _) = []
|
augustss/djinn
|
src/HCheck.hs
|
bsd-3-clause
| 4,754
| 0
| 21
| 1,323
| 2,264
| 1,136
| 1,128
| 127
| 10
|
{- |
Module : $EmptyHeader$
Description : <optional short description entry>
Copyright : (c) <Authors or Affiliations>
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <email>
Stability : unstable | experimental | provisional | stable | frozen
Portability : portable | non-portable (<reason>)
<optional description>
-}
module SegExamples where
import ModalLogic
import CombLogic
import GenericSequent
-- example Segala
test1 = And (At (K (And (At (KD (At (K T)))) F))) (And (And F (At (K F))) F)
test2 = At (K T)
test3 = At (KD F)
test4 = And (At (K T)) (At (K (And F (At (G 2 T))))) -- []T/\[](F/\[2]T)
|
mariefarrell/Hets
|
GMP/SegExamples.hs
|
gpl-2.0
| 638
| 0
| 19
| 131
| 182
| 95
| 87
| 8
| 1
|
smallest :: Integer -> Integer
smallest n
| modOfTen == n = n
| otherwise = modOfTen `min` greatest quotOfTen
where modOfTen = mod n 10
quotOfTen = quot n 10
|
OpenGenus/cosmos
|
code/mathematical_algorithms/src/smallest_digit_in_number/smallest_digit_in_number.hs
|
gpl-3.0
| 176
| 1
| 8
| 49
| 60
| 29
| 31
| -1
| -1
|
module A2 where
import C2
import D2 hiding (anotherFun)
main xs = sumSquares xs + anotherFun xs
|
mpickering/HaRe
|
old/testing/duplication/A2_TokOut.hs
|
bsd-3-clause
| 112
| 0
| 6
| 33
| 34
| 19
| 15
| 4
| 1
|
{-# LANGUAGE TemplateHaskell #-}
module T5737 where
import Language.Haskell.TH
makeAlpha n = [d| data Alpha = Alpha $(conT n) deriving (Show, Read) |]
|
urbanslug/ghc
|
testsuite/tests/th/T5737.hs
|
bsd-3-clause
| 159
| 0
| 5
| 31
| 23
| 16
| 7
| 4
| 1
|
{-# LANGUAGE DeriveFunctor, DatatypeContexts #-}
module ShouldFail where
-- Derive Functor on a type that uses 'a' in the wrong places
newtype InFunctionArgument a = InFunctionArgument (a -> Int)
deriving (Functor)
newtype OnSecondArg a = OnSecondArg (Either a a)
deriving (Functor)
-- Derive Functor on a type with no arguments
newtype NoArguments = NoArguments Int
deriving (Functor)
-- Derive Functor on a type with extra stupid-contraints on 'a'
data Eq a => StupidConstraint a = StupidType a
deriving (Functor)
-- A missing Functor instance
data NoFunctor a = NoFunctor
data UseNoFunctor a = UseNoFunctor (NoFunctor a)
deriving (Functor)
|
urbanslug/ghc
|
testsuite/tests/deriving/should_fail/drvfail-functor2.hs
|
bsd-3-clause
| 667
| 0
| 8
| 122
| 126
| 76
| 50
| 13
| 0
|
module Main where
import Control.Monad
import Blaze.ByteString.Builder
import qualified Data.ByteString as BS
import Records
import Text.Hastache
import Text.Hastache.Context
main :: IO ()
main = void $ sequence $ replicate 10000 $ toByteStringIO BS.putStr =<<
hastacheFileBuilder defaultConfig "toplevel.mustache"
(mkGenericContext (TopLevel {
thing = 12,
subs = [
SubLevel {
thing2 = False,
other = Just "w00t!"
},
SubLevel {
thing2 = True,
other = Nothing
}
]
}))
|
singpolyma/mustache2hs
|
benchmark/bench2.hs
|
isc
| 508
| 28
| 15
| 108
| 171
| 98
| 73
| 19
| 1
|
-- |
-- Module : HGE2D.Settings
-- Copyright : (c) 2016 Martin Buck
-- License : see LICENSE
--
-- Containing global settings used by the engine
module HGE2D.Settings where
---TODO define via class?
---TODO unused?
-- | Number of faces a circle should be created with
nFacesCircle :: Int
nFacesCircle = 100
|
I3ck/HGE2D
|
src/HGE2D/Settings.hs
|
mit
| 324
| 0
| 4
| 70
| 25
| 19
| 6
| 3
| 1
|
module Text.Gps (encode, decode) where
-- TODO: previous-line info encoding with whitespaces
-- *Main Data.Char> [x|x<-['\0'..'\995000'], isSpace x]
-- "\t\n\v\f\r \160\5760\8192\8193\8194\8195\8196\8197\8198\8199\8200\8201\8202\8239\8287\12288"
-- http://en.wikipedia.org/wiki/Whitespace_character
import Data.List (elemIndex)
encode :: String -> String
encode = go (0 :: Int, 0 :: Int)
where go (l, c) [] = line l . column c $ []
go (l, c) ('\n' : tail) = '\n' : (line l . column c $ go (l + 1, 0) tail)
go (l, c) (h : tail) | h < '\5760' = h : go (l, c + 1) tail
column c = (colMark:) . encodeNat c
line l = (lineMark:) . encodeNat l
colMark = '\12288'
lineMark = '\8287'
encodeNat :: Int -> String -> String
encodeNat 0 = id
encodeNat n | (more, rest) <- n `quotRem` divisor
= ((alphabet!!rest):) . encodeNat more
decodeNat :: String -> Int
decodeNat (head : tail) | Just digit <- head `elemIndex` alphabet = digit + divisor * decodeNat tail
decodeNat _ = 0
decodeNat' :: String -> (Int, String)
decodeNat' (head : tail) | Just digit <- head `elemIndex` alphabet = (digit + divisor * decTail, rest)
where (decTail, rest) = decodeNat' tail
decodeNat' rest = (0, rest)
alphabet = "\5760\8192\8193\8194\8195\8196\8197\8198\8199\8200\8201\8202\8239"
divisor = length alphabet
decode :: String -> (Int, Int)
decode = go 0
where go c ('\8287' : rest) = let (l, '\12288' : rest') = decodeNat' rest in (l, decodeNat rest' + c)
go c ('\n' : rest) = let (l', c') = go 0 rest in (l', c' + c)
go c (_ : rest) = go (pred c) rest
|
ggreif/text-gps
|
Text/Gps.hs
|
mit
| 1,617
| 0
| 12
| 363
| 648
| 346
| 302
| 29
| 3
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Database.Couch.Explicit.Internal
Description : Parameterized document-oriented requests to CouchDB
Copyright : Copyright (c) 2015, Michael Alan Dorman
License : MIT
Maintainer : mdorman@jaunder.io
Stability : experimental
Portability : POSIX
This module is not intended to be used directly---it is used to construct a number of otherwise-similar modules, where the modules are primarily concerned with the existence (or not) of a path prefix for documents.
The functions here are effectively derived from (and presented in the same order as) the <http://docs.couchdb.org/en/1.6.1/api/document/common.html Document API documentation>, though we don't link back to the specific functions here, since they're not meant for direct use.
Each function takes a 'Database.Couch.Types.Context'---which, among other things, holds the name of the database---as its final parameter, and returns a 'Database.Couch.Types.Result'.
-}
module Database.Couch.Explicit.DocBase where
import Control.Monad (return, unless)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Except (throwE)
import Data.Aeson (FromJSON, ToJSON,
Value (Null, Number, String),
object)
import Data.ByteString (ByteString, null)
import Data.Function (($), (.))
import Data.Maybe (Maybe, maybe)
import Data.Monoid ((<>))
import Database.Couch.Internal (standardRequest,
structureRequest)
import Database.Couch.RequestBuilder (RequestBuilder, addPath,
selectDb, selectDoc, setHeaders,
setJsonBody, setMethod,
setQueryParam)
import Database.Couch.ResponseParser (checkStatusCode,
getContentLength, getDocRev,
responseStatus, responseValue,
toOutputType)
import Database.Couch.Types (Context, DocId, DocRev,
Error (Unknown), ModifyDoc,
Result, RetrieveDoc, reqDocId,
reqDocRev, toHTTPHeaders,
toQueryParameters, unwrapDocRev)
import GHC.Num (fromInteger)
import Network.HTTP.Types (statusCode)
{- | Get the size and revision of the specified document
The return value is an object that should only contain the keys "rev" and "size", that can be easily parsed into a pair of (DocRev, Int):
>>> (,) <$> (getKey "rev" >>= toOutputType) <*> (getKey "size" >>= toOutputType)
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
meta :: (FromJSON a, MonadIO m)
=> ByteString -- ^ The prefix to use for the document
-> RetrieveDoc -- ^ Parameters for document retrieval
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
meta prefix param doc rev =
structureRequest request parse
where
request = do
setMethod "HEAD"
accessBase prefix doc rev
setQueryParam $ toQueryParameters param
parse = do
-- Do our standard status code checks
checkStatusCode
-- And then handle 304 appropriately
s <- responseStatus
docRev <- getDocRev
contentLength <- getContentLength
case statusCode s of
200 -> toOutputType $ object [("rev", String $ unwrapDocRev docRev), ("size", Number $ fromInteger contentLength)]
304 -> toOutputType Null
_ -> throwE Unknown
{- | Get the specified document
The return value is an object whose fields often vary, so it is most easily decoded as a 'Data.Aeson.Value':
>>> value :: Result Value <- DocBase.get "prefix" "pandas" Nothing ctx
If the specified DocRev matches, returns a JSON Null, otherwise a JSON value for the document.
Status: __Complete__ -}
get :: (FromJSON a, MonadIO m)
=> ByteString -- ^ A prefix for the document ID
-> RetrieveDoc -- ^ Parameters for document retrieval
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
get prefix param doc rev =
structureRequest request parse
where
request = do
accessBase prefix doc rev
setQueryParam $ toQueryParameters param
parse = do
-- Do our standard status code checks
checkStatusCode
-- And then handle 304 appropriately
s <- responseStatus
v <- responseValue
case statusCode s of
200 -> toOutputType v
304 -> toOutputType Null
_ -> throwE Unknown
{- | Create or replace the specified document
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.put "prefix" modifyDoc "pandas" Nothing SomeValue ctx >>= asBool
Status: __Complete__ -}
put :: (FromJSON a, MonadIO m, ToJSON b)
=> ByteString -- ^ A prefix for the document ID
-> ModifyDoc -- ^ The parameters for modifying the document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> b -- ^ The document
-> Context
-> m (Result a)
put prefix param docid rev doc =
standardRequest request
where
request = do
setMethod "PUT"
modBase prefix param docid rev
setJsonBody doc
{- | Delete the specified document
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.delete "prefix" modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
delete :: (FromJSON a, MonadIO m)
=> ByteString -- ^ A prefix for the document ID
-> ModifyDoc -- ^ The parameters for modifying the document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> Context
-> m (Result a)
delete prefix param docid rev =
standardRequest request
where
request = do
setMethod "DELETE"
modBase prefix param docid rev
{- | Copy the specified document
The return value is an object that can hold "id" and "rev" keys, but if you don't need those values, it is easily decoded into a 'Data.Bool.Bool' with our 'asBool' combinator:
>>> value :: Result Bool <- DocBase.delete "prefix" modifyDoc "pandas" Nothing ctx >>= asBool
Status: __Complete__ -}
copy :: (FromJSON a, MonadIO m)
=> ByteString -- ^ A prefix for the document ID
-> ModifyDoc -- ^ The parameters for modifying the document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> DocId -- ^ The destination document ID
-> Context
-> m (Result a)
copy prefix param source rev dest =
standardRequest request
where
request = do
setMethod "COPY"
modBase prefix param source rev
setHeaders [("Destination", destination)]
destination =
if null prefix
then reqDocId dest
else prefix <> "/" <> reqDocId dest
-- * Internal combinators
-- | Construct a path in a consistent fashion
docPath :: ByteString -- ^ A prefix for the document ID
-> DocId -- ^ The document ID
-> RequestBuilder ()
docPath prefix docid = do
selectDb
unless (null prefix) $
addPath prefix
selectDoc docid
-- | All retrievals want to allow 304s
accessBase :: ByteString -- ^ A prefix for the document ID
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> RequestBuilder ()
accessBase prefix docid rev = do
docPath prefix docid
maybe (return ()) (setHeaders . return . ("If-None-Match" ,) . reqDocRev) rev
-- | All modifications want to allow conflict recognition and parameters
modBase :: ByteString -- ^ A prefix for the document ID
-> ModifyDoc -- ^ The parameters for modifying the document
-> DocId -- ^ The document ID
-> Maybe DocRev -- ^ An optional document revision
-> RequestBuilder ()
modBase prefix param docid rev = do
docPath prefix docid
maybe (return ()) (setHeaders . return . ("If-Match" ,) . reqDocRev) rev
setHeaders $ toHTTPHeaders param
setQueryParam $ toQueryParameters param
|
mdorman/couch-simple
|
src/lib/Database/Couch/Explicit/DocBase.hs
|
mit
| 9,034
| 0
| 17
| 2,677
| 1,276
| 681
| 595
| 142
| 3
|
{-# LANGUAGE TemplateHaskell #-}
module Chimera.Engine.Core.Menu where
import FreeGame
import Control.Lens
import Data.Default
import qualified Data.Vector as V
import qualified Data.Map as M
import qualified Data.Foldable as F
import Chimera.State
data Item m = Item {
_caption :: String,
_exec :: m ()
}
makeLenses ''Item
data Select m = Select {
_items :: V.Vector (Item m),
_pointing :: Int
}
makeLenses ''Select
instance Default (Select m) where
def = Select {
_items = V.empty,
_pointing = 0
}
selectloop :: Font -> StateT (Select m) Game (Maybe (m ()))
selectloop font = do
its <- use items
let write y = translate (V2 100 (200+y)) . color white . text font 20
mapM_ (\i -> write (fromIntegral (i+1)*30) $ (its V.! i)^.caption) [0..V.length its-1]
use pointing >>= \p ->
translate (V2 70 (200+fromIntegral (p+1)*30)) . color white . text font 20 $ "|>"
keyDown KeyDown >>= \k -> when k $ pointing += 1
keyDown KeyUp >>= \k -> when k $ pointing -= 1
use pointing >>= \p -> do
when (p < 0) $ pointing .= 0
when (p > V.length its - 1) $ pointing .= (V.length its - 1)
keyChar 'Z' >>= \z ->
case z of
True -> return $ Just $ its V.! p ^. exec
False -> return Nothing
type MapInfo = M.Map String (Vec2, M.Map Key String)
data SelectMap = SelectMap {
_mapinfo :: MapInfo,
_pointing2 :: (String, Vec2)
}
makeLenses ''SelectMap
posloop :: Font -> [String] -> StateT SelectMap Game (Maybe String)
posloop font keys = do
(s,p) <- use pointing2
m <- use mapinfo
forM_ (wires s m) $ \(x,y) ->
color white . thickness 2 . line $ [x,y]
translate (p + 2) . color (Color 0.4 0.4 0.4 0.7) . text font 20 $ s
translate p . color white . text font 20 $ s
let keyMap = snd $ m M.! s
forM_ [KeyUp, KeyRight, KeyDown, KeyLeft] $ \k ->
keyDown k >>= \b -> when b $ case k `M.lookup` keyMap of
Just u -> when (u `elem` keys) $ pointing2 .= (u, fst $ m M.! u)
Nothing -> return ()
keyDown (charToKey 'Z') >>= \z -> case z of
True -> (Just . fst) `fmap` use pointing2
False -> return Nothing
where
wires :: String -> MapInfo -> [(Vec2, Vec2)]
wires s m = let (p,ps) = m M.! s in
F.toList $ fmap ((,) p . fst . (m M.!)) $ ps
|
myuon/Chimera
|
Chimera/Engine/Core/Menu.hs
|
mit
| 2,286
| 0
| 20
| 592
| 1,111
| 568
| 543
| 61
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Action (runAction, mkEnv, add, query, list, edit, dump) where
import Prelude hiding (putStrLn, putStr)
import Control.Monad (replicateM_, unless)
import Control.Monad.Trans.Reader
import Control.Monad.IO.Class (liftIO)
import System.IO (hPutStr, hClose)
import qualified System.IO as IO
import Control.DeepSeq (deepseq)
import Text.Printf
import Data.Foldable (forM_)
import Util (nameFromUrl, run, withTempFile, match_)
import Database (Database, Entry(..))
import qualified Database
import Cipher (Cipher)
import qualified Cipher
import Config (Config)
import qualified Config
newtype ActionM a = ActionM (ReaderT Env IO a)
deriving (Functor, Applicative, Monad)
runAction :: Env -> ActionM a -> IO a
runAction env (ActionM a) = runReaderT a env
data Env = Env {
envConfig :: Config
, envCipher :: Cipher
, envHandle :: IO.Handle
}
mkEnv :: Config -> Cipher -> IO.Handle -> Env
mkEnv conf cipher h = Env {
envConfig = conf
, envCipher = cipher
, envHandle = h
}
liftAction :: (Env -> IO a) -> ActionM a
liftAction action = ActionM $ do
env <- ask
liftIO $ action env
liftAction1 :: (Env -> b -> IO a) -> b -> ActionM a
liftAction1 action x = ActionM $ do
env <- ask
liftIO $ action env x
putStrLn :: String -> ActionM ()
putStrLn = liftAction1 (IO.hPutStrLn . envHandle)
putStr :: String -> ActionM ()
putStr = liftAction1 (IO.hPutStr . envHandle)
copyToClipboard :: String -> ActionM ()
copyToClipboard = liftAction1 (Config.copyToClipboard . envConfig)
encrypt :: String -> ActionM ()
encrypt = liftAction1 $ \Env{envCipher = c} -> Cipher.encrypt c
decrypt :: ActionM String
decrypt = liftAction $ \Env{envCipher = c} -> Cipher.decrypt c
openDatabase :: ActionM Database
openDatabase = Database.parse `fmap` decrypt
saveDatabase :: Database -> ActionM ()
saveDatabase = encrypt . Database.render
add :: String -> Maybe String -> ActionM ()
add url_ mUser = do
user <- maybe genUser return mUser
password_ <- genPassword
addEntry $ Entry {entryName = nameFromUrl url_, entryUser = Just user, entryPassword = Just password_, entryUrl = Just url_}
copyToClipboard user
copyToClipboard password_
copyToClipboard password_
where
genPassword = liftAction (Config.generatePassword . envConfig)
genUser = liftAction (Config.generateUser . envConfig)
addEntry entry =
-- An Entry may have pending exceptions (e.g. invalid URL), so we force
-- them with `deepseq` before we read the database. This way the user
-- gets an error before he has to enter his password.
entry `deepseq` do
db <- openDatabase
case Database.addEntry db entry of
Left err -> error err
Right db_ -> saveDatabase db_
query :: String -> Int -> Bool -> ActionM ()
query kw n passwordOnly = do
db <- openDatabase
case Database.lookupEntry db kw of
Left err -> putStrLn err
Right x -> x `deepseq` do -- force pending exceptions early..
unless passwordOnly $ do
forM_ (entryUrl x) $ \url -> do
putStrLn url
open url
forM_ (entryUser x)
copyToClipboard
forM_ (entryPassword x) $
replicateM_ n . copyToClipboard
where
open = liftAction1 (Config.openUrl . envConfig)
list :: Maybe String -> ActionM ()
list mPattern = do
db <- openDatabase
let names = Database.entryNames db
mapM_ (putStrLn . printf " %s") $ maybe names (flip match_ names) mPattern
edit :: Cipher -> IO ()
edit c = withTempFile $ \fn h -> do
IO.putStrLn $ "using temporary file: " ++ fn
Cipher.decrypt c >>= hPutStr h >> hClose h
run "vim" ["-n", "-i", "NONE", "-c", "set nobackup", "-c", "set ft=dosini", fn]
readFile fn >>= Cipher.encrypt c
run "shred" [fn]
dump :: ActionM ()
dump = decrypt >>= putStr
|
sol/pwsafe
|
src/Action.hs
|
mit
| 3,931
| 0
| 20
| 917
| 1,284
| 666
| 618
| 98
| 2
|
{-# LANGUAGE CPP #-}
module Main where
import qualified FizzBuzz as FB
import qualified Arith as Ar
import qualified Cipher as Ci
import qualified CP
import Test.HUnit hiding ( Test )
import Test.Framework ( defaultMain, testGroup, Test )
import Test.Framework.Providers.HUnit
import GHC.IO.Handle ( hDuplicate, hDuplicateTo )
import System.IO
import System.Directory ( getTemporaryDirectory )
import System.FilePath ( (</>) )
import System.Console.CmdTheLine ( unwrap, unwrapChoice, EvalExit )
import Control.Applicative ( (<$>) )
isRight, isLeft :: Either a b -> Bool
isRight (Right _) = True
isRight (Left _) = False
isLeft (Left _) = True
isLeft (Right _) = False
devNull :: String
#if defined(mingw_32_HOST_OS) || defined(__MINGW32__)
devNull = "nul"
#else
devNull = "/dev/null"
#endif
mute :: IO a -> IO a
mute action = do
withFile devNull WriteMode $ (\ h -> do
stdout_bak <- hDuplicate stdout
hDuplicateTo h stdout
v <- action
hDuplicateTo stdout_bak stdout
return v)
withInput :: [String] -> IO a -> IO a
withInput input action = do
tmpDir <- getTemporaryDirectory
withFile (tmpDir </> "cmdtheline_test_input") ReadWriteMode (\ h -> do
stdin_bak <- hDuplicate stdin
hDuplicateTo h stdin
mapM_ (hPutStrLn stdin) input
v <- action
hDuplicateTo stdin_bak stdin
return v)
unwrapFB, unwrapAr, unwrapCP, unwrapCi :: [String] -> IO (Either EvalExit (IO ()))
unwrapFB args = mute $ unwrap args ( FB.term, FB.termInfo )
unwrapAr args = mute $ unwrap args ( Ar.arithTerm, Ar.termInfo )
unwrapCP args = mute $ unwrap args ( CP.term, CP.termInfo )
unwrapCi args = mute $
unwrapChoice args Ci.defaultTerm [ Ci.rotTerm, Ci.morseTerm ]
tests :: [Test]
tests =
-- With FizzBuzz we'll test the different forms of option assignment and
-- flags.
[ testGroup "FizzBuzz"
[ testCase "w/o args" . assert $ isRight <$> unwrapFB []
, testCase "w/ good args" . assert $
isRight <$> unwrapFB [ "-q", "-s", "-v"
, "-f", "bob", "--buzz", "ann", "-t20"
]
, testCase "w/ bad args" . assert $ isLeft <$> unwrapFB [ "-zork" ]
]
-- With arith we'll test 'posRight' 'pos' positional argument partitioning.
, testGroup "arith"
[ testCase "w/o args" . assert $ isLeft <$> unwrapAr []
, testCase "w/ good args many" . assert $
isRight <$> unwrapAr [ "x^2+y*1", "x=2", "y=(11-1)/5" ]
, testCase "w/ good args one" . assert $
isRight <$> unwrapAr [ "x^2", "x=2" ]
, testCase "w/ bad args" . assert $
isLeft <$> unwrapAr [ "-pretty", "x^2", "x=2" ]
]
-- With cipher we'll test subcommands.
, testGroup "cipher"
[ testCase "w/o args" . assert $ isLeft <$> unwrapCi []
, testCase "morse" . assert $
isRight <$> withInput ["bob"] (unwrapCi [ "morse" ])
, testCase "rot" . assert $
isRight <$> withInput ["bob"] (unwrapCi [ "rot" ])
]
-- With cp we'll test 'revPosLeft' 'revPos' positional argument partitioning.
, testGroup "cp"
[ testCase "w/o args" . assert $ isLeft <$> unwrapCP []
, testCase "w/ good args many" . assert $
isRight <$> unwrapCP [ "-d", "cmdtheline.cabal", "LICENSE", "test" ]
, testCase "w/ good args one" . assert $
isRight <$> unwrapCP [ "-d", "cmdtheline.cabal", "foo" ]
]
]
main :: IO ()
main = defaultMain tests
|
MerelyAPseudonym/cmdtheline
|
test/Main.hs
|
mit
| 3,375
| 0
| 14
| 783
| 1,013
| 540
| 473
| 76
| 1
|
module Main where
import Board
import Control.Exception
import System.IO
takeTurn :: Board -> Marker -> IO Board
takeTurn brd m = do
putStr $ show m ++ "'s turn [0-8]: "
sqr <- getLine
en <- try (evaluate (read sqr :: Int) ) :: IO (Either SomeException Int)
case en of
Left _ -> takeTurn brd m
Right n -> if n >= 0 && n < 9 then
case mkMove brd m n of
Just brd' -> return brd'
Nothing -> takeTurn brd m
else takeTurn brd m
runGame :: Board -> IO ()
runGame brd = do
--X turn:
brd <- takeTurn brd X
if gameWon brd then
do print brd
putStrLn "X wins."
else do --O takes turn:
print brd
case noMoves brd of
True -> putStrLn "Mew."
False -> do
brd <- takeTurn brd O
if gameWon brd then
do print brd
putStrLn "O wins."
else do print brd
runGame brd
playAgain :: IO ()
playAgain = do
putStr "Play again? [y/n]: "
answer <- getLine
case answer of
"n" -> return ()
"y" -> main
_ -> playAgain
main :: IO ()
main = do
--Turn off buffering:
hSetBuffering stdout NoBuffering
--Run Game:
let brd = newBoard
print brd
runGame brd
--Play again?
playAgain
|
m0baxter/tic-tac-toe-hs
|
src/Main.hs
|
mit
| 1,366
| 0
| 18
| 535
| 443
| 205
| 238
| 48
| 4
|
{-|
Module : RaizSegGrau
Description : calculates the roots of a quadratic equation in Haskell
Copyright : (c) Fabrício Olivetti, 2017
License : GPL-3
Maintainer : fabricio.olivetti@gmail.com
The application of Baskhara
-}
module Main where
-- |'raizSegGrau' calculates the
-- real roots of a quadratic equation
raizSegGrau :: Double -> Double -> Double -> (Double, Double)
raizSegGrau a b c
| delta < 0 = error "Raízes negativas!"
| delta == 0 = (x1, x1) -- don't need to calc x2
| otherwise = (x1, x2)
where
x1 = (-b - sqrt delta) / (2*a)
x2 = (-b + sqrt delta) / (2*a)
delta = b**2 - 4*a*c
-- |'main' executa programa principal
main :: IO ()
main = do
print (raizSegGrau 2 4 1)
print (raizSegGrau 4 (-2) 1)
|
folivetti/BIGDATA
|
02 - Básico/RaizSegGrau.hs
|
mit
| 771
| 3
| 15
| 177
| 228
| 117
| 111
| 13
| 1
|
{-- Author: Manoel Vilela --}
import Data.Char (chr, ord)
import Data.Bits (xor)
parseFile :: String -> [Int]
parseFile s = read ("[" ++ s ++ "]")
passwords :: [[Int]]
passwords = [map ord [a,b,c] | a <- ['a'..'z'],
b <- ['a'..'z'],
c <- ['a'..'z']]
applyKey :: [Int] -> [Int] -> [Int]
applyKey content pass = [ x `xor` y | (x,y) <- pairs]
where pairs = zip content $ concat $ repeat pass
checkIt :: [Int] -> Bool
checkIt = all commonAscii
where commonAscii x = x `elem` asciiNumbers ++ asciiPunct
|| asciiLower x || asciiUpper x
asciiNumbers = [48..57]
asciiPunct = [32,33,34,39,40,41,44,45,46,58,59]
asciiLower x = x >= 97 && x <= 122
asciiUpper x = x >= 65 && x <= 90
decrypt :: [Int] -> [Int]
decrypt codes = head [decrypted | pass <- passwords,
let decrypted = applyKey codes pass,
checkIt decrypted]
main = do content <- readFile "../p059_cipher.txt"
print $ sum $ decrypt $ parseFile (head (lines content))
|
DestructHub/ProjectEuler
|
Problem059/Haskell/solution_1.hs
|
mit
| 1,112
| 0
| 12
| 360
| 453
| 246
| 207
| 25
| 1
|
module Y2016.M06.D14.Solution where
import Control.Arrow ((&&&))
import Data.Array (listArray, elems)
import Data.Matrix
{-- Inverting a matrix ... because we can!
We'll use the minors/cofactors/adjugate(transpose) method described here:
https://www.mathsisfun.com/algebra/matrix-inverse-minors-cofactors-adjugate.html
Whatever approach you choose it must be that:
(inverse a) `cross` a = identityMatrix
and
a `cross` (inverse a) = identityMatrix
So, let's get to it:
--}
minors :: Matrix a -> [[Matrix a]]
minors = uncurry map . (excludedSubMatrices &&& enumFromTo 1 . fst . snd . dims)
{-- So the minor of a is: fromLists (map (map determinant) (minors a))
*Y2016.M06.D14.Solution> pprint (fromLists (map (map determinant) (minors a)))
Matrix 3x3
| -2.0 4.0 2.0 |
| 1.0 4.0 1.0 |
| 1.0 -4.0 -3.0 |
Now we cofactors the minor:
--}
cofactors :: Num a => Matrix a -> Matrix a
cofactors mat =
M . listArray (dims mat)
. zipWith (*) (cycle [1,-1])
. elems $ matrix mat
{--
*Y2016.M06.D14.Solution> pprint (cofactors (fromLists (map (map determinant) (minors a))))
Matrix 3x3
| -2.0 -4.0 2.0 |
| -1.0 4.0 -1.0 |
| 1.0 4.0 -3.0 |
And now we just transpose that and multiply it by 1/det of the original matrix
to compute the inverse matrix:
--}
scalar :: Num a => a -> Matrix a -> Matrix a
scalar n mat = M . listArray (dims mat) . map (* n) . elems $ matrix mat
inverse :: RealFrac a => Matrix a -> Matrix a
inverse mat =
let det = determinant mat
comat = cofactors (fromLists (map (map determinant) (minors mat)))
in transpose ((1.0 / det) `scalar` comat)
{--
*Y2016.M06.D14.Solution> pprint (inverse a)
Matrix 3x3
| 0.5 0.25 -0.25 |
| 1.0 -1.0 -1.0 |
| -0.5 0.25 0.75 |
With the above defined, you can solve systems of equations, for, as you recall
AX = B
represents
A X B
--------------------------
| 2 1 2 | | x | | 3 |
| 1 -1 -1 | | y | = | 0 |
| 1 1 3 | | z | | 12 |
So:
X = (inverse A) `cross` B
So, given:
--}
a, b :: Matrix Float
a = fromLists [[2,1,2], [1, -1, -1], [1,1,3]]
b = transpose (fromLists [[3,0,12]]) -- note how b is defined
{--
Recall that you can 'view' matrices with pprint.
Now, set up the matrices and solve the below system of equations
x + z = 6
z - 3y = 7
2x + y + 3z = 15
with the below solver
--}
solver :: Matrix Float -> Matrix Float -> Matrix Float
solver a b = inverse a `cross` b
{--
*Y2016.M06.D14.Solution> pprint (solver a b)
Matrix 3x1
| -1.5 |
| -9.0 |
| 7.5 |
let's set up the second batch:
--}
c, d :: Matrix Float
c = fromLists [[1,0,1],[0,-3,1],[2,1,3]]
d = transpose $ fromLists [[6,7,15]]
{--
*Y2016.M06.D14.Solution> pprint (solver c d)
Matrix 3x1
| 2.0 |
| -1.0 |
| 4.0 |
which solves the systems of equations. YAY!
solver and inverse and its functions will be rolled into Data.Matrix
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2016/M06/D14/Solution.hs
|
mit
| 2,860
| 0
| 15
| 635
| 553
| 302
| 251
| -1
| -1
|
{-# LANGUAGE TypeOperators #-}
-- this listens on port 6000 and 6001.
import Control.Concurrent.Waitfree
import Network
import IO (Handle, hSetBuffering, BufferMode (NoBuffering), hPutStrLn, hGetLine, hPutStr)
handle :: PortID -> t -> IO Handle
handle p _ = withSocketsDo $ do
s <- listenOn p
(h,_,_) <- accept s
hSetBuffering h NoBuffering
return h
prepareHandle :: Thread t => PortID -> IO (K t Handle :*: HNil)
prepareHandle p = single $ handle p
readLine :: Thread t => t -> Handle -> IO ((Handle, String), String)
readLine th h = do
hPutStr h $ (show $ atid th) ++ " requiring input: "
str <- hGetLine h
return ((h, str), str)
readH :: Thread t => PortID -> IO (K t ((Handle, String), String) :*: HNil)
readH p = prepareHandle p >>= (readLine -*- return)
printTaken :: (Thread t) => t -> ((Handle, String), String) -> IO ThreadStatus
printTaken th ((h, selfs), peers) = do
hPutStrLn h $ "Thread " ++ (show $ atid th) ++ " got: " ++ show (selfs, peers)
return Finished
twoPrints :: HCons (K ZeroT ((Handle, String), String))
(HCons (K (SucT ZeroT) ((Handle, String), String)) HNil)
-> IO (HCons (K ZeroT ThreadStatus) (HCons (K (SucT ZeroT) ThreadStatus) HNil))
twoPrints = printTaken -*- printTaken -*- return
rerror :: Thread t => t -> (Handle, a) -> IO ThreadStatus
rerror th (h, _) = do
hPutStrLn h $ "Thread " ++ (show $ atid th) ++ " failed to read peer's input."
return Finished
content :: IO (K ZeroT ThreadStatus :*: (K (SucT ZeroT) ThreadStatus :*: HNil))
content =
comm (readH $ PortNumber 6000) rerror (readH $ PortNumber 6001) rerror >>= twoPrints
main :: IO ()
main = execute content
|
pirapira/waitfree
|
doc/sample/simple.hs
|
mit
| 1,694
| 0
| 14
| 375
| 721
| 372
| 349
| 36
| 1
|
{-# htermination compare :: Ord a => [a] -> [a] -> Ordering #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_compare_4.hs
|
mit
| 64
| 0
| 2
| 13
| 3
| 2
| 1
| 1
| 0
|
import Common
main = print $ product [ champernowne !! (10^x) | x <- [0..6] ]
champernowne = concat [ toDigits x | x <- [0..] ]
|
lekto/haskell
|
Project-Euler-Solutions/problem0040.hs
|
mit
| 130
| 0
| 10
| 29
| 68
| 36
| 32
| 3
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module WykopTypes where
import Control.Applicative ((<$>), (<*>), pure, empty)
import Control.Monad (mzero)
import Data.Aeson
import Data.Text (unpack)
import Data.Time (LocalTime(..))
import Data.Time.Format (parseTime)
import System.Locale (defaultTimeLocale)
import qualified Data.HashMap.Strict as H
import qualified Data.Vector as V
type PostData = [(String, String)]
type GetData = PostData
type URL = String
type Userkey = String
data Keys = Keys {
appKey :: String
, secretKey :: String
}
deriving (Show)
data Link = Link {
linkId :: Int
, linkTitle :: String
, linkDescription :: String
, linkTags :: String
, linkUrl :: URL
, linkSourceUrl :: URL
, linkVoteCount :: Int
, linkCommentCount :: Int
, linkReportCount :: Int
, linkRelatedCount :: Int
, linkDate :: LocalTime
, linkAuthor :: String
, linkAuthorAvatar :: URL
, linkAuthorAvatarBig :: URL
, linkAuthorAvatarMed :: URL
, linkAuthorAvatarLo :: URL
, linkAuthorGroup :: Int
, linkAuthorSex :: String
, linkPreview :: Maybe URL
, linkUserLists :: [Int]
, linkPlus18 :: Bool
, linkStatus :: Maybe String
, linkCanVote :: Bool
, linkHasOwnContent :: Bool
, linkCategory :: String
, linkUserVote :: Value -- false or "bury"
, linkUserObserve :: Maybe Bool
, linkUserFavorite :: Maybe Bool
, linkIsHot :: Bool
, linkGroup :: String
, linkType :: String
}
deriving (Show)
instance FromJSON LocalTime where
parseJSON (String v) =
case parseTime defaultTimeLocale "%F %T" (unpack v) of
Just time -> pure time
_ -> empty
parseJSON _ = mzero
instance FromJSON Link where
parseJSON (Object v) =
Link <$>
v .: "id" <*>
v .: "title" <*>
v .: "description" <*>
v .: "tags" <*>
v .: "url" <*>
v .: "source_url" <*>
v .: "vote_count" <*>
v .: "comment_count" <*>
v .: "report_count" <*>
v .: "related_count" <*>
v .: "date" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group" <*>
v .: "author_sex" <*>
v .:? "preview" <*>
(v .: "user_lists" >>= parseJSONArray) <*>
v .: "plus18" <*>
v .:? "status" <*>
v .: "can_vote" <*>
v .: "has_own_content" <*>
v .: "category" <*>
v .: "user_vote" <*>
v .:? "user_observe" <*>
v .:? "user_favorite" <*>
v .: "is_hot" <*>
v .: "group" <*>
v .: "type"
parseJSON _ = mzero
data Profile = Profile {
profLogin :: String
, profEmail :: String
, profPublicEmail :: String
, profName :: String
, profWWW :: URL
, profJabber :: String
, profGG :: String -- int in API
, profCity :: String
, profAbout :: String
, profAuthorGroup :: Int
, profLinksAdded :: Maybe Int
, profLinksPublished :: Maybe Int
, profComments :: Maybe Int
, profRank :: Maybe Int
, profFollowers :: Maybe Int
, profFollowing :: Maybe Int
, profEntries :: Maybe Int
, profDiggs :: Maybe Int
, profBuries :: Maybe Int -- int in API
, profGroups :: Maybe Int
, profAvatar :: URL
, profAvatarBig :: URL
, profAvatarMed :: URL
, profAvatarLo :: URL
, profIsObserved :: Maybe Bool
, profSex :: String -- undocumented
, profUserKey :: Maybe Userkey
}
deriving (Show)
instance FromJSON Profile where
parseJSON (Object v) =
Profile <$>
v .: "login" <*>
v .: "email" <*>
v .: "public_email" <*>
v .: "name" <*>
v .: "www" <*>
v .: "jabber" <*>
v .: "gg" <*>
v .: "city" <*>
v .: "about" <*>
v .: "author_group" <*>
v .:? "links_added" <*>
v .:? "links_published" <*>
v .:? "comments" <*>
v .:? "rank" <*>
v .:? "followers" <*>
v .:? "following" <*>
v .:? "entries" <*>
v .:? "diggs" <*>
v .:? "buries" <*>
v .:? "groups" <*>
v .: "avatar" <*>
v .: "avatar_big" <*>
v .: "avatar_med" <*>
v .: "avatar_lo" <*>
v .:? "is_observed" <*>
v .: "sex" <*>
v .:? "userkey"
parseJSON _ = mzero
data Comment = Comment {
commId :: Int
, commDate :: LocalTime
, commAuthor :: String
, commAuthorAvatar :: URL
, commAuthorAvatarBig :: URL
, commAuthorAvatarMed :: URL
, commAuthorAvatarLo :: URL
, commAuthorGroup :: Int
, commVoteCount :: Int
, commBody :: String
, commParentId :: Int
, commStatus :: Maybe String
, commEmbed :: Maybe Embed
, commAuthorSex :: String
, commVoteCountPlus :: Int
, commVoteCountMinus :: Maybe Int
, commSource :: Maybe String -- URL?
, commCanVote :: Bool
, commUserVote :: Maybe Bool
, commBlocked :: Bool
, commDeleted :: Bool
, commLink :: [Link]
}
deriving (Show)
instance FromJSON Comment where
parseJSON (Object v) =
Comment <$>
v .: "id" <*>
v .: "date" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group" <*>
v .: "vote_count" <*>
v .: "body" <*>
v .: "parent_id" <*>
v .:? "status" <*>
(v .:? "embed" >>= parseMaybeJSON) <*>
v .: "author_sex" <*>
v .: "vote_count_plus" <*>
v .:? "vote_count_minus" <*>
v .:? "source" <*>
v .: "can_vote" <*>
v .:? "user_vote" <*>
v .: "blocked" <*>
v .: "deleted" <*>
(v .: "link" >>= parseJSONArray)
parseJSON _ = mzero
data Bury = Bury {
buryReason :: Int
, buryAuthor :: String
, buryAuthorAvatar :: URL
, buryAuthorAvatarBig :: URL
, buryAuthorAvatarMed :: URL
, buryAuthorAvatarLo :: URL
, buryAuthorGroup :: Int
}
deriving (Show)
instance FromJSON Bury where
parseJSON (Object v) =
Bury <$>
v .: "reason" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group"
parseJSON _ = mzero
data Dig = Dig {
digAuthor :: String
, digAuthorAvatar :: URL
, digAuthorAvatarBig :: URL
, digAuthorAvatarMed :: URL
, digAuthorAvatarLo :: URL
, digAuthorGroup :: Int
}
deriving (Show)
instance FromJSON Dig where
parseJSON (Object v) =
Dig <$>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group"
parseJSON _ = mzero
data RelatedLink = RelatedLink {
relLinkId :: Int
, relLinkUrl :: URL
, relLinkTitle :: String
, relLinkVoteCount :: Int
, relLinkEntryCount :: Int
, relLinkUserVote :: Maybe Int
}
deriving (Show)
instance FromJSON RelatedLink where
parseJSON (Object v) =
RelatedLink <$>
v .: "id" <*>
v .: "url" <*>
v .: "title" <*>
v .: "vote_count" <*>
v .: "entry_count" <*>
v .:? "user_vote"
parseJSON _ = mzero
data Entry = Entry {
entryId :: Int
, entryAuthor :: String
, entryAuthorAvatar :: URL
, entryAuthorAvatarBig :: URL
, entryAuthorAvatarMed :: URL
, entryAuthorAvatarLo :: URL
, entryAuthorGroup :: Int
, entryDate :: LocalTime
, entryBody :: String
, entryUrl :: URL
, entryReceiver :: Maybe String
, entryReceiverAvatar :: Maybe URL
, entryReceiverAvatarBig :: Maybe URL
, entryReceiverAvatarMed :: Maybe URL
, entryReceiverAvatarLo :: Maybe URL
, entryReceiverGroup :: Maybe Int
, entryComments :: [EntryComment]
, entryVoteCount :: Int
, entryVoters :: [Dig]
, entryEmbed :: Maybe Embed
}
deriving (Show)
instance FromJSON Entry where
parseJSON (Object v) =
Entry <$>
v .: "id" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group" <*>
v .: "date" <*>
v .: "body" <*>
v .: "url" <*>
v .:? "receiver" <*>
v .:? "receiver_avatar" <*>
v .:? "receiver_avatar_big" <*>
v .:? "receiver_avatar_med" <*>
v .:? "receiver_avatar_lo" <*>
v .:? "receiver_group" <*>
(v .: "comments" >>= parseJSONArray) <*>
v .: "vote_count" <*>
(v .: "voters" >>= parseJSONArray) <*>
(v .:? "embed" >>= parseMaybeJSON)
parseJSON _ = mzero
--parseMaybeJSON :: (FromJSON a) => Maybe Value -> Parser (Maybe a)
parseMaybeJSON (Just x) = parseJSON x
parseMaybeJSON _ = pure Nothing
--parseJSONArray :: (FromJSON a) => Vector Value -> Parser [a]
parseJSONArray a = mapM parseJSON $ V.toList a
data EntryComment = EntryComment {
entryCommId :: Int
, entryCommAuthor :: String
, entryCommAuthorAvatar :: URL
, entryCommAuthorAvatarBig :: URL
, entryCommAuthorAvatarMed :: URL
, entryCommAuthorAvatarLo :: URL
, entryCommAuthorGroup :: Int
, entryCommDate :: LocalTime
, entryCommBody :: String
, entryCommVoteCount :: Int
, entryCommVoters :: [Dig]
, entryCommEmbed :: Maybe Embed
}
deriving (Show)
instance FromJSON EntryComment where
parseJSON (Object v) =
EntryComment <$>
v .: "id" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group" <*>
v .: "date" <*>
v .: "body" <*>
v .: "vote_count" <*>
(v .: "voters" >>= parseJSONArray) <*>
(v .:? "embed" >>= parseMaybeJSON)
parseJSON _ = mzero
data Notification = Notification {
notifId :: Int
, notifAuthor :: String
, notifAuthorAvatar :: URL
, notifAuthorAvatarBig :: URL
, notifAuthorAvatarMed :: URL
, notifAuthorAvatarLo :: URL
, notifAuthorGroup :: Int
, notifDate :: LocalTime
, notifBody :: String
, notifType :: String
, notifNew :: Bool
, notifUrl :: URL
, notifEntry :: Maybe NotifEntry
, notifLink :: Maybe Link
, notifComment :: Maybe WykopID
}
deriving (Show)
instance FromJSON Notification where
parseJSON (Object v) =
Notification <$>
v .: "id" <*>
v .: "author" <*>
v .: "author_avatar" <*>
v .: "author_avatar_big" <*>
v .: "author_avatar_med" <*>
v .: "author_avatar_lo" <*>
v .: "author_group" <*>
v .: "date" <*>
v .: "body" <*>
v .: "type" <*>
v .: "new" <*>
v .: "url" <*>
(v .:? "entry" >>= parseMaybeJSON) <*>
(v .:? "link" >>= parseMaybeJSON) <*>
(v .:? "comment" >>= parseMaybeJSON)
parseJSON _ = mzero
data NotifEntry = NotifEntry {
notEntId :: Int
, notEntBody :: String
, notEntUrl :: URL
}
deriving (Show)
instance FromJSON NotifEntry where
parseJSON (Object v) =
NotifEntry <$>
v .: "id" <*>
v .: "body" <*>
v .: "url"
data Embed = Embed {
embedType :: String
, embedPreview :: URL
, embedUrl :: URL
, embedSource :: URL
, embedPlus18 :: Bool
}
deriving (Show)
instance FromJSON Embed where
parseJSON (Object v) =
Embed <$>
v .: "type" <*>
v .: "preview" <*>
v .: "url" <*>
v .: "source" <*>
v .: "plus18"
parseJSON _ = mzero
data MyWykop = MyWykop {
myFeed :: [Either Link Entry]
}
deriving (Show)
instance FromJSON MyWykop where
parseJSON (Array v) =
MyWykop <$>
parseJSONArray v
parseJSON _ = mzero
instance FromJSON (Either Link Entry) where
parseJSON x@(Object v) =
case H.lookup "type" v of
Just "link" -> Left <$> parseJSON x
Just "entry" -> Right <$> parseJSON x
_ -> mzero
parseJSON _ = mzero
data WykopID = WykopID Int
deriving (Show)
instance FromJSON WykopID where
parseJSON (Object v) =
WykopID <$>
v .: "id"
parseJSON _ = mzero
|
mikusp/hwykop
|
WykopTypes.hs
|
mit
| 15,061
| 0
| 66
| 6,450
| 3,343
| 1,855
| 1,488
| 424
| 1
|
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit (testCase)
import Tests.Syntax
import Tests.Codegen
tests :: TestTree
tests = testGroup "Compiler tests"
[ testGroup "AST"
[ localOption (QuickCheckMaxSize 15) $
testProperty "roundtrip" roundtripAST
, testGroup "Compare .bond and .json"
[ testCase "attributes" $ compareAST "attributes"
, testCase "basic types" $ compareAST "basic_types"
, testCase "complex types" $ compareAST "complex_types"
, testCase "default values" $ compareAST "defaults"
, testCase "empty" $ compareAST "empty"
, testCase "field modifiers" $ compareAST "field_modifiers"
, testCase "generics" $ compareAST "generics"
, testCase "inheritance" $ compareAST "inheritance"
, testCase "type aliases" $ compareAST "aliases"
, testCase "documentation example" $ compareAST "example"
]
]
, testGroup "SchemaDef"
[ verifySchemaDef "attributes" "Foo"
, verifySchemaDef "basic_types" "BasicTypes"
, verifySchemaDef "defaults" "Foo"
, verifySchemaDef "field_modifiers" "Foo"
, verifySchemaDef "inheritance" "Foo"
, verifySchemaDef "alias_key" "foo"
, verifySchemaDef "maybe_blob" "Foo"
, verifySchemaDef "nullable_alias" "foo"
, verifySchemaDef "schemadef" "AliasBase"
, verifySchemaDef "schemadef" "EnumDefault"
, verifySchemaDef "schemadef" "StringTree"
, verifySchemaDef "example" "SomeStruct"
]
, testGroup "Types"
[ testCase "type alias resolution" aliasResolution
]
, testGroup "Codegen"
[ testGroup "C++"
[ verifyCppCodegen "attributes"
, verifyCppCodegen "basic_types"
, verifyCppCodegen "complex_types"
, verifyCppCodegen "defaults"
, verifyCppCodegen "empty"
, verifyCppCodegen "field_modifiers"
, verifyCppCodegen "generics"
, verifyCppCodegen "inheritance"
, verifyCppCodegen "aliases"
, verifyCppCodegen "alias_key"
, verifyCppCodegen "maybe_blob"
, verifyCodegen
[ "c++"
, "--allocator=arena"
]
"alias_with_allocator"
, verifyCodegen
[ "c++"
, "--allocator=arena"
, "--using=List=my::list<{0}, arena>"
, "--using=Vector=my::vector<{0}, arena>"
, "--using=Set=my::set<{0}, arena>"
, "--using=Map=my::map<{0}, {1}, arena>"
, "--using=String=my::string<arena>"
]
"custom_alias_with_allocator"
, verifyCodegen
[ "c++"
, "--allocator=arena"
, "--using=List=my::list<{0}>"
, "--using=Vector=my::vector<{0}>"
, "--using=Set=my::set<{0}>"
, "--using=Map=my::map<{0}, {1}>"
, "--using=String=my::string"
]
"custom_alias_without_allocator"
, verifyApplyCodegen
[ "c++"
, "--apply-attribute=DllExport"
]
"basic_types"
]
, testGroup "C#"
[ verifyCsCodegen "attributes"
, verifyCsCodegen "basic_types"
, verifyCsCodegen "complex_types"
, verifyCsCodegen "defaults"
, verifyCsCodegen "empty"
, verifyCsCodegen "field_modifiers"
, verifyCsCodegen "generics"
, verifyCsCodegen "inheritance"
, verifyCsCodegen "aliases"
, verifyCodegen
[ "c#"
, "--using=time=System.DateTime"
]
"nullable_alias"
]
]
]
main :: IO ()
main = defaultMain tests
|
alfpark/bond
|
compiler/tests/Main.hs
|
mit
| 4,159
| 0
| 12
| 1,472
| 599
| 309
| 290
| 91
| 1
|
import System.Environment
import Text.SSWC
import qualified Data.Text.IO as T
main :: IO ()
main = getArgs >>= dispatch
dispatch :: [String] -> IO ()
dispatch [] = putStrLn "usage: sswc filename"
dispatch (fnm:_) = do
edoc <- loadDocument fnm
case edoc of
Right doc -> do Right ts <- loadTemplates doc
let newDoc = runTemplates ts doc
T.putStrLn $ renderDocument newDoc
Left err -> putStrLn $ "error: "++err
|
openbrainsrc/sswc
|
src/Main.hs
|
mit
| 465
| 0
| 15
| 125
| 166
| 81
| 85
| 14
| 2
|
main = do
contents <- getContents
putStr (shortLinesOnly contents)
shortLinesOnly :: String -> String
shortLinesOnly input =
let allLines = lines input
shortLines = filter (\line -> length line < 10) allLines
result = unlines shortLines
in result
|
KHs000/haskellToys
|
src/scripts/shortlines.hs
|
mit
| 301
| 0
| 13
| 92
| 89
| 43
| 46
| 9
| 1
|
module Preprocessor.Hsx (
module Preprocessor.Hsx.Syntax
, module Preprocessor.Hsx.Build
, module Preprocessor.Hsx.Parser
, module Preprocessor.Hsx.Pretty
, module Preprocessor.Hsx.Transform
, parseFileContents
, parseFileContentsWithMode
, parseFile
) where
import Preprocessor.Hsx.Build
import Preprocessor.Hsx.Syntax
import Preprocessor.Hsx.Parser
import Preprocessor.Hsx.Pretty
import Preprocessor.Hsx.Transform
parseFile :: FilePath -> IO (ParseResult HsModule)
parseFile fp = readFile fp >>= (return . parseFileContentsWithMode (ParseMode fp))
parseFileContents :: String -> ParseResult HsModule
parseFileContents = parseFileContentsWithMode defaultParseMode
parseFileContentsWithMode :: ParseMode -> String -> ParseResult HsModule
parseFileContentsWithMode p rawStr =
let cleanStr = unlines [ s | s@(c:_) <- lines rawStr, c /= '#' ]
in parseModuleWithMode p cleanStr
|
timthelion/fenfire
|
Preprocessor/Hsx.hs
|
gpl-2.0
| 892
| 6
| 15
| 112
| 234
| 131
| 103
| 22
| 1
|
module Main where
import Data.List
import System.Console.Haskeline
import Datatypes
import Parser
import Demo
import License
import Manual
import SequenceCalculus
import Prover
main :: IO ()
main = runInputT defaultSettings (outputStrLn manual >> loop [])
loop :: Assumptions -> InputT IO ()
loop as = do
minput <- getInputLine ">> "
case minput of
Nothing -> return ()
Just "quit" -> return ()
Just "exit" -> return ()
Just "clear" -> loop []
Just "ls" -> mapM_ (outputStrLn.show) as >> loop as
Just "demo" -> mapM_ (outputStrLn.(uncurry prove')) examples >> loop as
Just "help" -> outputStrLn manual >> loop as
Just "license" -> outputStrLn license >> loop as
Just ('A':' ':l) -> case parse l of
Left err -> outputStrLn "ParseError" >> loop as
Right p -> loop (as `union` [A p])
Just l -> case parse l of
Left err -> outputStrLn "ParseError" >> loop as
Right p -> outputStrLn (prove' p as) >> loop as
prove' :: Proposition -> Assumptions -> String
prove' p as = underline ("Beweis von "++(init $ tail $ show (map fromProof as))++" ⊦ "++(show p)++":")
++ "\n"
++ case prove p as of
Nothing -> "Nicht beweisbar."
Just q -> unlines $ map show $ proofToSequence q
where underline x = x ++ '\n':(map (const '-') x)
|
lpeterse/crprover
|
Main.hs
|
gpl-2.0
| 1,683
| 1
| 17
| 682
| 549
| 263
| 286
| 37
| 12
|
import Data.Char
cap = unwords . map capitalizeWord . words
where capitalizeWord [] = []
capitalizeWord (c:cs) = toUpper c : map toLower cs
|
rootguy1/code-base
|
haskel/cap.hs
|
gpl-2.0
| 152
| 0
| 9
| 36
| 63
| 31
| 32
| 4
| 2
|
module Probability.RandomVariable.Macro where
import Types
import Prelude (error, sequence_)
import Macro.Math
import Macro.MetaMacro
import Macro.Text
import Macro.Tuple
import Functions.Application.Macro
import Functions.Basics.Macro
import Probability.ConditionalProbability.Macro
import Probability.Intro.Macro
import Probability.ProbabilityMeasure.Macro
-- * Random variable
-- | Concrete random variable
rv_ :: Note
rv_ = "X"
-- FIXME fix variable name
-- | Function declaration for concrete random variable
rvfunc_ :: Note
rvfunc_ = fun rv_ univ_ reals
-- FIXME fix variable name
-- | Probability value from random variable
vrv :: Note -> Note
vrv = fn rv_
-- FIXME fix variable name
-- * Probability distribution
-- | Set of probability distributions of Y-rvs
prdss :: Note -> Note
prdss = (^ "pd")
-- | Probability distribution given the random variable that it is of
--
-- > prdis_ "X"
-- >>> Pr_{X}
prdis_ :: Note -> Note
prdis_ x = prm_ ^: x
-- | The application of such a probability distribution
-- > prdis "X" "a"
-- >>> Pr_{X}(a)
prdis :: Note -> Note -> Note
prdis = prm . prdis_
-- Probability distribution given the random variables that it is of
prdiss_ :: [Note] -> Note
prdiss_ = prdis_ . cs
prdiss :: [Note] -> Note -> Note
prdiss = prm . prdiss_
-- * Random variable tuple
rtup :: Note -> Note -> Note
rtup = tuple
-- * Cumulative distribution function
dfsign_ :: Note
dfsign_ = "F"
-- | A cumulative distribution function given a random varable
df :: Note -> Note
df n = dfsign_ !: n
-- | A concrete cumulative distribution function
df_ :: Note
df_ = df rv_ -- probability distribution function
-- | Cumulative distribution at point argument with modified symbol
prdm :: Note -> Note -> Note
prdm = fn
-- | The cumulative distribution at point argument
prd :: Note -> Note
prd = prdm df_
-- * Density function
dsfsign_ :: Note
dsfsign_ = "f"
dsf :: Note -> Note
dsf n = dsfsign_ !: n -- probability density function modified
dsf_ :: Note
dsf_ = dsf rv_ -- probability density function
prds :: Note -> Note
prds = prdsm dsf_ -- probability density
-- | Probabilty density at point argument with modified symbol
prdsm :: Note -> Note -> Note
prdsm = fn
-- * Quantile function
qfsign_ :: Note
qfsign_ = "Q"
prqfm :: Note -> Note
prqfm n = qfsign_ !: n
prqf :: Note
prqf = prqfm rv_
prq :: Note -> Note
prq = app prqf
-- * Expected value
-- | Expected value
ev :: Note -> Note
ev n = "E" <> sqbrac n
-- | Expected value over given random variable
evm :: Note -> Note -> Note
evm m n = "E" !: m <> sqbrac n
-- | Expected value over given random variables
evms :: [Note] -> Note -> Note
evms ms = evm (sequence_ ms)
-- FIXME move this? to statistics
-- | Mean
mn :: Note -> Note
mn = ev
-- | Concrete mean
mn_ :: Note
mn_ = mu
-- * Covariance
-- | Covariance of two random variables
cov :: Note -> Note -> Note
cov = fn2 "Cov"
-- * Variance
-- | Variance
var :: Note -> Note
var n = "Var" <> sqbrac n
-- | Concrete variance
var_ :: Note
var_ = sd_ ^: 2
-- * Correlation
-- | Correlation of two random variables
cor :: Note -> Note -> Note
cor = fn2 "Cor"
-- * Standard deviation
-- | Concrete standard deviation
sd_ :: Note
sd_ = sigma
-- * Joint distribution
probs :: [Note] -> Note
probs vs = prob $ cs vs
cprobs :: Note -> [Note] -> Note
cprobs n [] = prob n
cprobs v cvs = cprob v (cs cvs)
cprobss :: [Note] -> [Note] -> Note
cprobss [] [] = error "Can't have conditional probability of no variables"
cprobss n [] = probs n
cprobss vs cvs = cprob (cs vs) (cs cvs)
-- * Copies
-- | Independent copy
icop :: Note -- Random variable
-> Note -- Power
-> Note
icop = (^:)
-- | Clone
clon :: Note -- Random variable
-> Note -- Power
-> Note
clon x q = x ^: (sqbrac q)
-- * Statistical distance
statd :: Note -> Note -> Note
statd = fn2 delta
-- * Empirical
-- | Empirical mean
emean :: Note -> Note
emean = comm1 "overline"
-- TODO Empirical variance
|
NorfairKing/the-notes
|
src/Probability/RandomVariable/Macro.hs
|
gpl-2.0
| 4,092
| 0
| 7
| 967
| 970
| 553
| 417
| 99
| 1
|
{-# LANGUAGE Arrows #-}
module ABSDataTests
(
absDataTests
) where
import Data.List
import Data.Maybe
import Data.Void
import FRP.Yampa
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import ABSData
import SIR
import Debug.Trace
-- note that we are creating also recovered messages
-- although a recovered agent never actually generates
-- one, but we need them to cover all cases
instance Arbitrary SIRMsg where
-- arbitrary :: Gen SIRMsg
arbitrary = elements [Contact Susceptible, Contact Infected, Contact Recovered]
contactRate :: Double
contactRate = 5.0
infectivity :: Double
infectivity = 0.05
illnessDuration :: Double
illnessDuration = 15.0
absDataTests :: RandomGen g
=> g
-> TestTree
absDataTests g
= testGroup
"SIR ABS Data Tests"
[ test_agent_behaviour_quickgroup g
--, test_agent_signal_quickgroup g
]
test_agent_behaviour_quickgroup :: RandomGen g
=> g
-> TestTree
test_agent_behaviour_quickgroup g
= testGroup "agent behaviour"
[ QC.testProperty "susceptible behaviour" (testCaseSusceptible g)
, QC.testProperty "interaction behaviour" (testCaseInteraction g) ]
-- | Testing the interaction between agents
-- test the interconnection of susceptible and infected agents
-- because the dynamics depend on the correct interplay between them
-- this is but a normal unit-test
-- TODO: implement
testCaseInteraction :: RandomGen g
=> g
-> Bool
testCaseInteraction _g0 = True
-- | Testing the susceptible agent
-- in this implementation, the number of infections depends solely
-- on the number of Contact Infected messages (randomize uisng quickcheck)
-- also the agent should generate on average contactRate Contact Susceptible messages
-- Note that we are not testing whether the susceptible agent generates
-- contact messages here as this is done in the interaction test
testCaseSusceptible :: RandomGen g
=> g
-> [AgentId]
-> [SIRDataFlow]
-> Bool
testCaseSusceptible g0 ais df = diff <= eps
where
n = 10000 -- TODO: how to select a 'correct' number of runs? conjecture: n -> infinity lets go the error (eps) to 0
eps = 0.1 -- TODO: how to select a 'correct' epsilon? conjecture: probably it depends on the ratio between dt and contact rate?
dt = 0.125 -- NOTE: to find out a suitable dt use the test itself: start e.g. with 1.0 and always half when test fail until it succeeds
diff = testSusceptible g0 n dt
testSusceptible :: RandomGen g
=> g -- ^ initial RNG
-> Int -- ^ number of runs
-> DTime -- ^ time-delta to use
-> Double -- ^ returns difference to target
testSusceptible g0 n dt
= trace
("df = " ++ show df ++ ", countFract = " ++ show countFract ++ " target = " ++ show target)
(abs (target - countFract))
where
totalContacts = length df
infContacts = length $ filter isInfectedContact df
count = testSusceptibleAux g0 n 0
countFract = fromIntegral count / fromIntegral n
-- IMPORTANT: in this test-case the number of infected does NOT
-- depend on the contact rate!!!! this will only be tested in
-- the combined test of susceptible and infected
-- Note that in the end in this data-driven implementation,
-- the probability of a susceptible agent becoming infected
-- follows a bernoulli trial: for each Contact Infected
-- message, the agent gets infected with a probability of
-- infectivity, thus we have success or fail with complementary
-- probability which add up to 1 => use bernoulli formula to
-- calculate the probability of being infected after N Contact
-- Infected messages => this is a binomial experiment (https://en.wikipedia.org/wiki/Bernoulli_trial):
-- "which consists of a fixed number {\displaystyle n} n of statistically independent Bernoulli trials,
-- each with a probability of success {\displaystyle p} p, and counts the number of successes."
-- The probability of exactly k successes in an experiment is given by
-- P(k) = (n over k) p^k q^(n-k), where n is total number of trials, p is prob of success and q = 1-p
-- in the susceptible case we are interested in the probability of at least one, which means
-- we have to add up P(1) to P(number of Contact Infected Messages)
-- TODO: this is for a single step, independent of dt, the more time-steps, the more likely it
-- is that an agent gets infected => we have a binomial experiment again
target = sum $ map (binomDistr totalContacts infectivity) [1..infContacts]
binomDistr :: Int
-> Double
-> Int
-> Double
binomDistr n p k = fromIntegral (binom n k) * (p ** fromIntegral k) * (1 - p) ** fromIntegral (n - k)
where
binom :: Int -> Int -> Int
binom _ 0 = 1
binom 0 _ = 0
binom n k = binom (n-1) (k-1) * n `div` k
isInfectedContact :: SIRDataFlow -> Bool
isInfectedContact (_, Contact Infected) = True
isInfectedContact _ = False
testSusceptibleAux :: RandomGen g
=> g
-> Int
-> Int
-> Int
testSusceptibleAux _ 0 count = count
testSusceptibleAux g n count
= testSusceptibleAux g'' (n-1) count'
where
(g', g'') = split g
steps = replicate 1 (dt, Nothing)
ret = embed (testSusceptibleSF g' n ais df) ((), steps)
gotInfected = True `elem` ret
count' = if gotInfected then count + 1 else count
testSusceptibleSF :: RandomGen g
=> g
-> AgentId
-> [AgentId]
-> [SIRDataFlow]
-> SF () Bool
testSusceptibleSF g aid ais df = proc _ -> do
let ain = (agentIn aid) { aiData = df }
ret <- susceptibleAgent g contactRate infectivity illnessDuration ais -< ain
case aoObservable ret of
Susceptible -> returnA -< False
Infected -> returnA -< True
Recovered -> returnA -< False -- TODO: should never occur, can we test this? seems not so, but we can pretty easily guarantee it due to simplicity of code
|
thalerjonathan/phd
|
coding/papers/pfe/testing/src/ABSDataTests.hs
|
gpl-3.0
| 6,690
| 1
| 15
| 2,112
| 1,008
| 544
| 464
| 101
| 6
|
{-# LANGUAGE FlexibleContexts #-}
-- |
-- Copyright : (c) 2010-2012 Benedikt Schmidt
-- License : GPL v3 (see LICENSE)
--
-- Maintainer : Benedikt Schmidt <beschmi@gmail.com>
--
-- Types for communicating with Maude.
module Term.Maude.Types (
-- * Maude terms
MaudeLit(..)
, MSubst
, MTerm
-- * conversion from/to maude terms
, lTermToMTerm
, lTermToMTerm'
, mTermToLNTerm
, runConversion
, msubstToLSubstVFresh
, msubstToLSubstVFree
) where
import Term.Term
import Term.LTerm
import Term.Substitution
import Utils.Misc
import Control.Monad.Fresh
import Control.Monad.Bind
import Control.Applicative
import Data.Traversable hiding (mapM)
import Data.Maybe
import qualified Data.Map as M
import Data.Map (Map)
-- Maude Terms
----------------------------------------------------------------------
data MaudeLit = MaudeVar Integer LSort
| FreshVar Integer LSort
| MaudeConst Integer LSort
deriving (Eq, Ord, Show)
type MTerm = Term MaudeLit
type MSubst = [((LSort, Integer), MTerm)]
------------------------------------------------------------------------
-- Convert between MTerms and LNTerms
------------------------------------------------------------------------
-- | Convert an @LNTerm@ to an @MTerm@.
lTermToMTerm' :: (MonadBind (Lit Name LVar) MaudeLit m, MonadFresh m)
=> LNTerm -- ^ The term to translate.
-> m MTerm
lTermToMTerm' = lTermToMTerm sortOfName
-- | Convert an @LNTerm@ with arbitrary names to an @MTerm@.
lTermToMTerm :: (MonadBind (Lit c LVar) MaudeLit m, MonadFresh m, Show c, Show (Lit c LVar), Ord c)
=> (c -> LSort) -- ^ A function that returns the sort of a constant.
-> VTerm c LVar -- ^ The term to translate.
-> m MTerm
lTermToMTerm sortOf =
go . viewTerm
where
go (Lit l) = lit <$> exportLit l
go (FApp o as) = fApp o <$> mapM (go . viewTerm) as
exportLit a@(Var lv) =
importBinding (\_ i -> MaudeVar i (lvarSort lv)) a "x"
exportLit a@(Con n) = importBinding (\_ i -> MaudeConst i (sortOf n)) a "a"
-- | Convert an 'MTerm' to an 'LNTerm' under the assumption that the bindings
-- for the constants are already available.
mTermToLNTerm :: (MonadBind MaudeLit (Lit c LVar) m, MonadFresh m, Show (Lit c LVar), Ord c, Show c)
=> String -- ^ Name hint for freshly generated variables.
-> MTerm -- ^ The maude term to convert.
-> m (VTerm c LVar)
mTermToLNTerm nameHint =
go . viewTerm
where
go (Lit l) = lit <$> importLit l
go (FApp o as) = fApp o <$> mapM (go . viewTerm) as
importLit a@(MaudeVar _ lsort) = importBinding (\n i -> Var (LVar n lsort i)) a nameHint
importLit a@(FreshVar _ lsort) = importBinding (\n i -> Var (LVar n lsort i)) a nameHint
importLit a = fromMaybe (error $ "fromMTerm: unknown constant `" ++ show a ++ "'") <$>
lookupBinding a
-- Back and forth conversions
------------------------------------------------------------------------
-- | Run a @BindT (Lit c LVar) MaudeLit Fresh@ computation
-- with an empty fresh supply and an empty binding map and return
-- the result and the resulting inverted binding map.
runConversion :: Ord c
=> BindT (Lit c LVar) MaudeLit Fresh a -- ^ Computation to execute.
-> (a, Map MaudeLit (Lit c LVar))
runConversion to =
(x, invertMap bindings)
where (x, bindings) = runBindT to noBindings `evalFresh` nothingUsed
-- | Run a @BindT MaudeLit (Lit c LVar) Fresh@ computation using the
-- supplied binding map and the corresponding fresh supply.
runBackConversion :: BindT MaudeLit (Lit c LVar) Fresh a -- ^ Computation to execute.
-> Map MaudeLit (Lit c LVar) -- ^ Binding map that should be used.
-> a
runBackConversion back bindings =
evalBindT back bindings `evalFreshAvoiding` M.elems bindings
------------------------------------------------------------------------
-- Conversion between Maude and Standard substitutions
------------------------------------------------------------------------
-- | @msubstToLSubstVFresh bindings substMaude@ converts a substitution
-- returned by Maude to a 'VFresh' substitution. It expects that the
-- range of the maude substitution contains only fresh variables in its
-- range and raises an error otherwise.
msubstToLSubstVFresh :: (Ord c, Show (Lit c LVar), Show c)
=> Map MaudeLit (Lit c LVar) -- ^ The binding map to use for constants.
-> MSubst -- ^ The maude substitution.
-> SubstVFresh c LVar
msubstToLSubstVFresh bindings substMaude
| not $ null [i | (_,t) <- substMaude, MaudeVar _ i <- lits t] =
error $ "msubstToLSubstVFresh: nonfresh variables in `"++show substMaude++"'"
| otherwise = removeRenamings $ substFromListVFresh slist
where
slist = runBackConversion (traverse translate substMaude) bindings
-- try to keep variable name for xi -> xj mappings
-- commented out, seems wrong
-- translate ((s,i), mt@(Lit (FreshVar _ _))) = do
-- lv <- lookupVar s i
-- (lv,) <$> mTermToLNTerm (lvarName lv) mt
translate ((s,i),mt) = (,) <$> lookupVar s i <*> mTermToLNTerm "x" mt
lookupVar s i = do b <- lookupBinding (MaudeVar i s)
case b of
Just (Var lv) -> return lv
_ -> error $ "msubstToLSubstVFrsh: binding for maude variable `"
++show (s,i) ++"' not found in "++show bindings
-- | @msubstToLSubstVFree bindings substMaude@ converts a substitution
-- returned by Maude to a 'VFree' substitution. It expects that the
-- maude substitution contains no fresh variables in its range and raises an
-- error otherwise.
msubstToLSubstVFree :: (Ord c, Show (Lit c LVar), Show c)
=> Map MaudeLit (Lit c LVar) -> MSubst -> Subst c LVar
msubstToLSubstVFree bindings substMaude
| not $ null [i | (_,t) <- substMaude, FreshVar _ i <- lits t] =
error $ "msubstToLSubstVFree: fresh variables in `"++show substMaude
| otherwise = substFromList slist
where
slist = evalBindT (traverse translate substMaude) bindings
`evalFreshAvoiding` M.elems bindings
translate ((s,i),mt) = (,) <$> lookupVar s i <*> mTermToLNTerm "x" mt
lookupVar s i = do b <- lookupBinding (MaudeVar i s)
case b of
Just (Var lv) -> return lv
_ -> error $ "msubstToLSubstVFree: binding for maude variable `"
++show (s,i)++"' not found in "++show bindings
|
ekr/tamarin-prover
|
lib/term/src/Term/Maude/Types.hs
|
gpl-3.0
| 6,817
| 0
| 16
| 1,796
| 1,558
| 823
| 735
| 95
| 4
|
module TicTacToe where
import Data.Either
import Data.Maybe
import Data.List
-- Board representation: => +---+---+---+
-- => | X | 2 | 3 |
-- 1 Board consists of 3 rows => +---+---+---+
-- 1 Row consists of 3 Cells => | 4 | 5 | 6 |
-- 1 Cell contains either a Symbol or an Integer => +---+---+---+
-- A symbol is either X (crosses) or O (noughts) => | 7 | 8 | O |
-- Integers in cells represent cell address => +---+---+---+
data Symbol = X | O
deriving (Show, Eq)
type Cell = Either Symbol Int
type Row = [Cell]
type Col = [Cell]
type Diag = [Cell]
data Board = Board Row Row Row
deriving (Eq)
instance Show Board where
show board =
(unlines (wrap "+---+---+---+" (map (concat . wrap "|" . map formatCell) (getBoardRows board))))
where
wrap :: String -> [String] -> [String]
wrap pattern str = [pattern] ++ intersperse pattern str ++ [pattern]
formatCell = either (\n -> " " ++ show n ++ " ") (\n -> " ")
createEmptyBoard :: Board
createEmptyBoard = Board [Right 1, Right 2, Right 3] [Right 4, Right 5, Right 6] [Right 7, Right 8, Right 9]
getBoardRows :: Board -> [Row]
getBoardRows (Board row1 row2 row3) = [row1, row2, row3]
getBoardCols :: Board -> [Col]
getBoardCols (Board [a, b, c] [d, e, f] [g, h, i]) = [[a, d, g], [b, e, h], [c, f, i]]
getBoardDiags :: Board -> [Diag]
getBoardDiags (Board [a, b, c] [d, e, f] [g, h, i]) = [[a, e, i], [c, e, g]]
allTheSame :: (Eq a) => [a] -> Bool
allTheSame xs = and $ map (== head xs) (tail xs)
hasWinningRow :: [Row] -> Bool
hasWinningRow rows = or $ map allTheSame rows
hasWinningCol :: [Col] -> Bool
hasWinningCol cols = or $ map allTheSame cols
hasWinningDiag :: [Diag] -> Bool
hasWinningDiag diags = or $ map allTheSame diags
checkWin :: Board -> Bool
checkWin board = or $ [r, c, d]
where
r = hasWinningRow (getBoardRows board)
c = hasWinningCol (getBoardCols board)
d = hasWinningDiag (getBoardDiags board)
boardToList :: Board -> [Cell]
boardToList (Board row1 row2 row3) = row1 ++ row2 ++ row3
listToBoard :: [Cell] -> Board
listToBoard [c1, c2, c3, c4, c5, c6, c7, c8, c9] = Board [c1, c2, c3] [c4, c5, c6] [c7, c8, c9]
availableMoves :: Board -> [Cell]
availableMoves board = filter isRight (boardToList board)
checkDraw :: Board -> Bool
checkDraw board
| checkWin board == True = False
| length (availableMoves board) > 0 = False
| otherwise = True
playMove :: Board -> Cell -> Cell -> Board
playMove board position move = resultBoard
where
boardList = boardToList board
replaceBoard = map (\x -> if x == position then move else x) boardList
resultBoard = listToBoard replaceBoard
getWinner :: Board -> String
getWinner board
| checkDraw board == True = "It's a draw!"
| hasPlayerWon board == True = "Congratulations! You win!"
| otherwise = "The computer wins!"
where
hasPlayerWon :: Board -> Bool
hasPlayerWon board = or allLines where
allLines = map func rowsColsDiags
func = (\x -> if (allTheSame x) && (head x) == (Left X) then True else False)
rowsColsDiags = getBoardRows board
-- AI logic starts here
cellEmpty :: Cell -> Bool
cellEmpty cell = if cell == (Left O) || cell == (Left X) then False else True
canWin :: Board -> Cell -> Bool
canWin board symbol = or wins
where
wins = map (\x -> checkWin (playMove board x symbol)) (availableMoves board)
playWin :: Board -> Board
playWin board = playMove board (head winPositions) (Left O)
where
winPositions = filter (\x -> checkWin (playMove board x (Left O))) (availableMoves board)
canAILose :: Board -> Bool
canAILose board = canWin board (Left X)
playBlock :: Board -> Board
playBlock board = playMove board (head losePositions) (Left O)
where
losePositions = filter (\x -> checkWin (playMove board x (Left X))) (availableMoves board)
checkFork :: Board -> Cell -> Bool
checkFork board symbol = (length possibleWins) == 2
where
possibleWins = filter (\x -> checkWin (playMove board x symbol)) (availableMoves board)
canFork :: Board -> Cell -> Bool
canFork board symbol = or forks
where
forks = map (\x -> checkFork (playMove board x symbol) symbol) (availableMoves board)
playFork :: Board -> Board
playFork board = playMove board (head forkPositions) (Left O)
where
forkPositions = filter (\x -> checkFork (playMove board x (Left O)) (Left O)) (availableMoves board)
playBlockFork :: Board -> Board
playBlockFork board = playMove board (head forkPositions) (Left O)
where
forkPositions = filter (\x -> checkFork (playMove board x (Left X)) (Left X)) (availableMoves board)
isCenterEmpty :: Board -> Bool
isCenterEmpty board@(Board [_, _, _] [_, center, _] [_, _, _])
| center == (Left O) || center == (Left X) = False
| otherwise = True
playCenter :: Board -> Board
playCenter board@(Board [_, _, _] [_, center, _] [_, _, _]) = playMove board center (Left O)
canCorner :: Board -> Bool
canCorner board@(Board [topLeft, _, topRight] [_, _, _] [bottomLeft, _, bottomRight])
| topLeft == (Left X) && isRight bottomRight = True
| topRight == (Left X) && isRight bottomLeft = True
| bottomLeft == (Left X) && isRight topRight = True
| bottomRight == (Left X) && isRight topLeft = True
| otherwise = False
playOppositeCorner :: Board -> Board
playOppositeCorner board@(Board [topLeft, _, topRight] [_, _, _] [bottomLeft, _, bottomRight])
| topLeft == (Left X) && isRight bottomRight = playMove board bottomRight (Left O)
| topRight == (Left X) && isRight bottomLeft = playMove board bottomLeft (Left O)
| bottomLeft == (Left X) && isRight topRight = playMove board topRight (Left O)
| bottomRight == (Left X) && isRight topLeft = playMove board topLeft (Left O)
| otherwise = playFirstAvailable board
hasEmptyCorner :: Board -> Bool
hasEmptyCorner board@(Board [topLeft, _, topRight] [_, _, _] [bottomLeft, _, bottomRight])
| isRight topLeft || isRight topRight || isRight bottomLeft || isRight bottomRight = True
| otherwise = False
playEmptyCorner :: Board -> Board
playEmptyCorner board@(Board [topLeft, _, topRight] [_, _, _] [bottomLeft, _, bottomRight])
| isRight topLeft = playMove board topLeft (Left O)
| isRight topRight = playMove board topRight (Left O)
| isRight bottomLeft = playMove board bottomLeft (Left O)
| isRight bottomRight = playMove board bottomRight (Left O)
| otherwise = playFirstAvailable board
hasEmptySide :: Board -> Bool
hasEmptySide board@(Board [_, topSide, _] [leftSide, _, rightSide] [_, bottomSide, _])
| isRight topSide || isRight leftSide || isRight rightSide || isRight bottomSide = True
| otherwise = False
playEmptySide :: Board -> Board
playEmptySide board@(Board [_, topSide, _] [leftSide, _, rightSide] [_, bottomSide, _])
| isRight topSide = playMove board topSide (Left O)
| isRight leftSide = playMove board leftSide (Left O)
| isRight rightSide = playMove board rightSide (Left O)
| isRight bottomSide = playMove board bottomSide (Left O)
| otherwise = playFirstAvailable board
playFirstAvailable :: Board -> Board
playFirstAvailable board = playMove board (head (availableMoves board)) (Left O)
-- Follows the unbeatable strategy explained here https://en.wikipedia.org/wiki/Tic-tac-toe
--
bestMoveAI :: Board -> Board
bestMoveAI board
| (canWin board (Left O)) == True = playWin board
| (canAILose board) == True = playBlock board
| (canFork board (Left O)) == True = playFork board
| (canFork board (Left X)) == True = playEmptySide board
| (isCenterEmpty board) == True = playCenter board
| (canCorner board) == True = playOppositeCorner board
| (hasEmptyCorner board) == True = playEmptyCorner board
| (hasEmptySide board) == True = playEmptySide board
| otherwise = playFirstAvailable board
|
veskoy/functional-programming-fmi
|
Project/TicTacToe.hs
|
gpl-3.0
| 7,892
| 0
| 15
| 1,685
| 3,152
| 1,638
| 1,514
| 145
| 2
|
module View.GUI where
import Graphics.UI.SDL
data GUIView
= StandardView {
stdViewScreen :: Surface
, stdViewZoomArea :: Surface
}
|
phaazon/phraskell
|
src/View/GUI.hs
|
gpl-3.0
| 155
| 0
| 8
| 42
| 33
| 21
| 12
| 6
| 0
|
-- | (This is a part of MIOS.)
-- Solver, the main data structure
{-# LANGUAGE
MultiWayIf
, RecordWildCards
, ScopedTypeVariables
, TupleSections
, ViewPatterns
#-}
{-# LANGUAGE Safe #-}
module SAT.Mios.Solver
(
-- * Solver
Solver (..)
, newSolver
-- * Misc Accessors
, nAssigns
, nClauses
, nLearnts
, decisionLevel
, valueVar
, valueLit
, locked
-- * State Modifiers
, setAssign
, enqueue
, assume
, cancelUntil
-- * Stats
, StatIndex (..)
, getStat
, setStat
, incrementStat
, getStats
)
where
import Control.Monad (unless, when)
import Data.List (intercalate)
import Numeric (showFFloat)
import SAT.Mios.Types
import SAT.Mios.Clause
import SAT.Mios.ClauseManager
import SAT.Mios.ClausePool
-- | __Fig. 2.(p.9)__ Internal State of the solver
data Solver = Solver
{
-------- Database
clauses :: !ClauseExtManager -- ^ List of problem constraints.
, learnts :: !ClauseExtManager -- ^ List of learnt clauses.
, watches :: !WatcherList -- ^ list of constraint wathing 'p', literal-indexed
-------- Assignment Management
, assigns :: !(Vec Int) -- ^ The current assignments indexed on variables
, phases :: !(Vec Int) -- ^ The last assignments indexed on variables
, trail :: !Stack -- ^ List of assignments in chronological order
, trailLim :: !Stack -- ^ Separator indices for different decision levels in 'trail'.
, qHead :: !Int' -- ^ 'trail' is divided at qHead; assignment part and queue part
, reason :: !ClauseVector -- ^ For each variable, the constraint that implied its value
, level :: !(Vec Int) -- ^ For each variable, the decision level it was assigned
, ndd :: !(Vec Int) -- ^ For each variable, the number of depending decisions
, conflicts :: !Stack -- ^ Set of literals in the case of conflicts
-------- Variable Order
, activities :: !(Vec Double) -- ^ Heuristic measurement of the activity of a variable
, order :: !VarHeap -- ^ Keeps track of the dynamic variable order.
-------- Configuration
, config :: !MiosConfiguration -- ^ search paramerters
, nVars :: !Int -- ^ number of variables
, claInc :: !Double' -- ^ Clause activity increment amount to bump with.
, varInc :: !Double' -- ^ Variable activity increment amount to bump with.
, rootLevel :: !Int' -- ^ Separates incremental and search assumptions.
-------- DB Size Adjustment
, learntSAdj :: Double' -- ^ used in 'SAT.Mios.Main.search'
, learntSCnt :: Int' -- ^ used in 'SAT.Mios.Main.search'
, maxLearnts :: Double' -- ^ used in 'SAT.Mios.Main.search'
-------- Working Memory
, ok :: !Int' -- ^ internal flag
, an'seen :: !(Vec Int) -- ^ used in 'SAT.Mios.Main.analyze'
, an'toClear :: !Stack -- ^ used in 'SAT.Mios.Main.analyze'
, an'stack :: !Stack -- ^ used in 'SAT.Mios.Main.analyze'
, an'lastDL :: !Stack -- ^ last decision level used in 'SAT.Mios.Main.analyze'
, clsPool :: ClausePool -- ^ clause recycler
, litsLearnt :: !Stack -- ^ used in 'SAT.Mios.Main.analyze' and 'SAT.Mios.Main.search' to create a learnt clause
, stats :: !(Vec Int) -- ^ statistics information holder
, lbd'seen :: !(Vec Int) -- ^ used in lbd computation
, lbd'key :: !Int' -- ^ used in lbd computation
-------- restart heuristics #62, clause evaluation criteria #74
, emaAFast :: !EMA -- ^ Number of Assignments Fast
, emaASlow :: !EMA -- ^ Number of Assignments Slow
, emaBDLvl :: !EMA -- ^ Backjumped and Restart Dicision Level
, emaCDLvl :: !EMA -- ^ Conflicting Level
, emaDFast :: !EMA -- ^ (Literal Block) Distance Fast
, emaDSlow :: !EMA -- ^ (Literal Block) Distance Slow
, nextRestart :: !Int' -- ^ next restart in number of conflict
, restartExp :: !Double' -- ^ incremented by blocking
, emaRstBias :: !EMA -- ^ average phase of restart
}
-- | returns an everything-is-initialized solver from the arguments.
newSolver :: MiosConfiguration -> CNFDescription -> IO Solver
newSolver conf (CNFDescription nv dummy_nc _) =
Solver
-- Clause Database
<$> newManager dummy_nc -- clauses
<*> newManager 2000 -- learnts
<*> newWatcherList nv 1 -- watches
-- Assignment Management
<*> newVec nv LBottom -- assigns
<*> newVec nv LBottom -- phases
<*> newStack nv -- trail
<*> newStack nv -- trailLim
<*> new' 0 -- qHead
<*> newClauseVector (nv + 1) -- reason
<*> newVec nv (-1) -- level
<*> newVec (2 * (nv + 1)) 0 -- ndd
<*> newStack nv -- conflicts
-- Variable Order
<*> newVec nv 0 -- activities
<*> newVarHeap nv -- order
-- Configuration
<*> return conf -- config
<*> return nv -- nVars
<*> new' 1.0 -- claInc
<*> new' 1.0 -- varInc
<*> new' 0 -- rootLevel
-- Learnt DB Size Adjustment
<*> new' 100 -- learntSAdj
<*> new' 100 -- learntSCnt
<*> new' 2000 -- maxLearnts
-- Working Memory
<*> new' LiftedT -- ok
<*> newVec nv 0 -- an'seen
<*> newStack nv -- an'toClear
<*> newStack nv -- an'stack
<*> newStack nv -- an'lastDL
<*> newClausePool 10 -- clsPool
<*> newStack nv -- litsLearnt
<*> newVec (fromEnum EndOfStatIndex) 0 -- stats
<*> newVec nv 0 -- lbd'seen
<*> new' 0 -- lbd'key
-- restart heuristics #62
<*> newEMA False ef -- emaAFast
<*> newEMA True es -- emaASlow
<*> newEMA True 2 -- emaBDLvl
<*> newEMA True 2 -- emaCDLvl
<*> newEMA False ef -- emaDFast
<*> newEMA True es -- emaDSlow
<*> new' 100 -- nextRestart
<*> new' 0.0 -- restartExp
<*> newEMA False 100 -- emaRstBias
where
(ef, es) = emaCoeffs conf
--------------------------------------------------------------------------------
-- Accessors
-- | returns the number of current assigments.
{-# INLINE nAssigns #-}
nAssigns :: Solver -> IO Int
nAssigns = get' . trail
-- | returns the number of constraints (clauses).
{-# INLINE nClauses #-}
nClauses :: Solver -> IO Int
nClauses = get' . clauses
-- | returns the number of learnt clauses.
{-# INLINE nLearnts #-}
nLearnts :: Solver -> IO Int
nLearnts = get' . learnts
-- | returns the current decision level.
{-# INLINE decisionLevel #-}
decisionLevel :: Solver -> IO Int
decisionLevel = get' . trailLim
-- | returns the assignment (:: 'LiftedBool' = @[-1, 0, -1]@) from 'Var'.
{-# INLINE valueVar #-}
valueVar :: Solver -> Var -> IO Int
valueVar = getNth . assigns
-- | returns the assignment (:: 'LiftedBool' = @[-1, 0, -1]@) from 'Lit'.
{-# INLINE valueLit #-}
valueLit :: Solver -> Lit -> IO Int
valueLit (assigns -> a) p = (\x -> if positiveLit p then x else negate x) <$> getNth a (lit2var p)
-- | __Fig. 7. (p.11)__
-- returns @True@ if the clause is locked (used as a reason). __Learnt clauses only__
{-# INLINE locked #-}
locked :: Solver -> Clause -> IO Bool
locked s c = (c ==) <$> (getNth (reason s) . lit2var =<< getNth (lits c) 1)
-------------------------------------------------------------------------------- Statistics
-- | returns the value of 'StatIndex'.
{-# INLINE getStat #-}
getStat :: Solver -> StatIndex -> IO Int
getStat (stats -> v) (fromEnum -> i) = getNth v i
-- | sets to 'StatIndex'.
{-# INLINE setStat #-}
setStat :: Solver -> StatIndex -> Int -> IO ()
setStat (stats -> v) (fromEnum -> i) x = setNth v i x
-- | increments a stat data corresponding to 'StatIndex'.
{-# INLINE incrementStat #-}
incrementStat :: Solver -> StatIndex -> Int -> IO ()
incrementStat (stats -> v) (fromEnum -> i) k = modifyNth v (+ k) i
-- | returns the statistics as a list.
{-# INLINABLE getStats #-}
getStats :: Solver -> IO [(StatIndex, Int)]
getStats (stats -> v) = mapM (\i -> (i, ) <$> getNth v (fromEnum i)) [minBound .. maxBound :: StatIndex]
-------------------------------------------------------------------------------- State Modifiers
-- | assigns a value to the /n/-th variable
setAssign :: Solver -> Int -> LiftedBool -> IO ()
setAssign Solver{..} v x = setNth assigns v x
-- | __Fig. 9 (p.14)__
-- Puts a new fact on the propagation queue, as well as immediately updating the variable's value
-- in the assignment vector. If a conflict arises, @False@ is returned and the propagation queue is
-- cleared. The parameter 'from' contains a reference to the constraint from which 'p' was
-- propagated (defaults to @Nothing@ if omitted).
{-# INLINABLE enqueue #-}
enqueue :: Solver -> Lit -> Clause -> IO Bool
enqueue s@Solver{..} p from = do
{-
-- bump psedue lbd of @from@
when (from /= NullClause && learnt from) $ do
l <- get' (lbd from)
k <- (12 +) <$> decisionLevel s
when (k < l) $ set' (lbd from) k
-}
let signumP = lit2lbool p
let v = lit2var p
val <- valueVar s v
if val /= LBottom
then return $ val == signumP -- Existing consistent assignment -- don't enqueue
else do setNth assigns v signumP -- New fact, store it
setNth level v =<< decisionLevel s
setNth reason v from -- NOTE: @from@ might be NULL!
pushTo trail p
return True
-- | __Fig. 12 (p.17)__
-- returns @False@ if immediate conflict.
--
-- __Pre-condition:__ propagation queue is empty
{-# INLINE assume #-}
assume :: Solver -> Lit -> IO Bool
assume s p = do
pushTo (trailLim s) =<< get' (trail s)
enqueue s p NullClause
-- | #M22: Revert to the states at given level (keeping all assignment at 'level' but not beyond).
{-# INLINABLE cancelUntil #-}
cancelUntil :: Solver -> Int -> IO ()
cancelUntil s@Solver{..} lvl = do
dl <- decisionLevel s
when (lvl < dl) $ do
lim <- getNth trailLim (lvl + 1)
ts <- get' trail
ls <- get' trailLim
let
loopOnTrail :: Int -> IO ()
loopOnTrail ((lim <) -> False) = return ()
loopOnTrail c = do
x <- lit2var <$> getNth trail c
setNth phases x =<< getNth assigns x
setNth assigns x LBottom
-- #reason to set reason Null
-- if we don't clear @reason[x] :: Clause@ here, @reason[x]@ remains as locked.
-- This means we can't reduce it from clause DB and affects the performance.
setNth reason x NullClause -- 'analyze` uses reason without checking assigns
-- FIXME: #polarity https://github.com/shnarazk/minisat/blosb/master/core/Solver.cc#L212
undoVO s x
-- insertHeap s x -- insertVerOrder
loopOnTrail $ c - 1
loopOnTrail ts
shrinkBy trail (ts - lim)
shrinkBy trailLim (ls - lvl)
set' qHead =<< get' trail
-------------------------------------------------------------------------------- VarOrder
-- | Interfate to select a decision var based on variable activity.
instance VarOrder Solver where
{-
-- | __Fig. 6. (p.10)__
-- Creates a new SAT variable in the solver.
newVar _ = return 0
-- i <- nVars s
-- Version 0.4:: push watches =<< newVec -- push'
-- Version 0.4:: push watches =<< newVec -- push'
-- push undos =<< newVec -- push'
-- push reason NullClause -- push'
-- push assigns LBottom
-- push level (-1)
-- push activities (0.0 :: Double)
-- newVar order
-- growQueueSized (i + 1) propQ
-- return i
-}
{-# SPECIALIZE INLINE updateVO :: Solver -> Var -> IO () #-}
updateVO = increaseHeap
{-# SPECIALIZE INLINE undoVO :: Solver -> Var -> IO () #-}
undoVO s v = inHeap s v >>= (`unless` insertHeap s v)
{-# SPECIALIZE INLINE selectVO :: Solver -> IO Var #-}
selectVO s = do
let
asg = assigns s
-- | returns the most active var (heap-based implementation)
loop :: IO Var
loop = do
n <- numElementsInHeap s
if n == 0
then return 0
else do
v <- getHeapRoot s
x <- getNth asg v
if x == LBottom then return v else loop
loop
-------------------------------------------------------------------------------- VarHeap
-- | A heap tree built from two 'Vec'.
-- This implementation is identical wtih that in Minisat-1.14.
-- Note: the zero-th element of @heap@ is used for holding the number of elements.
-- Note: VarHeap itself is not a @VarOrder@, because it requires a pointer to solver.
data VarHeap = VarHeap
{
heap :: !Stack -- order to var
, idxs :: !Stack -- var to order (index)
}
newVarHeap :: Int -> IO VarHeap
newVarHeap n = do
v1 <- newVec n 0
v2 <- newVec n 0
let
loop :: Int -> IO ()
loop ((<= n) -> False) = set' v1 n >> set' v2 n
loop i = setNth v1 i i >> setNth v2 i i >> loop (i + 1)
loop 1
return $ VarHeap v1 v2
{-# INLINE numElementsInHeap #-}
numElementsInHeap :: Solver -> IO Int
numElementsInHeap = get' . heap . order
{-# INLINE inHeap #-}
inHeap :: Solver -> Var -> IO Bool
inHeap Solver{..} n = case idxs order of at -> (/= 0) <$> getNth at n
{-# INLINE increaseHeap #-}
increaseHeap :: Solver -> Int -> IO ()
increaseHeap s@Solver{..} n = case idxs order of
at -> inHeap s n >>= (`when` (percolateUp s =<< getNth at n))
{-# INLINABLE percolateUp #-}
percolateUp :: Solver -> Int -> IO ()
percolateUp Solver{..} start = do
let VarHeap to at = order
v <- getNth to start
ac <- getNth activities v
let
loop :: Int -> IO ()
loop i = do
let iP = div i 2 -- parent
if iP == 0
then setNth to i v >> setNth at v i -- end
else do
v' <- getNth to iP
acP <- getNth activities v'
if ac > acP
then setNth to i v' >> setNth at v' i >> loop iP -- loop
else setNth to i v >> setNth at v i -- end
loop start
{-# INLINABLE percolateDown #-}
percolateDown :: Solver -> Int -> IO ()
percolateDown Solver{..} start = do
let (VarHeap to at) = order
n <- getNth to 0
v <- getNth to start
ac <- getNth activities v
let
loop :: Int -> IO ()
loop i = do
let iL = 2 * i -- left
if iL <= n
then do
let iR = iL + 1 -- right
l <- getNth to iL
r <- getNth to iR
acL <- getNth activities l
acR <- getNth activities r
let (ci, child, ac') = if iR <= n && acL < acR then (iR, r, acR) else (iL, l, acL)
if ac' > ac
then setNth to i child >> setNth at child i >> loop ci
else setNth to i v >> setNth at v i -- end
else setNth to i v >> setNth at v i -- end
loop start
{-# INLINABLE insertHeap #-}
insertHeap :: Solver -> Var -> IO ()
insertHeap s@(order -> VarHeap to at) v = do
n <- (1 +) <$> getNth to 0
setNth at v n
setNth to n v
set' to n
percolateUp s n
-- | returns the value on the root (renamed from @getmin@).
{-# INLINABLE getHeapRoot #-}
getHeapRoot :: Solver -> IO Int
getHeapRoot s@(order -> VarHeap to at) = do
r <- getNth to 1
l <- getNth to =<< getNth to 0 -- the last element's value
setNth to 1 l
setNth at l 1
setNth at r 0
modifyNth to (subtract 1) 0 -- pop
n <- getNth to 0
when (1 < n) $ percolateDown s 1
return r
|
shnarazk/mios
|
src/SAT/Mios/Solver.hs
|
gpl-3.0
| 17,089
| 0
| 46
| 5,941
| 3,383
| 1,761
| 1,622
| 372
| 4
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
-- |
-- Module : Network.Google.StreetViewPublish
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Publishes 360 photos to Google Maps, along with position, orientation,
-- and connectivity metadata. Apps can offer an interface for positioning,
-- connecting, and uploading user-generated Street View images.
--
-- /See:/ <https://developers.google.com/streetview/publish/ Street View Publish API Reference>
module Network.Google.StreetViewPublish
(
-- * Service Configuration
streetViewPublishService
-- * OAuth Scopes
, streetViewPublishScope
-- * API Declaration
, StreetViewPublishAPI
-- * Resources
-- ** streetviewpublish.photo.create
, module Network.Google.Resource.StreetViewPublish.Photo.Create
-- ** streetviewpublish.photo.delete
, module Network.Google.Resource.StreetViewPublish.Photo.Delete
-- ** streetviewpublish.photo.get
, module Network.Google.Resource.StreetViewPublish.Photo.Get
-- ** streetviewpublish.photo.startUpload
, module Network.Google.Resource.StreetViewPublish.Photo.StartUpload
-- ** streetviewpublish.photo.update
, module Network.Google.Resource.StreetViewPublish.Photo.Update
-- ** streetviewpublish.photos.batchDelete
, module Network.Google.Resource.StreetViewPublish.Photos.BatchDelete
-- ** streetviewpublish.photos.batchGet
, module Network.Google.Resource.StreetViewPublish.Photos.BatchGet
-- ** streetviewpublish.photos.batchUpdate
, module Network.Google.Resource.StreetViewPublish.Photos.BatchUpdate
-- ** streetviewpublish.photos.list
, module Network.Google.Resource.StreetViewPublish.Photos.List
-- * Types
-- ** LatLng
, LatLng
, latLng
, llLatitude
, llLongitude
-- ** Photo
, Photo
, photo
, pThumbnailURL
, pMapsPublishStatus
, pConnections
, pShareLink
, pUploadReference
, pCaptureTime
, pPose
, pDownloadURL
, pTransferStatus
, pPlaces
, pViewCount
, pPhotoId
-- ** UpdatePhotoRequest
, UpdatePhotoRequest
, updatePhotoRequest
, uprPhoto
, uprUpdateMask
-- ** Status
, Status
, status
, sDetails
, sCode
, sMessage
-- ** PhotoGetView
, PhotoGetView (..)
-- ** PhotoResponse
, PhotoResponse
, photoResponse
, prPhoto
, prStatus
-- ** Operation
, Operation
, operation
, oDone
, oError
, oResponse
, oName
, oMetadata
-- ** Empty
, Empty
, empty
-- ** PhotosListView
, PhotosListView (..)
-- ** StatusDetailsItem
, StatusDetailsItem
, statusDetailsItem
, sdiAddtional
-- ** ListPhotosResponse
, ListPhotosResponse
, listPhotosResponse
, lprNextPageToken
, lprPhotos
-- ** Connection
, Connection
, connection
, cTarget
-- ** BatchUpdatePhotosResponse
, BatchUpdatePhotosResponse
, batchUpdatePhotosResponse
, buprResults
-- ** BatchDeletePhotosResponse
, BatchDeletePhotosResponse
, batchDeletePhotosResponse
, bdprStatus
-- ** Pose
, Pose
, pose
, pRoll
, pHeading
, pLatLngPair
, pAccuracyMeters
, pAltitude
, pLevel
, pPitch
-- ** UploadRef
, UploadRef
, uploadRef
, urUploadURL
-- ** Xgafv
, Xgafv (..)
-- ** PhotosBatchGetView
, PhotosBatchGetView (..)
-- ** OperationMetadata
, OperationMetadata
, operationMetadata
, omAddtional
-- ** PhotoTransferStatus
, PhotoTransferStatus (..)
-- ** BatchUpdatePhotosRequest
, BatchUpdatePhotosRequest
, batchUpdatePhotosRequest
, buprUpdatePhotoRequests
-- ** BatchDeletePhotosRequest
, BatchDeletePhotosRequest
, batchDeletePhotosRequest
, bdprPhotoIds
-- ** Place
, Place
, place
, pLanguageCode
, pName
, pPlaceId
-- ** PhotoMapsPublishStatus
, PhotoMapsPublishStatus (..)
-- ** Level
, Level
, level
, lName
, lNumber
-- ** OperationResponse
, OperationResponse
, operationResponse
, orAddtional
-- ** BatchGetPhotosResponse
, BatchGetPhotosResponse
, batchGetPhotosResponse
, bgprResults
-- ** PhotoId
, PhotoId
, photoId
, piId
) where
import Network.Google.Prelude
import Network.Google.Resource.StreetViewPublish.Photo.Create
import Network.Google.Resource.StreetViewPublish.Photo.Delete
import Network.Google.Resource.StreetViewPublish.Photo.Get
import Network.Google.Resource.StreetViewPublish.Photo.StartUpload
import Network.Google.Resource.StreetViewPublish.Photo.Update
import Network.Google.Resource.StreetViewPublish.Photos.BatchDelete
import Network.Google.Resource.StreetViewPublish.Photos.BatchGet
import Network.Google.Resource.StreetViewPublish.Photos.BatchUpdate
import Network.Google.Resource.StreetViewPublish.Photos.List
import Network.Google.StreetViewPublish.Types
{- $resources
TODO
-}
-- | Represents the entirety of the methods and resources available for the Street View Publish API service.
type StreetViewPublishAPI =
PhotoGetResource :<|> PhotoCreateResource :<|>
PhotoStartUploadResource
:<|> PhotoDeleteResource
:<|> PhotoUpdateResource
:<|> PhotosListResource
:<|> PhotosBatchGetResource
:<|> PhotosBatchUpdateResource
:<|> PhotosBatchDeleteResource
|
brendanhay/gogol
|
gogol-streetviewpublish/gen/Network/Google/StreetViewPublish.hs
|
mpl-2.0
| 5,806
| 0
| 12
| 1,294
| 629
| 458
| 171
| 140
| 0
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module View.PledgeButton (
overlayImage,
fillInPledgeCount,
blankPledgeButton,
) where
import Import hiding ((<>))
import Diagrams.Prelude
import Diagrams.Backend.Rasterific
import Codec.Picture.Png
import Codec.Picture.Types
import Data.FileEmbed
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
fillInPledgeCount :: Integer -> Diagram B R2
fillInPledgeCount num = positiontext (text str # styled) <> boundingbox
where
str = addCommas (show num)
styled t = t # fc blue # fontSize (Local 16)
-- Magic numbers position the text in the center of the box
-- in the pledge button where it's supposed to go.
positiontext = translateX (-100) . translateY 12
-- invisible bounding box for text
boundingbox = rect 50 20 # lw none
addCommas :: String -> String
addCommas = reverse . go . reverse
where
go (c1:c2:c3:rest) | not (null rest) = c1:c2:c3:',':addCommas rest
go s = s
renderByteStringPng :: Int -> Diagram B R2 -> L.ByteString
renderByteStringPng w = encodePng . renderDia Rasterific opts
where
opts = RasterificOptions (Width (fromIntegral w))
-- | Use an image as the base of a diagram, drawing over it.
--
-- Returns a png in a ByteString that has the same size as the original
-- image.
overlayImage :: DImage Embedded -> Diagram B R2 -> L.ByteString
overlayImage img@(DImage _ w _ _) overlay = renderByteStringPng w dia
where
dia = overlay <> image img # sized Absolute
blankPledgeButton :: DImage Embedded
blankPledgeButton = (DImage (ImageRaster img) w h mempty)
where
img = either (error "bad static/img/pledge-button.png") id $
decodePng blankPledgeButtonPng
w = dynamicMap imageWidth img
h = dynamicMap imageHeight img
blankPledgeButtonPng :: B.ByteString
blankPledgeButtonPng = $(embedFile "static/img/pledge-button.png")
|
Happy0/snowdrift
|
View/PledgeButton.hs
|
agpl-3.0
| 1,847
| 8
| 12
| 304
| 527
| 278
| 249
| -1
| -1
|
{-
FCA - A generator of a Formal Concept Analysis Lattice
Copyright (C) 2014 Raymond Racine
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Data.Fca.Ident (
Ident,
Identable (..)
) where
import Crypto.Hash (Digest, MD5, hash)
import qualified Data.HashSet as Set
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Encoding (encodeUtf8)
import Data.Fca.Concept (Concept, cG)
import Data.Fca.SimpleTypes (Obj)
type Ident = Text
class Identable a where
ident :: a -> Text
instance Identable (Concept (Obj Text) a) where
ident c = hmd5
where
bs = encodeUtf8 $ T.concat $ Set.toList $ cG c
hmd5 = T.pack $ show (hash bs :: Digest MD5)
|
RayRacine/hsfca
|
src/Data/Fca/Ident.hs
|
agpl-3.0
| 1,628
| 0
| 11
| 434
| 209
| 124
| 85
| 22
| 0
|
module SSH.Server
(
-- * Higher-level functions
ErrorCode (..)
, LogVerbosity (..)
, getError
, getErrorCode
, getBindError
, getBindErrorCode
, getPubkeyHash
, setRsaKey
, setBindPort
, setLogVerbosity
)
where
import Data.Word
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Storable
import Foreign.Ptr
import Foreign.ForeignPtr
import SSH.LibSSH.Server
type Server = Ptr Bind
data ErrorCode
= NoError -- ^ No error occured.
| RequestDenied -- ^ The last request was denied but situation is recoverable.
| Fatal -- ^ A fatal error occurred. This could be an unexpected disconnection.
deriving (Eq, Show)
data LogVerbosity
= NoLog
| Warning
| Protocol
| Packet
| Functions
deriving (Eq, Show)
getPubkeyHash :: Ptr Session -> IO String
getPubkeyHash session
= do ptr <- malloc :: IO (Ptr (Ptr CChar))
len <- ssh_get_pubkey_hash session ptr
if len < 0
then return ""
else do cstr <- peek ptr
peekCStringLen (cstr, fromIntegral len)
setBindPort :: Word16 -> Server -> IO CInt
setBindPort port bind
= do ptr <- malloc :: IO (Ptr CInt)
poke ptr (fromIntegral port)
result <- ssh_bind_options_set bind ssh_BIND_OPTIONS_BINDPORT ptr
free ptr
return result
setRsaKey :: String -> Server -> IO CInt
setRsaKey path bind
= do ptr <- newCString path
result <- ssh_bind_options_set bind ssh_BIND_OPTIONS_RSAKEY ptr
free ptr
return result
-- | Set the session logging verbosity.
setLogVerbosity :: LogVerbosity -> Server -> IO CInt
setLogVerbosity verbosity bind
= do ptr <- malloc :: IO (Ptr CInt)
poke ptr $ ssh_log_e
$ case verbosity of
NoLog -> ssh_LOG_NOLOG
Warning -> ssh_LOG_WARNING
Protocol -> ssh_LOG_PROTOCOL
Packet -> ssh_LOG_PACKET
Functions -> ssh_LOG_FUNCTIONS
result <- ssh_bind_options_set bind ssh_BIND_OPTIONS_LOG_VERBOSITY ptr
free ptr
return result
-- | Retrieve the error text message from the last error.
getError :: Ptr Session -> IO String
getError session
= ssh_error session >>= peekCString
-- | Retrieve the error code from the last error.
getErrorCode :: Ptr Session -> IO ErrorCode
getErrorCode session
= do code <- ssh_error_code session
let x | code == ssh_NO_ERROR = NoError
| code == ssh_REQUEST_DENIED = RequestDenied
| code == ssh_FATAL = Fatal
| otherwise = Fatal
return x
-- | Retrieve the error text message from the last error.
getBindError :: Server -> IO String
getBindError bind
= ssh_error bind >>= peekCString
-- | Retrieve the error code from the last error.
getBindErrorCode :: Server -> IO ErrorCode
getBindErrorCode bind
= do code <- ssh_error_code bind
let x | code == ssh_NO_ERROR = NoError
| code == ssh_REQUEST_DENIED = RequestDenied
| code == ssh_FATAL = Fatal
| otherwise = Fatal
return x
|
lpeterse/haskell-libssh
|
SSH/Server.hs
|
lgpl-3.0
| 3,182
| 0
| 13
| 955
| 764
| 376
| 388
| 88
| 5
|
module BuiltIn.Finance (builtInFinance) where
import qualified Data.Map as M
import BuiltIn.Common
import Type
import Types
retDoll :: Double -> Interpreter EvalError Value
retDoll x = return . VNum $ fromIntegral ((round $ 100 * x) :: Integer) / 100
biDb :: BuiltIn
biDb = BuiltIn
{ evalVal = db
, emitVal = const "DB"
, typeSig = typeNum :-> typeNum :-> typeNum :-> typeNum :-> typeNum :-> typeNum
, argHelp = "cost salvage life period month"
, addHelp = Nothing
}
db :: [Value] -> Interpreter EvalError Value
db [VNum cost, VNum svg, VNum lif, VNum per, VNum mon] =
retDoll . dif $ drop (truncate per - 1) allp
where
dif (a:b:_) = b - a
dif _ = error "Whoa"
allp = 0 : scanl pdep st [1..lif]
st = cost * drate * mon/12
drate = round3 $ 1 - ((svg/cost)**(1/lif))
round3 x = fromIntegral (round (x * 1000) :: Integer) / 1000
pdep b x
| x == lif = ((cost - b) * drate * (12 - mon)) / 12 + b
| otherwise = (cost - b) * drate + b
db _ = infError
biDdb :: BuiltIn
biDdb = BuiltIn
{ evalVal = ddb
, emitVal = const "DDB"
, typeSig = typeNum :-> typeNum :-> typeNum :-> typeNum :-> typeNum :-> typeNum
, argHelp = "cost salvage life period factor"
, addHelp = Nothing
}
ddb :: [Value] -> Interpreter EvalError Value
ddb [VNum cost, VNum sv, VNum lif, VNum per, VNum fac] =
retDoll . dif $ drop (truncate per - 1) allp
where
dif (a:b:_) = b - a
dif _ = error "Whoa"
allp = scanl pdep 0 [1..lif]
dr = 1/lif * fac
pdep b _ = if cost - mdep b < sv
then cost - sv
else mdep b
mdep x = dr * (cost - x) + x
ddb _ = infError
biNpv :: BuiltIn
biNpv = BuiltIn
{ evalVal = npv
, emitVal = const "NPV"
, typeSig = typeNum :-> typeList typeNum :-> typeNum
, argHelp = "rate [cash_flows]"
, addHelp = Nothing
}
npv :: [Value] -> Interpreter EvalError Value
npv [VNum rate, VList xs]
| length xs > 255 = biErr "Too many arguments (>255)"
| otherwise = do
xs' <- vListToDbls xs
return . VNum . sum $ zipWith calcPer xs' [1..]
where
calcPer cf p = cf / (1 + rate)**p
npv _ = infError
biSln :: BuiltIn
biSln = BuiltIn
{ evalVal = sln
, emitVal = const "SLN"
, typeSig = typeNum :-> typeNum :-> typeNum :-> typeNum
, argHelp = "cost salvage life"
, addHelp = Nothing
}
sln :: [Value] -> Interpreter EvalError Value
sln [VNum cost, VNum svg, VNum life] =
return $ VNum $ (cost - svg) / life
sln _ = infError
builtInFinance :: M.Map String BuiltIn
builtInFinance = M.fromList
[ ("db", biDb)
, ("ddb", biDdb)
, ("npv", biNpv)
, ("sln", biSln)
]
|
ahodgen/archer-calc
|
src/BuiltIn/Finance.hs
|
bsd-2-clause
| 2,722
| 0
| 14
| 795
| 1,100
| 587
| 513
| 78
| 3
|
-- |
--
-- Copyright:
-- This file is part of the package vimeta. It is subject to the
-- license terms in the LICENSE file found in the top-level
-- directory of this distribution and at:
--
-- https://github.com/pjones/vimeta
--
-- No part of this package, including this file, may be copied,
-- modified, propagated, or distributed except according to the terms
-- contained in the LICENSE file.
--
-- License: BSD-2-Clause
--
-- The configuration file.
module Vimeta.Core.Config
( Config (..),
defaultConfig,
configFileName,
readConfig,
writeConfig,
)
where
import Control.Monad.Except
import Data.Aeson hiding (encodeFile)
import Data.Aeson.Types (typeMismatch)
import Data.Yaml (decodeFileEither, encodeFile)
import Network.API.TheMovieDB (Key)
import System.Directory
( XdgDirectory (XdgConfig),
createDirectoryIfMissing,
doesFileExist,
getXdgDirectory,
)
import System.FilePath (takeDirectory, (</>))
import Vimeta.Core.Tagger
-- | Vimeta configuration.
data Config = Config
{ configTMDBKey :: Key,
configFormatMovie :: Text,
configFormatTV :: Text,
configVerbose :: Bool,
configDryRun :: Bool
}
instance FromJSON Config where
parseJSON (Object v) =
Config <$> v .: "tmdb_key"
<*> v .: "cmd_movie"
<*> v .: "cmd_tv"
<*> v .:? "verbose" .!= False
<*> v .:? "dryrun" .!= False
parseJSON x = typeMismatch "configuration" x
instance ToJSON Config where
toJSON c =
object
[ "tmdb_key" .= configTMDBKey c,
"cmd_movie" .= configFormatMovie c,
"cmd_tv" .= configFormatTV c
]
defaultConfig :: Tagger -> Config
defaultConfig tagger =
Config
{ configTMDBKey = "your API key goes here",
configFormatMovie = fmtMovie,
configFormatTV = fmtTV,
configVerbose = False,
configDryRun = False
}
where
(fmtMovie, fmtTV) = formatStringsForTagger tagger
-- | Get the name of the configuration file.
configFileName :: IO FilePath
configFileName =
getXdgDirectory XdgConfig "vimeta"
<&> (</> "config.yml")
-- | Read the configuration file and return a 'Config' value or an error.
readConfig :: (MonadIO m) => ExceptT String m Config
readConfig = do
filename <- liftIO configFileName
exists <- liftIO (doesFileExist filename)
if exists
then decodeConfig filename
else throwError $ missingFile filename
where
decodeConfig :: (MonadIO m) => FilePath -> ExceptT String m Config
decodeConfig fn = do
result <- liftIO $ decodeFileEither fn
case result of
Left e -> throwError (show e)
Right a -> return a
missingFile :: FilePath -> String
missingFile fn =
"no config file found, use the `config' command "
++ "to create "
++ fn
writeConfig :: (MonadIO m) => Config -> ExceptT String m FilePath
writeConfig c = do
(filename, exists) <- liftIO $ do
fn <- configFileName
ex <- doesFileExist fn
return (fn, ex)
when exists $ throwError (existError filename)
liftIO (createDirectoryIfMissing True (takeDirectory filename))
liftIO (encodeFile filename c)
return filename
where
existError :: FilePath -> String
existError fn = "please remove the existing config file first: " ++ fn
|
pjones/vimeta
|
src/Vimeta/Core/Config.hs
|
bsd-2-clause
| 3,261
| 0
| 17
| 743
| 753
| 409
| 344
| 81
| 3
|
module MonadServ.JSONObject where
import MonadServ.JSON
class JSONObject a where
toJSON :: a -> Value
|
jcaldwell/monadserv
|
src/MonadServ/JSONObject.hs
|
bsd-2-clause
| 111
| 0
| 7
| 23
| 29
| 16
| 13
| 4
| 0
|
module Module1 (
increaseBy2
)where
import Data.Global
import Data.IORef
someVar :: IORef Int
someVar = declareIORef "my-global-var" 0
increaseBy2 :: IO ()
increaseBy2 = atomicModifyIORef someVar inc2
where
inc2 x = (2+x, ())
|
jm-g/global-variables
|
examples/multimodule/Module1.hs
|
bsd-3-clause
| 239
| 0
| 8
| 46
| 79
| 43
| 36
| 9
| 1
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Types where
import Data.Typeable
import Control.Exception
import Control.Monad.Except
import Control.Monad.Reader
import Data.Aeson
import GHC.Generics
import Network.HTTP.Client
import Network.Wreq
import Data.Scientific
import qualified Data.Text as T
data GideonException = NoSuchCharacterException
| InvalidTokenException String
| SE SomeException
| PE String
| HE HttpException
| OE String
| InvalidArgument T.Text
deriving (Show, Typeable)
instance Exception GideonException
data GideonMetadata = GideonMetadata
{ currentUser :: String
} deriving (Show, Generic)
instance ToJSON GideonMetadata
instance FromJSON GideonMetadata
type AccessTokenType = String
type UserIDType = String
type StationIDType = Scientific
type RegionIDType = Scientific
type ConstellationIDType = Scientific
type SolarSystemIDType = Scientific
type CorpIDType = Scientific
showSci :: Scientific -> String
showSci = show . coefficient
data AuthInfo = AuthInfo
{ authOpt :: Options
, userID :: UserIDType
, accessToken :: AccessTokenType
, charName :: String
} deriving (Show)
newtype Gideon a = Gideon
{ unGideon :: ReaderT AuthInfo (ExceptT GideonException IO) a
} deriving ( Functor
, Applicative
, Monad
, MonadIO
, MonadReader AuthInfo
, MonadError GideonException)
runGideon :: Gideon a -> AuthInfo -> IO (Either GideonException a)
runGideon g authinfo = runExceptT (runReaderT (unGideon g) authinfo)
type Param = (String, String)
type Params = [Param]
data MarketOrder = MarketOrder
{ moStationID :: T.Text
, moStationName :: T.Text
, moVolEntered :: Int
, moVolRemaining :: Int
, moTypeID :: T.Text
, moPrice :: Double
, moOrderID :: T.Text
} deriving (Show, Eq)
-- I'm in Thera!
data TheraWormholeConnection = TWC
{ twcOutSignatureID :: SignatureType
, twcInSignatureID :: SignatureType
, twcWormholeType :: T.Text
, twcDesSolarSystem :: T.Text
, twcDesRegion :: T.Text
} deriving (Show, Eq)
type STPrefix = T.Text
type STSuffix = T.Text
data SignatureType = ST STPrefix STSuffix
instance Eq SignatureType where
ST p1 _ == ST p2 _ = p1 == p2
instance Show SignatureType where
show (ST p s) = T.unpack p ++ "-" ++ T.unpack s
-- currently only contains signature id
data ProbeScannerResult = PSR
{ psrSignatureID :: SignatureType
} deriving (Show)
|
Frefreak/Gideon
|
src/Types.hs
|
bsd-3-clause
| 2,707
| 0
| 9
| 689
| 647
| 374
| 273
| 81
| 1
|
{-# LANGUAGE CPP #-}
module System.Environment.XDG.BaseDir
( getUserDataDir
, getUserDataFile
, getUserConfigDir
, getUserConfigFile
, getUserCacheDir
, getUserCacheFile
, getSystemDataDirs
, getSystemDataFiles
, getSystemConfigDirs
, getSystemConfigFiles
, getAllDataDirs
, getAllDataFiles
, getAllConfigDirs
, getAllConfigFiles
) where
import Data.Maybe ( fromMaybe )
import System.FilePath ( (</>), splitSearchPath )
import System.Environment ( getEnvironment, getEnv )
import Control.Exception ( try )
import System.Directory ( getHomeDirectory )
import Control.Monad ( liftM2 )
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
getDefault "XDG_DATA_HOME" = getEnv "AppData"
getDefault "XDG_CONFIG_HOME" = userRelative $ "Local Settings"
getDefault "XDG_CACHE_HOME" = userRelative $ "Local Settings" </> "Cache"
getDefault "XDG_DATA_DIRS" = getEnv "ProgramFiles"
getDefault "XDG_CONFIG_DIRS" = getEnv "ProgramFiles"
getDefault _ = return ""
#else
getDefault "XDG_DATA_HOME" = userRelative $ ".local" </> "share"
getDefault "XDG_CONFIG_HOME" = userRelative $ ".config"
getDefault "XDG_CACHE_HOME" = userRelative $ ".cache"
getDefault "XDG_DATA_DIRS" = return $ "/usr/local/share:/usr/share"
getDefault "XDG_CONFIG_DIRS" = return $ "/etc/xdg"
getDefault _ = return $ ""
#endif
-- | Get the directory for user-specific data files.
getUserDataDir :: String -> IO FilePath
getUserDataDir = singleDir "XDG_DATA_HOME"
-- | Get the directory for user-specific configuration files.
getUserConfigDir :: String -> IO FilePath
getUserConfigDir = singleDir "XDG_CONFIG_HOME"
-- | Get the directory for user-specific cache files.
getUserCacheDir :: String -> IO FilePath
getUserCacheDir = singleDir "XDG_CACHE_HOME"
-- | Get a list of the system-wide data directories.
getSystemDataDirs :: String -> IO [FilePath]
getSystemDataDirs = multiDirs "XDG_DATA_DIRS"
-- | Get a list of the system-wide configuration directories.
getSystemConfigDirs :: String -> IO [FilePath]
getSystemConfigDirs = multiDirs "XDG_CONFIG_DIRS"
-- | Get a list of all data directories.
getAllDataDirs :: String -> IO [FilePath]
getAllDataDirs a = liftM2 (:) (getUserDataDir a) (getSystemDataDirs a)
-- | Get a list of all configuration directories.
getAllConfigDirs :: String -> IO [FilePath]
getAllConfigDirs a = liftM2 (:) (getUserConfigDir a) (getSystemConfigDirs a)
-- | Get the path to a specific user data file.
getUserDataFile :: String -> String -> IO FilePath
getUserDataFile a f = fmap (</> f) $ getUserDataDir a
-- | Get the path to a specific user configuration file.
getUserConfigFile :: String -> String -> IO FilePath
getUserConfigFile a f = fmap (</> f) $ getUserConfigDir a
-- | Get the path to a specific user cache file.
getUserCacheFile :: String -> String -> IO FilePath
getUserCacheFile a f = fmap (</> f) $ getUserCacheDir a
-- | Get a list of all paths for a specific system data file.
getSystemDataFiles :: String -> String -> IO [FilePath]
getSystemDataFiles a f = fmap (map (</> f)) $ getSystemDataDirs a
-- | Get a list of all paths for a specific system configuration file.
getSystemConfigFiles :: String -> String -> IO [FilePath]
getSystemConfigFiles a f = fmap (map (</> f)) $ getSystemConfigDirs a
-- | Get a list of all paths for a specific data file.
getAllDataFiles :: String -> String -> IO [FilePath]
getAllDataFiles a f = fmap (map (</> f)) $ getAllDataDirs a
-- | Get a list of all paths for a specific configuration file.
getAllConfigFiles :: String -> String -> IO [FilePath]
getAllConfigFiles a f = fmap (map (</> f)) $ getAllConfigDirs a
singleDir :: String -> String -> IO FilePath
singleDir key app = envLookup key >>= return . (</> app)
multiDirs :: String -> String -> IO [FilePath]
multiDirs key app = envLookup key >>= return . map (</> app) . splitSearchPath
envLookup :: String -> IO String
envLookup key = do env <- getEnvironment
case lookup key env of
Just val -> return val
Nothing -> getDefault key
userRelative :: FilePath -> IO FilePath
userRelative p = getHomeDirectory >>= return . (</> p)
|
willdonnelly/xdg-basedir
|
System/Environment/XDG/BaseDir.hs
|
bsd-3-clause
| 4,333
| 0
| 10
| 908
| 904
| 480
| 424
| 67
| 2
|
{-# LANGUAGE NoImplicitPrelude #-}
-- | A linear version of a Functor
module Data.Functor.LFunctor where
import Data.Linear (flip, liftUnit, ($), (.))
import Data.Functor.Compose (Compose(..))
import Data.Functor.Sum (Sum(..))
import Data.Functor.Identity (Identity(..))
class LFunctor f where
fmap :: (a ⊸ b) ⊸ f a ⊸ f b
(<$) :: a ⊸ f () ⊸ f a
(<$) = fmap . liftUnit
(<$>) :: LFunctor f => (a ⊸ b) ⊸ f a ⊸ f b
(<$>) = fmap
($>) :: LFunctor f => f () ⊸ a ⊸ f a
($>) = flip (<$)
infixl 4 $>
infixl 4 <$
infixl 4 <$>
instance (LFunctor f, LFunctor g) => LFunctor (Compose f g) where
fmap f (Compose x) = Compose (fmap (fmap f) x)
instance (LFunctor f, LFunctor g) => LFunctor (Sum f g) where
fmap f (InL x) = InL $ fmap f x
fmap f (InR y) = InR $ fmap f y
instance LFunctor Identity where
fmap f (Identity a) = Identity $ f a
instance LFunctor ((,) s) where
fmap f (a, b) = (a, f b)
|
m0ar/safe-streaming
|
src/Data/Functor/LFunctor.hs
|
bsd-3-clause
| 928
| 0
| 10
| 206
| 463
| 254
| 209
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
module UseHaskellAPIClient where
import Data.Proxy
import Servant.API
import Servant.Client
import UseHaskellAPI
import UseHaskellAPITypes
restAuthAPI :: Proxy AuthAPI
restAuthAPI = Proxy
restLockAPI :: Proxy LockAPI
restLockAPI = Proxy
restFileAPI :: Proxy FileAPI
restFileAPI = Proxy
restDirAPI :: Proxy DirAPI
restDirAPI = Proxy
restTransAPI :: Proxy TransAPI
restTransAPI = Proxy
-- | The function type of the interface here.
-- Each function matches one of the endpoints in type API from UseHaskellAPI.hs
signUp :: Login -> ClientM ResponseData
logIn :: Login -> ClientM [ResponseData]
loadPublicKey :: ClientM [ResponseData]
-- lock stuff here
lock :: Message3 -> ClientM Bool
unlock :: Message3 -> ClientM Bool
locked :: Message -> ClientM Bool
-- file service stuff here
download :: Message -> ClientM [Message]
upload :: Message3 -> ClientM Bool
updateShadowDB :: Shadow -> ClientM Bool
pushTransaction :: String -> ClientM Bool
replicateFile :: Message -> ClientM Bool
-- directory service stuff here
lsDir :: StrWrap -> ClientM ResponseData
lsFile :: Message -> ClientM [FsContents]
fileQuery :: Message3 -> ClientM [SendFileRef]
mapFile :: Message3 -> ClientM [SendFileRef]
dirShadowing :: Message4 -> ClientM [SendFileRef]
-- transaction stuff here (phase 1 client to transaction server)
beginTransaction :: StrWrap -> ClientM ResponseData
tUpload :: FileTransaction -> ClientM Bool
commit :: Message -> ClientM Bool
abort :: Message -> ClientM Bool
readyCommit :: Message -> ClientM Bool
confirmCommit :: Message -> ClientM Bool
-- | The following provides the implementations of these types
-- Note that the order of the functions must match the endpoints in the type API from UseHaskell.hs
(signUp :<|> logIn :<|> loadPublicKey) = client restAuthAPI
(lock :<|> unlock :<|> locked) = client restLockAPI
(download :<|> upload :<|> updateShadowDB :<|> pushTransaction :<|> replicateFile) = client restFileAPI
(lsDir :<|> lsFile :<|> fileQuery :<|> mapFile :<|> dirShadowing) = client restDirAPI
(beginTransaction :<|> tUpload :<|> commit :<|> abort :<|> readyCommit :<|> confirmCommit) = client restTransAPI
|
crowley100/my_distro_API
|
src/UseHaskellAPIClient.hs
|
bsd-3-clause
| 2,400
| 0
| 10
| 417
| 513
| 273
| 240
| 49
| 1
|
{-# LANGUAGE PackageImports #-}
-- |
-- Module : Crypto.Hash.SHA224
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- A module containing SHA224 bindings
--
module Crypto.Hash.SHA224
( Ctx(..)
-- * Incremental hashing Functions
, init -- :: Ctx
, update -- :: Ctx -> ByteString -> Ctx
, updates -- :: Ctx -> [ByteString] -> Ctx
, finalize -- :: Ctx -> ByteString
-- * Single Pass hashing
, hash -- :: ByteString -> ByteString
, hashlazy -- :: ByteString -> ByteString
) where
import Prelude hiding (init)
import qualified Data.ByteString.Lazy as L
import Data.ByteString (ByteString)
import Crypto.Hash.Internal (digestToByteString, digestToByteStringWitness)
import qualified "cryptonite" Crypto.Hash as H
-- | SHA224 Context
newtype Ctx = Ctx (H.Context H.SHA224)
-- | init a context
init :: Ctx
init = Ctx H.hashInit
-- | update a context with a bytestring
update :: Ctx -> ByteString -> Ctx
update (Ctx ctx) d = Ctx $ H.hashUpdate ctx d
-- | updates a context with multiples bytestring
updates :: Ctx -> [ByteString] -> Ctx
updates (Ctx ctx) d =
Ctx $ H.hashUpdates ctx d
-- | finalize the context into a digest bytestring
finalize :: Ctx -> ByteString
finalize (Ctx ctx) = digestToByteString $ H.hashFinalize ctx
-- | hash a strict bytestring into a digest bytestring
hash :: ByteString -> ByteString
hash d = digestToByteStringWitness H.SHA224 $ H.hash d
-- | hash a lazy bytestring into a digest bytestring
hashlazy :: L.ByteString -> ByteString
hashlazy l = digestToByteStringWitness H.SHA224 $ H.hashlazy l
|
vincenthz/hs-cryptohash
|
Crypto/Hash/SHA224.hs
|
bsd-3-clause
| 1,679
| 0
| 8
| 337
| 322
| 190
| 132
| 28
| 1
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.VertexAttrib64Bit
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.VertexAttrib64Bit (
-- * Extension Support
glGetARBVertexAttrib64Bit,
gl_ARB_vertex_attrib_64bit,
-- * Enums
pattern GL_DOUBLE_MAT2,
pattern GL_DOUBLE_MAT2x3,
pattern GL_DOUBLE_MAT2x4,
pattern GL_DOUBLE_MAT3,
pattern GL_DOUBLE_MAT3x2,
pattern GL_DOUBLE_MAT3x4,
pattern GL_DOUBLE_MAT4,
pattern GL_DOUBLE_MAT4x2,
pattern GL_DOUBLE_MAT4x3,
pattern GL_DOUBLE_VEC2,
pattern GL_DOUBLE_VEC3,
pattern GL_DOUBLE_VEC4,
pattern GL_RGB32I,
-- * Functions
glGetVertexAttribLdv,
glVertexAttribL1d,
glVertexAttribL1dv,
glVertexAttribL2d,
glVertexAttribL2dv,
glVertexAttribL3d,
glVertexAttribL3dv,
glVertexAttribL4d,
glVertexAttribL4dv,
glVertexAttribLPointer
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/VertexAttrib64Bit.hs
|
bsd-3-clause
| 1,249
| 0
| 5
| 176
| 144
| 97
| 47
| 30
| 0
|
{-# OPTIONS_GHC -fbang-patterns #-}
-- Copyright (c) 2008 Stephen C. Harris.
-- See COPYING file at the root of this distribution for copyright information.
module HMQ.ReverseEngineering where
import System.IO
import System.FilePath
import System.Directory
import System.Time
import Text.Regex
import Data.Maybe
import Data.List
import Data.Typeable
import Data.Set(Set)
import qualified Data.Set as Set
import qualified Data.Map as Map
import HMQ.Utils.Strings
import HMQ.ForeignKeyLink
import HMQ.Metadata.TableMetadata(TableMetadata, TableIdentifier, FieldMetadata, ForeignKeyConstraint)
import qualified HMQ.Metadata.TableMetadata as TMD
import HMQ.MappedQuery
{- TODO:
And child''parent and parent''child when there's only one fk between them
-}
-- Generates entity source files for a given schema pattern.
-- Returns the count of written entity source files.
generateEntityModuleSourceFiles :: Options -> FilePath -> [TableMetadata] -> IO ()
generateEntityModuleSourceFiles opts outputDir [] = return ()
generateEntityModuleSourceFiles opts outputDir (tmd: tmds) =
do
createDirectoryIfMissing True (takeDirectory outputFile)
writeFile outputFile moduleSrc
generateEntityModuleSourceFiles opts outputDir tmds
where
outputFile = outputDir ++ "/" ++ subRegex (mkRegex "\\.") moduleQName "/" ++ ".hs"
moduleSrc = entityModuleSourceCode moduleDef
moduleQName = entityModuleQName moduleDef
moduleDef = entityModuleDefinition opts tmd
entityModuleSourceCode :: EntityModuleDefinition -> String
entityModuleSourceCode modDef =
"{-# OPTIONS_GHC -fbang-patterns #-}\n\n"
++ "module " ++ entityModuleQName modDef ++ " where"
++ "\n\n"
++ unlines (entityModuleModuleImports modDef)
++ "\n\n\n"
++ entityModuleEntityDefinition modDef
++ "\n\n"
++ entityModuleExtractorDefinition modDef
++ "\n\n"
++ entityModuleTableMetadataDefinition modDef
++ "\n\n"
++ entityModuleMappedQueryDefinition modDef
++ "\n"
entityModuleDefinition :: Options -> TableMetadata -> EntityModuleDefinition
entityModuleDefinition opts tableMd =
EntityModuleDefinition
{
entityModuleQName = moduleQName,
entityModuleTableMetadata = tableMd,
entityModuleEntityName = entityName,
entityModuleModuleImports = entityModuleImports opts,
entityModuleEntityDefinition = makeEntityDefinition entityName fieldDefs,
entityModuleExtractorDefinition = makeEntityRowValueExtractorDefinition opts entityName tableMd,
entityModuleTableMetadataDefinition = makeEntityTableMetadataDefinition opts tableMd,
entityModuleMappedQueryDefinition = makeEntityMappedQueryDefinition entityName
}
where
tableId = TMD.tableIdentifier tableMd
moduleQName = outputModulesQualifiedNamesPrefix opts ++ entityModuleNamingFunction opts tableId
entityName = entityNamingFunction opts tableId
fieldDefs = map (fieldDefinitionFunction opts) (TMD.fieldMetadatas tableMd)
----------------------------------------------------------------------
-- Functions for generating the parts of the generated entity modules
makeEntityDefinition :: String -> [EntityFieldDefinition] -> String
makeEntityDefinition entityName fieldDefs =
unlines [ "data " ++ entityName ++ " = ",
" " ++ entityName,
" {",
listAsString fieldDefLine ",\n" fieldDefs,
" }",
" deriving (Show)",
""
]
where
fieldDefLine efd = " " ++ entityFieldName efd ++ " :: " ++ entityFieldTypeString efd
makeEntityRowValueExtractorDefinition :: Options -> String -> TableMetadata -> String
makeEntityRowValueExtractorDefinition opts entityName tableMd =
unlines [
"-- The extractor function which creates " ++ indefiniteArticleFor entityName ++ " " ++ entityName ++ " from a result row.",
"rowValueExtractor :: EntityRowValueExtractor " ++ entityName,
"rowValueExtractor !tableAlias !qry =",
" let",
" leadingColIx = fromMaybe (error $ \"No columns for table alias \" ++ tableAlias ++ \" found in query.\") $",
" findIndex ((tableAlias ++ \".\") `isPrefixOf`) (selectFieldExprs qry)",
" in",
" leadingColIx `seq`",
" (\\(!row) ->",
" let",
" " ++ listAsString (("fv" ++) . show) ":" fieldNums ++ ":_ = drop leadingColIx row",
" in",
" -- Check first pk field to determine if there's a value for this row",
" if fv" ++ show firstPkFieldRelativeColNum ++ " == SqlNull then",
" Nothing",
" else",
" Just $ " ++ entityName ++ " " ++ listAsString (\fNum -> "(fromSql fv" ++ show fNum ++ ")") " " fieldNums,
" )"
]
where
fieldNums = [1..(length $ TMD.fieldMetadatas tableMd)]
firstPkFieldRelativeColNum =
if not (null pks) then
1 + fromMaybe (error $ "Primary key field " ++ head pks ++ " not found in field metadatas for table " ++ tableName ++ ".")
(elemIndex (head pks) (TMD.fieldNames tableMd))
else
error $ "Table " ++ tableName ++ " has no primary key: row value extractors require a primary key."
pks = TMD.primaryKeyFieldNames tableMd
tableName = TMD.tableIdentifierString (TMD.tableIdentifier tableMd)
makeEntityTableMetadataDefinition :: Options -> TableMetadata -> String
makeEntityTableMetadataDefinition opts tableMd =
"tableMetadata :: TableMetadata\n"
++ "tableMetadata = \n"
++ " " ++ show tableMd ++ "\n"
makeEntityMappedQueryDefinition :: String -> String
makeEntityMappedQueryDefinition entityName =
"mappedQuery :: MappedQuery " ++ entityName ++ " " ++ entityName ++ " " ++ entityName ++ "\n"
++ "mappedQuery = MappedTable tableMetadata rowValueExtractor\n"
-- Functions for generating the parts of the generated entity modules
----------------------------------------------------------------------
-------------------------------------------
-- Foreign key module generation
generateForeignKeyLinksModuleSourceFile :: Options -> String -> [TableMetadata] -> IO ()
generateForeignKeyLinksModuleSourceFile opts outputDir tableMd =
do
createDirectoryIfMissing True parentDir
writeFile outputFile moduleSrc
where
parentDir = takeDirectory outputFile
outputFile = outputDir ++ "/" ++ subRegex (mkRegex "\\.") moduleQName "/" ++ ".hs"
moduleQName = outputModulesQualifiedNamesPrefix opts ++ foreignKeyLinksModuleName opts
moduleSrc = foreignKeyLinksModuleSourceCode moduleDef
moduleDef = foreignKeyLinksModuleDefinition opts tableMd
foreignKeyLinksModuleDefinition :: Options -> [TableMetadata] -> ForeignKeyLinksModuleDefinition
foreignKeyLinksModuleDefinition opts tableMds =
foldl' (addDefsForFkc opts) emptyFkLinksModule fkcs
where
fkcs = concatMap TMD.foreignKeyConstraints tableMds
moduleQName = outputModulesQualifiedNamesPrefix opts ++ foreignKeyLinksModuleName opts
emptyFkLinksModule = ForeignKeyLinksModuleDefinition moduleQName fixedImports Set.empty Set.empty [] []
fixedImports = ["import Data.Dynamic",
"",
"import HMQ.ForeignKeyLink"]
-- Add link definitions for a foreign key constraint
addDefsForFkc :: Options -> ForeignKeyLinksModuleDefinition -> ForeignKeyConstraint -> ForeignKeyLinksModuleDefinition
addDefsForFkc !opts !fkMod !fkc =
ForeignKeyLinksModuleDefinition
{
fksModuleQName = moduleQName,
fksModuleFixedImports = fixedImports,
fksModuleEntityImports = entityModuleImports,
fksModuleEntityMappedQueries = entityMappedQueries,
fksModuleLinkDefs = linkDefs,
fksModuleDynamicLinkDefs = dynamicLinkDefs
}
where
srcTable = TMD.sourceTable fkc
tgtTable = TMD.targetTable fkc
srcModuleQName = outputModulesQualifiedNamesPrefix opts ++ entityModuleNamingFunction opts srcTable
tgtModuleQName = outputModulesQualifiedNamesPrefix opts ++ entityModuleNamingFunction opts tgtTable
-- The many-one link
manyOneLinkName = manyToOneForeignKeyLinkNamingFunction opts fkc
eqFieldsLiteral = "[" ++ listAsString (\(f1,f2) -> "(" ++ quote f1 ++ "," ++ quote f2 ++ ")") "," (TMD.equatedFields fkc) ++ "]"
manyOneLinkDef =
manyOneLinkName ++ " =\n"
++ " ManyToOne\n"
++ " (ForeignKey\n"
++ " " ++ srcModuleQName ++ ".tableMetadata\n"
++ " " ++ tgtModuleQName ++ ".tableMetadata\n"
++ " " ++ eqFieldsLiteral ++ "\n"
++ " " ++ srcModuleQName ++ ".rowValueExtractor\n"
++ " " ++ tgtModuleQName ++ ".rowValueExtractor\n"
++ " )"
-- The one-many link
oneManyLinkName = oneToManyForeignKeyLinkNamingFunction opts fkc
oneManyLinkDef = oneManyLinkName ++ " = reverseLink " ++ manyOneLinkName
linkDefs = manyOneLinkDef : oneManyLinkDef : fksModuleLinkDefs fkMod
-- Dynamic links
dynamicManyOneLink = "toDynamicForeignKeyLink " ++ manyOneLinkName
dynamicOneManyLink = "toDynamicForeignKeyLink " ++ oneManyLinkName
dynamicLinkDefs = dynamicManyOneLink : dynamicOneManyLink : fksModuleDynamicLinkDefs fkMod
entityModuleImports = Set.insert ("import qualified " ++ srcModuleQName)
(Set.insert ("import qualified " ++ tgtModuleQName)
(fksModuleEntityImports fkMod))
entityMappedQueries = Set.insert (tableAliasBaseName srcTable ++ " = " ++ srcModuleQName ++ ".mappedQuery\n")
(Set.insert (tableAliasBaseName tgtTable ++ " = " ++ tgtModuleQName ++ ".mappedQuery\n")
(fksModuleEntityMappedQueries fkMod))
foreignKeyLinksModuleSourceCode :: ForeignKeyLinksModuleDefinition -> String
foreignKeyLinksModuleSourceCode fkmod =
"module " ++ fksModuleQName fkmod ++ " where"
++ "\n\n"
++ unlines (fksModuleFixedImports fkmod)
++ "\n"
++ unlines (Set.toList $ fksModuleEntityImports fkmod)
++ "\n\n\n"
++ " -- Entity module mapped queries\n"
++ unlines (Set.toList $ fksModuleEntityMappedQueries fkmod)
++ "\n\n\n"
++ unlines (intersperse "\n" $ fksModuleLinkDefs fkmod)
++ "\n\n\n"
-- Dynamic link definitions are commented out for now, because CalendarTime isn't in class Typeable, so the entities with dates/times are Typeable.
++ "{- Dynamic representation of all foreign key links, both many-one and one-many.\n"
++ "dynamicForeignKeyLinks :: [ForeignKeyLink Dynamic Dynamic]\n"
++ "dynamicForeignKeyLinks =\n"
++ " [\n"
++ listAsString (indent 8) ",\n" (fksModuleDynamicLinkDefs fkmod)
++ "\n"
++ " ]\n-}\n"
-- Foreign key module generation
-------------------------------------------
-----------------
-- Defaults
defaultOptions = Options {
entityModuleNamingFunction = defaultEntityModuleNamingFunction :: TableIdentifier -> String,
foreignKeyLinksModuleName = "GeneratedForeignKeyLinks",
outputModulesQualifiedNamesPrefix = "", -- Prepended to the above to form the final qualified output module names
entityNamingFunction = defaultEntityNamingFunction :: TableIdentifier -> String,
fieldDefinitionFunction = defaultFieldDefinitionFunction :: FieldMetadata -> EntityFieldDefinition,
entityModuleImports = defaultEntityModuleImports,
manyToOneForeignKeyLinkNamingFunction = defaultManyToOneForeignKeyLinkNamingFunction,
oneToManyForeignKeyLinkNamingFunction = defaultOneToManyForeignKeyLinkNamingFunction
}
defaultEntityModuleNamingFunction :: TableIdentifier -> String
defaultEntityModuleNamingFunction = ("GeneratedEntities." ++) . capitalize . lowerCase . TMD.tableName
defaultEntityNamingFunction :: TableIdentifier -> String
defaultEntityNamingFunction = camelCase True . singularize . TMD.tableName
defaultFieldDefinitionFunction :: FieldMetadata -> EntityFieldDefinition
defaultFieldDefinitionFunction fieldMd =
EntityFieldDefinition { entityFieldName = fieldName, entityFieldTypeString = typeStr }
where
fieldName = camelCase False $ TMD.fieldName fieldMd
typeStr = standardTypeStringForField fieldMd
standardTypeStringForField :: FieldMetadata -> String
standardTypeStringForField fieldMd =
let baseType = if TMD.isSmallIntegral fieldMd then "Int"
else if TMD.isLargeIntegral fieldMd then "Integer"
else if TMD.isPreciseDecimal fieldMd then "Rational"
else if TMD.isSinglePrecisionFloating fieldMd then "Float"
else if TMD.isDoublePrecisionFloating fieldMd then "Double"
else if TMD.isCharacter fieldMd then "String"
else if TMD.isBooleanOrBit fieldMd then "Bool"
else if TMD.isDate fieldMd || TMD.isDateTime fieldMd then "CalendarTime"
else if TMD.isTime fieldMd then "TimeDiff"
else
error $ "Field type of field " ++ show fieldMd ++ " is currently not supported."
nullable = fromMaybe True (TMD.fieldIsNullable fieldMd)
maybeWrap tstr = if nullable then "Maybe " ++ tstr else tstr
in
maybeWrap baseType
defaultEntityModuleImports :: [String]
defaultEntityModuleImports =
[
"import Data.List",
"import Data.Maybe",
"import System.Time",
"import Database.HDBC",
"",
"import HMQ.Metadata.TableMetadata",
"import HMQ.Query hiding(tableIdentifier)",
"import HMQ.ForeignKeyLink",
"import HMQ.MappedQuery",
"import HMQ.RowValueExtractors"
]
defaultManyToOneForeignKeyLinkNamingFunction :: ForeignKeyConstraint -> String
defaultManyToOneForeignKeyLinkNamingFunction fkc =
tableAliasBaseName srcTable ++ "'" ++ concatenatedFkFields
where
srcTable = TMD.sourceTable fkc
concatenatedFkFields = listAsString (lowerCase . fst) "_" (TMD.equatedFields fkc)
defaultOneToManyForeignKeyLinkNamingFunction :: ForeignKeyConstraint -> String
defaultOneToManyForeignKeyLinkNamingFunction fkc =
tableAliasBaseName tgtTable ++ "''" ++ tableAliasBaseName srcTable ++ "'" ++ concatenatedFkFields
where
tgtTable = TMD.targetTable fkc
srcTable = TMD.sourceTable fkc
concatenatedFkFields = listAsString (lowerCase . snd) "_" (TMD.equatedFields fkc)
-- Defaults
-----------------
----------------------------------------
-- Auxiliary types and related functions
----------------------------------------
data Options =
Options
{
entityModuleNamingFunction :: TableIdentifier -> String,
foreignKeyLinksModuleName :: String,
outputModulesQualifiedNamesPrefix :: String, -- Prepended to the above to form the final qualified module names
entityNamingFunction :: TableIdentifier -> String,
fieldDefinitionFunction :: FieldMetadata -> EntityFieldDefinition,
entityModuleImports :: [String],
manyToOneForeignKeyLinkNamingFunction :: ForeignKeyConstraint -> String,
oneToManyForeignKeyLinkNamingFunction :: ForeignKeyConstraint -> String
}
data EntityModuleDefinition =
EntityModuleDefinition
{
entityModuleQName :: String,
entityModuleTableMetadata :: TableMetadata,
entityModuleEntityName :: String,
entityModuleModuleImports :: [String],
entityModuleEntityDefinition :: String,
entityModuleExtractorDefinition :: String,
entityModuleTableMetadataDefinition :: String,
entityModuleMappedQueryDefinition :: String
}
data EntityFieldDefinition =
EntityFieldDefinition
{
entityFieldName :: String,
entityFieldTypeString :: String
}
data ForeignKeyLinksModuleDefinition =
ForeignKeyLinksModuleDefinition
{
fksModuleQName :: String,
fksModuleFixedImports :: [String],
fksModuleEntityImports :: (Set String),
fksModuleEntityMappedQueries :: (Set String),
fksModuleLinkDefs :: [String],
fksModuleDynamicLinkDefs :: [String]
}
|
scharris/hmq
|
ReverseEngineering.hs
|
bsd-3-clause
| 17,701
| 0
| 27
| 4,996
| 2,757
| 1,483
| 1,274
| -1
| -1
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Foundation.Input where
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core
import Foundation.Common
import Control.Applicative
import Control.Monad
import Data.Maybe (catMaybes)
-- ButtonGroup {{{
data ButtonGroup = ButtonGroup
{ buttonGroupStyle :: ButtonStyle
, buttonGroup :: [Button]
}
instance ToElement ButtonGroup where
toElement (ButtonGroup s g)
| length g > 8 = fail "Button Group has too many buttons! (css can't handle more than 8, sorry)"
| otherwise = UI.ul #
set classes (bgLen : "button-group" : buttonClasses s) #+
map buildBtn g
where
buildBtn b = UI.li #+ [toElement $ applyButtonGroupRadius b]
bgLen = "even-" ++ show (length g)
applyButtonGroupRadius :: Button -> Button
applyButtonGroupRadius b = b
{ buttonStyle = ButtonStyle
(buttonSize $ buttonStyle b)
(buttonColor $ buttonStyle b)
Nothing
(buttonDisabled $ buttonStyle b)
}
-- }}}
-- Button {{{
data Button = Button
{ buttonLabel :: Label
, buttonStyle :: ButtonStyle
, buttonAction :: Element -> IO ()
}
instance ToElement Button where
toElement (Button lbl s act) = do
lbl' <- toElements lbl
but <- UI.button # set classes ("button" : buttonClasses s) #+ map element lbl'
on UI.click but $ const $ act but
element but
plainBtnStyle :: ButtonStyle
plainBtnStyle = ButtonStyle Nothing Nothing Nothing False
roundBtnStyle :: ButtonStyle
roundBtnStyle = ButtonStyle Nothing Nothing (Just BtnRound) False
radiusBtnStyle :: ButtonStyle
radiusBtnStyle = ButtonStyle Nothing Nothing (Just BtnRadius) False
buttonClasses :: ButtonStyle -> [String]
buttonClasses s = catMaybes
[ bSize <$> buttonSize s
, bColor <$> buttonColor s
, bRadius <$> buttonRadius s
, maybeWhen (buttonDisabled s) "disabled"
]
where
bSize sz = case sz of
BtnTiny -> "tiny"
BtnSmall -> "small"
BtnLarge -> "large"
bColor co = case co of
BtnSecondary -> "secondary"
BtnAlert -> "alert"
BtnSuccess -> "success"
bRadius rd = case rd of
BtnRadius -> "radius"
BtnRound -> "round"
data ButtonStyle = ButtonStyle
{ buttonSize :: Maybe ButtonSize
, buttonColor :: Maybe ButtonColor
, buttonRadius :: Maybe ButtonRadius
, buttonDisabled :: Bool
}
alertBtn :: ButtonStyle -> ButtonStyle
alertBtn bs = bs { buttonColor = Just BtnAlert }
successBtn :: ButtonStyle -> ButtonStyle
successBtn bs = bs { buttonColor = Just BtnSuccess }
secondaryBtn :: ButtonStyle -> ButtonStyle
secondaryBtn bs = bs { buttonColor = Just BtnSecondary }
data ButtonSize
= BtnTiny
| BtnSmall
| BtnLarge
data ButtonColor
= BtnSecondary
| BtnAlert
| BtnSuccess
data ButtonRadius
= BtnRadius
| BtnRound
-- }}}
-- Dropdown {{{
data Dropdown = Dropdown
{ dropdownId :: String
, dropdownBlankDef :: Bool
, dropdownOpts :: [Option]
}
instance ToElementAction Dropdown String where
toElementAction d = do
sel <- UI.select # set UI.id_ (dropdownId d) #+ map toElement
((if dropdownBlankDef d then (opt "" :) else id) $
dropdownOpts d)
let getVal = get value sel
let setVal s = void $ element sel # set value s
{-void $ element sel #
set UI.selection
((+ 1) <$> elemIndex s (map optString $ dropdownOpts d))
-}
return (sel,getVal,setVal)
-- Option
data Option = Option
{ optString :: String
, optDisabled :: Bool
}
instance ToElement Option where
toElement o = option #
set disabled (optDisabled o) #
set value (optString o) #~
optString o
opt :: String -> Option
opt s = Option s False
disableOption :: Option -> Option
disableOption o = o { optDisabled = True }
enableOption :: Option -> Option
enableOption o = o { optDisabled = False }
-- }}}
-- Radios {{{
data Radios a = Radios
{ radioName :: String
, radioDefault :: Maybe String
, radioOptions :: [(a,String)]
}
radOpt :: String -> (IO Element, String)
radOpt s = (string s, s)
instance ToElements a => ToElementsAction (Radios a) (Maybe String) where
toElementsAction (Radios _ _ []) = fail "Empty Radio Options"
toElementsAction (Radios nm mdef (r:rs)) = do
(r',v) <- mkOption (r,0)
(rs',vs) <- fmap unzip $ mapM mkOption $ zip rs [1..]
let setVal ms = forM_ (r':rs') $ \rad -> do
mv <- Just <$> get value rad
void $ element rad # set UI.checked (mv == ms)
let getVal = do vals <- fmap catMaybes $ forM (r':rs') $ \rad -> do
chkd <- get UI.checked rad
if chkd
then Just <$> get value rad
else return Nothing
case vals of
[x] -> return $ Just x
[] -> return Nothing
_ -> fail $ "More than one radio button checked??: " ++ show vals
return (v:vs,getVal,setVal)
where
mkOption :: ToElements a => ((a,String),Integer) -> IO (Element,Element)
mkOption ((a,val),i) = do
let idStr = nm ++ show i
inp <- UI.input #*
[ set UI.name nm
, set UI.type_ "radio"
, set UI.id_ idStr
, set value val
, set checked (mdef == Just val)
]
cts <- toElements a
lab <- label #
set for idStr #
set UI.valign "middle" #+
( element inp
: UI.span #~ " "
: map element cts
)
return (inp,lab)
-- }}}
-- Checkboxes {{{
data Checkboxes a = Checkboxes
{ checkboxName :: String
, checkboxDefaults :: [String]
, checkboxOptions :: [(a,String)]
}
instance ToElements a => ToElementsAction (Checkboxes a) [String] where
toElementsAction (Checkboxes _ _ []) = fail "Empty Checkbox Options"
toElementsAction (Checkboxes nm defs (c:cs)) = do
(c',v) <- mkOption c
(cs',vs) <- fmap unzip $ mapM mkOption cs
let setVal ss = forM_ (c':cs') $ \cbx -> do
mv <- get value cbx
when (mv `elem` ss) $ void $
element cbx # set UI.checked True
let getVal = fmap catMaybes $ forM (c':cs') $ \cbx -> do
chkd <- get UI.checked cbx
if chkd
then Just <$> get value cbx
else return Nothing
return (v:vs,getVal,setVal)
where
mkOption (a,val) = do
let chkd = val `elem` defs
inp <- UI.input #*
[ set UI.name nm
, set UI.type_ "checkbox"
, set UI.id_ nm
, set UI.style [("display","none")]
, set value val
, if chkd then set UI.checked True else id
]
cts <- toElements a
lab <- label # set for nm #+
( element inp
: UI.span #
set classes ((if chkd then ("checked" :) else id) ["custom","checkbox"])
: map element cts
)
return (inp,lab)
-- }}}
-- LegendFor {{{
data LegendFor a = LegendFor
{ legendStr :: String
, legendFor :: a
}
instance ToElements a => ToElement (LegendFor a) where
toElement (LegendFor leg a) = do
cts <- toElements a
fieldset #+
( legend #~ leg
: map element cts
)
-- }}}
-- LabelFor {{{
data LabelFor a = LabelFor
{ labelId :: String
, labelLab :: Label
, labelFor :: a
}
instance ToElement a => ToElements (LabelFor a) where
toElements (LabelFor idStr lbl a) = do
lbl' <- toElements lbl
lab <- label # set for idStr #+ map element lbl'
anch <- toElement a # set UI.id_ idStr
return [ lab , anch ]
-- }}}
|
kylcarte/threepenny-extras
|
src/Foundation/Input.hs
|
bsd-3-clause
| 7,994
| 0
| 20
| 2,581
| 2,543
| 1,311
| 1,232
| 203
| 6
|
module Network.TeleHash.SwitchApi
(
-- * Telehash-c api
switch_send
, switch_sending
, switch_sendingQ
, switch_receive
, switch_open
, switch_pop
, switch_seed
, switch_note
-- * chan api
, chan_start
, chan_new
, chan_free
, chan_reliable
, chan_reset
, chan_in
, chan_packet
, chan_pop
, chan_pop_all
, chan_end
, chan_fail
, chan_notes
, chan_notes_all
, chan_note
, chan_reply
, chan_receive
, chan_send
, chan_ack
, chan_queue
, chan_dequeue
, chan_tick
-- * link api
, link_hn
-- * hn api
, hn_fromaddress
-- * seek api
, peer_send
) where
import Control.Exception
import Control.Monad
import Control.Monad.State
import Data.List
import Data.Maybe
import Prelude hiding (id, (.), head, either)
import System.Time
import Network.TeleHash.Convert
import Network.TeleHash.Crypt
import Network.TeleHash.Hn
import Network.TeleHash.Packet
import Network.TeleHash.Path
import Network.TeleHash.Paths
import Network.TeleHash.Types
import Network.TeleHash.Utils
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Base16 as B16
import qualified Data.ByteString.Char8 as BC
-- import qualified Data.ByteString.Lazy as BL
import qualified Data.HashMap.Strict as HM
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Text as Text
switch_sending :: TeleHash (Maybe TxTelex)
switch_sending = do
sw <- get
case (swOut sw) of
[] -> return Nothing
(p:ps) -> do
put $ sw { swOut = ps
, swLast = if null ps then Nothing else (swLast sw)
}
return (Just p)
{-
packet_t switch_sending(switch_t s)
{
packet_t p;
if(!s || !s->out) return NULL;
p = s->out;
s->out = p->next;
if(!s->out) s->last = NULL;
return p;
}
-}
-- ---------------------------------------------------------------------
-- |Receive a `NetworkPacket` via a `Path`. This function is called
-- from the driving code.
switch_receive :: NetworkPacket -> Path -> ClockTime -> TeleHash ()
switch_receive rxPacket path timeNow = do
logT $ "switch_receive:path=" ++ showPathJson (pJson path)
-- hnSelf <- getOwnHN
-- putPathIfNeeded hnSelf path
-- counterVal <- incPCounter
let packet = NetworkTelex
{ ntSender = path
, ntId = 0 -- counterVal
, ntAt = timeNow
, ntPacket = rxPacket
}
case rxPacket of
OpenPacket _b _bs -> do
-- process open packet
open <- crypt_deopenize rxPacket
case open of
DeOpenizeVerifyFail -> do
logT $ ">>>>:DEOPEN fail for " ++ show rxPacket
return ()
deOpenizeResult -> do
logP $ ">>>>:DEOPEN " ++ showJson (doJs open)
logT $ "receive.deopenize verified ok " -- ++ show open
let minner = parseJsVal (doJs open) :: Maybe OpenizeInner
case minner of
Nothing -> do
logT $ "switch_receive:invalid inner js:" ++ (BC.unpack $ lbsTocbs $ Aeson.encode $ doJs open)
return ()
Just inner -> do
-- logT $ "switch_receive:openize:inner=" ++ show inner
mfrom <- hn_frompacket inner deOpenizeResult
-- mfrom <- hn_getparts (oiFrom inner)
case mfrom of
Nothing -> do
logT $ "switch_receive:openize:invalid from" ++ show (oiFrom inner)
return ()
Just from -> do
logT $ "switch_receive:openize:from=" ++ show (hHashName from)
mlineCrypto <- case hCrypto from of
Nothing -> return Nothing
Just c -> crypt_line open c inner
case mlineCrypto of
Nothing -> do
-- not new/valid, ignore
logT $ "old or invalid open, ignoring"
return ()
Just lineCrypto -> do
-- line is open
logR $ "line in " ++ show (cLined lineCrypto,(hHashName from),cLineHex lineCrypto)
-- DEBUG_PRINTF("line in %d %s %d %s",from->c->lined,from->hexname,from,from->c->lineHex);
logP $ ">>>>:LINE IN " ++ show (cLined lineCrypto,(hHashName from),cLineHex lineCrypto)
from2 <- withHN (hHashName from) $ \from1 -> from1 { hCrypto = Just lineCrypto }
if cLined lineCrypto == LineReset
then chan_reset (hHashName from2)
else return ()
putHexLine (cLineHex lineCrypto) (hHashName from)
logT $ "switch_receive:openize:path=" ++ show (path)
if isJust (pBridgeChan path)
then putPath (hHashName from) path
else return ()
-- logT $ "switch_receive:openize:calling hn_path for path" ++ showJson (pJson path)
inVal <- hn_path (hHashName from) (pJson path)
from3 <- getHN (hHashName from2)
-- logT $ "switch_receive:openize:hn_path returned" ++ showJson inVal
logT $ "switch_receive:openize:hn_path returned" ++ show inVal
switch_open (hHashName from) inVal -- in case
case hOnopen from3 of
Nothing -> do
logT $ "switch_receive:openize:no onopen"
return ()
Just onopen -> do
logT $ "switch_receive:openize:processing onopen:" ++ show onopen
void $ withHN (hHashName from) $ \from4 -> from4 { hOnopen = Nothing }
switch_send (onopen { tOut = pJson (gfromJust "onopen" inVal) })
return ()
LinePacket pbody -> do
-- its a line
logT $ "switch_receive:got line msg:length=" ++ show (BC.length pbody)
let lineID = BC.unpack $ B16.encode $ BC.take 16 pbody
-- logT $ "receive:lineID=" ++ lineID
mfrom <- getHexLineMaybe lineID
case mfrom of
Nothing -> do
-- if(packet.length == 2) return; // empty packets are NAT pings
if BC.length pbody == 0
then return () -- empty packets are NAT pings
else do
logT $ "switch_receive: no line found for " ++ lineID ++ "," ++ show pbody
return ()
{-
-- From equivalent thjs code
// a matching line is required to decode the packet
if(!line) {
if(!self.bridgeLine[lineID]) return debug("unknown line received", lineID, packet.sender);
debug("BRIDGE",JSON.stringify(self.bridgeLine[lineID]),lineID);
var id = crypto.createHash("sha256").update(packet.body).digest("hex")
if(self.bridgeCache[id]) return; // drop duplicates
self.bridgeCache[id] = true;
// flat out raw retransmit any bridge packets
return self.send(self.bridgeLine[lineID],msg);
}
-}
Just fromHn -> do
from <- getHN fromHn
inVal <- hn_path (hHashName from) (pJson path)
p <- crypt_delineize (gfromJust "switch_receive" $ hCrypto from) packet
-- logT $ "crypt_delineize result:" ++ show p
case p of
Left err -> do
-- DEBUG_PRINTF("invlaid line from %s %s",path_json(in),from->hexname);
logT $ "invalid line from " ++ show (inVal,hHashName from)
logP $ "delineize:err " ++ err
return ()
Right rx -> do
mchan <- chan_in (hHashName from) rx
logP $ ">>>>:" ++ show (fmap showChan mchan,showPathJson $ rtSender rx,showPacketShort $ rtPacket rx)
case mchan of
Just chan -> do
sw <- get
-- if new channel w/ seq, configure as reliable
-- logT $ "switch_receive (chan,rx) :" ++ show (chan,rx)
-- logT $ "switch_receive (chState,seq) :" ++ show (chState chan,packet_has_key rx "seq")
chan2 <- if (chState chan == ChanStarting && packet_has_key rx "seq")
then chan_reliable (chUid chan) (swWindow sw)
else return chan
putChan chan2
logT $ "receive:sending to chan:" ++ showChan chan2
chan_receive (chUid chan2) rx
Nothing -> do
-- bounce it
if packet_has_key rx "err"
then return ()
else do
let txp = packet_new fromHn
tx = txp { tOut = pJson path }
tx2 = packet_set_str tx "err" "unknown channel"
switch_send tx2
{-
// bounce it!
if(!packet_get_str(p,"err"))
{
packet_set_str(p,"err","unknown channel");
p->to = from;
p->out = in;
switch_send(s, p);
}else{
packet_free(p);
}
-}
PingPongPacket _p -> do
-- handle valid pong responses, start handshake
{-
if(util_cmp("pong",packet_get_str(p,"type")) == 0
&& util_cmp(xht_get(s->index,"ping"),packet_get_str(p,"trace")) == 0
&& (from = hn_fromjson(s->index,p)) != NULL)
{
DEBUG_PRINTF("pong from %s",from->hexname);
in = hn_path(from, in);
switch_open(s,from,in);
packet_free(p);
return;
}
-}
assert False undefined
{-
void switch_receive(switch_t s, packet_t p, path_t in)
{
hn_t from;
packet_t inner;
crypt_t c;
chan_t chan;
char hex[3];
char lineHex[33];
if(!s || !p || !in) return;
// handle open packets
if(p->json_len == 1)
{
util_hex(p->json,1,(unsigned char*)hex);
c = xht_get(s->index,hex);
if(!c) return (void)packet_free(p);
inner = crypt_deopenize(c, p);
DEBUG_PRINTF("DEOPEN %d",inner);
if(!inner) return (void)packet_free(p);
from = hn_frompacket(s->index, inner);
if(crypt_line(from->c, inner) != 0) return; // not new/valid, ignore
// line is open!
DEBUG_PRINTF("line in %d %s %d %s",from->c->lined,from->hexname,from,from->c->lineHex);
if(from->c->lined == 1) chan_reset(s, from);
xht_set(s->index, (const char*)from->c->lineHex, (void*)from);
in = hn_path(from, in);
switch_open(s, from, in); // in case we need to send an open
if(from->onopen)
{
packet_t last = from->onopen;
from->onopen = NULL;
last->out = in;
switch_send(s, last);
}
return;
}
// handle line packets
if(p->json_len == 0)
{
util_hex(p->body, 16, (unsigned char*)lineHex);
from = xht_get(s->index, lineHex);
if(from)
{
in = hn_path(from, in);
p = crypt_delineize(from->c, p);
if(!p)
{
DEBUG_PRINTF("invlaid line from %s %s",path_json(in),from->hexname);
return;
}
// route to the channel
if((chan = chan_in(s, from, p)))
{
// if new channel w/ seq, configure as reliable
if(chan->state == CHAN_STARTING && packet_get_str(p,"seq")) chan_reliable(chan, s->window);
return chan_receive(chan, p);
}
// bounce it!
if(!packet_get_str(p,"err"))
{
packet_set_str(p,"err","unknown channel");
p->to = from;
p->out = in;
switch_send(s, p);
}else{
packet_free(p);
}
return;
}
}
// handle valid pong responses, start handshake
if(util_cmp("pong",packet_get_str(p,"type")) == 0 && util_cmp(xht_get(s->index,"ping"),packet_get_str(p,"trace")) == 0 && (from = hn_fromjson(s->index,p)) != NULL)
{
DEBUG_PRINTF("pong from %s",from->hexname);
in = hn_path(from, in);
switch_open(s,from,in);
packet_free(p);
return;
}
// handle pings, respond if local only or dedicated seed
if(util_cmp("ping",packet_get_str(p,"type")) == 0 && (s->isSeed || path_local(in)))
{
switch_pong(s,p,in);
packet_free(p);
return;
}
// nothing processed, clean up
packet_free(p);
}
-}
-- ---------------------------------------------------------------------
-- |Main entry point to send a message. Will initiate seek/open
-- process if the destination is unknown
switch_send :: TxTelex -> TeleHash ()
switch_send p = do
sw <- get
-- require recipient at least, and not us
if (tTo p) == (swId sw)
then do
logT $ "switch_send:to is us, dropping packet"
return ()
else do
-- encrypt the packet to the line, chains together
hc <- getHN (tTo p)
-- logT $ "switch_send:p=" ++ show p
-- insert the JS into the packet head
p2 <- telexToPacket p
logT $ "switch_send:p2=" ++ show p2
(mcrypto1,mlined) <- crypt_lineize (hCrypto hc) p2
-- putHN $ hc { hCrypto = mcrypto1 }
void $ withHN (tTo p) $ \hc1 -> hc1 { hCrypto = mcrypto1 }
case mlined of
Just lined -> do
switch_sendingQ $ p2 { tLp = Just lined}
Nothing -> do
-- queue most recent packet to be sent after opened
logT $ "switch_send:queueing packet until line:" ++ show (tTo p2) ++ "," ++ showJson (tJs p2)
logR $ "switch_send:queueing packet until line:" ++ show (tTo p2) ++ "," ++ showJson (tJs p2)
void $ withHN (tTo p2) $ \hc2 -> hc2 { hOnopen = Just p2 }
-- no line, so generate open instead
switch_open (tTo p2) Nothing
-- send a peer request if required
logT $ "switch_send:hVias=" ++ show (hVias hc)
if hVias hc == Map.empty
then return ()
else do
let vias = Map.toList (hVias hc)
-- putHN $ hc { hVias = Map.empty }
void $ withHN (hHashName hc) $ \hc3 -> hc3 { hVias = Map.empty }
forM_ vias $ \(hn,see) -> do
peer_send hn see
return ()
-- ---------------------------------------------------------------------
switch_open :: HashName -> Maybe Path -> TeleHash ()
switch_open hn direct = do
hc <- getHN hn
case hCrypto hc of
Nothing -> do
logT $ "switch_open: can't open, no key for " ++ (unHN (hHashName hc))
sw <- get
case (swHandler sw) of
Just handler -> handler hn -- calls _seek_auto
Nothing -> return ()
Just crypto -> do
-- actually send the open
sw <- get
let inner1 = packet_new (hHashName hc)
inner2 = packet_set_str inner1 "to" (unHN $ hHashName hc)
inner3 = packet_set inner2 "from" (swParts sw)
inner = OpenizeInner { oiAt = cAtOut crypto
, oiTo = hHashName hc
, oiFrom = swParts sw
, oiLine = cLineHex crypto
}
case Map.lookup "1a" (swIndexCrypto sw) of
Nothing -> do
logT $ "switch_open: missing crypto"
assert False undefined
Just cryptoSelf -> do
mopen <- crypt_openize cryptoSelf crypto inner
logT $ "opening to " ++ show ("1a",hHashName hc)
case mopen of
Nothing -> do
logT $ "switch_open: could not openize, discarding"
return ()
Just open -> do
-- TODO: send this via all known paths
let inner4 = case direct of
Just path -> inner3 {tOut = pJson path}
Nothing -> inner3
logT $ "switch_open:sending " ++ show inner4
switch_sendingQ $ inner4 { tLp = Just open }
{-
// todo change all .see processing to add via info, and change inConnect
function vias()
{
if(!hn.vias) return;
var todo = hn.vias;
delete hn.vias; // never use more than once so we re-seek
// send a peer request to all of them
Object.keys(todo).forEach(function(via){
self.whois(via).peer(hn.hashname,todo[via]);
});
}
// if there's via information, just try that
if(hn.vias) return vias();
-}
{-
// tries to send an open if we haven't
void switch_open(switch_t s, hn_t to, path_t direct)
{
packet_t open, inner;
if(!to) return;
if(!to->c)
{
DEBUG_PRINTF("can't open, no key for %s",to->hexname);
if(s->handler) s->handler(s,to);
return;
}
// actually send the open
inner = packet_new();
packet_set_str(inner,"to",to->hexname);
packet_set(inner,"from",(char*)s->parts->json,s->parts->json_len);
open = crypt_openize((crypt_t)xht_get(s->index,to->hexid), to->c, inner);
DEBUG_PRINTF("opening to %s %hu %s",to->hexid,packet_len(open),to->hexname);
if(!open) return;
open->to = to;
if(direct) open->out = direct;
switch_sendingQ(s, open);
}
-}
-- ---------------------------------------------------------------------
-- |internally adds to sending queue
switch_sendingQ :: TxTelex -> TeleHash ()
switch_sendingQ p = do
-- logT $ "switch_sendingQ " ++ show p
-- if there's no path, find one or copy to many
mp <- if tOut p == PNone
then do
let toVal = tTo p
-- if the last path is alive, just use that
to <- getHN toVal
(done,p2) <- do
case hLast to of
Just lastJson -> do
lastPath <- getPath (hHashName to) lastJson
-- logT $ "switch_sendingQ:lastPath=" ++ show lastPath
alive <- path_alive lastPath
-- logT $ "switch_sendingQ:alive=" ++ show alive
if alive
then return (True, p { tOut = lastJson })
else return (False,p)
Nothing -> return (False,p)
if done
then return (Just p2)
else do
-- try sending to all paths
forM_ (Map.elems (hPaths to)) $ \path1 -> do
-- logT $ "switch_sendingQ:processing path=" ++ show path1
switch_sendingQ $ p { tOut = pJson path1 }
return Nothing
else do
return (Just p)
-- logT $ "switch_sendingQ:mp=" ++ show mp
case mp of
Nothing -> return ()
Just p3 -> do
timeNow <- io getClockTime
path <- getPath (tTo p3) (tOut p3)
logT $ "switch_sendingQ:path=" ++ show path
-- Tunnel if necessary
case pBridgeChan path of
Nothing -> do
putPath (tTo p3) (path { pAtOut = Just timeNow })
sw <- get
put $ sw { swOut = (swOut sw) ++ [p3]
, swLast = Just p3
}
Just cid -> do
c <- getChan cid
let pp1 = packet_new (chTo c)
pp2 = packet_body pp1 (unLP $ gfromJust "switch_sendingQ" $ tLp p3)
pp3 = packet_set_int pp2 "c" (unChannelId $ chId c)
chan_send cid pp3
return ()
{-
// internally adds to sending queue
void switch_sendingQ(switch_t s, packet_t p)
{
packet_t dup;
if(!p) return;
// if there's no path, find one or copy to many
if(!p->out)
{
// just being paranoid
if(!p->to)
{
packet_free(p);
return;
}
// if the last path is alive, just use that
if(path_alive(p->to->last)) p->out = p->to->last;
else{
int i;
// try sending to all paths
for(i=0; p->to->paths[i]; i++)
{
dup = packet_copy(p);
dup->out = p->to->paths[i];
switch_sendingQ(s, dup);
}
packet_free(p);
return;
}
}
// update stats
p->out->atOut = platform_seconds();
// add to the end of the queue
if(s->last)
{
s->last->next = p;
s->last = p;
return;
}
s->last = s->out = p;
}
-}
-- ---------------------------------------------------------------------
-- |Returns Uid of channels requiring processing
switch_pop :: TeleHash (Maybe Uid)
switch_pop = do
sw <- get
case Set.elems (swChans sw) of
[] -> do
return Nothing
(c:_) -> do
chan_dequeue c
return $ Just c
{-
chan_t switch_pop(switch_t s)
{
chan_t c;
if(!s->chans) return NULL;
c = s->chans;
chan_dequeue(c);
return c;
}
-}
-- ---------------------------------------------------------------------
switch_seed :: HashName -> TeleHash ()
switch_seed hn = do
sw <- get
put $ sw { swSeeds = Set.insert hn (swSeeds sw)}
{-
void switch_seed(switch_t s, hn_t hn)
{
if(!s->seeds) s->seeds = bucket_new();
bucket_add(s->seeds, hn);
}
-}
-- ---------------------------------------------------------------------
-- |Periodic processing for a channel
chan_tick :: Uid -> TeleHash ()
chan_tick cid = do
c <- getChan cid
-- logT $ "chan_tick called for " ++ show cid
-- assert False undefined
case chTimeout c of
Nothing -> return ()
Just timeout -> do
now <- io getClockTime
-- isTimeOut
if isJust (chRecvAt c) && isTimeOut now (chRecvAt c) timeout
then do
logT $ "chan_tick:got timeout " ++ show (showChan c,now,chRecvAt c,timeout)
if chState c /= ChanEnded
then do
-- signal incoming error if still open, restarts timer
let p1 = packet_new (chTo c)
p2 = packet_set_str p1 "err" "timeout"
p3 = packet_set_int p2 "c" (unChannelId $ chId c)
chan_receive cid (txTelexToRxTelex p3)
else do
-- clean up references if needed
void $ chan_end cid Nothing
return ()
else return ()
return ()
{-
-- JS timeout processing
// raw channels always timeout/expire after the last received packet
function timer()
{
if(chan.timer) clearTimeout(chan.timer);
chan.timer = setTimeout(function(){
// signal incoming error if still open, restarts timer
if(!chan.ended) return hn.receive({js:{err:"timeout",c:chan.id}});
// clean up references if ended
hn.chanEnded(chan.id);
}, arg.timeout);
}
chan.timeout = function(timeout)
{
arg.timeout = timeout;
timer();
}
chan.timeout(arg.timeout || defaults.chan_timeout);
-}
-- ---------------------------------------------------------------------
-- |sends a note packet to it's channel if it can, !0 for error
switch_note :: TxTelex -> TeleHash OkFail
switch_note note = do
-- logT $ "switch_note:note=" ++ show note
-- cstr <- showAllChans
-- logT $ "switch_note:all chans=\n" ++ cstr
case packet_get_int note ".to" of
Nothing -> return Fail
Just toVal -> do
logT $ "switch_note:toVal=" ++ show toVal
mc <- getChanMaybe toVal
case mc of
Nothing -> do
logT $ "switch_note:cannot retrieve channel uid " ++ show toVal
return Fail
Just c -> do
let c2 = c { chNotes = (chNotes c) ++ [note] }
putChan c2
chan_queue c2
return Ok
{-
// sends a note packet to it's channel if it can, !0 for error
int switch_note(switch_t s, packet_t note)
{
chan_t c;
packet_t notes;
if(!s || !note) return -1;
c = xht_get(s->index,packet_get_str(note,".to"));
if(!c) return -1;
notes = c->notes;
while(notes) notes = notes->next;
if(!notes) c->notes = note;
else notes->next = note;
chan_queue(c);
return 0;
}
-}
-- ---------------------------------------------------------------------
-- =====================================================================
-- chan api
-- Based on the telehash-c version
-- ---------------------------------------------------------------------
-- |kind of a macro, just make a reliable channel of this type to this hashname
chan_start :: HashName -> String -> TeleHash TChan
chan_start hn typ = do
c <- chan_new hn typ Nothing
window <- gets swWindow
chan_reliable (chUid c) window
{-
// kind of a macro, just make a reliable channel of this type to this hashname
chan_t chan_start(switch_t s, char *hn, char *type)
{
chan_t c;
if(!s || !hn) return NULL;
c = chan_new(s, hn_gethex(s->index,hn), type, 0);
return chan_reliable(c, s->window);
}
-}
-- ---------------------------------------------------------------------
-- |new channel, pass Nothing for channel id to create an outgoing one
chan_new :: HashName -> String -> Maybe ChannelId -> TeleHash TChan
chan_new toHn typ mcid = do
logT $ "chan_new:" ++ show (toHn,typ,mcid)
to <- getHN toHn
sw <- get
let base = if (swId sw) > toHn
then 1 else 2::Int
logT $ "chan_new:(base,hChanOut)" ++ show (base,hChanOut to)
if hChanOut to == nullChannelId
then chan_reset toHn
else return ()
to2 <- getHN toHn
-- use new id if none given
cid <- case mcid of
Nothing -> do
let c = hChanOut to2
co = c + 2
withHN toHn $ \hc -> hc {hChanOut = co}
return c
Just c -> do
logT $ "chan_new:using cid:" ++ show c
return c
uid <- getNextUid
logT $ "chan_new:channel new (cid,uid,typ)=" ++ show (cid,uid,typ)
let chan = TChan
{ chId = cid
, chUid = uid
, chTo = toHn
, chType = typ
, chReliable = 0
, chState = ChanStarting
, chLast = Nothing
, chNext = Nothing
, chIn = []
, chNotes = []
, chHandler = Nothing
, chTimeout = Just param_chan_timeout_secs
, chRecvAt = Nothing
, chArg = CArgNone
, chSeq = Nothing
, chMiss = Nothing
}
void $ withHN toHn (\hc -> hc { hChans = Map.insert cid (chUid chan) (hChans hc) })
putChan chan
logT $ "chan_new:created " ++ showChan chan
return chan
-- ---------------------------------------------------------------------
{-
// configures channel as a reliable one, must be in STARTING state, is max # of packets to buffer before backpressure
chan_t chan_reliable(chan_t c, int window);
-}
chan_reliable :: Uid -> Int -> TeleHash TChan
chan_reliable cid window = do
c <- getChan cid
-- logT $ "chan_reliable (c,window):" ++ show (c,window)
if window == 0 || chState c /= ChanStarting || chReliable c /= 0
then return c
else do
let c2 = c { chReliable = window }
putChan c2
chan_seq_init c2
chan_miss_init (chUid c2)
c3 <- getChan (chUid c2)
return c3
{-
chan_t chan_reliable(chan_t c, int window)
{
if(!c || !window || c->state != CHAN_STARTING || c->reliable) return c;
c->reliable = window;
chan_seq_init(c);
chan_miss_init(c);
return c;
}
-}
-- ---------------------------------------------------------------------
-- |resets channel state for a hashname
chan_reset :: HashName -> TeleHash ()
chan_reset toHn = do
logT $ "chan_reset:" ++ show toHn
sw <- get
to1 <- getHN toHn
-- sort both hashnames alphabetically and the lower/first sorted one
-- uses only even numbers (2 or greater), while the higher/second
-- one uses odd numbers (1 or greater).
let base = if (swId sw) > (hHashName to1)
then 1 else 2
void $ withHN toHn $ \hc ->
if (hChanOut hc == nullChannelId
|| channelSlot (hChanOut hc) /= channelSlot (CID base))
then hc {hChanOut = CID base}
else hc
-- fail any existing chans from them
void $ withHNM toHn $ \hc -> do
forM_ (Map.elems $ hChans hc) $ \cid -> do
ch <- getChan cid
if channelSlot (chId ch) == channelSlot (CID base)
then return ()
else void $ chan_fail cid Nothing
hc' <- getHN (hHashName hc)
logT $ "chan_reset:(toHn,base,hChanOut)=" ++ show (toHn,base,hChanOut hc')
return hc'
{-
void chan_reset(switch_t s, hn_t to)
{
uint8_t base = (strncmp(s->id->hexname,to->hexname,64) > 0) ? 1 : 2;
if(!to->chanOut) to->chanOut = base;
// fail any existing chans from them
xht_walk(to->chans, &walkend, (void*)&base);
}
void walkend(xht_t h, const char *key, void *val, void *arg)
{
uint8_t base = *(uint8_t*)arg;
chan_t c = (chan_t)val;
if(c->id % 2 != base % 2) chan_fail(c,NULL);
}
-}
-- ---------------------------------------------------------------------
-- |returns existing or creates new and adds to from
chan_in :: HashName -> RxTelex -> TeleHash (Maybe TChan)
chan_in hn p = do
case getRxTelexChannelId p of
Nothing -> do
logT $ "chan_in:no channel id"
assert False undefined
Just cid -> do
mchan <- getChanFromHn hn cid
case mchan of
Just chan -> return (Just chan)
Nothing -> do
from <- getHN hn
-- logT $ "chan_in:p=" ++ show p
let mtyp = getRxTelexType p
-- logT $ "chan_in:mtyp=" ++ show mtyp
-- logT $ "chan_in:cid,hChanout from=" ++ show (cid,hChanOut from)
if (mtyp == Nothing
|| channelSlot cid == channelSlot (hChanOut from))
then do
logT $ "chan_in:can't make channel " ++ show (hn,mtyp,cid,hChanOut from)
return Nothing
else do
logT $ "chan_in:making new chan"
chan <- chan_new hn (gfromJust "chan_in" mtyp) (Just cid)
return (Just chan)
{-
chan_t chan_in(switch_t s, hn_t from, packet_t p)
{
chan_t c;
unsigned long id;
char hexid[9], *type;
if(!from || !p) return NULL;
id = strtol(packet_get_str(p,"c"), NULL, 10);
util_hex((unsigned char*)&id,4,(unsigned char*)hexid);
c = xht_get(from->chans, hexid);
if(c) return c;
type = packet_get_str(p, "type");
if(!type || id % 2 == from->chanOut % 2) return NULL;
return chan_new(s, from, type, id);
}
-}
-- ---------------------------------------------------------------------
-- |create a packet ready to be sent for this channel, returns Nothing for backpressure
chan_packet :: Uid -> Bool -> TeleHash (Maybe TxTelex)
chan_packet cid incSeq = do
chan <- getChan cid
if chState chan == ChanEnded
then return Nothing
else do
mp <- if incSeq && chReliable chan /= 0
then chan_seq_packet cid
else return $ Just (packet_new (chTo chan))
chan2 <- getChan cid
-- logT $ "chan_packet:chSeq=" ++ show (chSeq chan2)
case mp of
Nothing -> do
logT $ "chan_packet:mp=Nothing"
return Nothing
Just p -> do
let p1 = p { tTo = chTo chan2 }
alive <- case chLast chan2 of
Nothing -> return False
Just lpj -> do
lp <- getPath (chTo chan2) lpj
path_alive lp
let p2 = if alive
then p1 { tOut = gfromJust "chan_packet" $ chLast chan }
else p1
p3 = if chState chan2 == ChanStarting
then packet_set_str p2 "type" (chType chan2)
else p2
p4 = packet_set_int p3 "c" (unChannelId $ chId chan2)
-- chan3 <- getChan cid
-- logT $ "chan_packet:chSeq 3=" ++ show (chSeq chan3)
return (Just p4)
-- ---------------------------------------------------------------------
-- |pop a packet from this channel to be processed, caller must free
chan_pop :: Uid -> TeleHash (Maybe RxTelex)
chan_pop chanUid = do
mchan <- getChanMaybe chanUid
case mchan of
Nothing -> return Nothing
Just chan -> do
-- logT $ "chan_pop:(uid,id,chReliable)=" ++ show (chanUid,chId chan,chReliable chan)
if (chReliable chan /= 0)
then chan_seq_pop chanUid
else do
if null (chIn chan)
then return Nothing
else do
let p = head (chIn chan)
let c2 = chan { chIn = tail (chIn chan) }
putChan c2
return (Just p)
{-
packet_t chan_pop(chan_t c)
{
packet_t p;
if(!c) return NULL;
if(c->reliable) return chan_seq_pop(c);
if(!c->in) return NULL;
p = c->in;
c->in = p->next;
if(!c->in) c->inend = NULL;
return p;
}
-}
-- ---------------------------------------------------------------------
chan_pop_all :: Uid -> TeleHash [RxTelex]
chan_pop_all uid = do
let
go acc = do
mrx <- chan_pop uid
case mrx of
Nothing -> return acc
Just rx -> go (acc ++ [rx])
msgs <- go []
return msgs
-- ---------------------------------------------------------------------
-- flags channel as gracefully ended, optionally adds end to packet
chan_end :: Uid -> Maybe TxTelex -> TeleHash (Maybe TxTelex)
chan_end chanId p = do
logT $ "channel end " ++ show (chanId)
chan <- getChan chanId
let
pret = case p of
Nothing -> Nothing
Just pkt -> Just (packet_set pkt "end" True)
chan_dequeue chanId
rmChanFromHn (chTo chan) (chUid chan)
rmChan chanId
return pret
-- ---------------------------------------------------------------------
-- |immediately fails/removes channel, if err tries to send message
chan_fail :: Uid -> Maybe String -> TeleHash ()
chan_fail cid merr = do
c <- getChan cid
logT $ "channel fail " ++ show (chId c,chUid c,merr)
case merr of
Just err -> do
if chState c /= ChanEnded
then do
e <- chan_packet cid True
case e of
Nothing -> return ()
Just e1 -> do
let e2 = packet_set_str e1 "err" err
chan_send cid e2
else return ()
Nothing -> return ()
-- no grace period for reliable
let c2 = c { chState = ChanEnded }
putChan c2
chan_dequeue cid
rmChanFromHn (chTo c) (chUid c)
rmChan cid
return ()
-- ---------------------------------------------------------------------
chan_free :: TChan -> TeleHash ()
chan_free chan = do
logT $ "chan_free " ++ show (chId chan,chUid chan)
-- remove references
chan_dequeue (chUid chan)
rmChanFromHn (chTo chan) (chUid chan)
if (chReliable chan /= 0)
then do
chan_seq_free chan
chan_miss_free (chUid chan)
else return ()
if null (chIn chan)
then return ()
else do
logT $ "unused packets on channel " ++ show (chId chan)
if null (chNotes chan)
then return ()
else do
logT $ "unused notes on channel " ++ show (chId chan)
-- must be last, remove from the index
rmChan (chUid chan)
-- ---------------------------------------------------------------------
-- |get the next incoming note waiting to be handled
chan_notes :: TChan -> TeleHash (Maybe TxTelex)
chan_notes cIn = do
c <- getChan (chUid cIn)
if null (chNotes c)
then return Nothing
else do
let r = head (chNotes c)
c2 = c {chNotes = tail (chNotes c)}
putChan c2
return (Just r)
-- ---------------------------------------------------------------------
-- |get all the incoming notes waiting to be handled
chan_notes_all :: TChan -> TeleHash [TxTelex]
chan_notes_all cIn = do
c <- getChan (chUid cIn)
let r = chNotes c
putChan $ c {chNotes = []}
return r
-- ---------------------------------------------------------------------
-- |stamp or create (if Nothing) a note as from this channel
chan_note :: TChan -> Maybe RxTelex -> TeleHash RxTelex
chan_note c mnote = do
let r = case mnote of
Just n -> n
Nothing -> packet_new_rx
let r2 = packet_set_int r ".from" (chUid c)
return r2
-- ---------------------------------------------------------------------
-- |send the note back to the creating channel, frees note
chan_reply :: Uid -> TxTelex -> TeleHash OkFail
chan_reply cid note = do
c <- getChan cid
-- logT $ "chan_reply:c,note=" ++ showChan c ++ "," ++ show note
case packet_get_int note ".from" of
Nothing -> do
logT $ "chan_reply:missing .from in note"
return Fail
Just from -> do
let note2 = packet_set_int note ".to" from
note3 = packet_set_int note2 ".from" (chUid c)
switch_note note3
-- ---------------------------------------------------------------------
-- |internal, receives/processes incoming packet
chan_receive :: Uid -> RxTelex -> TeleHash ()
chan_receive cid p = do
c <- getChan cid
-- logT $ "channel in " ++ show (chId c,p)
if chState c == ChanEnded
then return ()
else do
now <- io getClockTime
let
c2 = if chState c == ChanStarting
then c {chState = ChanOpen}
else c
c3 = case packet_get_str p "end" of
Nothing -> c2
Just _ -> c2 {chState = ChanEnding }
c4 = case packet_get_str p "err" of
Nothing -> c3
Just _ -> c3 {chState = ChanEnding }
c5 = c4 { chRecvAt = Just now }
putChan c5
if (chReliable c5 /= 0)
then do
chan_miss_check (chUid c5) p
r <- chan_seq_receive (chUid c5) p
logT $ "chan_receive:chan_seq_receive returned " ++ show (cid,r)
if not r
then return () -- queued, nothing more to do
else chan_queue c5
else do
-- add to the end of the raw packet queue
let c6 = c5 { chIn = (chIn c5) ++ [p]}
putChan c6
-- queue for processing
chan_queue c6
-- ---------------------------------------------------------------------
-- |According to the spec an ack-only packet should have only `ack`
-- and `c`, and `miss` elements in it, explicityly not a `seq`.
-- However some broken implementations include the `seq` field.
-- Returns `True` if either a correct or broken ack-only packet is received.
-- https://github.com/telehash/telehash.org/blob/master/reliable.md#ack---acknowledgements
isAckOnlyPacket :: RxTelex -> Bool
isAckOnlyPacket p = r
where
acceptedFields (k,_) = (Text.unpack k) `elem` ["ack","c","miss","seq"]
bodyOk = (unBody $ paBody (rtPacket p)) == BC.pack ""
headerOk = filter (\x -> not $ acceptedFields x) (HM.toList $ rtJs p) == []
r = bodyOk && headerOk
-- ---------------------------------------------------------------------
-- |smartly send based on what type of channel we are
chan_send :: Uid -> TxTelex -> TeleHash ()
chan_send cid p = do
c <- getChan cid
-- logT $ "chan_send:channel out " ++ show (chUid c,chId c,p)
p2 <- if chReliable c /= 0
then do
-- track the actual packet being sent in the miss structure
case chMiss c of
Nothing -> do
logT $ "chan_send:reliable channel should have a miss structure"
assert False undefined
Just miss -> do
let miss2 = miss { mPackets = Map.insert (tId p) p (mPackets miss)}
c2 = c { chMiss = Just miss2 }
putChan c2
return p
else return p
c3 <- getChan cid
case tOut p2 of
PNone -> return ()
_ -> do
putPathIfNeeded (chTo c3) (pathFromPathJson $ tOut p2)
putChan $ c3 { chLast = Just (tOut p2) }
switch_send p2
-- ---------------------------------------------------------------------
-- |optionally sends reliable channel ack-only if needed
chan_ack :: Uid -> TeleHash ()
chan_ack cid = do
mc <- getChanMaybe cid
case mc of
Nothing -> do
logT $ "chan_ack:channel dead:" ++ show cid
return ()
Just c -> do
if not (chReliable c /= 0)
then return ()
else do
mp <- chan_seq_ack cid Nothing
case mp of
Nothing -> return ()
Just p -> do
switch_send p
-- ---------------------------------------------------------------------
-- |add to switch processing queue
chan_queue :: TChan -> TeleHash ()
chan_queue c = do
-- add to switch queue
queueChan c
-- ---------------------------------------------------------------------
-- |remove channel id from switch processing queue
chan_dequeue :: Uid -> TeleHash ()
chan_dequeue c = do
dequeueChan c
-- ---------------------------------------------------------------------
-- |add ack, miss to any packet
chan_seq_ack :: Uid -> Maybe TxTelex -> TeleHash (Maybe TxTelex)
chan_seq_ack cid mp = do
c <- getChan cid
case chSeq c of
Nothing -> do
logT $ "chan_seq_ack:chSeq not populated"
assert False undefined
Just s -> do
-- detemine if we need to ack
if seNextIn s == 0
then do
logT $ "chan_seq_ack ack not needed " ++ show cid
return mp
else do
if isNothing mp && seAcked s /= 0 && seAcked s == (seNextIn s) - 1
then do
return Nothing
else do
mp2 <- case mp of
Nothing -> do
-- ack-only packet
mcp <- chan_packet cid False
return mcp
Just pp -> return (Just pp)
case mp2 of
Nothing -> do
return Nothing
Just p -> do
c1 <- getChan cid
let s1 = gfromJust "chan_seq_ack" $ chSeq c1
s2 = s1 { seAcked = (seNextIn s) - 1 }
p2 = packet_set_int p "ack" (seAcked s2)
c2 = c { chSeq = Just s2 }
putChan c2
-- check if miss is not needed
if seSeen s2 < seNextIn s2 || Map.member 0 (seIn s2)
then do
return (Just p2)
else do
-- create miss array, up to 10 ids of missing packets
let misses = concatMap (\i -> if Map.member i (seIn s2) then [i] else [])
$ [1 .. min 10 (chReliable c2)]
missVal = show misses
logT $ "chan_seq_ack:missVal=" ++ missVal
return $ Just (packet_set_str p2 "miss" missVal)
-- ---------------------------------------------------------------------
-- |new sequenced packet, NULL for backpressure
chan_seq_packet :: Uid -> TeleHash (Maybe TxTelex)
chan_seq_packet cid = do
c <- getChan cid
logT $ "chan_seq_packet:" ++ showChan c ++ "," ++ show (chSeq c)
case chSeq c of
Nothing -> do
logT $ "chan_seq_packet:no chSeq structure"
return Nothing
Just s -> do
-- Create a packet with unique transmit id, for local miss tracking
txid <- getNextTxid
let p = (packet_new (chTo c)) { tId = txid }
-- make sure there's tracking space
miss <- chan_miss_track cid (seId s) p
c2 <- getChan cid
if miss /= 0
then return Nothing
else do
-- set seq and add any acks
let p2 = packet_set_int p "seq" (seId s)
s2 = s { seId = (seId s) + 1 }
putChan $ c2 { chSeq = Just s2 }
logT $ "chan_seq_packet about to call chan_seq_ack"
r <- chan_seq_ack cid (Just p2)
ccc <- getChan cid
logT $ "chan_seq_packet about to call chan_seq_ack done " ++ show (chSeq ccc)
return r
-- ---------------------------------------------------------------------
-- |buffers packets until they're in order, returns True if some are ready to pop
chan_seq_receive :: Uid -> RxTelex -> TeleHash Bool
chan_seq_receive cid p = do
c <- getChan cid
-- logT $ "chan_seq_receive:" ++ show (c,p)
case chSeq c of
Nothing -> do
logT $ "chan_seq_receive: no chSeq struct for " ++ show (c,p)
return False
Just s -> do
-- drop or cache incoming packet
let mseq = packet_get_int p "seq"
let idVal = case mseq of
Nothing -> 0
Just v -> v
offset = idVal - (seNextIn s)
if mseq == Nothing || offset < 0 || offset >= chReliable c
|| (Map.member offset (seIn s))
then do
logT $ "chan_seq_receive:nothing to do:" ++ show (cid,mseq,offset,chReliable c,seIn s)
return False
else do
let -- track highest seen
seen = if idVal > seSeen s then idVal else seSeen s
s2 = s { seIn = Map.insert offset p (seIn s)
, seSeen = seen
}
c2 = c { chSeq = Just s2 }
putChan c2
return $ Map.member 0 (seIn s2)
-- ---------------------------------------------------------------------
-- |returns ordered packets for this channel, updates ack
chan_seq_pop :: Uid -> TeleHash (Maybe RxTelex)
chan_seq_pop cid = do
c <- getChan cid
case chSeq c of
Nothing -> do
logT $ "chan_seq_pop:missing chSeq structure" ++ show c
return Nothing
Just s -> do
case Map.lookup 0 (seIn s) of
Nothing -> return Nothing
Just p -> do
-- pop off the first, slide any others back, and return
let inNew = Map.fromList $ tail $ map (\(k,v) -> (k - 1,v)) (Map.toList $ seIn s)
sNew = s { seNextIn = (seNextIn s) + 1
, seIn = inNew
}
-- logT $ "chan_seq_pop:seIn s=" ++ show (seIn s)
-- logT $ "chan_seq_pop:inNew =" ++ show inNew
putChan $ c { chSeq = Just sNew }
if isAckOnlyPacket p
then do
logT $ "chan_seq_pop:discarding ack-only packet:" ++ show p
chan_seq_pop cid
else return (Just p)
-- ---------------------------------------------------------------------
chan_seq_init :: TChan -> TeleHash ()
chan_seq_init cIn = do
c <- getChan (chUid cIn)
let seqVal = Seq
{ seId = 0
, seNextIn = 0
, seSeen = 0
, seAcked = 0
, seIn = Map.empty
}
c2 = c { chSeq = Just seqVal, chTimeout = Nothing }
putChan c2
-- ---------------------------------------------------------------------
chan_seq_free :: TChan -> TeleHash ()
chan_seq_free cIn = do
c <- getChan (chUid cIn)
putChan $ c { chSeq = Nothing }
-- ---------------------------------------------------------------------
-- |tracks packet for outgoing, eventually free's it, 0 ok or 1 for full/backpressure
chan_miss_track :: Uid -> Int -> TxTelex -> TeleHash Int
chan_miss_track cid seqVal p = do
c <- getChan cid
case (chMiss c) of
Nothing -> do
logT $ "chan_miss_track:chMiss not populated"
assert False undefined
Just m -> do
if seqVal - (mNextAck m) > (chReliable c) - 1
then return 1
else do
-- logT $ "chan_miss_track:storing packet id for cid in mOut at " ++ show (cid,(seqVal - (mNextAck m)))
let m2 = m { mOut = Map.insert (seqVal - (mNextAck m)) (tId p) (mOut m) }
putChan $ c { chMiss = Just m2 }
-- logT $ "chan_miss_track:mOut= " ++ show (mOut m2)
return 0
-- ---------------------------------------------------------------------
{-
// buffers packets to be able to re-send
void chan_miss_send(chan_t c, packet_t p);
-}
-- ---------------------------------------------------------------------
-- | looks at incoming miss/ack and resends or frees
chan_miss_check :: Uid -> RxTelex -> TeleHash ()
chan_miss_check cid p = do
-- logT $ "chan_miss_check for " ++ show (cIn,p)
c <- getChan cid
case chMiss c of
Nothing -> do
logT $ "chan_miss_check: no chMiss structure for " ++ show c
Just m -> do
case packet_get_int p "ack" of
Nothing -> do
logT $ "chan_miss_check: no ack field"
return () -- grow some
Just ack -> do
let offset = ack - (mNextAck m)
if offset < 0 || offset >= (chReliable c)
then do
logT $ "chan_miss_check:offset check:" ++ show (offset,chReliable c)
return ()
else do
-- free and shift up to the ack
-- logT $ "chan_miss_check:(cid,ack,nNextAck m,mOut m,mPackets m,chReliable c)="
-- ++ show (cid,ack,mNextAck m,mOut m,mPackets m,chReliable c)
let ackCount = (ack - (mNextAck m))
-- acked = [mNextAck m .. ack]
if ackCount > 0
then do
let
mout2 = Map.fromList $ map (\(k,v) -> (k - ackCount, v))
$ drop ackCount $ Map.toAscList (mOut m)
toRemove = map snd $ take ackCount $ Map.toAscList (mOut m)
ps = foldl' (\acc k -> Map.delete k acc) (mPackets m) toRemove
m2 = m { mNextAck = (mNextAck m) + ackCount
, mOut = mout2
, mPackets = ps
}
putChan $ c { chMiss = Just m2 }
else return ()
-- track any miss packets if we have them and resend
let mmiss = packet_get_packet p "miss"
case mmiss of
Nothing -> return ()
Just miss -> do
assert False undefined
{-
// looks at incoming miss/ack and resends or frees
void chan_miss_check(chan_t c, packet_t p)
{
uint32_t ack;
int offset, i;
char *id, *sack;
packet_t miss = packet_get_packet(p,"miss");
miss_t m = (miss_t)c->miss;
sack = packet_get_str(p,"ack");
if(!sack) return; // grow some
ack = (uint32_t)strtol(sack, NULL, 10);
// bad data
offset = ack - m->nextack;
if(offset < 0 || offset >= c->reliable) return;
// free and shift up to the ack
while(m->nextack <= ack)
{
// TODO FIX, refactor check into two stages
// packet_free(m->out[0]);
memmove(m->out,m->out+1,(sizeof (packet_t)) * (c->reliable - 1));
m->out[c->reliable-1] = 0;
m->nextack++;
}
// track any miss packets if we have them and resend
if(!miss) return;
for(i=0;(id = packet_get_istr(miss,i));i++)
{
ack = (uint32_t)strtol(id,NULL,10);
offset = ack - m->nextack;
if(offset >= 0 && offset < c->reliable && m->out[offset]) switch_send(c->s,m->out[offset]);
}
}
-}
-- ---------------------------------------------------------------------
chan_miss_init :: Uid -> TeleHash ()
chan_miss_init cid = do
logT $ "chan_miss_init for uid " ++ show cid
c <- getChan cid
let miss = Miss { mNextAck = 0
, mOut = Map.empty
, mPackets = Map.empty
}
c2 = c {chMiss = Just miss }
putChan c2
-- ---------------------------------------------------------------------
chan_miss_free :: Uid -> TeleHash ()
chan_miss_free cid = do
logT $ "chan_miss_free for uid " ++ show cid
c <- getChan cid
putChan $ c { chMiss = Nothing }
-- ---------------------------------------------------------------------
-- =====================================================================
-- link API
-- ---------------------------------------------------------------------
-- |create/fetch/maintain a link to this hn
link_hn :: HashName -> Maybe Uid -> TeleHash (Maybe ChannelId)
link_hn hn mcid = do
logR $ "LINKTRY:" ++ show hn
hc <- getHN hn
c <- case mcid of
Nothing -> do
case hLinkChan hc of
Nothing -> do
c <- chan_new hn "link" Nothing
let c2 = c { chTimeout = Just param_link_dead_secs }
putChan c2
return c2
Just cid -> getChan cid
Just cid -> getChan cid
void $ withHN hn $ \hc2 -> hc2 { hLinkChan = Just (chUid c) }
mp <- chan_packet (chUid c) True
case mp of
Nothing -> return Nothing
Just p -> do
-- TODO: populate "see" and "bridge" values
sw <- get
let p2 = packet_set p "seed" (swIsSeed sw)
chan_send (chUid c) p2
return $ Just (chId c)
{-
-- JS version
// request a new link to them
hn.link = function(callback)
{
if(!callback) callback = function(){}
debug("LINKTRY",hn.hashname);
var js = {seed:self.seed};
js.see = self.buckets[hn.bucket].sort(function(a,b){ return a.age - b.age }).filter(function(a){ return a.seed }).map(function(seed){ return seed.address(hn) }).slice(0,8);
// add some distant ones if none
if(js.see.length < 8) Object.keys(self.buckets).forEach(function(bucket){
if(js.see.length >= 8) return;
self.buckets[bucket].sort(function(a,b){ return a.age - b.age }).forEach(function(seed){
if(js.see.length >= 8 || !seed.seed || js.see.indexOf(seed.address(hn)) != -1) return;
js.see.push(seed.address(hn));
});
});
if(self.isBridge(hn)) js.bridges = self.paths.filter(function(path){return !isLocalPath(path)}).map(function(path){return path.type});
if(hn.linked)
{
hn.linked.send({js:js});
return callback();
}
hn.linked = hn.raw("link", {retry:3, js:js}, function(err, packet, chan){
inLink(err, packet, chan);
callback(packet.js.err);
});
}
-}
-- ---------------------------------------------------------------------
{-
link_get :: TeleHash Link
link_get = do
sw <- get
case swLink sw of
Nothing -> do
let l = Link
{ lMeshing = False
, lMeshed = Set.empty
, lSeeding = False
, lLinks = Map.empty
, lBuckets = []
}
put $ sw {swLink = Just l}
return l
Just l -> return l
-}
{-
link_t link_get(switch_t s)
{
link_t l;
l = xht_get(s->index,"link");
return l ? l : link_new(s);
}
-}
-- =====================================================================
-- hn api
-- ---------------------------------------------------------------------
-- |Unpack a see term and construct a HashContainer from it if there
-- is not one already. In either case, capture any optional IP:port as
-- a path. The hn is of the peer returning the see
hn_fromaddress :: [String] -> HashName -> TeleHash (Maybe HashName)
hn_fromaddress address hnPeer = do
logT $ "hn_fromaddress:" ++ show address
let mdetails = case address of
[hn1,csid1] -> Just (hn1,csid1,Nothing)
[hn1,csid1,ip,port] -> Just (hn1,csid1,Just (ip,port))
_xs -> Nothing -- error $ "hn_fromaddress:invalid address:" ++ show xs
case mdetails of
Nothing -> do
logT $ "hn_fromaddress:invalid address:" ++ show address
return Nothing
Just (hnStr,csid,mipp) -> do
let hn = HN hnStr
_hc <- hn_get hn -- insert into DHT if not present
hc1 <- withHN hn $ \hc -> hc { hVias = Map.insert hnPeer address (hVias hc) }
-- logT $ "hn_fromaddress:hVias=" ++ show (hc1)
logT $ "hn_fromaddress:hVias=" ++ show (hHashName hc1,hVias hc1)
case hCrypto hc1 of
Nothing -> do
void $ withHN hn $ \hc2 -> hc2 {hCsid = csid}
Just _ -> return ()
-- Send the NAT punch if ip,port given
case mipp of
Nothing -> return ()
Just (ipStr,portStr) -> do
logT $ "hn_fromaddress:sending NAT punch to" ++ show mipp
let punch = packet_new hn
path = PathIPv4 (read ipStr) (read portStr)
punch2 = punch { tOut = PIPv4 path }
punch3 = punch2 { tLp = Just (toLinePacket newPacket) }
-- putPath hn (Path PtIPv4 (PIPv4 path) Nothing Nothing Nothing Nothing)
void $ path_get hn (PIPv4 path)
switch_sendingQ punch3
-- update path if required
-- see.pathGet({type:"ipv4",ip:parts[2],port:parseInt(parts[3])});
return (Just hn)
-- ---------------------------------------------------------------------
-- |Send a NAT punch to the given ip,port
hn_nat_punch :: HashName -> String -> String -> TeleHash ()
hn_nat_punch hn ipStr portStr = do
logT $ "peer_send:must still send NAT punch to" ++ show (ipStr,portStr)
let punch = packet_new hn
path = PathIPv4 (read ipStr) (read portStr)
punch2 = punch { tOut = PIPv4 path }
punch3 = punch2 { tLp = Just (toLinePacket newPacket) }
void $ path_get hn (PIPv4 path)
switch_sendingQ punch3
-- =====================================================================
-- peer api
-- ---------------------------------------------------------------------
-- csid may be address format
peer_send :: HashName -> [String] -> TeleHash ()
peer_send to address = do
logT $ "seek:peer_send:" ++ show (to,address)
if length address /= 2 && length address /= 4
then do
logT $ "peer_send: malformed address " ++ show address
return ()
else do
let (hn,csid,mipp) = case address of
[hn1,csid1] -> (hn1,csid1,Nothing)
[hn1,csid1,ip,port] -> (hn1,csid1,Just (ip,port))
xs -> error $ "peer_send:invalid address:" ++ show xs
mcrypto <- getCrypto csid
case mcrypto of
Nothing -> do
logT $ "peer_send:no cipher set for " ++ csid
return ()
Just cs -> do
-- new peer channel
c <- chan_new to "peer" Nothing
let c2 = c {chHandler = Just peer_handler }
putChan c2
mp <- chan_packet (chUid c2) True
case mp of
Nothing -> do
logT $ "peer_send:cannot create packet for " ++ show c2
return ()
Just p -> do
let p2 = packet_set_str p "peer" hn
p3 = packet_body p2 (cKey cs)
-- Send the NAT punch if ip,port given
case mipp of
Nothing -> return ()
Just (ipStr,portStr) -> do
logT $ "peer_send:must still send NAT punch to" ++ show mipp
let punch = packet_new (HN hn)
path = PathIPv4 (read ipStr) (read portStr)
punch2 = punch { tOut = PIPv4 path }
punch3 = punch2 { tLp = Just (toLinePacket newPacket) }
putPath (HN hn) (Path PtIPv4 (PIPv4 path) Nothing Nothing Nothing Nothing)
switch_sendingQ punch3
chan_send (chUid c2) p3
{-
// csid may be address format
void peer_send(switch_t s, hn_t to, char *address)
{
char *csid, *ip = NULL, *port;
packet_t punch = NULL;
crypt_t cs;
chan_t c;
packet_t p;
if(!address) return;
if(!(csid = strchr(address,','))) return;
*csid = 0;
csid++;
// optional address ,ip,port for punch
if((ip = strchr(csid,',')))
{
*ip = 0;
ip++;
}
if(!(cs = xht_get(s->index,csid))) return;
// new peer channel
c = chan_new(s, to, "peer", 0);
c->handler = peer_handler;
p = chan_packet(c);
packet_set_str(p,"peer",address);
packet_body(p,cs->key,cs->keylen);
// send the nat punch packet if ip,port is given
if(ip && (port = strchr(ip,',')))
{
*port = 0;
port++;
punch = packet_new();
c->arg = punch->out = path_new("ipv4"); // free path w/ peer channel cleanup
path_ip(punch->out,ip);
path_port(punch->out,atoi(port));
switch_sendingQ(s,punch);
}
chan_send(c, p);
}
-}
-- ---------------------------------------------------------------------
peer_handler :: Uid -> TeleHash ()
peer_handler cid = do
c <- getChan cid
-- remove the NAT punch path if any
case chArg c of
CArgPath path -> do
path_free path
putChan $ c { chArg = CArgNone }
return ()
_ -> return ()
logT $ "seek:peer_handler:" ++ show (chTo c)
rxs <- chan_pop_all cid
forM_ rxs $ \p -> do
-- logT $ "peer_handler:processing " ++ show p
let mrelayp = fromNetworkPacket (LP $ unBody $ paBody $ rtPacket p)
logT $ "peer_handler:tunneled packet " -- ++ show mrelayp
case mrelayp of
Nothing -> do
logT $ "peer_handler:discarding bad tunneled packet:" ++ show p
Just relayp -> do
logT $ "peer_handler:calling switch_receive for tunneled packet:" -- ++ show relayp
let path = (pathFromPathJson $ rtSender p)
path2 = path { pBridgeChan = Just cid }
switch_receive relayp path2 (rtAt p)
-- TODO: process relayed packets
{-
void peer_handler(chan_t c)
{
// remove the nat punch path if any
if(c->arg)
{
path_free((path_t)c->arg);
c->arg = NULL;
}
DEBUG_PRINTF("peer handler %s",c->to->hexname);
// TODO process relay'd packets
}
-}
-- ---------------------------------------------------------------------
path_free :: PathJson -> TeleHash ()
path_free _path = return ()
{-
void path_free(path_t p)
{
if(p->id) free(p->id);
if(p->json) free(p->json);
free(p);
}
-}
|
alanz/htelehash
|
src/Network/TeleHash/SwitchApi.hs
|
bsd-3-clause
| 60,694
| 74
| 74
| 18,990
| 11,871
| 5,815
| 6,056
| 972
| 17
|
{-# LANGUAGE TypeFamilies, FlexibleInstances #-}
module Rubik.Face where
import Prelude hiding (Left, Right)
import Data.Array as A
import Control.Applicative
import Rubik.Key as K
import Rubik.Turn as T
import Rubik.Negate as N
import Rubik.V2
import Rubik.Abs
{-
data File = Left | Center | Right
deriving (Eq,Ord,Enum,Show,Ix)
instance Negate File where
negate Left = Right
negate Center = Center
negate Right = Right
instance Key File where
universe = [Left, Center, Right]
data Rank = Top | Middle | Bottom
deriving (Eq,Ord,Enum,Show,Ix)
instance Negate Rank where
negate Top = Bottom
negate Middle = Middle
negate Bottom = Top
instance Key Rank where
universe = [Top, Middle, Bottom]
data Square = Square Rank File
deriving (Eq,Ord,Ix)
instance Show Square where
show (Square r f) = [ head (show r) , head (show f) ]
instance Key Square where
universe = [ Square r f | r <- universe, f <- universe ]
corners :: (Square,Square)
corners = (Square Top Left,Square Bottom Right)
squares :: [[Square]]
squares = [ [ Square a b | b <- [Left .. Right] ] | a <- [Top .. Bottom]]
type Face a = Square -> a
facePlacement :: Face (Int,Int)
facePlacement (Square a b) = (file b,rank a)
where
rank Top = 0
rank Middle = 1
rank Bottom = 2
file Left = 0
file Center = 1
file Right = 2
-}
type Face a = V2 Abs -> a
{-
facePlacement :: Face (Int,Int)
facePlacement (V2 a b) = (f a, f (N.negate b))
where
f MinusOne = 0
f Zero = 1
f PlusOne = 2
-}
|
andygill/rubik-solver
|
src/Rubik/Face.hs
|
bsd-3-clause
| 1,674
| 0
| 6
| 503
| 78
| 52
| 26
| 11
| 0
|
#! /usr/local/bin/stack runghc
{-# LANGUAGE QuasiQuotes,OverloadedStrings #-}
import UnitB.FunctionTable
main :: IO ()
main = do
renderSpecMDFile "README.md" $ do
-- verifySpec $ do
title "logic-function-tables"
"Linux / OSX: " >> link (image "Build Status" "https://travis-ci.org/unitb/logic-function-tables.svg?branch=master")
"https://travis-ci.org/unitb/logic-function-tables"
""
""
"Verification of function table specifications"
section "TODO" $ do
listNum $ do
item $ strike "Adaptive cell height based on contents"
item $ strike "Add bold, italics and strikethrough"
item $ strike "Make UnitB.FunctionTable the one-stop module for all the eDSL"
item $ strike "improve the parsing of expressions when arrays are provided: \\array{r{}@l}"
item "Add a command to automatically insert the verification results in the document"
item "add support for quasi quoters in literate code"
item "prove invariants"
item "Add support for held-for"
item "Color table cells based on verification results"
""
section "Example" $ do
"The following table:"
""
code <- [exec|
do enumSort "Status" [("sOff","off"),("sOn","on")]
enumSort' "Mode" ["off","normal","init","fail"]
enumSort' "Validity" ["valid","invalid"]
constant "INIT" "\\Bool"
controlled "md" "Mode"
monitored "sw" "Status"
constant "initOk" "\\Bool"
monitored "st" "Validity"
table (raw "\\cMd") $ do
cellH 2 (raw "\\INIT \\lor \\mSw = \\sOff") (raw "\\off")
branch (conjList
[ (raw "\\neg \\INIT")
, (raw "\\neg \\mSw = \\sOff") ]) $ do
cell (raw "\\preCMd = \\off") (raw "\\init")
branch (raw "\\preCMd = \\init") $ do
cell (raw "\\neg \\initOk") (raw "\\init")
cell (raw "\\initOk") (raw "\\normal")
branch (raw "\\preCMd \\in \\{\\normal,\\fail\\} ") $ do
cell (raw "\\mSt = \\valid") (raw "\\normal")
cell (raw "\\mSt = \\invalid \\lor \\preCMd = \\fail")
(raw "\\fail") |]
""
"is specified by the following Haskell code (in README.hs):"
""
code
-- [syntax|haskell|
-- enumSort "Status" [("sOff","off"),("sOn","on")]
-- enumSort' "Mode" ["off","normal","init","fail"]
-- enumSort' "Validity" ["valid","invalid"]
-- constant "INIT" "\\Bool"
-- controlled "md" "Mode"
-- monitored "sw" "Status"
-- constant "initOk" "\\Bool"
-- monitored "st" "Validity"
-- table [tex|\cMd| ] $ do
-- cellH 2 [tex|\INIT \lor \mSw = \sOff| ] [tex|\off| ]
-- branch (conjList
-- [ [tex|\neg \INIT| ]
-- , [tex|\neg \mSw = \sOff| ] ]) $ do
-- cell [tex|\preCMd = \off| ] [tex|\init| ]
-- branch [tex|\preCMd = \init| ] $ do
-- cell [tex|\neg \initOk| ] [tex|\init| ]
-- cell [tex|\initOk| ] [tex|\normal| ]
-- branch [tex|\preCMd \in \{\normal,\fail\} | ] $ do
-- cell [tex|\mSt = \valid| ] [tex|\normal| ]
-- cell [tex|\mSt = \invalid \lor \preCMd = \fail| ]
-- [tex|\fail| ] |]
""
"The verification results can be obtained by replacing"
"`renderSpecMDFile \"README.md\"` with `verifySpec`. The above table"
"produces the following results:"
""
verificationResult
[verbatim|
\cMd
(1/1/completeness,Valid)
(1/1/disjointness-0-1,Valid)
(1/2/WD/1,Valid)
(1/2/completeness,Valid)
(1/2/disjointness-0-1,ValUnknown)
(1/WD/0,Valid)
(1/WD/1,Valid)
(1/WD/2,Valid)
(1/completeness,Valid)
(1/disjointness-0-1,Valid)
(1/disjointness-0-2,Valid)
(1/disjointness-1-2,Valid)
(completeness,Valid)
(disjointness-0-1,Valid)
Success: 13 / 14
Total: 13 / 14 |]
""
"We inserted a disjointness problem on purpose and Z3 found it"
"easily."
""
"To regenerate README.md, simply use:"
""
[verbatim| ./README.hs |]
|
unitb/logic-function-tables
|
README.hs
|
bsd-3-clause
| 4,736
| 0
| 17
| 1,773
| 270
| 127
| 143
| 45
| 1
|
{-# LANGUAGE DeriveGeneric #-}
module Models.List where
import GHC.Generics
import Data.Aeson (FromJSON, ToJSON)
import Models.Item
data List = List
{ listId :: Int -- ^ List id
, listName :: String -- ^ List name
, listItems :: [Item] -- ^ List items
} deriving (Show, Generic)
instance FromJSON List
instance ToJSON List
|
bendiksolheim/listify-backend
|
src/Models/List.hs
|
bsd-3-clause
| 343
| 0
| 9
| 73
| 88
| 53
| 35
| 12
| 0
|
module Main where
import qualified Test.Data.ART as ART
import qualified Test.Data.ART.Children as Children
import qualified Test.Data.ART.Internal.Array as Array
import qualified Test.Data.ART.Internal.SortingNetwork as Sort
import qualified Test.Data.ART.Key as Key
import Test.Tasty
main = defaultMain tests
tests :: TestTree
tests = testGroup "Test" [ testGroup "Keys" Key.tests
, testGroup "Children" Children.tests
, testGroup "ART" ART.tests
, testGroup "Array" Array.tests
, testGroup "SortingNetwork" Sort.tests
]
|
TikhonJelvis/adaptive-radix-trees
|
test/test.hs
|
bsd-3-clause
| 730
| 0
| 8
| 269
| 133
| 84
| 49
| 14
| 1
|
module Language.AtomHD
(
-- * Types
DesignAction
, Design
, Action
, E
, Name
-- * Compilation
, compile
-- * Design Stuff
, reg
, array
, fifo
, (==>)
, (-:)
-- ** Interface Methods
, methodValue
, methodAction
, methodActionValue
-- * Action Stuff
, cond
, (<==)
, assignArray
, display
, finish
, atomically
, ifelse
, when
, case_
-- * Expressions
, local
, (%)
, true
, false
, not_
, module Data.Monoid
, (#)
, (##)
, (==.)
, (/=.)
, mux
, (!)
, elements
-- * Utilities
, width
, size
, bytes
, bits
) where
import Control.Monad.State hiding (guard, when)
import Data.Bits
import Data.Char (toLower)
import Data.List
import Data.Monoid
import Text.Printf
infixr 9 %, #, ##, !
infix 4 ==., /=.
infixr 0 <==, -:, ==>
type Design = StateT DesignDB IO
type Action = StateT ActionDB Design
type Name = String
data DesignDB = DesignDB
{ path :: [Name]
, regs :: [([Name], Int, Integer)]
, arrays :: [([Name], Int, Int, Integer)]
, locals :: [([Name], E)]
, rules :: [([Name], E, [Action'])]
, methods :: [([Name], Method)]
}
data ActionDB = ActionDB
{ guard :: E
, actions :: [Action']
}
data Method
= MethodValue [Int] Int E
| MethodAction [Int] E [Action']
| MethodActionValue [Int] Int E [Action'] E
data Action'
= Assign E E
| Display String [E]
| Finish
| Atomically E [Action']
deriving Show
-- | Expressions.
data E
= EConst Int Integer
| EReg [Name] Int -- width
| EArray [Name] Int Int -- size width
| ELocal [Name] Int -- width
| EIndex E E
| ESelect Int Int E
| EConcat E E
| EAdd E E
| ESub E E
| EMul E E
| ENot E
| EAnd E E
| EOr E E
| EXor E E
| EEq E E
| EMux E E E
deriving (Show, Eq)
instance Num E where
(+) = EAdd
(*) = ESub
(-) = EMul
abs = id
signum = error "Num E signum not defined."
fromInteger = EConst 8 -- XXX Not good. Need unsized values.
instance Bits E where
(.&.) = EAnd
(.|.) = EOr
xor = EXor
complement = ENot
shift = error "Bits E shift not defined."
rotate = error "Bits E rotate not defined."
bit i = 8 % (bit i)
testBit = error "Bits E testBit not defined."
bitSize = width
isSigned _ = False
instance Monoid E where
mempty = 0%0
mappend = EConcat
-- | Operations valid in both Design and Action monads.
class Monad m => DesignAction m where
-- | Create a local expression.
local :: Name -> E -> m E
-- | Create a new namespace.
(-:) :: Name -> m a -> m a
instance DesignAction Design where
local name a = do
d <- get
put d { locals = locals d ++ [(path d ++ [name], a)] }
return $ ELocal (path d ++ [name]) (width a)
name -: design = do
modify $ \ d -> d { path = path d ++ [name] }
a <- design
modify $ \ d -> d { path = init $ path d }
return a
instance DesignAction Action where
local name value = lift $ local name value
name -: action = do
lift $ modify $ \ d -> d { path = path d ++ [name] }
a <- action
lift $ modify $ \ d -> d { path = init $ path d }
return a
-- | Register declaration.
reg :: Name -> Int -> Integer -> Design E
reg name width value = do
d <- get
put d { regs = regs d ++ [(path d ++ [name], width, value)] }
return $ EReg (path d ++ [name]) width
-- | Register array declaration.
array :: Name -> Int -> Int -> Integer -> Design E
array name size width value = do
d <- get
put d { arrays = arrays d ++ [(path d ++ [name], size, width, value)] }
return $ EArray (path d ++ [name]) size width
-- | FIFO declaration.
fifo :: Name -> [(Int, Integer)] -> Design E
fifo = undefined
-- | Defines a state transition rule.
(==>) :: Name -> Action () -> Design ()
name ==> rule = do
modify $ \ d -> d { path = path d ++ [name] }
ActionDB guard actions <- execStateT rule ActionDB { guard = true, actions = [] }
modify $ \ d -> d { path = init $ path d, rules = rules d ++ [(path d, guard, actions)] }
-- | A non-state modifying method returning a value.
methodValue :: Name -> [Int] -> Int -> ([E] -> E) -> Design ()
methodValue name widths width f = modify $ \ d -> d { methods = methods d ++ [(path d ++ [name], MethodValue widths width result)] }
where
result = f [ ELocal ["arg" ++ show i] w | (w, i) <- zip widths [0 :: Int ..] ]
-- | A state modifying method.
methodAction :: Name -> [Int] -> ([E] -> Action ()) -> Design ()
methodAction name widths f = do
modify $ \ d -> d { path = path d ++ [name] }
((), ActionDB guard actions) <- runStateT (f [ ELocal ["arg" ++ show i] w | (w, i) <- zip widths [0 :: Int ..] ]) ActionDB { guard = true, actions = [] }
modify $ \ d -> d { path = init $ path d, methods = methods d ++ [(path d, MethodAction widths guard actions)] }
-- | A state modifying method that returns a value.
methodActionValue :: Name -> [Int] -> Int -> ([E] -> Action E) -> Design ()
methodActionValue name widths width f = do
modify $ \ d -> d { path = path d ++ [name] }
(result, ActionDB guard actions) <- runStateT (f [ ELocal ["arg" ++ show i] w | (w, i) <- zip widths [0 :: Int ..] ]) ActionDB { guard = true, actions = [] }
modify $ \ d -> d { path = init $ path d, methods = methods d ++ [(path d, MethodActionValue widths width guard actions result)] }
-- | State update.
(<==) :: E -> E -> Action ()
a <== b = modify $ \ d -> d { actions = actions d ++ [Assign a b] }
-- | Update an entire array.
assignArray :: E -> [E] -> Action ()
assignArray a vs = sequence_ [ a ! 8%i <== v | (i, v) <- zip [0 ..] vs ] --XXX 8%i is not good. Need to have unsized values.
-- | Guard conditions.
cond :: E -> Action ()
cond a = modify $ \ d -> d { guard = EAnd (guard d) a }
-- | Display something for simulation.
display :: String -> [E] -> Action ()
display str args = modify $ \ d -> d { actions = actions d ++ [Display str args] }
-- | Stop a simulation.
finish :: Action ()
finish = modify $ \ d -> d { actions = actions d ++ [Finish] }
-- | Execute a sub action atomically. Does not block parent action from executing.
atomically :: Action () -> Action ()
atomically action = do
a <- get
ActionDB guard actions' <- lift $ execStateT action ActionDB { guard = true, actions = [] }
put a { actions = actions a ++ [Atomically guard actions'] }
-- | Conditional branch within an Action.
ifelse :: E -> Action () -> Action () -> Action ()
ifelse pred onTrue onFalse = do
when pred onTrue
when (complement pred) onFalse
-- | Conditional action.
when :: E -> Action () -> Action ()
when pred action = atomically $ cond pred >> action
-- | Case statements.
case_ :: [(E, Action ())] -> Action () -> Action ()
case_ cases def = case cases of
[] -> def
(test, action) : rest -> ifelse test action $ case_ rest def
-- | Constant bit vector given width and value.
(%) :: Int -> Integer -> E
(%) = EConst
-- | False constant.
false :: E
false = 1%0
-- | True constant.
true :: E
true = 1%1
-- | Negation.
not_ :: E -> E
not_ = complement
-- | Bit range selection.
(#) :: E -> (Int, Int) -> E
a # (msb, lsb) = ESelect msb lsb a
-- | Single bit selection.
(##) :: E -> Int -> E
a ## b = a#(b,b)
-- | Bit vector equality.
(==.) :: E -> E -> E
(==.) = EEq
-- | Bit vector inequality.
(/=.) :: E -> E -> E
a /=. b = complement $ a ==. b
-- | Mux: mux test onTrue onFalse
mux :: E -> E -> E -> E
mux = EMux
-- | Array indexing.
(!) :: E -> E -> E
(!) = EIndex
-- | All elements of an array.
elements :: E -> [E]
elements a = [ a ! 8 % fromIntegral i | i <- [0 .. size a - 1] ]
-- | Width of a bit vector.
width :: E -> Int
width a = case a of
EConst w _ -> w
EReg _ w -> w
EArray _ _ w -> w
ELocal _ w -> w
EIndex a _ -> width a
EConcat a b -> width a + width b
ESelect msb lsb _ -> msb - lsb + 1
EAdd a _ -> width a
ESub a _ -> width a
EMul a _ -> width a
ENot a -> width a
EAnd a _ -> width a
EOr a _ -> width a
EXor a _ -> width a
EEq _ _ -> 1
EMux _ a _ -> width a
-- | The size on a register array.
size :: E -> Int
size a = case a of
EArray _ s _ -> s
_ -> error "Invalid expression: size not applied to array."
-- | Extract the bytes of a bit vector.
bytes :: E -> [E]
bytes a = [ a # (lsb + 8 - 1, lsb) | lsb <- reverse [0, 8 .. width a - 1] ] -- Ignores msbs if not divisible by 8.
-- | Extract the bits of a bit vector.
bits :: E -> [E]
bits a = [ a # (i, i) | i <- reverse [0 .. width a - 1] ]
-- | Compiles a design.
compile :: FilePath -> Design () -> IO ()
compile file design = execStateT design DesignDB { path = [], regs = [], arrays = [], locals = [], rules = [], methods = [] } >>= writeFile file . bsv file
var :: [Name] -> String
var path = toLower a : b
where
a : b = intercalate "__" path
bsv :: FilePath -> DesignDB -> String
bsv file (DesignDB _ regs arrays locals rules methods) = unlines $
[ printf "// Generated by AtomHD."
, printf "package %s;" m
, printf ""
, printf "import Vector :: *;"
, printf ""
, printf "interface %s;" m
, unlines $ map methodDecl methods
, printf "endinterface"
, printf ""
, printf "module mk%s (%s);" m m
, unlines [ printf "Reg#(Bit#(%d)) %s <- mkReg(%d);" w (var path) v | (path, w, v) <- regs ]
, unlines [ printf "Vector#(%d, Reg#(Bit#(%d))) %s <- replicateM(mkReg(%d'h%x));" s w (var path) w v | (path, s, w, v) <- arrays ]
, unlines [ printf "Bit#(%d) %s = %s;" (width a) (var path) (expr a) | (path, a) <- locals ]
, unlines $ map rule rules
, unlines $ map method methods
, printf "endmodule"
, printf "endpackage"
]
where
m = takeWhile (/= '.') file
expr :: E -> String
expr a = case a of
EConst w v -> printf "%d'h%x" w v
EReg path _ -> var path
EArray path _ _ -> var path
ELocal path _ -> var path
EIndex a (EConst _ b) -> printf "%s[%d]" (expr a) b
EIndex a b -> printf "%s[%s]" (expr a) (expr b)
EConcat a b -> printf "{%s, %s}" (expr a) (expr b)
ESelect msb lsb a -> printf "(%s)[%d:%d]" (expr a) msb lsb
EAdd a b -> printf "(%s + %s)" (expr a) (expr b)
ESub a b -> printf "(%s - %s)" (expr a) (expr b)
EMul a b -> printf "(%s * %s)" (expr a) (expr b)
ENot a -> printf "(~ %s)" (expr a)
EAnd a b -> printf "(%s & %s)" (expr a) (expr b)
EOr a b -> printf "(%s | %s)" (expr a) (expr b)
EXor a b -> printf "(%s ^ %s)" (expr a) (expr b)
EEq a b -> printf "pack(%s == %s)" (expr a) (expr b)
EMux a b c -> printf "(unpack(%s) ? %s : %s)" (expr a) (expr b) (expr c)
rule :: ([Name], E, [Action']) -> String
rule (path, guard, actions) = unlines
[ printf "rule %s (1'b1 == %s);" (var path) (expr guard)
, indent $ unlines $ map action actions
, printf "endrule"
]
method :: ([Name], Method) -> String
method a@(_, m) = case m of
MethodValue _ _ result -> unlines
[ methodDecl a
, printf " return %s;" (expr result)
, printf "endmethod"
]
MethodAction _ guard actions -> unlines
[ init (methodDecl a) ++ " if (unpack(" ++ expr guard ++ "));"
, indent $ unlines $ map action actions
, printf "endmethod"
]
MethodActionValue _ _ guard actions result -> unlines
[ init (methodDecl a) ++ " if (unpack(" ++ expr guard ++ "));"
, indent $ unlines $ map action actions
, printf " return %s;" (expr result)
, printf "endmethod"
]
methodDecl :: ([Name], Method) -> String
methodDecl (path, a) = case a of
MethodValue widths width _ -> printf "method Bit#(%d) %s%s;" width (var path) (declArgs widths)
MethodAction widths _ _ -> printf "method Action %s%s;" (var path) (declArgs widths)
MethodActionValue widths width _ _ _ -> printf "method ActionValue#(Bit#(%d)) %s%s;" width (var path) (declArgs widths)
where
declArgs widths
| null widths = ""
| otherwise = "(" ++ intercalate ", " [ printf "Bit#(%d) arg%d" w i | (w, i) <- zip widths [0 :: Int ..] ] ++ ")"
action :: Action' -> String
action a = case a of
Assign a b -> printf "%s <= %s;" (expr a) (expr b)
Display str args -> printf "$display(\"%s\"%s);" str $ concatMap ((", " ++) . expr) args
Finish -> printf "$finish;"
Atomically g a -> unlines
[ printf "if (unpack(%s)) begin" (expr g)
, indent $ unlines $ map action a
, printf "end"
]
indent :: String -> String
indent = unlines . map (" " ++) . lines
|
tomahawkins/atom-hd
|
Language/AtomHD.hs
|
bsd-3-clause
| 12,415
| 0
| 15
| 3,353
| 5,157
| 2,732
| 2,425
| 319
| 17
|
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE TupleSections #-}
module Language.Fixpoint.Solver.Worklist
( -- * Worklist type is opaque
Worklist, Stats
-- * Initialize
, init
-- * Pop off a constraint
, pop
-- * Add a constraint and all its dependencies
, push
-- * Constraints with Concrete RHS
, unsatCandidates
-- * Statistics
, wRanks
)
where
import Debug.Trace (trace)
import Prelude hiding (init)
import Language.Fixpoint.Types.PrettyPrint -- (PTable (..), PPrint (..))
import qualified Language.Fixpoint.Types as F
import Language.Fixpoint.Solver.Types
import Language.Fixpoint.Solver.Graph
import Control.Arrow (first)
import qualified Data.HashMap.Strict as M
import qualified Data.Set as S
import qualified Data.List as L
import Data.Graph (graphFromEdges)
import Text.PrettyPrint.HughesPJ (text)
-- | Worklist -------------------------------------------------------------
data Worklist a = WL { wCs :: !WorkSet
, wPend :: !(CMap ())
, wDeps :: CSucc
, wCm :: !(CMap (F.SimpC a))
, wRankm :: !(CMap Rank)
, wLast :: !(Maybe CId)
, wRanks :: !Int
, wTime :: !Int
, wConcCs :: ![CId]
}
data Stats = Stats { numKvarCs :: !Int
, numConcCs :: !Int
, numSccs :: !Int
} deriving (Eq, Show)
instance PPrint (Worklist a) where
pprint = pprint . S.toList . wCs
instance PTable Stats where
ptable s = DocTable [ (text "# Sliced Constraints", pprint (numKvarCs s))
, (text "# Target Constraints", pprint (numConcCs s))
]
instance PTable (Worklist a) where
ptable = ptable . stats
-- | WorkItems ------------------------------------------------------------
type WorkSet = S.Set WorkItem
data WorkItem = WorkItem { wiCId :: !CId -- ^ Constraint Id
, wiTime :: !Int -- ^ Time at which inserted
, wiRank :: !Rank -- ^ Rank of constraint
} deriving (Eq, Show)
instance PPrint WorkItem where
pprint = text . show
instance Ord WorkItem where
compare (WorkItem i1 t1 r1) (WorkItem i2 t2 r2)
= mconcat [ compare (rScc r1) (rScc r2) -- SCC
, compare t1 t2 -- TimeStamp
, compare (rIcc r1) (rIcc r2) -- Inner SCC
, compare (rTag r1) (rTag r2) -- Tag
, compare i1 i2 -- Otherwise Set drops items
]
-- | Ranks ----------------------------------------------------------------
data Rank = Rank { rScc :: !Int -- ^ SCC number with ALL dependencies
, rIcc :: !Int -- ^ SCC number without CUT dependencies
, rTag :: !F.Tag -- ^ The constraint's Tag
} deriving (Eq, Show)
---------------------------------------------------------------------------
-- | Initialize worklist and slice out irrelevant constraints -------------
---------------------------------------------------------------------------
init :: F.SInfo a -> Worklist a
---------------------------------------------------------------------------
init fi = WL { wCs = items
, wPend = addPends M.empty kvarCs
, wDeps = cSucc cd
, wCm = cm
, wRankm = rankm
, wLast = Nothing
, wRanks = cNumScc cd
, wTime = 0
, wConcCs = concCs
}
where
cm = F.cm fi
cd = cDeps fi
rankm = cRank cd
items = S.fromList $ workItemsAt rankm 0 <$> kvarCs
concCs = fst <$> ics
kvarCs = fst <$> iks
(ics,iks) = L.partition (isTarget . snd) (M.toList cm)
---------------------------------------------------------------------------
-- | Candidate Constraints to be checked AFTER computing Fixpoint ---------
---------------------------------------------------------------------------
unsatCandidates :: Worklist a -> [F.SimpC a]
---------------------------------------------------------------------------
unsatCandidates w = [ lookupCMap (wCm w) i | i <- wConcCs w ]
---------------------------------------------------------------------------
pop :: Worklist a -> Maybe (F.SimpC a, Worklist a, Bool)
---------------------------------------------------------------------------
pop w = do
(i, is) <- sPop $ wCs w
Just ( lookupCMap (wCm w) i
, popW w i is
, newSCC w i
)
popW :: Worklist a -> CId -> WorkSet -> Worklist a
popW w i is = w { wCs = is
, wLast = Just i
, wPend = remPend (wPend w) i }
newSCC :: Worklist a -> CId -> Bool
newSCC oldW i = oldRank /= newRank
where
oldRank = lookupCMap rankm <$> wLast oldW
newRank = Just $ lookupCMap rankm i
rankm = wRankm oldW
---------------------------------------------------------------------------
push :: F.SimpC a -> Worklist a -> Worklist a
---------------------------------------------------------------------------
push c w = w { wCs = sAdds (wCs w) wis'
, wTime = 1 + t
, wPend = addPends wp is'
}
where
i = F.subcId c
is' = filter (not . isPend wp) $ wDeps w i
wis' = workItemsAt (wRankm w) t <$> is'
t = wTime w
wp = wPend w
workItemsAt :: CMap Rank -> Int -> CId -> WorkItem
workItemsAt !r !t !i = WorkItem { wiCId = i
, wiTime = t
, wiRank = lookupCMap r i }
---------------------------------------------------------------------------
-- | Constraint Dependencies ----------------------------------------------
---------------------------------------------------------------------------
data CDeps = CDs { cSucc :: CSucc
, cRank :: CMap Rank
, cNumScc :: Int
}
---------------------------------------------------------------------------
cDeps :: F.SInfo a -> CDeps
---------------------------------------------------------------------------
cDeps fi = CDs { cSucc = gSucc cg
, cNumScc = gSccs cg
, cRank = M.fromList [(i, rf i) | i <- is ]
}
where
rf = rankF (F.cm fi) outRs inRs
inRs = inRanks fi es outRs
outRs = gRanks cg
es = gEdges cg
cg = cGraph fi
cm = F.cm fi
is = M.keys cm
rankF :: CMap (F.SimpC a) -> CMap Int -> CMap Int -> CId -> Rank
rankF cm outR inR = \i -> Rank (outScc i) (inScc i) (tag i)
where
outScc = lookupCMap outR
inScc = lookupCMap inR
tag = F._ctag . lookupCMap cm
---------------------------------------------------------------------------
inRanks :: F.SInfo a -> [DepEdge] -> CMap Int -> CMap Int
---------------------------------------------------------------------------
inRanks fi es outR
| ks == mempty = outR
| otherwise = fst $ graphRanks g' vf'
where
ks = F.kuts fi
cm = F.cm fi
(g', vf', _) = graphFromEdges es'
es' = [(i, i, filter (not . isCut i) js) | (i,_,js) <- es ]
isCut i j = S.member i cutCIds && isEqOutRank i j
isEqOutRank i j = lookupCMap outR i == lookupCMap outR j
cutCIds = S.fromList [i | i <- M.keys cm, isKutWrite i ]
isKutWrite = any (`F.ksMember` ks) . kvWriteBy cm
---------------------------------------------------------------------------
stats :: Worklist a -> Stats
---------------------------------------------------------------------------
stats w = Stats (kn w) (cn w) (wRanks w)
where
kn = M.size . wCm
cn = length . wConcCs
---------------------------------------------------------------------------
-- | Pending API
---------------------------------------------------------------------------
addPends :: CMap () -> [CId] -> CMap ()
addPends = L.foldl' addPend
addPend :: CMap () -> CId -> CMap ()
addPend m i = M.insert i () m
remPend :: CMap () -> CId -> CMap ()
remPend m i = M.delete i m
isPend :: CMap () -> CId -> Bool
isPend w i = M.member i w
---------------------------------------------------------------------------
-- | Set API --------------------------------------------------------------
---------------------------------------------------------------------------
sAdds :: WorkSet -> [WorkItem] -> WorkSet
sAdds = L.foldl' (flip S.insert)
sPop :: WorkSet -> Maybe (CId, WorkSet)
sPop = fmap (first wiCId) . S.minView
|
gridaphobe/liquid-fixpoint
|
src/Language/Fixpoint/Solver/Worklist.hs
|
bsd-3-clause
| 8,981
| 0
| 14
| 2,775
| 2,224
| 1,194
| 1,030
| 189
| 1
|
{-# LANGUAGE MonadComprehensions #-}
module MComp where
import Control.Applicative
data Opt a = Yes a | No deriving Show
instance Functor Opt where
fmap f No = No
fmap f (Yes a) = Yes $ f a
instance Applicative Opt where
pure = Yes
No <*> _ = No
(Yes f) <*> a = fmap f a
instance Monad Opt where
(Yes a) >>= f = f a
No >>= _ = No
instance Alternative Opt where
empty = No
No <|> b = b
a <|> _ = a
mcomp1 :: Opt Int
mcomp1 = [ x + y | x <- genX, y <- genY ]
where genX = Yes 1
genY = Yes 2
mcomp2 :: Opt Int
mcomp2 = [ x + y | x <- genX, y <- genY ]
where genX = Yes 1
genY = No
-- mcomp3 & mcomp4 require and Alternative instance
mcomp3 :: Opt Int
mcomp3 = [ x + y | x <- genX, y <- genY, x > 0, y > 0 ]
where genX = Yes 1
genY = Yes 2
mcomp4 :: Opt Int
mcomp4 = [ x + y | x <- genX, y <- genY, x < 0, y > 0 ]
where genX = Yes 1
genY = Yes 2
|
dterei/Scraps
|
haskell/parsers/MComp.hs
|
bsd-3-clause
| 913
| 0
| 8
| 288
| 433
| 222
| 211
| 34
| 1
|
{- | Module : ./GMP/GMP-CoLoSS/GMP/Prover.hs
- Description : Implementation of the generic sequent calculus
- Copyright : (c) Daniel Hausmann & Lutz Schroeder, DFKI Lab Bremen,
- Rob Myers & Dirk Pattinson, Department of Computing, ICL
- License : GPLv2 or higher, see LICENSE.txt
- Maintainer : hausmann@dfki.de
- Stability : provisional
- Portability : portable
-
- Provides the implementation of the generic proving function.
- Also contains an optimized version of the proving function (using so-called
- 'memoizing')
-}
module GMP.Prover where
import Data.List
import Data.Ratio
import Data.Maybe
import Debug.Trace
import GMP.Logics.Generic
import GMP.Logics.K
{- ------------------------------------------------------------------------------
sequent calculus implementation
------------------------------------------------------------------------------ -}
{- Inference Rules
map a sequent to the list of all premises that derive
the sequent. Note that a premise is a list of sequents:
to prove Gamma, A /\ B we need both Gamma, A and Gamma, B as premises.
to prove Gamma, neg(A /\ B), we need Gamma, neg A, neg B as premise.
to prove A, neg A, Gamma we need no premises
So a premise is a list of sequents, and the list of all possible
premises therefore has type [[ Sequent ]] -}
{- the functions below compute the list of all possible premises
that allow to derive a given sequent using the rule that
lends its name to the function. -}
{- faster to check for atomic axioms
axiom1 xs = [ [] | p <- xs, (Not q) <- xs, p==q] -}
axiom_rule :: Sequent -> Premises
axiom_rule (Sequent xs) = [ [[Sequent ([] :: [Formula (K (K (K ())))])]] |
(Atom n) <- xs, (Neg (Atom m)) <- xs, m == n]
true_rule :: Sequent -> Premises
true_rule (Sequent xs) = [ [[Sequent ([] :: [Formula (K (K (K ())))])]] | T <- xs]
negfalse_rule :: Sequent -> Premises
negfalse_rule (Sequent xs) = [ [[Sequent ([] :: [Formula (K (K (K ())))])]] |
(Neg F) <- xs]
conj_rule :: Sequent -> Premises
conj_rule (Sequent as) = [ [[Sequent (p : delete f as)],
[Sequent (q : delete f as)]] | f@(And p q) <- as]
-- the rule for the modal operator
modal_rule :: [Bool] -> Sequent -> Premises
modal_rule flags (Sequent xs) = emptify (fMatch flags xs)
-- the rule for the modal operator - optimised version
omodal_rule :: [Bool] -> [Sequent] -> Sequent -> Premises
omodal_rule flags [Sequent ec] (Sequent xs) = emptify (fMatchOptimised flags xs [])
{- collect all possible premises, i.e. the union of the possible
premises taken over the set of all rules in one to get the
recursion off the ground. -}
{- CAVEAT: the order of axioms /rules has a HUGE impact on performance.
this is as good as it gets if we apply the individual rules
message for the afterworld: if youm want to find proofs quickly,
first look at the rules that induce branching.
we can do slightly better if we apply all rules that do not
induce branching in one single step. -}
allRules :: [Bool] -> Sequent -> Premises
allRules flags (Sequent seq) = let t = Sequent (expand seq)
axioms = axiom_rule t
trues = true_rule t
negfalses = negfalse_rule t
modals = modal_rule flags t
conjs = conj_rule t
in if flags !! 1 then
trace ("\n Axiom-rule: " ++ prettylll axioms ++
" True-rule: " ++ prettylll trues ++
" NegFalse-rule: " ++ prettylll negfalses ++
" Modal-rule: " ++ prettylll modals ++
" Conj-rule: " ++ prettylll conjs )
(axioms ++ trues ++ negfalses ++ conjs ++ modals)
else
axioms ++ trues ++ negfalses ++ conjs ++ modals
oallRules :: [Bool] -> [Sequent] -> Sequent -> Premises
oallRules flags ec (Sequent seq) = let t = Sequent (expand seq)
axioms = axiom_rule t
trues = true_rule t
negfalses = negfalse_rule t
modals = omodal_rule flags ec t
conjs = conj_rule t
in trace
("\n Axiom-rule: " ++ prettylll axioms ++
" True-rule: " ++ prettylll trues ++
" NegFalse-rule: " ++ prettylll negfalses ++
" Modal-rule: " ++ prettylll modals ++
" Conj-rule: " ++ prettylll conjs )
(axioms ++ trues ++ negfalses ++ conjs ++ modals)
{- A sequent is provable iff there exists a set of premises that
prove the sequent such that all elements in the list of premises are
themselves provable. -}
sprovable :: [Bool] -> Sequent -> Bool
sprovable flags (Sequent []) = True
sprovable flags (Sequent seq) = if flags !! 1 then
trace ("\n <Current Sequent:> " ++ pretty_seq (Sequent (expand seq))) $
any (all (any (sprovable flags))) (allRules flags (Sequent seq))
else any (all (any (sprovable flags))) (allRules flags (Sequent seq))
-- optimized, alla
osprovable :: [Bool] -> [Sequent] -> Sequent -> Bool
osprovable flags ec (Sequent []) = True
osprovable flags ec (Sequent seq) =
trace ("\n <Current Sequent:> " ++ pretty_seq (Sequent (expand seq))) $
any (all (any (osprovable flags ec))) (oallRules flags ec (Sequent seq))
-- specialisation to formulae
provable :: (SigFeature a b (c d), Eq (a (b (c d)))) => Formula (a (b (c d))) -> [Bool] -> Bool
provable phi flags = sprovable flags (Sequent [phi])
oprovable :: (SigFeature a b (c d), Eq (a (b (c d)))) => [Bool] -> [Sequent] -> Formula (a (b (c d))) -> Bool
oprovable flags ec phi = osprovable flags ec (Sequent [phi])
-- a formula is satisfiable iff it's negation is not provable
satisfiable :: (SigFeature a b (c d), Eq (a (b (c d)))) => Formula (a (b (c d))) -> [Bool] -> Bool
satisfiable phi flags = not (provable (neg phi) flags)
osatisfiable :: (SigFeature a b (c d), Eq (a (b (c d)))) => [Bool] -> [Sequent] -> Formula (a (b (c d))) -> Bool
osatisfiable flags ec phi = not (oprovable flags ec (neg phi))
|
spechub/Hets
|
GMP/GMP-CoLoSS/GMP/Prover.hs
|
gpl-2.0
| 6,643
| 0
| 19
| 2,119
| 1,637
| 844
| 793
| 70
| 2
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE OverloadedStrings #-}
module Preprocess
(preprocess)
where
import qualified Data.Text as T
preprocess :: T.Text -> T.Text
preprocess txt = T.cons '\"' $ T.snoc escaped '\"'
where escaped = T.concatMap escaper txt
escaper :: Char -> T.Text
escaper c
| c == '\t' = "\"\t\""
| c == '\n' = "\"\n\""
| c == '\"' = "\"\""
| otherwise = T.singleton c
|
Pold87/Haggressive
|
src-lib/Preprocess.hs
|
gpl-2.0
| 411
| 0
| 8
| 95
| 139
| 71
| 68
| 14
| 1
|
#!/usr/bin/env runhaskell
import Hledger.Vty (main)
|
Lainepress/hledger
|
hledger-vty/hledger-vty.hs
|
gpl-3.0
| 52
| 0
| 5
| 5
| 12
| 7
| 5
| 1
| 0
|
{-# 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.CloudFront.CreateDistribution
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Create a new distribution.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonCloudFront/latest/APIReference/CreateDistribution.html AWS API Reference> for CreateDistribution.
module Network.AWS.CloudFront.CreateDistribution
(
-- * Creating a Request
createDistribution
, CreateDistribution
-- * Request Lenses
, cdDistributionConfig
-- * Destructuring the Response
, createDistributionResponse
, CreateDistributionResponse
-- * Response Lenses
, cdrsETag
, cdrsDistribution
, cdrsLocation
, cdrsResponseStatus
) where
import Network.AWS.CloudFront.Types
import Network.AWS.CloudFront.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The request to create a new distribution.
--
-- /See:/ 'createDistribution' smart constructor.
newtype CreateDistribution = CreateDistribution'
{ _cdDistributionConfig :: DistributionConfig
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateDistribution' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdDistributionConfig'
createDistribution
:: DistributionConfig -- ^ 'cdDistributionConfig'
-> CreateDistribution
createDistribution pDistributionConfig_ =
CreateDistribution'
{ _cdDistributionConfig = pDistributionConfig_
}
-- | The distribution\'s configuration information.
cdDistributionConfig :: Lens' CreateDistribution DistributionConfig
cdDistributionConfig = lens _cdDistributionConfig (\ s a -> s{_cdDistributionConfig = a});
instance AWSRequest CreateDistribution where
type Rs CreateDistribution =
CreateDistributionResponse
request = postXML cloudFront
response
= receiveXML
(\ s h x ->
CreateDistributionResponse' <$>
(h .#? "ETag") <*> (parseXML x) <*>
(h .#? "Location")
<*> (pure (fromEnum s)))
instance ToElement CreateDistribution where
toElement
= mkElement
"{http://cloudfront.amazonaws.com/doc/2015-04-17/}DistributionConfig"
.
_cdDistributionConfig
instance ToHeaders CreateDistribution where
toHeaders = const mempty
instance ToPath CreateDistribution where
toPath = const "/2015-04-17/distribution"
instance ToQuery CreateDistribution where
toQuery = const mempty
-- | The returned result of the corresponding request.
--
-- /See:/ 'createDistributionResponse' smart constructor.
data CreateDistributionResponse = CreateDistributionResponse'
{ _cdrsETag :: !(Maybe Text)
, _cdrsDistribution :: !(Maybe Distribution)
, _cdrsLocation :: !(Maybe Text)
, _cdrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateDistributionResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cdrsETag'
--
-- * 'cdrsDistribution'
--
-- * 'cdrsLocation'
--
-- * 'cdrsResponseStatus'
createDistributionResponse
:: Int -- ^ 'cdrsResponseStatus'
-> CreateDistributionResponse
createDistributionResponse pResponseStatus_ =
CreateDistributionResponse'
{ _cdrsETag = Nothing
, _cdrsDistribution = Nothing
, _cdrsLocation = Nothing
, _cdrsResponseStatus = pResponseStatus_
}
-- | The current version of the distribution created.
cdrsETag :: Lens' CreateDistributionResponse (Maybe Text)
cdrsETag = lens _cdrsETag (\ s a -> s{_cdrsETag = a});
-- | The distribution\'s information.
cdrsDistribution :: Lens' CreateDistributionResponse (Maybe Distribution)
cdrsDistribution = lens _cdrsDistribution (\ s a -> s{_cdrsDistribution = a});
-- | The fully qualified URI of the new distribution resource just created.
-- For example:
-- https:\/\/cloudfront.amazonaws.com\/2010-11-01\/distribution\/EDFDVBD632BHDS5.
cdrsLocation :: Lens' CreateDistributionResponse (Maybe Text)
cdrsLocation = lens _cdrsLocation (\ s a -> s{_cdrsLocation = a});
-- | The response status code.
cdrsResponseStatus :: Lens' CreateDistributionResponse Int
cdrsResponseStatus = lens _cdrsResponseStatus (\ s a -> s{_cdrsResponseStatus = a});
|
fmapfmapfmap/amazonka
|
amazonka-cloudfront/gen/Network/AWS/CloudFront/CreateDistribution.hs
|
mpl-2.0
| 5,079
| 0
| 14
| 1,018
| 689
| 412
| 277
| 89
| 1
|
module Bench.Pos.Explorer.ServerBench
( runTimeBenchmark
, runSpaceBenchmark
) where
import Universum
import Criterion.Main (bench, defaultConfig, defaultMainWith, nfIO)
import Criterion.Types (Config (..))
import Weigh (io, mainWith)
import Test.QuickCheck (arbitrary, generate)
import Pos.Explorer.DB (defaultPageSize)
import Pos.Explorer.ExplorerMode (ExplorerTestParams,
runExplorerTestMode)
import Pos.Explorer.ExtraContext (ExtraContext (..), makeMockExtraCtx)
import Pos.Explorer.TestUtil (BlockNumber, SlotsPerEpoch,
generateValidExplorerMockableMode)
import Pos.Explorer.Web.ClientTypes (CBlockEntry)
import Pos.Explorer.Web.Server (getBlocksPage, getBlocksTotal)
import Test.Pos.Chain.Genesis.Dummy (dummyEpochSlots)
import Test.Pos.Chain.Txp.Arbitrary.Unsafe ()
import Test.Pos.Configuration (withDefConfigurations)
----------------------------------------------------------------
-- Mocked functions
----------------------------------------------------------------
type BenchmarkTestParams = (ExplorerTestParams, ExtraContext)
-- | @getBlocksTotal@ function for benchmarks.
getBlocksTotalBench :: BenchmarkTestParams -> IO Integer
getBlocksTotalBench (testParams, extraContext) =
withDefConfigurations $ \_ _ _ -> runExplorerTestMode
testParams
extraContext
getBlocksTotal
-- | @getBlocksPage@ function for the last page for benchmarks.
getBlocksPageBench :: BenchmarkTestParams -> IO (Integer, [CBlockEntry])
getBlocksPageBench (testParams, extraContext) =
withDefConfigurations $ \_ _ _ ->
runExplorerTestMode testParams extraContext
$ getBlocksPage
dummyEpochSlots
Nothing
(Just $ fromIntegral defaultPageSize)
-- | This is used to generate the test environment. We don't do this while benchmarking
-- the functions since that would include the time/memory required for the generation of the
-- mock blockchain (test environment), and we don't want to include that in our benchmarks.
generateTestParams
:: BlockNumber
-> SlotsPerEpoch
-> IO BenchmarkTestParams
generateTestParams totalBlocksNumber slotsPerEpoch = do
testParams <- testParamsGen
-- We replace the "real" blockchain with our custom generated one.
mode <- generateValidExplorerMockableMode totalBlocksNumber slotsPerEpoch
-- The extra context so we can mock the functions.
let extraContext :: ExtraContext
extraContext = withDefConfigurations $ \_ _ _ -> makeMockExtraCtx mode
pure (testParams, extraContext)
where
-- | Generated test parameters.
testParamsGen :: IO ExplorerTestParams
testParamsGen = generate arbitrary
-- | Extracted common code. This needs to be run before the benchmarks since we don't
-- want to include time/memory of the test data generation in the benchmarks.
usingGeneratedBlocks :: IO (BenchmarkTestParams, BenchmarkTestParams, BenchmarkTestParams)
usingGeneratedBlocks = do
blocks100 <- generateTestParams 100 10
blocks1000 <- generateTestParams 1000 10
blocks10000 <- generateTestParams 10000 10
pure (blocks100, blocks1000, blocks10000)
----------------------------------------------------------------
-- Time benchmark
----------------------------------------------------------------
-- | Time @getBlocksPage@.
runTimeBenchmark :: IO ()
runTimeBenchmark = do
-- Generate the test environment before the benchmarks.
(blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks
defaultMainWith getBlocksPageConfig
[ bench "getBlocksTotal 100 blocks" $ nfIO $ getBlocksTotalBench blocks100
, bench "getBlocksTotal 1000 blocks" $ nfIO $ getBlocksTotalBench blocks1000
, bench "getBlocksTotal 10000 blocks" $ nfIO $ getBlocksTotalBench blocks10000
, bench "getBlocksPage 100 blocks" $ nfIO $ getBlocksPageBench blocks100
, bench "getBlocksPage 1000 blocks" $ nfIO $ getBlocksPageBench blocks1000
, bench "getBlocksPage 10000 blocks" $ nfIO $ getBlocksPageBench blocks10000
]
where
-- | Configuration.
getBlocksPageConfig :: Config
getBlocksPageConfig = defaultConfig
{ reportFile = Just "bench/results/ServerBackend.html"
}
----------------------------------------------------------------
-- Space benchmark
----------------------------------------------------------------
-- | Space @getBlocksPage@.
runSpaceBenchmark :: IO ()
runSpaceBenchmark = do
-- Generate the test environment before the benchmarks.
(blocks100, blocks1000, blocks10000) <- usingGeneratedBlocks
mainWith $ do
io "getBlocksTotal 100 blocks" getBlocksTotalBench blocks100
io "getBlocksTotal 1000 blocks" getBlocksTotalBench blocks1000
io "getBlocksTotal 10000 blocks" getBlocksTotalBench blocks10000
io "getBlocksPage 100 blocks" getBlocksPageBench blocks100
io "getBlocksPage 1000 blocks" getBlocksPageBench blocks1000
io "getBlocksPage 10000 blocks" getBlocksPageBench blocks10000
|
input-output-hk/cardano-sl
|
explorer/bench/Bench/Pos/Explorer/ServerBench.hs
|
apache-2.0
| 5,219
| 0
| 12
| 1,047
| 795
| 438
| 357
| 75
| 1
|
module Settings.Builders.Haddock (haddockBuilderArgs) where
import Hadrian.Haskell.Cabal
import Hadrian.Haskell.Cabal.Type
import Hadrian.Utilities
import Packages
import Rules.Documentation
import Settings.Builders.Common
import Settings.Builders.Ghc
-- | Given a version string such as "2.16.2" produce an integer equivalent.
versionToInt :: String -> Int
versionToInt = read . dropWhile (=='0') . filter (/='.')
haddockBuilderArgs :: Args
haddockBuilderArgs = mconcat
[ builder (Haddock BuildIndex) ? do
output <- getOutput
inputs <- getInputs
root <- getBuildRoot
mconcat
[ arg $ "-B" ++ root -/- stageString Stage1 -/- "lib"
, arg $ "--lib=" ++ root -/- stageString Stage1 -/- "lib"
, arg "--gen-index"
, arg "--gen-contents"
, arg "-o", arg $ takeDirectory output
, arg "-t", arg "Haskell Hierarchical Libraries"
, arg "-p", arg "libraries/prologue.txt"
, pure [ "--read-interface="
++ (takeFileName . takeDirectory) haddock
++ "," ++ haddock | haddock <- inputs ] ]
, builder (Haddock BuildPackage) ? do
output <- getOutput
pkg <- getPackage
root <- getBuildRoot
context <- getContext
version <- expr $ pkgVersion pkg
synopsis <- expr $ pkgSynopsis pkg
deps <- getContextData depNames
haddocks <- expr $ haddockDependencies context
hVersion <- expr $ pkgVersion haddock
statsDir <- expr $ haddockStatsFilesDir
ghcOpts <- haddockGhcArgs
mconcat
[ arg "--verbosity=0"
, arg $ "-B" ++ root -/- stageString Stage1 -/- "lib"
, arg $ "--lib=" ++ root -/- stageString Stage1 -/- "lib"
, arg $ "--odir=" ++ takeDirectory output
, arg "--no-tmp-comp-dir"
, arg $ "--dump-interface=" ++ output
, arg "--html"
, arg "--hyperlinked-source"
, arg "--hoogle"
, arg "--quickjump"
, arg $ "--title=" ++ pkgName pkg ++ "-" ++ version
++ ": " ++ synopsis
, arg $ "--prologue=" ++ takeDirectory output -/- "haddock-prologue.txt"
, arg $ "--optghc=-D__HADDOCK_VERSION__="
++ show (versionToInt hVersion)
, map ("--hide=" ++) <$> getContextData otherModules
, pure [ "--read-interface=../" ++ dep
++ ",../" ++ dep ++ "/src/%{MODULE}.html#%{NAME},"
++ haddock | (dep, haddock) <- zip deps haddocks ]
, pure [ "--optghc=" ++ opt | opt <- ghcOpts, not ("--package-db" `isInfixOf` opt) ]
, getInputs
, arg "+RTS"
, arg $ "-t" ++ (statsDir -/- pkgName pkg ++ ".t")
, arg "--machine-readable"
, arg "-RTS" ] ]
|
sdiehl/ghc
|
hadrian/src/Settings/Builders/Haddock.hs
|
bsd-3-clause
| 2,924
| 0
| 19
| 976
| 733
| 371
| 362
| 65
| 1
|
{-# LANGUAGE NoImplicitPrelude, MagicHash, TypeOperators,
DataKinds, TypeFamilies, FlexibleContexts, MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Module : Java.Math
-- Copyright : (c) Jyothsna Srinivas 2017
--
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : jyothsnasrinivas17@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Bindings for Java Math utilities
--
-----------------------------------------------------------------------------
module Java.Math where
import GHC.Base
import GHC.Int
import Java.Array
import Java.PrimitiveBase
import Java.Wrappers
-- Start java.math.BigDecimal
data {-# CLASS "java.math.BigDecimal" #-} BigDecimal = BigDecimal (Object# BigDecimal)
deriving Class
data {-# CLASS "java.math.BigDecimal[]" #-} BigDecimalArray = BigDecimalArray (Object# BigDecimalArray)
deriving Class
instance JArray BigDecimal BigDecimalArray
foreign import java unsafe abs :: BigDecimal -> BigDecimal
foreign import java unsafe "abs" absMathContext :: BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe add :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "add"
addMathContext :: BigDecimal -> BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe byteValueExact :: BigDecimal -> Byte
foreign import java unsafe compareTo :: BigDecimal -> BigDecimal -> Int
foreign import java unsafe divide :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "divide" divide2 :: BigDecimal -> BigDecimal -> Int -> BigDecimal
foreign import java unsafe "divide" divide3 :: BigDecimal -> BigDecimal -> Int -> Int -> BigDecimal
foreign import java unsafe "divide"
divide4 :: BigDecimal -> BigDecimal -> Int -> RoundingMode -> BigDecimal
foreign import java unsafe "divide" divide5 :: BigDecimal -> BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe "divide" divide6 :: BigDecimal -> BigDecimal -> RoundingMode -> BigDecimal
foreign import java unsafe divideAndRemainder :: BigDecimal -> BigDecimal -> BigDecimalArray
foreign import java unsafe "divideAndRemainder"
divideAndRemainder2 :: BigDecimal -> BigDecimal -> MathContext -> BigDecimalArray
foreign import java unsafe divideToIntegralValue :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "divideToIntegralValue"
divideToIntegralValue2 :: BigDecimal -> BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe doubleValue :: BigDecimal -> Double
foreign import java unsafe equals :: BigDecimal -> Object -> Bool
foreign import java unsafe floatValue :: BigDecimal -> Float
foreign import java unsafe hashCode :: BigDecimal -> Int
foreign import java unsafe intValue :: BigDecimal -> Int
foreign import java unsafe intValueExact :: BigDecimal -> Int
foreign import java unsafe longValue :: BigDecimal -> Int64
foreign import java unsafe longValueExact :: BigDecimal -> Int64
foreign import java unsafe max :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe min :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe movePointLeft :: BigDecimal -> Int -> BigDecimal
foreign import java unsafe movePointRight :: BigDecimal -> Int -> BigDecimal
foreign import java unsafe multiply :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "multiply"
multiplyMathContext :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe negate :: BigDecimal -> BigDecimal
foreign import java unsafe "negate" negateMathContext :: BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe plus :: BigDecimal -> BigDecimal
foreign import java unsafe "plus" plusMathContext :: BigDecimal -> BigDecimal
foreign import java unsafe pow :: BigDecimal -> Int -> BigDecimal
foreign import java unsafe "pow" powMathContect :: BigDecimal -> Int -> MathContext -> BigDecimal
foreign import java unsafe precision :: BigDecimal -> Int
foreign import java unsafe remainder :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "remainder"
remainderMathContext :: BigDecimal -> BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe round :: BigDecimal -> MathContext -> BigDecimal
foreign import java unsafe scale :: BigDecimal -> Int
foreign import java unsafe scaleByPowerOfTen :: BigDecimal -> Int -> BigDecimal
foreign import java unsafe setScale :: BigDecimal -> Int -> BigDecimal
foreign import java unsafe "setScale" setScale2 :: BigDecimal -> Int -> Int -> BigDecimal
foreign import java unsafe "setScale" setScale3 :: BigDecimal -> Int -> RoundingMode -> BigDecimal
foreign import java unsafe shortValueExact :: BigDecimal -> Short
foreign import java unsafe signum :: BigDecimal -> Int
foreign import java unsafe stripTrailingZeros :: BigDecimal -> BigDecimal
foreign import java unsafe subtract :: BigDecimal -> BigDecimal -> BigDecimal
foreign import java unsafe "subtract"
subtractMathContext :: BigDecimal -> BigDecimal -> MathContext -> BigDecimal
-- foreign import java unsafe toBigInteger :: BigDecimal -> BigInteger
--
-- foreign import java unsafe toBigIntegerExact :: BigDecimal -> BigInteger
foreign import java unsafe toEngineeringString :: BigDecimal -> String
foreign import java unsafe toPlainString :: BigDecimal -> String
foreign import java unsafe toString :: BigDecimal -> String
foreign import java unsafe ulp :: BigDecimal -> BigDecimal
-- foreign import java unsafe unscaledValue :: BigDecimal -> BigInteger
-- End java.math.BigDecimal
-- Start java.math.MathContext
data {-# CLASS "java.math.MathContext" #-} MathContext = MathContext (Object# MathContext)
deriving Class
foreign import java unsafe getPrecision :: MathContext -> Int
foreign import java unsafe getRoundingMode :: MathContext -> RoundingMode
foreign import java unsafe "hashCode" hashCodeMathContext :: MathContext -> Int
-- End java.math.MathContext
-- Start java.math.RoundingMode
data {-# CLASS "java.math.RoundingMode" #-} RoundingMode = RoundingMode (Object# RoundingMode)
deriving Class
foreign import java unsafe "@static @field java.math.RoundingMode.CEILING" rmCEILING :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.DOWN" rmDOWN :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.FLOOR" rmFLOOR :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.HALF_DOWN" rmHALF_DOWN :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.HALF_EVEN" rmHALF_EVEN :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.HALF_UP" rmHALF_UP :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.UNNECESSARY" rmUNNECESSARY :: RoundingMode
foreign import java unsafe "@static @field java.math.RoundingMode.UP" rmUP :: RoundingMode
-- End java.math.RoundingMode
-- Start java.math.BigInteger
data BigInteger = BigInteger @java.math.BigInteger
deriving Class
type instance Inherits BigInteger = '[JNumber, Object]
-- End java.math.BigInteger
|
rahulmutt/ghcvm
|
libraries/base/Java/Math.hs
|
bsd-3-clause
| 7,175
| 171
| 8
| 1,026
| 1,538
| 798
| 740
| -1
| -1
|
{-# LANGUAGE LambdaCase, OverloadedStrings, RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Brick
import Brick.Widgets.DeviceList
import Brick.Widgets.Border
import Brick.Widgets.HelpMessage
import Brick.Widgets.WrappedText
import Brick.BChan
import Graphics.Vty hiding (Event, nextEvent,(<|>))
import qualified Graphics.Vty as Vty
import DBus.UDisks2.Simple
import qualified Data.Text.IO as T
import qualified Data.Text as T
import qualified Data.Vector as V
import Data.Text (Text)
import System.Exit
import System.IO
import Control.Monad
import Control.Concurrent (forkIO)
import Data.Monoid
import Control.Monad.IO.Class
import Control.Monad.Trans.Maybe
import Data.Maybe
import System.Environment
import System.Posix.User
import Control.Exception
import System.IO.Error
import Control.Applicative
import System.Process
data AppState = AppState {
devList :: List String Device,
message :: Text,
shownHelp :: Maybe KeyBindings,
connection :: Connection
}
helpMsg :: KeyBindings
helpMsg = KeyBindings
[ ("General",
[ ("q", "Quit")
, ("Esc", "Close dialog")
])
, ("Movement",
[ ("j, Down", "Select next device")
, ("k, Up", "Select previous device")
, ("g, Home", "Select first device")
, ("G, End", "Select last device")
])
, ("Device operations",
[ ("RET", "Mount or unmount device")
, ("s", "Open mount point in shell")
])
, ("Display settings",
[ ("t", "Toggle display of system devices") ])
]
draw :: AppState -> [Widget String]
draw (AppState dl msg dia _) = maybeToList dia' ++ [w]
where w = renderDeviceList dl
<=> hBorder
<=> wrappedText msg
dia' = help <$> dia
handler :: AppState -> BrickEvent String Event -> EventM String (Next AppState)
handler appState@AppState{..} e = case e of
VtyEvent e'@(EvKey _ _) ->
handleKey e' (clearMessage appState) -- clear message on every keystroke
VtyEvent _ -> continue appState
AppEvent (DeviceAdded dev) ->
continueWith $ onList (listAppend dev)
AppEvent (DeviceRemoved dev) ->
continueWith $ onList (listRemoveEq dev)
AppEvent (DeviceChanged old new) ->
continueWith $ onList (listSwap old new)
where continueWith :: (AppState -> AppState) -> EventM String (Next AppState)
continueWith f = continue (f appState)
handleKey (EvKey (KChar 'q') []) as = halt as
handleKey (EvKey (KChar '?') []) as = do
resetHelpWidget -- scroll to the beginning
continue (showHelp as)
handleKey ev as = case shownHelp of
Nothing -> handleListKey ev as
Just b -> handleDialogKey b ev as
handleListKey (EvKey KEnter []) as =
liftIO (withSelected mountUnmount as) >>= continue
handleListKey (EvKey (KChar 't') []) as =
liftIO (toggleSystemDevices as) >>= continue
handleListKey (EvKey (KChar 's') []) as =
suspendAndResume (withSelected openShell as)
handleListKey ev as = do
lst' <- handleHJKLEvent ev devList
continue $ as { devList = lst' }
handleDialogKey _ (EvKey KEsc []) as = continue (hideHelp as)
handleDialogKey b ev as = void (handleKeyBindingsEvent ev b) >> continue as
theme :: AttrMap
theme = attrMap defAttr
[ (listSelectedAttr, black `on` white)
, (helpAttr <> "title", fg green)
]
main :: IO ()
main = do
let config = ConConfig { configIncludeInternal = False }
(con,devs) <- connect config >>= \case
Left err -> do
T.hPutStrLn stderr err
exitWith (ExitFailure 1)
Right x -> return x
let devList = listMoveTo 0 $ newDeviceList "devices" devs
app = App
{ appDraw = draw
, appChooseCursor = neverShowCursor
, appHandleEvent = handler
, appStartEvent = return
, appAttrMap = const theme
}
eventChan <- newBChan 100
void $ forkIO $ eventThread con eventChan
void $ customMain (userConfig >>= mkVty) (Just eventChan) app $
AppState devList "Welcome! Press '?' to get help." Nothing con
eventThread :: Connection -> BChan Event -> IO ()
eventThread con chan = forever $ do
ev <- nextEvent con
writeBChan chan ev
----------------------------------------------------------------------
-- Actions
----------------------------------------------------------------------
mountUnmount :: Device -> AppState -> IO AppState
mountUnmount dev as
| devMounted dev = unmount (connection as) dev >>= \case
Left err -> return $ showMessage as $ "error: " <> err
Right () -> return $ showMessage as "Device unmounted"
| otherwise = mount (connection as) dev >>= \case
Left err -> return $ showMessage as $ "error: " <> err
Right mp -> return $ showMessage as $ "Device mounted at " <> mp
toggleSystemDevices :: AppState -> IO AppState
toggleSystemDevices as = do
newDevList <- modifyConfig (connection as) $ \con ->
con { configIncludeInternal = not $ configIncludeInternal con }
return $ onList (listSimpleReplace $ V.fromList newDevList) as
openShell :: Device -> AppState -> IO AppState
openShell dev as = case devMountPoints dev V.!? 0 of
Nothing -> return $ showMessage as "Device not mounted. No mount point to open."
Just directory -> do
userShell <- getUserShell
res <- (callShell userShell >> return Nothing)
`catch` (\(e :: SomeException) -> return $ Just (show e))
return $ case res of
Nothing -> as
Just err -> showMessage as (T.pack err)
where callShell sh = do
T.putStrLn ("\nRunning shell in " <> directory)
T.putStrLn "Use Ctrl+D or 'exit' to return to device list."
(_,_,_,h) <- createProcess
(proc sh []) { cwd = Just (T.unpack directory)
, delegate_ctlc = True
}
void $ waitForProcess h
----------------------------------------------------------------------
-- Helpers
----------------------------------------------------------------------
showMessage :: AppState -> Text -> AppState
showMessage as msg = as { message = msg }
clearMessage :: AppState -> AppState
clearMessage = flip showMessage " "
showHelp :: AppState -> AppState
showHelp as = as { shownHelp = Just bindings }
where bindings = helpMsg
hideHelp :: AppState -> AppState
hideHelp as = as { shownHelp = Nothing }
-- | Returns the current shell of the user.
--
-- Considers this information in order:
-- 1. The SHELL environment variable
-- 2. The default shell of the user
-- 3. /bin/bash
getUserShell :: IO FilePath
getUserShell =
-- fromJust is OK here, because "/bin/bash" is always Just
fmap fromJust $
runMaybeT $ getEnvShell <|> getDefShell <|> return "/bin/bash"
where getEnvShell :: MaybeT IO FilePath
getEnvShell = ifExists $ getEnv "SHELL"
getDefShell :: MaybeT IO FilePath
getDefShell = do
uid <- liftIO getEffectiveUserID
user <- ifExists $ getUserEntryForID uid
return $ userShell user
ifExists :: IO a -> MaybeT IO a
ifExists action = MaybeT $ tryJust (guard . isDoesNotExistError) action >>= \case
Left _ -> return Nothing
Right res -> return (Just res)
-- not onLisp!
onList :: (List String Device -> List String Device) -> AppState -> AppState
onList f appState = appState { devList = f (devList appState)}
withSelected :: (Device -> AppState -> IO AppState) -> AppState -> IO AppState
withSelected action as = case listSelectedElement (devList as) of
Nothing -> return $ showMessage as "No device selected"
Just (_, dev) -> action dev as
|
rootzlevel/device-manager
|
src/Main.hs
|
bsd-3-clause
| 7,733
| 0
| 19
| 1,878
| 2,278
| 1,179
| 1,099
| 174
| 12
|
{-# LANGUAGE PackageImports #-}
module Main where
import System.Environment
import qualified Data.ByteString.Lazy as L
import "cryptonite" Crypto.Hash
import qualified "cryptohash" Crypto.Hash as Old
main = do
args <- getArgs
case args of
[] -> error "usage: bench <big-file>"
"old":x:_ -> do
r <- L.readFile x
let d = Old.hashlazy r :: Old.Digest Old.SHA1
putStrLn $ show d
x:_ -> do
r <- L.readFile x
let d = hashlazy r :: Digest SHA1
putStrLn $ show d
|
tekul/cryptonite
|
benchs/Hash.hs
|
bsd-3-clause
| 570
| 0
| 16
| 191
| 174
| 88
| 86
| 18
| 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="ms-MY">
<title>Highlighter</title>
<maps>
<homeID>highlighter</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>
|
thc202/zap-extensions
|
addOns/highlighter/src/main/javahelp/help_ms_MY/helpset_ms_MY.hs
|
apache-2.0
| 964
| 77
| 66
| 155
| 404
| 205
| 199
| -1
| -1
|
{-# LANGUAGE PolyKinds, RankNTypes, ScopedTypeVariables #-}
module T8616 where
import Data.Proxy
import GHC.Exts
withSomeSing :: forall k (kproxy :: k). Proxy kproxy
withSomeSing = undefined :: (Any :: k)
-- The 'k' is bought into scope by the type signature
-- This is a type error, but should not crash GHC
foo = (undefined :: Proxy (a :: k)) :: forall k (a :: k). Proxy a
-- Again, the 'k' is bought into scope by the type signature
-- No type error though
|
sdiehl/ghc
|
testsuite/tests/polykinds/T8616.hs
|
bsd-3-clause
| 471
| 1
| 8
| 95
| 93
| 58
| 35
| 7
| 1
|
{-# Language CPP #-}
-- | Settings are centralized, as much as possible, into this file. This
-- includes database connection settings, static file locations, etc.
-- In addition, you can configure a number of different aspects of Yesod
-- by overriding methods in the Yesod typeclass. That instance is
-- declared in the Foundation.hs file.
module Settings where
import ClassyPrelude.Yesod
import Control.Exception (throw)
import Data.Aeson (Result (..), fromJSON, withObject, (.!=),
(.:?))
import Data.FileEmbed (embedFile)
import Data.Yaml (decodeEither')
import Database.Persist.Sqlite (SqliteConf)
import Language.Haskell.TH.Syntax (Exp, Name, Q)
import Network.Wai.Handler.Warp (HostPreference)
import Yesod.Default.Config2 (applyEnvValue, configSettingsYml)
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
-- | Runtime settings to configure this application. These settings can be
-- loaded from various sources: defaults, environment variables, config files,
-- theoretically even a database.
data AppSettings = AppSettings
{ appStaticDir :: String
-- ^ Directory from which to serve static files.
, appDatabaseConf :: SqliteConf
-- ^ Configuration settings for accessing the database.
, appRoot :: Maybe Text
-- ^ Base for all generated URLs. If @Nothing@, determined
-- from the request headers.
, appHost :: HostPreference
-- ^ Host/interface the server should bind to.
, appPort :: Int
-- ^ Port to listen on
, appIpFromHeader :: Bool
-- ^ Get the IP address from the header when logging. Useful when sitting
-- behind a reverse proxy.
, appDetailedRequestLogging :: Bool
-- ^ Use detailed request logging system
, appShouldLogAll :: Bool
-- ^ Should all log messages be displayed?
, appReloadTemplates :: Bool
-- ^ Use the reload version of templates
, appMutableStatic :: Bool
-- ^ Assume that files in the static dir may change after compilation
, appSkipCombining :: Bool
-- ^ Perform no stylesheet/script combining
-- Example app-specific configuration values.
, appCopyright :: Text
-- ^ Copyright text to appear in the footer of the page
, appAnalytics :: Maybe Text
-- ^ Google Analytics code
}
instance FromJSON AppSettings where
parseJSON = withObject "AppSettings" $ \o -> do
let defaultDev =
#if DEVELOPMENT
True
#else
False
#endif
appStaticDir <- o .: "static-dir"
appDatabaseConf <- o .: "database"
appRoot <- o .:? "approot"
appHost <- fromString <$> o .: "host"
appPort <- o .: "port"
appIpFromHeader <- o .: "ip-from-header"
appDetailedRequestLogging <- o .:? "detailed-logging" .!= defaultDev
appShouldLogAll <- o .:? "should-log-all" .!= defaultDev
appReloadTemplates <- o .:? "reload-templates" .!= defaultDev
appMutableStatic <- o .:? "mutable-static" .!= defaultDev
appSkipCombining <- o .:? "skip-combining" .!= defaultDev
appCopyright <- o .: "copyright"
appAnalytics <- o .:? "analytics"
return AppSettings {..}
-- | Settings for 'widgetFile', such as which template languages to support and
-- default Hamlet settings.
--
-- For more information on modifying behavior, see:
--
-- https://github.com/yesodweb/yesod/wiki/Overriding-widgetFile
widgetFileSettings :: WidgetFileSettings
widgetFileSettings = def
-- | How static files should be combined.
combineSettings :: CombineSettings
combineSettings = def
-- The rest of this file contains settings which rarely need changing by a
-- user.
widgetFile :: String -> Q Exp
widgetFile = (if appReloadTemplates compileTimeAppSettings
then widgetFileReload
else widgetFileNoReload)
widgetFileSettings
-- | Raw bytes at compile time of @config/settings.yml@
configSettingsYmlBS :: ByteString
configSettingsYmlBS = $(embedFile configSettingsYml)
-- | @config/settings.yml@, parsed to a @Value@.
configSettingsYmlValue :: Value
configSettingsYmlValue = either throw id $ decodeEither' configSettingsYmlBS
-- | A version of @AppSettings@ parsed at compile time from @config/settings.yml@.
compileTimeAppSettings :: AppSettings
compileTimeAppSettings =
case fromJSON $ applyEnvValue False mempty configSettingsYmlValue of
Error e -> error e
Success settings -> settings
-- The following two functions can be used to combine multiple CSS or JS files
-- at compile time to decrease the number of http requests.
-- Sample usage (inside a Widget):
--
-- > $(combineStylesheets 'StaticR [style1_css, style2_css])
combineStylesheets :: Name -> [Route Static] -> Q Exp
combineStylesheets = combineStylesheets'
(appSkipCombining compileTimeAppSettings)
combineSettings
combineScripts :: Name -> [Route Static] -> Q Exp
combineScripts = combineScripts'
(appSkipCombining compileTimeAppSettings)
combineSettings
|
notae/haskell-exercise
|
yesod/my-project/Settings.hs
|
bsd-3-clause
| 5,447
| 0
| 12
| 1,463
| 706
| 405
| 301
| -1
| -1
|
{-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-overlapping-patterns #-}
module PMC003 where
f :: Bool -> Bool -> ()
f _ False = ()
f True False = ()
f _ _ = ()
|
ezyang/ghc
|
testsuite/tests/pmcheck/should_compile/pmc003.hs
|
bsd-3-clause
| 176
| 0
| 7
| 43
| 56
| 30
| 26
| 6
| 1
|
{-# LANGUAGE GADTs, ExistentialQuantification #-}
module ShouldFail where
data T = forall a. T a (a->Int)
f ~(T x f) = f x
|
siddhanathan/ghc
|
testsuite/tests/gadt/lazypat.hs
|
bsd-3-clause
| 131
| 0
| 8
| 31
| 48
| 26
| 22
| 4
| 1
|
{-# LANGUAGE UnicodeSyntax, Arrows, RankNTypes #-}
module T8959b where
foo :: Int -> Int
foo = ()
bar :: ()
bar = proc x -> do return -< x
baz = () :: (forall a. a -> a) -> a
|
urbanslug/ghc
|
testsuite/tests/ghci/scripts/T8959b.hs
|
bsd-3-clause
| 179
| 1
| 8
| 44
| 73
| 41
| 32
| 7
| 1
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
module Compiler where
import qualified Data.List
import qualified Expr
import Data.List((\\))
import Expr(Expr(..), Id)
import FreshName
import Type
import Debug.Trace(traceShow)
import Debug.Trace(traceShowId)
-- Intermediate language in normal form
data AtomicExpr =
ALitInt Type2 Integer |
ALitBool Type2 Bool |
AVar Type2 Id |
AExternVar Type2 Id
data ComplexExpr =
COpAdd Type2 AtomicExpr AtomicExpr |
COpSub Type2 AtomicExpr AtomicExpr |
COpMul Type2 AtomicExpr AtomicExpr |
COpDiv Type2 AtomicExpr AtomicExpr |
COpLT Type2 AtomicExpr AtomicExpr |
COpEQ Type2 AtomicExpr AtomicExpr |
CIf Type2 AtomicExpr ExprNF ExprNF |
CApp Type2 AtomicExpr AtomicExpr |
CAbs Type2 Id ExprNF |
CAbsRec Type2 Id Id ExprNF
data ExprNF =
EVal Type2 AtomicExpr |
ELet Type2 Id ComplexExpr ExprNF
class Typeable a where
getType :: a -> Type2
instance Typeable AtomicExpr where
getType (ALitInt ty _) = ty
getType (ALitBool ty _) = ty
getType (AVar ty _) = ty
getType (AExternVar ty _) = ty
instance Typeable ComplexExpr where
getType (COpAdd ty _ _) = ty
getType (COpSub ty _ _) = ty
getType (COpMul ty _ _) = ty
getType (COpDiv ty _ _) = ty
getType (COpLT ty _ _) = ty
getType (COpEQ ty _ _) = ty
getType (CIf ty _ _ _) = ty
getType (CApp ty _ _) = ty
getType (CAbs ty _ _) = ty
getType (CAbsRec ty _ _ _) = ty
instance Typeable ExprNF where
getType (EVal ty _) = ty
getType (ELet ty _ _ _) = ty
-- Pretty print
instance Show AtomicExpr where
show (ALitInt _ n) = show n
show (ALitBool _ True) = "true"
show (ALitBool _ False) = "false"
show (AVar _ x) = x
--show (AVar ty x) = "(" ++ x ++ " : " ++ show ty ++ ")"
show (AExternVar _ f) = f
instance Show ComplexExpr where
show (COpAdd _ e1 e2) = show e1 ++ " + " ++ show e2
show (COpSub _ e1 e2) = show e1 ++ " - " ++ show e2
show (COpMul _ e1 e2) = show e1 ++ " * " ++ show e2
show (COpDiv _ e1 e2) = show e1 ++ " / " ++ show e2
show (COpLT _ e1 e2) = show e1 ++ " < " ++ show e2
show (COpEQ _ e1 e2) = show e1 ++ " = " ++ show e2
show (CIf _ e1 e2 e3) =
"if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
show (CApp _ e1 e2) = show e1 ++ " " ++ show e2
show (CAbs _ x e) = "(fun " ++ x ++ " -> " ++ show e ++ ")"
show (CAbsRec _ f x e) = "(fun " ++ x ++ " -> " ++ show e ++ ")"
instance Show ExprNF where
show (EVal _ x) = show x
show (ELet _ f abs@(CAbsRec ty _ _ _) e2) =
"let rec " ++ f ++ " = " ++ show abs ++ " in\n" ++ show e2
--"let rec " ++ f ++ " : " ++ show ty ++ " = " ++ show abs ++ " in\n" ++ show e2
show (ELet _ x e1 e2) =
"let " ++ x ++ " = " ++ show e1 ++ " in\n" ++ show e2
--"let " ++ x ++ " : " ++ show (getType e1) ++ " = " ++ show e1 ++ " in\n" ++ show e2
-- Expression -> normal form
nfBinOp :: TyExpr2 -> TyExpr2 -> (Type2 -> AtomicExpr -> AtomicExpr -> ComplexExpr) ->
Type2 -> (Type2 -> Id -> AtomicExpr) -> (AtomicExpr -> NameGen ExprNF) ->
NameGen ExprNF
nfBinOp e1 e2 op ty s k = nf e1 s (\a -> nf e2 s (\b -> do
c <- fresh
d <- k (AVar ty c)
return (ELet (getType d) c (op ty a b) d)))
nf :: TyExpr2 -> (Type2 -> Id -> AtomicExpr) -> (AtomicExpr -> NameGen ExprNF) ->
NameGen ExprNF
nf (LitInt ty n) s k = k (ALitInt ty n)
nf (LitBool ty b) s k = k (ALitBool ty b)
nf (Var ty x) s k = k (s ty x)
nf (ExternVar ty x) s k = k (AExternVar ty x)
nf (OpAdd ty e1 e2) s k = nfBinOp e1 e2 COpAdd ty s k
nf (OpSub ty e1 e2) s k = nfBinOp e1 e2 COpSub ty s k
nf (OpMul ty e1 e2) s k = nfBinOp e1 e2 COpMul ty s k
nf (OpDiv ty e1 e2) s k = nfBinOp e1 e2 COpDiv ty s k
nf (OpLT ty e1 e2) s k = nfBinOp e1 e2 COpLT ty s k
nf (OpEQ ty e1 e2) s k = nfBinOp e1 e2 COpEQ ty s k
nf (If ty e1 e2 e3) s k = nf e1 s (\e1' -> do
a <- fresh
e2' <- nf e2 s (return . EVal (Expr.getType e2))
e3' <- nf e3 s (return . EVal (Expr.getType e3))
b <- k (AVar (Expr.getType e2) a)
let ifTy = getType e2'
return (ELet (getType b) a (CIf ifTy e1' e2' e3') b))
nf (Let ty (x, _) e1 e2) s k =
nf e1 s (\a ->
nf e2 (\ty y -> if y == x then a else s ty y) (return . EVal (Expr.getType e2)))
nf (Abs ty x e) s k = do
a <- fresh
b <- nf e s (return . EVal (Expr.getType e))
c <- k (AVar ty a)
return (ELet (getType c) a (CAbs ty x b) c)
nf (AbsRec ty f x e) s k = do
a <- fresh
let subst ty y = if y == f then AVar ty a else s ty y
b <- nf e subst (return . EVal (Expr.getType e))
c <- k (AVar ty a)
return (ELet (getType c) a (CAbsRec ty a x b) c)
nf (App ty e1 e2) s k = nf e1 s (\e1' -> nf e2 s (\e2' -> do
a <- fresh
d <- k (AVar ty a)
return (ELet (getType d) a (CApp ty e1' e2') d)))
toNormalFormM :: TyExpr2 -> NameGen ExprNF
toNormalFormM e = nf e AVar (return . EVal (Expr.getType e))
toNormalForm :: TyExpr2 -> ExprNF
toNormalForm = runNameGen . toNormalFormM
-- Intermediate language in normal form with closures
data AtomicExprCl =
ACLitInt Type2 Integer |
ACLitBool Type2 Bool |
ACExternVar Type2 Id |
ACVar Type2 Id |
ACVarSelf Type2 Id |
ACVarEnv Type2 Integer
type Env = [AtomicExprCl]
data ComplexExprCl =
CCOpAdd Type2 AtomicExprCl AtomicExprCl |
CCOpSub Type2 AtomicExprCl AtomicExprCl |
CCOpMul Type2 AtomicExprCl AtomicExprCl |
CCOpDiv Type2 AtomicExprCl AtomicExprCl |
CCOpLT Type2 AtomicExprCl AtomicExprCl |
CCOpEQ Type2 AtomicExprCl AtomicExprCl |
CCIf Type2 AtomicExprCl ExprNFCl ExprNFCl |
CCApp Type2 AtomicExprCl AtomicExprCl |
CCClosure Type2 Id ExprNFCl Env
data ExprNFCl =
ECVal Type2 AtomicExprCl |
ECLet Type2 Id ComplexExprCl ExprNFCl
instance Typeable ComplexExprCl where
getType (CCOpAdd ty _ _) = ty
getType (CCOpSub ty _ _) = ty
getType (CCOpMul ty _ _) = ty
getType (CCOpDiv ty _ _) = ty
getType (CCOpLT ty _ _) = ty
getType (CCOpEQ ty _ _) = ty
getType (CCIf ty _ _ _) = ty
getType (CCApp ty _ _) = ty
getType (CCClosure ty _ _ _) = ty
-- Pretty print
instance Show AtomicExprCl where
show (ACLitInt _ n) = show n
show (ACLitBool _ b) = show b
show (ACExternVar _ f) = "extern " ++ f
show (ACVar _ x) = x
--show (ACVar ty x) = "(" ++ x ++ " : " ++ show ty ++ ")"
show (ACVarSelf _ _) = "env.self"
show (ACVarEnv _ n) = "env." ++ show n
--show (ACVarEnv ty n) = "(env." ++ show n ++ " : " ++ show ty ++ ")"
instance Show ComplexExprCl where
show (CCOpAdd _ e1 e2) = show e1 ++ " + " ++ show e2
show (CCOpSub _ e1 e2) = show e1 ++ " - " ++ show e2
show (CCOpMul _ e1 e2) = show e1 ++ " * " ++ show e2
show (CCOpDiv _ e1 e2) = show e1 ++ " / " ++ show e2
show (CCOpLT _ e1 e2) = show e1 ++ " < " ++ show e2
show (CCOpEQ _ e1 e2) = show e1 ++ " = " ++ show e2
show (CCIf _ e1 e2 e3) =
"if " ++ show e1 ++ " then " ++ show e2 ++ " else " ++ show e3
show (CCApp _ e1 e2) = show e1 ++ " " ++ show e2
show (CCClosure _ x f env) =
"Closure (fun env -> fun " ++ x ++ " -> " ++ show f ++ ", " ++ show env ++ ")"
instance Show ExprNFCl where
show (ECVal _ x) = show x
show (ECLet ty x e1 e2) =
"let " ++ x ++ " = " ++ show e1 ++ " in\n" ++ show e2
--"let " ++ x ++ " : " ++ show (getType e1) ++ " = " ++ show e1 ++ " in\n" ++ show e2
class PrettyPrint a where
prettyPrint :: String -> a -> String
instance PrettyPrint ComplexExprCl where
prettyPrint prefix (CCOpAdd _ e1 e2) = show e1 ++ " + " ++ show e2
prettyPrint prefix (CCOpSub _ e1 e2) = show e1 ++ " - " ++ show e2
prettyPrint prefix (CCOpMul _ e1 e2) = show e1 ++ " * " ++ show e2
prettyPrint prefix (CCOpDiv _ e1 e2) = show e1 ++ " / " ++ show e2
prettyPrint prefix (CCOpLT _ e1 e2) = show e1 ++ " < " ++ show e2
prettyPrint prefix (CCOpEQ _ e1 e2) = show e1 ++ " = " ++ show e2
prettyPrint prefix (CCIf _ e1 e2 e3) = "\n" ++
prefix ++ " if " ++ show e1 ++ " then\n" ++
prettyPrint (" " ++ prefix) e2 ++ "\n" ++
prefix ++ " else\n" ++
prettyPrint (" " ++ prefix) e3
prettyPrint prefix (CCApp _ e1 e2) = show e1 ++ " " ++ show e2
prettyPrint prefix (CCClosure _ x f env) =
"Closure (fun env = " ++ show env ++ " -> fun " ++ x ++ " ->\n" ++
prettyPrint (" " ++ prefix) f ++ ")"
instance PrettyPrint ExprNFCl where
prettyPrint prefix (ECVal _ x) = prefix ++ show x
prettyPrint prefix (ECLet _ x e1 e2) =
prefix ++ "let " ++ x ++ " = " ++ prettyPrint prefix e1 ++ " in\n" ++
prettyPrint prefix e2
atExprGetType (ACLitInt ty _) = ty
atExprGetType (ACLitBool ty _) = ty
atExprGetType (ACExternVar ty _) = ty
atExprGetType (ACVar ty _) = ty
atExprGetType (ACVarSelf ty _) = ty
atExprGetType (ACVarEnv ty _) = ty
-- Normal form -> normal form with closure
class FreeVariables a where
fv :: a -> [(Id, Type2)]
instance FreeVariables AtomicExpr where
fv (ALitInt _ _) = []
fv (ALitBool _ _) = []
fv (AVar ty x) = [(x, ty)]
fv (AExternVar _ x) = []
instance FreeVariables ComplexExpr where
fv (COpAdd _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (COpSub _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (COpMul _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (COpDiv _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (COpLT _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (COpEQ _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (CIf _ e1 e2 e3) =
let u = Data.List.union in (fv e1) `u` (fv e2) `u` (fv e3)
fv (CApp _ e1 e2) = Data.List.union (fv e1) (fv e2)
fv (CAbs _ x e) = [p | p@(y,_) <- fv e, y /= x]
fv (CAbsRec _ f x e) = [p | p@(y,_) <- fv e, y /= x && y /= f]
instance FreeVariables ExprNF where
fv (EVal _ x) = fv x
fv (ELet _ x e1 e2) = Data.List.union (fv e1) [p | p <- fv e2, fst p /= x]
clAt :: (Type2 -> Id -> AtomicExprCl) -> AtomicExpr -> AtomicExprCl
clAt s (ALitInt ty n) = ACLitInt ty n
clAt s (ALitBool ty b) = ACLitBool ty b
clAt s (AVar ty x) = s ty x
clAt s (AExternVar ty x) = ACExternVar ty x
clAbs ty s f (x, e) =
let fvs = [p | p@(y,_) <- fv e, y /= x] in
let fFvs = [p | p@(y,_) <- fvs, y /= f] in
let env = map (uncurry (flip s)) fFvs in
let subst ty y =
if y == x then
ACVar ty x
else if y == f then
ACVarSelf ty f
else
case Data.List.elemIndex y (map fst fvs) of
Nothing -> s ty y
Just n -> ACVarEnv (snd (fvs !! n)) (toInteger n)
in CCClosure ty x (clExpr subst e) env
clCo :: (Type2 -> Id -> AtomicExprCl) -> ComplexExpr -> ComplexExprCl
clCo s (COpAdd ty e1 e2) = CCOpAdd ty (clAt s e1) (clAt s e2)
clCo s (COpSub ty e1 e2) = CCOpSub ty (clAt s e1) (clAt s e2)
clCo s (COpMul ty e1 e2) = CCOpMul ty (clAt s e1) (clAt s e2)
clCo s (COpDiv ty e1 e2) = CCOpDiv ty (clAt s e1) (clAt s e2)
clCo s (COpLT ty e1 e2) = CCOpLT ty (clAt s e1) (clAt s e2)
clCo s (COpEQ ty e1 e2) = CCOpEQ ty (clAt s e1) (clAt s e2)
clCo s (CIf ty e1 e2 e3) = CCIf ty (clAt s e1) (clExpr s e2) (clExpr s e3)
clCo s (CApp ty e1 e2) = CCApp ty (clAt s e1) (clAt s e2)
clCo s (CAbs ty x e) = clAbs ty s "" (x, e)
clCo s (CAbsRec ty f x e) = clAbs ty s f (x, e)
clExpr :: (Type2 -> Id -> AtomicExprCl) -> ExprNF -> ExprNFCl
clExpr s (EVal ty a) = ECVal ty (clAt s a)
clExpr s (ELet ty x e1 e2) = ECLet ty x (clCo s e1) (clExpr s e2)
toClosure :: ExprNF -> ExprNFCl
toClosure = clExpr ACVar
|
authchir/mini-ml
|
src/Compiler.hs
|
isc
| 11,602
| 0
| 24
| 3,336
| 5,469
| 2,725
| 2,744
| 262
| 4
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Chip8.Emulator.SDL ( runSDLEmulator
) where
import Data.Word (Word8, Word32)
import Data.List (foldl')
import Data.Bits ((.|.))
import Data.STRef (STRef, readSTRef, writeSTRef)
import Control.Monad (foldM_, when)
import Control.Monad.ST (RealWorld, stToIO)
import Data.Array.ST (getElems)
import Control.Monad.Reader (ReaderT, ask, runReaderT)
import Control.Monad.Trans (MonadIO, lift)
import Control.Applicative
import System.Random (newStdGen, randomR)
import Control.Concurrent (threadDelay)
import Control.Concurrent.Suspend.Lifted
import Control.Concurrent.Timer
import qualified Data.Array.BitArray.ST as BA
import qualified Graphics.UI.SDL as SDL
import Foreign.C.String
import Foreign.C.Types
import Foreign.Ptr
import Foreign.Marshal.Alloc (alloca)
import Foreign.Marshal.Utils (with, maybePeek)
import Foreign.Storable (peek)
import Chip8.Monad
import Chip8.VideoMemory (VideoMemory, clearVideoMemory, draw, vScale, vWidth, vHeight)
import Chip8.Event (EventState(..), Key(..))
import Chip8.Memory (Memory(..), Address(..))
import qualified Chip8.Memory as Memory
import qualified Chip8.Event as Event
newtype SDLEmulator a = SDLEmulator (ReaderT (Memory RealWorld) IO a)
deriving (Functor, Applicative, Monad, MonadIO)
type Risky a = Either String a
data Colour = Black | White deriving Show
screenWidth :: CInt
screenWidth = fromIntegral vWidth
screenHeight :: CInt
screenHeight = fromIntegral vHeight
screenScale :: CInt
screenScale = fromIntegral vScale
instance MonadEmulator SDLEmulator where
load address = SDLEmulator $ do
mem <- ask
lift $ stToIO $ Memory.load mem address
store address value = SDLEmulator $ do
mem <- ask
lift $ stToIO $ Memory.store mem address value
clearScreen = SDLEmulator $ do
mem <- ask
lift $ stToIO $ clearVideoMemory (videoMemory mem)
drawSprite x y n (Ram address) = SDLEmulator $ do
mem <- ask
sprite <- lift $ stToIO $ fmap (take n . drop (fromIntegral address)) (getElems $ memory mem)
lift $ stToIO $ draw (videoMemory mem) x y sprite
drawSprite _ _ _ _ = error "Incorrect Address in drawSprite"
randomWord8 = SDLEmulator $ do
mem <- ask
g <- lift $ stToIO $ readSTRef $ stdGen mem
let (rnd, g') = randomR (0x0, 0xFF) g
lift $ stToIO $ writeSTRef (stdGen mem) g'
return rnd
handleEvents = SDLEmulator $ do
mem <- ask
let kes = eventState mem
lift $ handleNextEvent kes
waitForKeyPress = SDLEmulator $ do
mem <- ask
lift $ getKey (eventState mem)
where
getKey kes = do
handleNextEvent kes
k <- stToIO $ readSTRef $ lastEventKeyDown kes
case k of
Nothing -> getKey kes
Just key -> return key
isKeyPressed key = SDLEmulator $ do
mem <- ask
lift $ stToIO $ Event.isKeyPressed (eventState mem) key
sleep = SDLEmulator $ lift $ threadDelay 800
isDone = SDLEmulator $ do
mem <- ask
lift $ stToIO $ Event.isTimeToQuit (eventState mem)
drawVideoMemory :: SDL.Renderer -> VideoMemory RealWorld -> IO ()
drawVideoMemory renderer vram = do
vm <- stToIO $ BA.getElems vram
drawVM vm
where
pixel x y = SDL.Rect (screenScale * fromIntegral x) (screenScale * fromIntegral y) screenScale screenScale
drawVM mem = do
foldM_ drawBit 0 mem
SDL.renderPresent renderer
drawBit a i = do
let x = a `mod` vWidth
let y = a `div` vWidth
_ <- fillRectangle renderer (pixel x y) (if i then White else Black)
return $ a + 1
initializeSDL :: [Word32] -> IO (Risky())
initializeSDL flags = do
initiSuccess <- SDL.init $ foldl' (.|.) 0 flags
return $ if initiSuccess < 0 then Left "SDL could not initialize!" else Right ()
catchRisky :: Risky a -> IO a
catchRisky = either throwSDLError return
throwSDLError :: String -> IO a
throwSDLError message = do
errorString <- SDL.getError >>= peekCString
fail (message ++ " SDL_Error: " ++ errorString)
createWindow :: String -> IO (Risky SDL.Window)
createWindow windowTitle = withCAString windowTitle $ \title -> do
window <- SDL.createWindow title SDL.windowPosUndefined SDL.windowPosUndefined (screenWidth * screenScale) (screenHeight * screenScale) SDL.windowFlagShown
return $ if window == nullPtr then Left "Window could not be created!" else Right window
createRenderer :: SDL.Window -> CInt -> [Word32] -> IO (Risky SDL.Renderer)
createRenderer window index flags = do
renderer <- SDL.createRenderer window index $ foldl' (.|.) 0 flags
return $ if renderer == nullPtr then Left "Renderer could not be created!" else Right renderer
clearWindow :: SDL.Renderer -> IO CInt
clearWindow renderer = do
_ <- setColor renderer Black
SDL.renderClear renderer
setColor :: SDL.Renderer -> Colour -> IO CInt
setColor renderer White = SDL.setRenderDrawColor renderer 0xFF 0xFF 0xFF 0xFF
setColor renderer Black = SDL.setRenderDrawColor renderer 0x00 0x00 0x00 0x00
fillRectangle :: SDL.Renderer -> SDL.Rect -> Colour -> IO CInt
fillRectangle renderer shape color = do
_ <- setColor renderer color
with shape $ SDL.renderFillRect renderer
pollEvent :: IO (Maybe SDL.Event)
pollEvent = alloca $ \pointer -> do
status <- SDL.pollEvent pointer
if status == 1
then maybePeek peek pointer
else return Nothing
handleNextEvent :: EventState RealWorld -> IO ()
handleNextEvent es = do
maybeEvent <- pollEvent
case maybeEvent of
Nothing -> return ()
Just (SDL.QuitEvent _ _) -> stToIO $ Event.timeToQuit es
Just (SDL.KeyboardEvent eventType _ _ _ _ keysym) ->
case eventType of
768 -> do -- SDL_KEYDOWN
stToIO $ Event.setLastKeyPressed es (keymap keysym)
setKeyHandler keysym True
769 -> do -- SDL_KEYUP
stToIO $ Event.setLastKeyPressed es Nothing
setKeyHandler keysym False
_ -> stToIO $ Event.setLastKeyPressed es Nothing
where
setKeyHandler key b =
case keymap key of
Just k -> stToIO $ Event.setKey es k b
_ -> return ()
_ -> return ()
keymap :: SDL.Keysym -> Maybe Key
keymap (SDL.Keysym keysymScancode _ _) =
case keysymScancode of
36 -> Just K1 -- 7
37 -> Just K2 -- 8
38 -> Just K3 -- 9
39 -> Just KC -- 0
24 -> Just K4 -- u
12 -> Just K5 -- i
18 -> Just K6 -- o
19 -> Just KD -- p
13 -> Just K7 -- j
14 -> Just K8 -- k
15 -> Just K9 -- l
51 -> Just KE -- ;
16 -> Just KA -- m
54 -> Just K0 -- ,
55 -> Just KB -- .
56 -> Just KF -- /
_ -> Nothing
decTimer :: STRef RealWorld Word8 -> IO ()
decTimer timer = do
v <- stToIO $ readSTRef timer
when (v > 0) (stToIO $ writeSTRef timer (v - 1))
runSDLEmulator :: SDLEmulator a -> IO ()
runSDLEmulator (SDLEmulator reader) = do
initializeSDL [SDL.initFlagVideo] >>= catchRisky
window <- createWindow "CHIP-8 Emulator" >>= catchRisky
renderer <- createRenderer window (-1) [SDL.rendererFlagAccelerated] >>= catchRisky
_ <- clearWindow renderer
g <- newStdGen
mem <- stToIO $ Memory.new g
_ <- repeatedTimer (drawVideoMemory renderer (videoMemory mem)) (usDelay 100)
_ <- repeatedTimer (decTimer $ delayTimer mem) (msDelay 17)
_ <- runReaderT reader mem
SDL.destroyRenderer renderer
SDL.destroyWindow window
SDL.quit
|
ksaveljev/chip-8-emulator
|
Chip8/Emulator/SDL.hs
|
mit
| 7,586
| 0
| 18
| 1,875
| 2,555
| 1,282
| 1,273
| 187
| 17
|
module Station.Types.Card.Time where
import Import
import Data.Scientific (Scientific)
import qualified Data.Time.Calendar as CAL
import Data.Time.Clock (UTCTime(..), DiffTime,
getCurrentTime)
import Data.Time.Clock.AnnouncedLeapSeconds (lst)
import qualified Data.Time.Clock.TAI as TAI
-- | International Atomic Time (Temps Atomique International).
--
-- Stored and serialized as the number of seconds since the Unix epoch.
newtype TAI
= TAI { _unTAI :: Scientific }
deriving (Eq, Show, FromJSON, ToJSON)
getTAI :: IO TAI
getTAI = TAI
. truncateToThreeDecimals
-- ^ TODO: Move truncation to serialization.
. taiFromUTC
<$> getCurrentTime
taiFromUTC :: UTCTime -> Scientific
taiFromUTC = realToFrac . f . TAI.utcToTAITime lst
where
-- The only way the library allows getting out of @AbsoluteTime@
-- is through @diffAbsoluteTime@.
f :: TAI.AbsoluteTime -> DiffTime
f current = TAI.diffAbsoluteTime -- diffAbsoluteTime a b = a - b
current
(TAI.utcToTAITime lst unixEpoch)
unixEpoch :: UTCTime
unixEpoch = UTCTime
{ utctDay = CAL.ModifiedJulianDay 40587
, utctDayTime = 0
}
-- | See this answer:
-- http://stackoverflow.com/a/31952975/1132816
--
-- TODO: There really should be a robost rounding function in a lib
-- somewhere. For one thing we should be rounding not truncating.
truncateToThreeDecimals :: Scientific -> Scientific
truncateToThreeDecimals a = fromIntegral (floor (a * b) :: Int) / b
where
b :: Scientific
b = 10 ^ (3 :: Int)
|
seagreen/station
|
src/Station/Types/Card/Time.hs
|
mit
| 1,740
| 0
| 10
| 508
| 298
| 179
| 119
| 30
| 1
|
-- | For importing into Network.Campfire.Types for use
-- by TemplateHaskell
module Network.Campfire.Types.TH (deriveJSONOptions) where
import Data.Aeson.TH
import Data.Char(toLower, isLower)
import Data.List(intercalate, groupBy)
-- | Options for renaming fields of record types in
-- Network.Campfire.Types
deriveJSONOptions :: Options
deriveJSONOptions =
defaultOptions { fieldLabelModifier = mixedCaseToFieldLabel }
-- goes from identifiersLikeThis to like_this
mixedCaseToFieldLabel :: String -> String
mixedCaseToFieldLabel =
intercalate "_" . -- concatenate words, separated by "_"
map (map toLower) . -- lower case all characters in words
groupBy inSameWord . -- group words into lists
dropWhile isLower -- drop lower-case prefix (record selector prefix)
inSameWord :: Char -> Char -> Bool
inSameWord _ = isLower
|
joshmcgrath08/campfire-lib
|
Network/Campfire/Types/TH.hs
|
mit
| 846
| 0
| 10
| 132
| 137
| 81
| 56
| 15
| 1
|
eratosSieve :: [Integer] -> [Integer]
eratosSieve (n:ns)
| n*n > last ns = n:ns
eratosSieve (n:ns) = n:eratosSieve [ i | i<-ns, i `mod` n /= 0]
primeList' :: Integer -> [Integer]
primeList' n = eratosSieve [2..n]
primeFactorizeCount :: Integer -> Integer -> Integer
primeFactorizeCount n p
| n `mod` p == 0 = 1 + primeFactorizeCount (n `div` p) p
| otherwise = 0
primeFactorizeWoker :: Integer -> [Integer] -> [Integer]
primeFactorizeWoker n [] = []
primeFactorizeWoker n (p:px) = [primeFactorizeCount n p] ++ primeFactorizeWoker n px
primeFactorizeList :: Integer -> [(Integer, Integer)]
primeFactorizeList n = zip ( primeList' n ) (primeFactorizeWoker n ( primeList' n))
primeFactorize :: Integer -> [(Integer, Integer)]
primeFactorize n = [ tuple | tuple <- primeFactorizeList n, snd tuple /= 0 ]
|
mino2357/Hello_Haskell
|
2018-02-25.hsproj/Main.hs
|
mit
| 817
| 0
| 10
| 145
| 362
| 189
| 173
| 17
| 1
|
module AbilityTests where
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit as HUnit
import EverCraft
ability_setting_tests :: Test.Framework.Test
ability_setting_tests = testGroup "Character has ability scores" [
testCase "they default to 10" $ default_ability_scores @?= [10,10,10,10,10,10],
testCase "they can be set" $ set_ability_scores @?= [1,2,3,4,5,6]
]
default_ability_scores = abilities_as_list defaultCharacter
set_ability_scores = abilities_as_list defaultCharacter {abilities = set_abilities}
where set_abilities = newAbilities{strength=1,dexterity=2,constitution=3,wisdom=4,intelligence=5,charisma=6}
abilities_as_list character = [strength a, dexterity a, constitution a, wisdom a, intelligence a, charisma a]
where a = abilities character
ability_modifier_tests :: Test.Framework.Test
ability_modifier_tests = testGroup "Character abilities have a modifier associated with their value" [
test_modifier 1 (-5), -- LOL
test_modifier 2 (-4), -- LOL
test_modifier 3 (-4), -- LOL
test_modifier 4 (-3), -- LOL
test_modifier 5 (-3), -- LOL
test_modifier 6 (-2), -- LOL
test_modifier 7 (-2), -- LOL
test_modifier 8 (-1), -- LOL
test_modifier 9 (-1), -- LOL
test_modifier 10 0, -- LOL
test_modifier 11 0, -- LOL
test_modifier 12 1, -- LOL
test_modifier 13 1, -- LOL
test_modifier 14 2, -- LOL
test_modifier 15 2, -- LOL
test_modifier 16 3, -- LOL
test_modifier 17 3, -- LOL
test_modifier 18 4, -- LOL
test_modifier 19 4, -- LOL
test_modifier 20 5 -- LOL
]
test_modifier score modifier = testCase "modifier score" $ abilityModifier score @?= modifier
strength_modifier_tests :: Test.Framework.Test
strength_modifier_tests = testGroup "Strength modifier modifies aspects" [
testCase "Strength modifier modifies attack roll" $ modifiedAttackRoll (newCharacter{abilities=newAbilities{strength=2}}) 7 @?= (7 + abilityModifier 2)
]
dexterity_modifier_tests :: Test.Framework.Test
dexterity_modifier_tests = testGroup "Dexterity modifier modifies aspects" [
testCase "Dexterity modifier modifies armor class" $ armorClass (newCharacter{abilities=newAbilities{dexterity=2}}) @?= baseArmorClass + abilityModifier 2
]
tests = [ability_setting_tests, ability_modifier_tests, strength_modifier_tests, dexterity_modifier_tests]
|
coreyhaines/evercraft_kata
|
test/AbilityTests.hs
|
mit
| 2,369
| 0
| 15
| 385
| 642
| 363
| 279
| 44
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Views.Layout (layout) where
import Assets.CSS (layoutCss)
import Data.Monoid (mempty)
import Data.Text.Lazy (toStrict)
import Prelude hiding (head)
import Text.Blaze.Html (Html)
import Text.Blaze.Html5 (Html, body, docTypeHtml, head,
link, meta, script, style,
title, (!))
import Text.Blaze.Html5.Attributes (charset, content, href,
httpEquiv, media, name, rel, src)
import Views.Utils (pet)
import Views.NavBar (navBar)
layout :: Html -> Html -> Html
layout t b = docTypeHtml $ do
pet "<!--[if lt IE 7]> <html class='no-js lt-ie9 lt-ie8 lt-ie7'> <![endif]-->"
pet "<!--[if IE 7]> <html class='no-js lt-ie9 lt-ie8'/> <![endif]-->"
pet "<!--[if IE 8]> <html class='no-js lt-ie9'> <![endif]-->"
pet "<!--[if gt IE 8]><!--> <html class='no-js'> <!--<![endif]-->"
head $ do
title t
meta ! charset "utf-8"
meta ! httpEquiv "X-UA-Compatible" ! content "IE=edge,chrome=1"
meta ! name "description" ! content "Inspire Text"
meta ! name "viewport" ! content "width=device-width"
link ! href "//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" ! rel "stylesheet" ! media "screen"
style $ pet $ toStrict layoutCss
body $ do
navBar >> b
script ! src "//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" $ mempty
script ! src "//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js" $ mempty
|
av-ast/hello-scotty
|
src/Views/Layout.hs
|
mit
| 1,696
| 0
| 14
| 513
| 361
| 187
| 174
| 32
| 1
|
module Rebase.Data.Semigroup.Foldable.Class
(
module Data.Semigroup.Foldable.Class
)
where
import Data.Semigroup.Foldable.Class
|
nikita-volkov/rebase
|
library/Rebase/Data/Semigroup/Foldable/Class.hs
|
mit
| 131
| 0
| 5
| 12
| 26
| 19
| 7
| 4
| 0
|
{-|
Module : Jupyter.Test.Install
Description : Tests for the Jupyter.Install module.
Copyright : (c) Andrew Gibiansky, 2016
License : MIT
Maintainer : andrew.gibiansky@gmail.com
Stability : stable
Portability : POSIX
-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
module Jupyter.Test.Install (installTests) where
-- Imports from 'base'
import Control.Monad (forM_)
import Data.List (isInfixOf)
import Data.Maybe (fromMaybe)
import Data.Proxy (Proxy(..))
import System.Environment (setEnv, lookupEnv)
import System.IO (stderr, stdout)
-- Imports from 'directory'
import System.Directory (setPermissions, getPermissions, Permissions(..), canonicalizePath,
createDirectoryIfMissing, removeFile, doesFileExist)
-- Imports from 'bytestring'
import qualified Data.ByteString.Char8 as CBS
-- Imports from 'aeson'
import Data.Aeson (decodeStrict, Value)
-- Imports from 'text'
import qualified Data.Text as T
-- Imports from 'extra'
import Control.Exception.Extra (bracket)
import System.IO.Extra (withTempDir)
-- Imports from 'silently'
import System.IO.Silently (hCapture_)
-- Imports from 'tasty'
import Test.Tasty (TestTree, testGroup)
-- Imports from 'tasty-hunit'
import Test.Tasty.HUnit (testCase, (@=?), assertFailure, assertBool)
-- Imports from 'jupyter'
import Jupyter.Install.Internal
import Jupyter.Test.Utils (shouldThrow, inTempDir)
import qualified Jupyter.Install.Internal as I
installTests :: TestTree
installTests = testGroup "Install Tests"
[ testVersionNumberParsing
, testVersionNumberPrinting
, testFindingJupyterExecutable
, testJupyterVersionReading
, testStderrIsUntouched
, testCorrectJupyterVersionsAccepted
, testKernelspecFilesCreated
, testEndToEndInstall
]
-- | Test that version numbers from jupyter --version are properly parsed.
testVersionNumberParsing :: TestTree
testVersionNumberParsing = testCase "Version number parsing" $ do
Just (I.JupyterVersion 10 1 0) @=? I.parseVersion "10.1.0"
Just (I.JupyterVersion 4 1 2000) @=? I.parseVersion "4.1.2000"
Just (I.JupyterVersion 4 1 0) @=? I.parseVersion "4.1"
Just (I.JupyterVersion 4 0 0) @=? I.parseVersion "4"
Nothing @=? I.parseVersion ".xx.4"
Nothing @=? I.parseVersion "4.1.2.1.2"
-- | Test that version numbers from jupyter --version are properly printed to the user.
testVersionNumberPrinting :: TestTree
testVersionNumberPrinting = testCase "Version number printing" $ do
parseThenShow "10.1.0"
parseThenShow "4.1.200"
parseThenShow "4.1.0"
where
parseThenShow str =
Just str @=? (I.showVersion <$> I.parseVersion str)
-- | Set the PATH variable to a particular value during execution of an IO action.
withPath :: String -> IO a -> IO a
withPath newPath action =
bracket resetPath (setEnv "PATH") (const action)
where
resetPath = do
path <- lookupEnv "PATH"
setEnv "PATH" newPath
return $ fromMaybe "" path
-- | Test that `jupyter` is found by `which` if it is on the PATH, and isn't found if its not on the
-- path or isn't executable. Ensures that all returned paths are absolute and canonical.
testFindingJupyterExecutable :: TestTree
testFindingJupyterExecutable = testCase "PATH searching" $
-- Run the entire test in a temporary directory.
inTempDir $ \tmp ->
-- Set up a PATH that has both relative and absolute paths.
withPath (".:test-path/twice:" ++ tmp ++ "/test-path-2") $
-- For each possible location test executable finding.
forM_ [".", "test-path/twice", "test-path-2"] $ \prefix -> do
let path = prefix ++ "/jupyter"
createDirectoryIfMissing True prefix
-- When the file doesn't exist it should not be found.
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- When the file is not executable it should not be found.
writeFile path "#!/bin/bash\ntrue"
which "jupyter" `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- When the file is executable, it should be found, and be an absolute path
-- that ultimately resolves to what we expect.
setExecutable path
jupyterLoc <- which "jupyter"
expectedLoc <- canonicalizePath $ tmp ++ "/" ++ prefix ++ "/jupyter"
expectedLoc @=? jupyterLoc
-- Clean up to avoid messing with future tests.
removeFile path
-- | Test that the install script can parse the version numbers output by Jupyter.
testJupyterVersionReading :: TestTree
testJupyterVersionReading = testCase "jupyter --version parsing" $
inTempDir $ \_ ->
-- Set up a jupyter executable that outputs what we expect.
withPath "." $ do
writeMockJupyter ""
setExecutable "jupyter"
path <- which "jupyter"
-- Version too low.
writeMockJupyter "1.2.0"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- Could not parse output.
writeMockJupyter "..."
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
writeMockJupyter "asdf"
verifyJupyterCommand path `shouldThrow` (Proxy :: Proxy JupyterKernelspecException)
-- Works.
writeMockJupyter "3.0.0"
verifyJupyterCommand path
writeMockJupyter "4.1.4000"
verifyJupyterCommand path
-- | Create a mock 'jupyter' command, which always outputs a particular string to stdout and exits
-- with exit code zero.
writeMockJupyter :: String -> IO ()
writeMockJupyter out = writeMockJupyter' out "" 0
-- | Create a mock 'jupyter' command, which outputs given strings to stdout and stderr and exits
-- with the provided exit code.
writeMockJupyter' :: String -- ^ What to output on stdout
-> String -- ^ What to output on stderr
-> Int -- ^ What exit code to exit with
-> IO ()
writeMockJupyter' stdoutOut stderrOut errCode =
writeFile "jupyter" $
unlines
[ "#!/bin/bash"
, "echo -n \"" ++ stdoutOut ++ "\""
, "echo -n \"" ++ stderrOut ++ "\" >/dev/stderr"
, "exit " ++ show errCode
]
testStderrIsUntouched :: TestTree
testStderrIsUntouched = testCase "stderr is piped through" $
inTempDir $ \_ ->
-- Set up a jupyter executable that outputs something to stderr.
withPath "." $ do
let msg = "An error"
writeMockJupyter' "Some output" msg 0
setExecutable "jupyter"
-- Check that stderr goes through as usual.
stderrOut <- hCapture_ [stderr] (runJupyterCommand "jupyter" [])
msg @=? stderrOut
-- Check that stdout of the command is not output but is captured.
writeMockJupyter' "stdout" "" 0
stdoutOut <- hCapture_ [stdout] (runJupyterCommand "jupyter" [])
"" @=? stdoutOut
testCorrectJupyterVersionsAccepted :: TestTree
testCorrectJupyterVersionsAccepted = testCase "Correct jupyter versions accepted" $ do
assertBool "Version 3 supported" $ jupyterVersionSupported $ JupyterVersion 3 0 0
assertBool "Version 3.1 supported" $ jupyterVersionSupported $ JupyterVersion 3 1 0
assertBool "Version 4 supported" $ jupyterVersionSupported $ JupyterVersion 4 0 0
assertBool "Version 10 supported" $ jupyterVersionSupported $ JupyterVersion 10 0 0
assertBool "Version 2.3 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 2 3 0
assertBool "Version 1.0 not supported" $ not $ jupyterVersionSupported $ JupyterVersion 1 0 0
testKernelspecFilesCreated :: TestTree
testKernelspecFilesCreated = testCase "kernelspec files created" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
-- Test that all required files are created
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
assertBool "kernel.js not copied" =<< doesFileExist (kernelspecDir ++ "/kernel.js")
assertBool "logo-64x64.png not copied" =<< doesFileExist (kernelspecDir ++ "/logo-64x64.png")
assertBool "kernel.json not created" =<< doesFileExist (kernelspecDir ++ "/kernel.json")
-- Test that the file is valid JSON and {connection_file} is present.
withTempDir $ \kernelspecDir -> do
prepareKernelspecDirectory kernelspec kernelspecDir
kernelJson <- readFile (kernelspecDir ++ "/kernel.json")
assertBool "{connection_file} not found" $ "\"{connection_file}\"" `isInfixOf` kernelJson
case decodeStrict (CBS.pack kernelJson) :: Maybe Value of
Nothing -> assertFailure "Could not decode kernel.json file as JSON"
Just _ -> return ()
-- Test that all previously-existing files are gone
withTempDir $ \kernelspecDir -> do
let prevFile1 = kernelspecDir ++ "/tmp.file"
prevFile2 = kernelspecDir ++ "/kernel.js"
writeFile prevFile1 "test1"
writeFile prevFile2 "test2"
prepareKernelspecDirectory kernelspec { kernelspecJsFile = Nothing } kernelspecDir
assertBool "previous file still exists" =<< fmap not (doesFileExist prevFile1)
assertBool "previous kernel.js file still exists" =<< fmap not (doesFileExist prevFile2)
-- Test that end-to-end installs work as expected, and call the 'jupyter kernelspec install'
-- in the way that they are expected to.
testEndToEndInstall :: TestTree
testEndToEndInstall = testCase "installs end-to-end" $
inTempDir $ \tmp -> do
kernelspec <- createTestKernelspec tmp
withPath "." $ do
writeFile "jupyter" $ jupyterScript True
setExecutable "jupyter"
result1 <- installKernel InstallLocal kernelspec
case result1 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
writeFile "jupyter" $ jupyterScript False
result2 <- installKernel InstallGlobal kernelspec
case result2 of
InstallFailed msg -> assertFailure $ "Failed to install kernelspec: " ++ T.unpack msg
_ -> return ()
where
jupyterScript user =
unlines
[ "#!/bin/bash"
, "if [[ $1 == \"--version\" ]]; then"
, "echo 4.1.0"
, "else"
, "[[ \"$1 $2 $4\" == \"kernelspec install --replace\" ]] || exit 1"
, if user
then "[[ \"$5\" == \"--user\" ]] || exit 0"
else ""
, "fi"
]
-- Create a kernelspec that refers to newly generated files in the provided directory.
createTestKernelspec :: String -> IO Kernelspec
createTestKernelspec tmp = do
let kernelJsFile = tmp ++ "/" ++ "kernel.js"
writeFile kernelJsFile "kernel.js"
let kernelLogoFile = tmp ++ "/" ++ "logo-64x64.png"
writeFile kernelLogoFile "logo-64x64.png"
return
Kernelspec
{ kernelspecDisplayName = "Test"
, kernelspecLanguage = "test"
, kernelspecCommand = \exe conn -> [exe, conn, "--test"]
, kernelspecJsFile = Just kernelJsFile
, kernelspecLogoFile = Just kernelLogoFile
, kernelspecEnv = mempty
}
-- | Make a file executable.
setExecutable :: FilePath -> IO ()
setExecutable path = do
perms <- getPermissions path
setPermissions path perms { executable = True }
|
gibiansky/jupyter-haskell
|
tests/Jupyter/Test/Install.hs
|
mit
| 11,430
| 0
| 17
| 2,672
| 2,099
| 1,058
| 1,041
| 188
| 4
|
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
-- | The Participant Server, which runs the Consensus algorithm, ultimately "accepting" and sending a 2B to Observer Servers
module Hetcons.Participant (Participant, new_participant, participant_server, basic_participant_server, current_nanoseconds ) where
import Hetcons.Hetcons_State ( Participant_State, start_State )
import Hetcons.Parsable (Parsable)
import Hetcons.Receive ()
import Hetcons.Receive_Message
( Hetcons_Server(Hetcons_Server)
,hetcons_Server_crypto_id
,hetcons_Server_private_key
,hetcons_Server_address_book
,hetcons_Server_state_var
,hetcons_Server_verify_1a
,hetcons_Server_verify_1b
,hetcons_Server_verify_2a
,hetcons_Server_verify_2b
,hetcons_Server_verify_proof
,hetcons_Server_verify_quorums
,hetcons_Server_log_chan
,Receivable(receive)
,run_Hetcons_Transaction_IO
,Hetcons_Transaction
)
import Hetcons.Send_Message_IO ( default_Address_Book )
import Hetcons.Signed_Message
( Recursive_1b
,Verified
,Recursive_1a
,Recursive(non_recursive)
,Recursive_Proof_of_Consensus
,Monad_Verify(verify)
,original )
import Hetcons.Value ( Value, Contains_1a, extract_1a )
import Hetcons_Participant ( process )
import Hetcons_Participant_Iface
( Hetcons_Participant_Iface, ping, proposal_1a, phase_1b )
import Charlotte_Types
( Proposal_1a(proposal_1a_timestamp), Crypto_ID, Timestamp, Slot_Value )
import Control.Concurrent ( forkIO, ThreadId, threadDelay )
import Control.Concurrent.Chan (newChan)
import qualified Control.Concurrent.Map as CMap ( empty )
import Control.Monad.Logger(unChanLoggingT, LoggingT, runStdoutLoggingT )
import Data.ByteString.Lazy ( ByteString )
import Data.Hashable (Hashable)
import Data.HashSet (HashSet)
import Data.Thyme.Clock
( getCurrentTime, UTCTime, UTCView(UTCTime) )
import Data.Thyme.Time.Core
( toThyme
,fromThyme
,diffUTCTime
,toMicroseconds
,fromMicroseconds
,fromGregorian )
import Thrift.Server ( runBasicServer )
-- | The participant Datum is just a Hetcons_Server with a Participant_State (defined in Hetcons_State)
type Participant v = Hetcons_Server (Participant_State v) v
-- | given a Cryptographic ID (public key), and a private key, produces a new Participant Datum
new_participant :: (Value v) => (LoggingT IO a -> IO a) -> Crypto_ID -> ByteString -> IO (Participant v)
new_participant run_logger cid pk =
do { ab <- default_Address_Book
; sv <- start_State
; v1a <- CMap.empty
; v1b <- CMap.empty
; v2a <- CMap.empty
; v2b <- CMap.empty
; vproof <- CMap.empty
; vq <- CMap.empty
; chan <- newChan
; forkIO $ (run_logger $ unChanLoggingT chan) >> return ()
;return (Hetcons_Server {
hetcons_Server_crypto_id = cid
,hetcons_Server_private_key = pk
,hetcons_Server_address_book = ab
,hetcons_Server_state_var = sv
,hetcons_Server_verify_1a = v1a
,hetcons_Server_verify_1b = v1b
,hetcons_Server_verify_2a = v2a
,hetcons_Server_verify_2b = v2b
,hetcons_Server_verify_proof = vproof
,hetcons_Server_verify_quorums = vq
,hetcons_Server_log_chan = chan
})}
-- | Given a Participant Datum, and a Port Number, launches a Participant Server, and returns the ThreadId of that server.
participant_server :: (Value v, Show v, Eq v, Hashable v, Integral a, Parsable (Hetcons_Transaction (Participant_State v) v v)) => (Participant v) -> a -> IO ThreadId
participant_server participant port = forkIO $ runBasicServer participant process $ fromIntegral port
-- | Given a Cryptographic ID (public key), a private key, and a Port Number, launches a Participant Server, and returns the ThreadId of that server.
basic_participant_server :: (Integral a) => Crypto_ID -> ByteString -> a -> IO ThreadId
basic_participant_server cid pk port = do { (participant :: Participant Slot_Value) <- new_participant runStdoutLoggingT cid pk
; participant_server participant port}
-- | The current time, in nanoseconds since 1970 began.
-- Of course, our library only actually does microseconds, so we're multiplying by 1000
current_nanoseconds :: IO Timestamp
current_nanoseconds = do { now <- getCurrentTime
; return $ 1000 * (toMicroseconds $ diffUTCTime now ((toThyme $ fromThyme (UTCTime (fromGregorian 1970 0 0) (fromMicroseconds 0))) :: UTCTime))}
-- | the timestamp contained in (the proposal of) this message
message_timestamp :: forall a v . (Value v, Contains_1a (Verified (a v)) v) => (Verified (a v)) -> Timestamp
message_timestamp = proposal_1a_timestamp . non_recursive . original . (extract_1a :: (Verified (a v)) -> (Verified (Recursive_1a v)))
-- | delay this thread by some number of nanoseconds
-- note that the library we're using actually works in microseconds, so we're dividing by 1000, rounding down
delay_nanoseconds :: Timestamp -> IO ()
delay_nanoseconds = threadDelay . floor . (/1000) . fromIntegral
-- | delay this thread until the current time in nanoseconds is at least that of the timestamp in the message
delay_message :: (Contains_1a (Verified (a v)) v) => (Verified (a v)) -> IO ()
delay_message m = do { now <- current_nanoseconds
; delay_nanoseconds (now - (message_timestamp m))}
-- | Technically, run_Hetcons_Transaction_IO needs something to do in the event a transaction returns a Proof_of_Consensus.
-- However, that should never happen on a Participant Server, so we just throw an error.
on_consensus :: (Show v) => (Verified (Recursive_Proof_of_Consensus v)) -> IO ()
on_consensus = error . ("Somehow a Participant Proved Consensus: \n" ++) . show
-- | Participant implements the Thrift Hetcons_Participant_Iface, meaning it acts as a Participant Server using the API defined in Thrift.
instance forall v . (Value v, Show v, Eq v, Hashable v, Parsable (Hetcons_Transaction (Participant_State v) v v)) => Hetcons_Participant_Iface (Participant v) where
-- | When Pinged, a Participant returns ()
ping _ = return ()
-- | When it gets a 1A, the participant verifies it, delays it until our clock reaches its timestamp, and then runs `receive` (in a Hetcons_Transaction for atomicity)
proposal_1a participant message witness
= do { (verified :: (Verified (Recursive_1a v))) <- run_Hetcons_Transaction_IO participant on_consensus witness $ verify message -- TODO: this doesn't need a TX
; delay_message verified
; run_Hetcons_Transaction_IO participant on_consensus witness $ receive verified}
-- | When it gets a 1B, the participant verifies it, delays it until our clock reaches its timestamp, and then runs `receive` (in a Hetcons_Transaction for atomicity)
phase_1b participant message witness
= do { (verified :: (Verified (Recursive_1b v))) <- run_Hetcons_Transaction_IO participant on_consensus witness $ verify message -- TODO: this doesn't need a TX
; delay_message verified
; run_Hetcons_Transaction_IO participant on_consensus witness $ receive verified}
|
isheff/hetcons
|
src/Hetcons/Participant.hs
|
mit
| 7,325
| 0
| 18
| 1,418
| 1,446
| 808
| 638
| 108
| 1
|
module SSH.Types
( getWord32be'
, putWord32be'
, getString
, putString
, runStrictGet
, runStrictPut
) where
import Control.Applicative ((<$>))
import Data.Binary.Get (Get, getWord32be, getByteString, runGet)
import Data.Binary.Put (Put, putWord32be, putByteString, runPut)
import qualified Data.ByteString as B
import Data.ByteString.Lazy (fromStrict, toStrict)
getWord32be' :: (Integral a) => Get a
getWord32be' = fromIntegral <$> getWord32be
putWord32be' :: (Integral a) => a -> Put
putWord32be' = putWord32be . fromIntegral
getString :: Get B.ByteString
getString = getWord32be' >>= getByteString
putString :: B.ByteString -> Put
putString s = do
putWord32be (fromIntegral $ B.length s)
putByteString s
runStrictGet :: Get c -> B.ByteString -> c
runStrictGet = (. fromStrict) . runGet
runStrictPut :: Put -> B.ByteString
runStrictPut = toStrict . runPut
|
mithrandi/ssh-key-generator
|
SSH/Types.hs
|
mit
| 958
| 0
| 11
| 214
| 266
| 153
| 113
| 26
| 1
|
module ExportProduct (exportProduct, exportUcmToLatex, exportAspectInterfacesToLatex, exportSourceCode) where
import System.IO
-- import System
import System.Directory
import System.FilePath
import System.Process
import System.Exit
import Control.Monad
import Control.Exception
import Ensemble.Types
import ComponentModel.Types
import SPL.Types
import UseCaseModel.Types
import UseCaseModel.PrettyPrinter.Latex
import UseCaseModel.PrettyPrinter.LatexUserActions
import UseCaseModel.PrettyPrinter.XML
import qualified BasicTypes as Core
exportProduct :: FilePath -> FilePath -> InstanceModel -> IO ()
exportProduct s o p =
let
ucmodel = ucModel $ instanceAssetBase p
cmodel = components $ buildData $ instanceAssetBase p
in do
print "\n Use cases... "
print $ ucmodel
exportUcmToLatex (o ++ "/use-cases.tex") (ucmodel)
exportUcmToLatexUserActions (o ++ "/simplified-use-cases.tex") (ucmodel)
exportUcmToXML (o ++ "/use-cases.xml") (ucmodel)
print "\n Copying source files to output directory \n"
print $ map (++ "\n") [fst c | c <- cmodel]
exportSourceCode s o p
exportSourceCode :: FilePath -> FilePath -> InstanceModel -> IO ()
exportSourceCode s o p =
let bd = buildData $ instanceAssetBase p
in do
copySourceFiles s o (components bd)
exportBuildFile (o ++ "/build.lst") (buildEntries bd)
preprocessFiles (o ++ "/build.lst") (preProcessFiles bd) o
preprocessFiles :: String -> [String] -> String -> IO()
preprocessFiles _ [] _ = return()
preprocessFiles flags files outputFolder = do
pid <- runCommand ("java -jar preprocessor.jar \"" ++ flags ++ "\"" ++ (concatPaths files outputFolder))
waitForProcess pid >>= exitWith
concatPaths :: [String] -> String -> String
concatPaths [] _ = ""
concatPaths (str:strs) outputFolder = " \"" ++ outputFolder </> str ++ "\"" ++ (concatPaths strs outputFolder)
-- -----------------------------------------------------------------------
-- Exports a use case model as a latex document.
-- -----------------------------------------------------------------------
exportUcmToLatex f ucm =
bracket (openFile f WriteMode)
hClose
(\h -> hPutStr h (show (ucmToLatex ucm)))
exportUcmToLatexUserActions f ucm =
bracket (openFile f WriteMode)
hClose
(\h -> hPutStr h (show (ucmToLatexUserActions ucm)))
exportUcmToXML f ucm =
bracket (openFile f WriteMode)
hClose
(\h -> hPutStr h (show (ucmToXML ucm)))
exportAspectInterfacesToLatex f ucm =
bracket (openFile f WriteMode)
hClose
(\h -> hPutStr h (show (aspectInterfacesToLatex ucm)))
-- ----------------------------------------------------------------------
-- Copy selected source files to the output directory
-- ----------------------------------------------------------------------
copySourceFiles source out [] = return ()
copySourceFiles source out (c:cs) =
do
createOutDir out c
copySourceFile source out c
copySourceFiles source out cs
-- --------------------------------------------------------------------
-- Exports the list of build entries as a build file. The format of this
-- build file should describe, for instance, which Eclipse plugins
-- have to be considered when building an application.
-- -------------------------------------------------------------------
exportBuildFile f es =
bracket (openFile f WriteMode)
hClose
(\h -> hPutStr h (concat [e ++ "\n" | e <- es]))
createOutDir out c =
do
print $ "Selected output dir: " ++ out
print $ "Selected output component" ++ (snd c)
let new = out </> (snd c)
let newDir = dropFileName new
print new
print newDir
createDirectoryIfMissing True newDir
-- copy a component from source directory to the out directory.
-- Note that a component is a pair of ids (Id, Id), indicating the
-- names of the input and output files. Usually they have the same
-- name.
copySourceFile source out c =
do
let old = source </> (fst c)
let new = out </> (snd c)
isFile <- doesFileExist old
isDirectory <- doesDirectoryExist old
if isFile then do
codeLines <- getLinesFromFile old
writeLinesToFile new codeLines
else if isDirectory then do
contents <- getDirectoryContents old
let contents' = normalizeContents contents
let newSource = source </> (fst c)
copySourceFiles newSource new contents'
else do
undefined
normalizeContents :: [String] -> [(String,String)]
normalizeContents [] = []
normalizeContents (".":xs) = normalizeContents xs
normalizeContents ("..":xs) = normalizeContents xs
normalizeContents (x:xs) = [(x,x)] ++ normalizeContents xs
getLinesFromFile :: String -> IO [String]
getLinesFromFile path = do
handle <- openFile path ReadMode
contents <- hGetContents handle
return $ lines contents
writeLinesToFile :: FilePath -> [String] -> IO ()
writeLinesToFile path codeLines = do
handler <- openFile path WriteMode
printLinesToHandler handler codeLines
printLinesToHandler :: Handle -> [String] -> IO ()
printLinesToHandler _ [] = return ()
printLinesToHandler handler (x:xs) = do
hPutStrLn handler x
printLinesToHandler handler xs
|
hephaestus-pl/hephaestus
|
willian/ExportProduct.hs
|
mit
| 5,141
| 0
| 16
| 913
| 1,426
| 710
| 716
| 115
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns, CPP #-}
{-# LANGUAGE NamedFieldPuns #-}
module Network.Wai.Handler.Warp.HTTP2.Sender (frameSender) where
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative
#endif
import Control.Concurrent.STM
import qualified Control.Exception as E
import Control.Monad (unless, void, when)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Builder.Extra as B
import Foreign.Ptr
import Network.HTTP2
import Network.HTTP2.Priority
import Network.Wai
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.HTTP2.EncodeFrame
import Network.Wai.Handler.Warp.HTTP2.HPACK
import Network.Wai.Handler.Warp.HTTP2.Types
import Network.Wai.Handler.Warp.IORef
import qualified Network.Wai.Handler.Warp.Settings as S
import qualified Network.Wai.Handler.Warp.Timeout as T
import Network.Wai.Handler.Warp.Types
import Network.Wai.Internal (Response(..))
import qualified System.PosixCompat.Files as P
#ifdef WINDOWS
import qualified System.IO as IO
#else
import Network.Wai.Handler.Warp.FdCache
import Network.Wai.Handler.Warp.SendFile (positionRead)
import System.Posix.IO (openFd, OpenFileFlags(..), defaultFileFlags, OpenMode(ReadOnly), closeFd)
import System.Posix.Types
#endif
----------------------------------------------------------------
data Leftover = LZero
| LOne B.BufferWriter
| LTwo BS.ByteString B.BufferWriter
----------------------------------------------------------------
unlessClosed :: Context -> Connection -> Stream -> IO () -> IO ()
unlessClosed ctx
Connection{connSendAll}
strm@Stream{streamState,streamNumber}
body = E.handle resetStream $ do
state <- readIORef streamState
unless (isClosed state) body
where
resetStream e = do
closed ctx strm (ResetByMe e)
let rst = resetFrame InternalError streamNumber
connSendAll rst
getWindowSize :: TVar WindowSize -> TVar WindowSize -> IO WindowSize
getWindowSize connWindow strmWindow = do
-- Waiting that the connection window gets open.
cw <- atomically $ do
w <- readTVar connWindow
check (w > 0)
return w
-- This stream window is greater than 0 thanks to the invariant.
sw <- atomically $ readTVar strmWindow
return $ min cw sw
frameSender :: Context -> Connection -> InternalInfo -> S.Settings -> IO ()
frameSender ctx@Context{outputQ,connectionWindow}
conn@Connection{connWriteBuffer,connBufferSize,connSendAll}
ii settings = go `E.catch` ignore
where
initialSettings = [(SettingsMaxConcurrentStreams,recommendedConcurrency)]
initialFrame = settingsFrame id initialSettings
bufHeaderPayload = connWriteBuffer `plusPtr` frameHeaderLength
headerPayloadLim = connBufferSize - frameHeaderLength
go = do
connSendAll initialFrame
loop
-- ignoring the old priority because the value might be changed.
loop = dequeue outputQ >>= \(out, _) -> switch out
ignore :: E.SomeException -> IO ()
ignore _ = return ()
switch OFinish = return ()
switch (OGoaway frame) = connSendAll frame
switch (OFrame frame) = do
connSendAll frame
loop
switch (OResponse strm rsp aux) = do
unlessClosed ctx conn strm $ do
lim <- getWindowSize connectionWindow (streamWindow strm)
-- Header frame and Continuation frame
let sid = streamNumber strm
endOfStream = case aux of
Persist{} -> False
Oneshot hb -> not hb
len <- headerContinue sid rsp endOfStream
let total = len + frameHeaderLength
case aux of
Oneshot True -> do -- hasBody
-- Data frame payload
(off, _) <- sendHeadersIfNecessary total
let payloadOff = off + frameHeaderLength
Next datPayloadLen mnext <-
fillResponseBodyGetNext conn ii payloadOff lim rsp
fillDataHeaderSend strm total datPayloadLen mnext
maybeEnqueueNext strm mnext
Oneshot False -> do
-- "closed" must be before "connSendAll". If not,
-- the context would be switched to the receiver,
-- resulting the inconsistency of concurrency.
closed ctx strm Finished
flushN total
Persist sq tvar -> do
(off, needSend) <- sendHeadersIfNecessary total
let payloadOff = off + frameHeaderLength
Next datPayloadLen mnext <-
fillStreamBodyGetNext conn payloadOff lim sq tvar strm
-- If no data was immediately available, avoid sending an
-- empty data frame.
if datPayloadLen > 0 then
fillDataHeaderSend strm total datPayloadLen mnext
else
when needSend $ flushN off
maybeEnqueueNext strm mnext
loop
switch (ONext strm curr) = do
unlessClosed ctx conn strm $ do
lim <- getWindowSize connectionWindow (streamWindow strm)
-- Data frame payload
Next datPayloadLen mnext <- curr lim
fillDataHeaderSend strm 0 datPayloadLen mnext
maybeEnqueueNext strm mnext
loop
-- Flush the connection buffer to the socket, where the first 'n' bytes of
-- the buffer are filled.
flushN :: Int -> IO ()
flushN n = bufferIO connWriteBuffer n connSendAll
headerContinue sid rsp endOfStream = do
builder <- hpackEncodeHeader ctx ii settings rsp
(len, signal) <- B.runBuilder builder bufHeaderPayload headerPayloadLim
let flag0 = case signal of
B.Done -> setEndHeader defaultFlags
_ -> defaultFlags
flag = if endOfStream then setEndStream flag0 else flag0
fillFrameHeader FrameHeaders len sid flag connWriteBuffer
continue sid len signal
continue _ len B.Done = return len
continue sid len (B.More _ writer) = do
flushN $ len + frameHeaderLength
(len', signal') <- writer bufHeaderPayload headerPayloadLim
let flag = case signal' of
B.Done -> setEndHeader defaultFlags
_ -> defaultFlags
fillFrameHeader FrameContinuation len' sid flag connWriteBuffer
continue sid len' signal'
continue sid len (B.Chunk bs writer) = do
flushN $ len + frameHeaderLength
let (bs1,bs2) = BS.splitAt headerPayloadLim bs
len' = BS.length bs1
void $ copy bufHeaderPayload bs1
fillFrameHeader FrameContinuation len' sid defaultFlags connWriteBuffer
if bs2 == "" then
continue sid len' (B.More 0 writer)
else
continue sid len' (B.Chunk bs2 writer)
-- True if the connection buffer has room for a 1-byte data frame.
canFitDataFrame total = total + frameHeaderLength < connBufferSize
-- Re-enqueue the stream in the output queue if more output is immediately
-- available; do nothing otherwise.
maybeEnqueueNext :: Stream -> Control DynaNext -> IO ()
maybeEnqueueNext strm (CNext next) = do
let out = ONext strm next
enqueueOrSpawnTemporaryWaiter strm outputQ out
-- If the streaming is not finished, it must already have been
-- written to the 'TVar' owned by 'waiter', which will
-- put it back into the queue when more output becomes available.
maybeEnqueueNext _ _ = return ()
-- Send headers if there is not room for a 1-byte data frame, and return
-- the offset of the next frame's first header byte and whether the headers
-- still need to be sent.
sendHeadersIfNecessary total
| canFitDataFrame total = return (total, True)
| otherwise = do
flushN total
return (0, False)
fillDataHeaderSend strm otherLen datPayloadLen mnext = do
-- Data frame header
let sid = streamNumber strm
buf = connWriteBuffer `plusPtr` otherLen
total = otherLen + frameHeaderLength + datPayloadLen
flag = case mnext of
CFinish -> setEndStream defaultFlags
_ -> defaultFlags
fillFrameHeader FrameData datPayloadLen sid flag buf
-- "closed" must be before "connSendAll". If not,
-- the context would be switched to the receiver,
-- resulting the inconsistency of concurrency.
case mnext of
CFinish -> closed ctx strm Finished
_ -> return ()
flushN total
atomically $ do
modifyTVar' connectionWindow (subtract datPayloadLen)
modifyTVar' (streamWindow strm) (subtract datPayloadLen)
fillFrameHeader ftyp len sid flag buf = encodeFrameHeaderBuf ftyp hinfo buf
where
hinfo = FrameHeader len flag sid
----------------------------------------------------------------
{-
ResponseFile Status ResponseHeaders FilePath (Maybe FilePart)
ResponseBuilder Status ResponseHeaders Builder
ResponseStream Status ResponseHeaders StreamingBody
ResponseRaw (IO ByteString -> (ByteString -> IO ()) -> IO ()) Response
-}
fillResponseBodyGetNext :: Connection -> InternalInfo -> Int -> WindowSize -> Response -> IO Next
fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize}
_ off lim (ResponseBuilder _ _ bb) = do
let datBuf = connWriteBuffer `plusPtr` off
room = min (connBufferSize - off) lim
(len, signal) <- B.runBuilder bb datBuf room
return $ nextForBuilder connWriteBuffer connBufferSize len signal
#ifdef WINDOWS
fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize}
_ off lim (ResponseFile _ _ path mpart) = do
let datBuf = connWriteBuffer `plusPtr` off
room = min (connBufferSize - off) lim
(start, bytes) <- fileStartEnd path mpart
-- fixme: how to close Handle? GC does it at this moment.
h <- IO.openBinaryFile path IO.ReadMode
IO.hSeek h IO.AbsoluteSeek start
len <- IO.hGetBufSome h datBuf (mini room bytes)
let bytes' = bytes - fromIntegral len
return $ nextForFile len connWriteBuffer connBufferSize h bytes' (return ())
#else
fillResponseBodyGetNext Connection{connWriteBuffer,connBufferSize}
ii off lim (ResponseFile _ _ path mpart) = do
(fd, refresh) <- case fdCacher ii of
Just fdcache -> getFd fdcache path
Nothing -> do
fd' <- openFd path ReadOnly Nothing defaultFileFlags{nonBlock=True}
th <- T.register (timeoutManager ii) (closeFd fd')
return (fd', T.tickle th)
let datBuf = connWriteBuffer `plusPtr` off
room = min (connBufferSize - off) lim
(start, bytes) <- fileStartEnd path mpart
len <- positionRead fd datBuf (mini room bytes) start
refresh
let len' = fromIntegral len
return $ nextForFile len connWriteBuffer connBufferSize fd (start + len') (bytes - len') refresh
#endif
fillResponseBodyGetNext _ _ _ _ _ = error "fillResponseBodyGetNext"
fileStartEnd :: FilePath -> Maybe FilePart -> IO (Integer, Integer)
fileStartEnd path Nothing = do
end <- fromIntegral . P.fileSize <$> P.getFileStatus path
return (0, end)
fileStartEnd _ (Just part) =
return (filePartOffset part, filePartByteCount part)
----------------------------------------------------------------
fillStreamBodyGetNext :: Connection -> Int -> WindowSize -> TBQueue Sequence -> TVar Sync -> Stream -> IO Next
fillStreamBodyGetNext Connection{connWriteBuffer,connBufferSize}
off lim sq tvar strm = do
let datBuf = connWriteBuffer `plusPtr` off
room = min (connBufferSize - off) lim
(leftover, cont, len) <- runStreamBuilder datBuf room sq
nextForStream connWriteBuffer connBufferSize sq tvar strm leftover cont len
----------------------------------------------------------------
fillBufBuilder :: Buffer -> BufSize -> Leftover -> DynaNext
fillBufBuilder buf0 siz0 leftover lim = do
let payloadBuf = buf0 `plusPtr` frameHeaderLength
room = min (siz0 - frameHeaderLength) lim
case leftover of
LZero -> error "fillBufBuilder: LZero"
LOne writer -> do
(len, signal) <- writer payloadBuf room
getNext len signal
LTwo bs writer
| BS.length bs <= room -> do
buf1 <- copy payloadBuf bs
let len1 = BS.length bs
(len2, signal) <- writer buf1 (room - len1)
getNext (len1 + len2) signal
| otherwise -> do
let (bs1,bs2) = BS.splitAt room bs
void $ copy payloadBuf bs1
getNext room (B.Chunk bs2 writer)
where
getNext l s = return $ nextForBuilder buf0 siz0 l s
nextForBuilder :: Buffer -> BufSize -> BytesFilled -> B.Next -> Next
nextForBuilder _ _ len B.Done
= Next len CFinish
nextForBuilder buf siz len (B.More _ writer)
= Next len (CNext (fillBufBuilder buf siz (LOne writer)))
nextForBuilder buf siz len (B.Chunk bs writer)
= Next len (CNext (fillBufBuilder buf siz (LTwo bs writer)))
----------------------------------------------------------------
runStreamBuilder :: Buffer -> BufSize -> TBQueue Sequence
-> IO (Leftover, Bool, BytesFilled)
runStreamBuilder buf0 room0 sq = loop buf0 room0 0
where
loop !buf !room !total = do
mbuilder <- atomically $ tryReadTBQueue sq
case mbuilder of
Nothing -> return (LZero, True, total)
Just (SBuilder builder) -> do
(len, signal) <- B.runBuilder builder buf room
let !total' = total + len
case signal of
B.Done -> loop (buf `plusPtr` len) (room - len) total'
B.More _ writer -> return (LOne writer, True, total')
B.Chunk bs writer -> return (LTwo bs writer, True, total')
Just SFlush -> return (LZero, True, total)
Just SFinish -> return (LZero, False, total)
fillBufStream :: Buffer -> BufSize -> Leftover -> TBQueue Sequence -> TVar Sync -> Stream -> DynaNext
fillBufStream buf0 siz0 leftover0 sq tvar strm lim0 = do
let payloadBuf = buf0 `plusPtr` frameHeaderLength
room0 = min (siz0 - frameHeaderLength) lim0
case leftover0 of
LZero -> do
(leftover, cont, len) <- runStreamBuilder payloadBuf room0 sq
getNext leftover cont len
LOne writer -> write writer payloadBuf room0 0
LTwo bs writer
| BS.length bs <= room0 -> do
buf1 <- copy payloadBuf bs
let len = BS.length bs
write writer buf1 (room0 - len) len
| otherwise -> do
let (bs1,bs2) = BS.splitAt room0 bs
void $ copy payloadBuf bs1
getNext (LTwo bs2 writer) True room0
where
getNext = nextForStream buf0 siz0 sq tvar strm
write writer1 buf room sofar = do
(len, signal) <- writer1 buf room
case signal of
B.Done -> do
(leftover, cont, extra) <- runStreamBuilder (buf `plusPtr` len) (room - len) sq
let !total = sofar + len + extra
getNext leftover cont total
B.More _ writer -> do
let !total = sofar + len
getNext (LOne writer) True total
B.Chunk bs writer -> do
let !total = sofar + len
getNext (LTwo bs writer) True total
nextForStream :: Buffer -> BufSize -> TBQueue Sequence -> TVar Sync -> Stream
-> Leftover -> Bool -> BytesFilled
-> IO Next
nextForStream _ _ _ tvar _ _ False len = do
atomically $ writeTVar tvar SyncFinish
return $ Next len CFinish
nextForStream buf siz sq tvar strm LZero True len = do
let out = ONext strm (fillBufStream buf siz LZero sq tvar strm)
atomically $ writeTVar tvar $ SyncNext out
return $ Next len CNone
nextForStream buf siz sq tvar strm leftover True len =
return $ Next len (CNext (fillBufStream buf siz leftover sq tvar strm))
----------------------------------------------------------------
#ifdef WINDOWS
fillBufFile :: Buffer -> BufSize -> IO.Handle -> Integer -> IO () -> DynaNext
fillBufFile buf siz h bytes refresh lim = do
let payloadBuf = buf `plusPtr` frameHeaderLength
room = min (siz - frameHeaderLength) lim
len <- IO.hGetBufSome h payloadBuf room
refresh
let bytes' = bytes - fromIntegral len
return $ nextForFile len buf siz h bytes' refresh
nextForFile :: BytesFilled -> Buffer -> BufSize -> IO.Handle -> Integer -> IO () -> Next
nextForFile 0 _ _ _ _ _ = Next 0 CFinish
nextForFile len _ _ _ 0 _ = Next len CFinish
nextForFile len buf siz h bytes refresh =
Next len (CNext (fillBufFile buf siz h bytes refresh))
#else
fillBufFile :: Buffer -> BufSize -> Fd -> Integer -> Integer -> IO () -> DynaNext
fillBufFile buf siz fd start bytes refresh lim = do
let payloadBuf = buf `plusPtr` frameHeaderLength
room = min (siz - frameHeaderLength) lim
len <- positionRead fd payloadBuf (mini room bytes) start
let len' = fromIntegral len
refresh
return $ nextForFile len buf siz fd (start + len') (bytes - len') refresh
nextForFile :: BytesFilled -> Buffer -> BufSize -> Fd -> Integer -> Integer -> IO () -> Next
nextForFile 0 _ _ _ _ _ _ = Next 0 CFinish
nextForFile len _ _ _ _ 0 _ = Next len CFinish
nextForFile len buf siz fd start bytes refresh =
Next len (CNext (fillBufFile buf siz fd start bytes refresh))
#endif
mini :: Int -> Integer -> Int
mini i n
| fromIntegral i < n = i
| otherwise = fromIntegral n
|
iquiw/wai
|
warp/Network/Wai/Handler/Warp/HTTP2/Sender.hs
|
mit
| 18,038
| 0
| 20
| 5,142
| 4,301
| 2,125
| 2,176
| 303
| 18
|
{-# LANGUAGE OverloadedStrings #-}
module Y2018.M05.D18.Exercise where
-- Before we insert new articles, let's step back in time for a moment. Recall
import Y2018.M04.D09.Exercise
{--
where we uploaded tags, we uploaded a sample set of 10 tags. There are a lot
more tags than 10 for the World Policy Journal. Today we're going to find out
how many.
The REST endpoint for the tags is as follows:
--}
import Y2018.M04.D11.Exercise (PageNumber)
tagEndpoint :: PageNumber -> FilePath
tagEndpoint pn = "https://worldpolicy.org/wp-json/wp/v2/tags?per_page=100&page="
++ show pn
-- The JSON format we already know and parse (see above exercise) and the
-- tags are exhausted when the Value returned is the empty list.
-- How many tags are there for this REST endpoint?
downloadTags :: IO [Tag]
downloadTags = undefined
-- You may want to use some pagination function to help define downloadTags
-- hint: see definitions in Y2018.M04.D13 for downloading packets and use
-- a similar approach
{-- BONUS -----------------------------------------------------------------
Create an application that downloads all the tags from the REST endpoint and
then uploads those tags to a PostgreSQL data table as described in the module
Y2018.M04.D09.
-- BONUS-BONUS ------------------------------------------------------------
Create an application that does the same thing, but for categories this time.
See Y2018.M04.D06 for information on categories (very (VERY)) much like tags.
--}
|
geophf/1HaskellADay
|
exercises/HAD/Y2018/M05/D18/Exercise.hs
|
mit
| 1,486
| 0
| 6
| 233
| 77
| 50
| 27
| 9
| 1
|
{-|
Module : Language.X86.HwTranslator
Description : Virtual Asm to Hardware Asm translator
Copyright : (c) Jacob Errington and Frederic Lafrance, 2016
License : MIT
Maintainer : goto@mail.jerrington.me
Stability : experimental
This module is reponsible for the translation between virtual and hardware
assembly. The main steps of this translation are:
* Compute lifetimes for every virtual register in the program (see
"Language.X86.Lifetime")
* Allocate hardware locations for every virtual register (see
"Language.X86.HwAllocator")
-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.X86.HwTranslator where
import Language.Common.Misc
import Language.Common.Storage
import Language.X86.Core
import Language.X86.Hardware
import Language.X86.Hardware.Registers
import Language.X86.Lifetime
import Language.X86.Virtual
import Control.Monad.Identity
import Control.Monad.Except
import Control.Monad.State
import Control.Monad.Trans.Free
import qualified Data.Set as S
import qualified Data.Map.Strict as M
type Alg f a = f a -> a
translate
:: M.Map SizedVirtualRegister HardwareLocation
-> [(SizedHardwareRegister, LifetimeSpan)]
-> VirtualAsm Int ()
-> HardwareTranslation Int (HardwareAsm Int ())
translate vToH live = iterM phi . ($> pure ()) where
phi :: Alg
(AsmF Int (Operand SizedVirtualRegister Int))
(HardwareTranslation Int (HardwareAsm Int ()))
phi a = case a of
-- Pass through newLabel
NewLabel f -> do
l <- gets _lc
modify $ \s -> s { _lc = _lc s + 1 }
f l
-- Pass through setLabel
SetLabel l m -> do
p <- m
pure $ do
setLabel l
p
Prologue di n -> do
code <- case di of
-- Function prologue: make space on the stack for spills, push
-- safe registers that are in use throughout this function.
Save -> do
off <- negate <$> gets _currentSpillOffset
pregs <- S.elems <$> gets _safeRegistersUsed
let np = length pregs
let stkoff = alignmentPadding (negate off + np * 8) 16 - np * 8
let s = sub rsp (Immediate $ ImmI $ fromIntegral $ stkoff)
saveCode <- forM pregs $ \(SizedRegister _ reg) -> case reg of
FloatingHwRegister _ -> throwError $ InvariantViolation
"No floating register is safe"
IntegerHwRegister r -> pure $ push $ fixedIntReg64 r
pure $ s >> sequence_ saveCode
-- Mirror image of Prologue Save (pop safe registers, clear the
-- space on the stack.
Load -> do
off <- gets _currentSpillOffset
pregs <- S.elems <$> gets _safeRegistersUsed
let np = length pregs
let stkoff = alignmentPadding (negate off + np * 8) 16 - np * 8
let a' = add rsp (Immediate $ ImmI $ fromIntegral $ stkoff)
-- Obviously, this popping needs to be done in reverse.
loadCode <- forM (reverse pregs) $ \(SizedRegister _ reg) -> case reg of
FloatingHwRegister _ -> throwError $ InvariantViolation
"No floating register is safe"
IntegerHwRegister r -> pure $ pop $ fixedIntReg64 r
pure $ sequence_ loadCode >> a'
next <- n
pure $ code >> next
Scratch di n ->
case di of
-- On a scratch save, push all the scratch registers that are
-- currently live.
Save -> do
i <- gets _ip
let sr = getLiveScratch i live
modify $ \s -> s { _latestSavedRegisters = sr }
let ss = map (push . Register . Direct) sr
next <- n
pure $ do
sequence_ ss
when (length sr `mod` 2 /= 0) $ do
sub rsp (Immediate (ImmI 8))
next
-- Mirror: pop in reverse the registers we had saved before.
Load -> do
sr <- gets _latestSavedRegisters
let ss = map (pop . Register . Direct) (reverse sr)
next <- n
pure $ do
when (length sr `mod` 2 /= 0) $ do
-- remove the dummy push for 16 byte alignment
add rsp (Immediate (ImmI 8))
sequence_ ss
next
Emit i n -> do
s <- translateInst i
modify $ \st -> st { _ip = _ip st + 1 }
next <- n
pure $ s >> next
translateInst i = case i of
Ret -> pure ret
Mov v1 v2 -> (v1, v2) ?~> mov
Call v -> v !~> call
Add v1 v2 -> (v1, v2) ?~> add
Sub v1 v2 -> (v1, v2) ?~> sub
Mul _ v1 v2 -> (v1, v2) ?~> imul
Xor v1 v2 -> (v1, v2) ?~> xor
Inc v -> v !~> inc
Dec v -> v !~> dec
Push v -> v !~> push
Pop v -> v !~> pop
Nop -> pure nop
Syscall -> pure syscall
Int v -> v !~> int
Cmp v1 v2 -> (v1, v2) ?~> cmp
Test v1 v2 -> (v1, v2) ?~> test
Sal v1 v2 -> (v1, v2) ?~> sal
Sar v1 v2 -> (v1, v2) ?~> sar
Jump cond v -> v !~> (jump cond)
Setc cond v -> v !~> (setc cond)
Neg1 v -> v !~> neg1
Neg2 v -> v !~> neg2
And v1 v2 -> (v1, v2) ?~> bwand
Or v1 v2 -> (v1, v2) ?~> bwor
Cvt s1 s2 v1 v2 -> (v1, v2) ?~> cvt s1 s2
Div _ v1 v2 v3 -> (v1, v2, v3) &~> idiv
Cqo v1 v2 -> (v1, v2) ?~> cqo
AddSse s v1 v2 -> (v1, v2) ?~> addsse s
SubSse s v1 v2 -> (v1, v2) ?~> subsse s
MulSse s v1 v2 -> (v1, v2) ?~> mulsse s
DivSse s v1 v2 -> (v1, v2) ?~> divsse s
Pxor v1 v2 -> (v1, v2) ?~> pxor
Movq v1 v2 -> (v1, v2) ?~> movq
CmpSse s t v1 v2 -> (v1, v2) ?~> cmpsse s t
-- Translates an operand from virtual to hardware, and synthesizes the
-- given instruction that uses the hardware operand.
--
-- This operator is pronounced "translate".
v !~> fInst = do
v' <- translateOp v
pure $ fInst v'
{- A two-operand version of (!~>). A check is made to ensure that the
operands are not both indirects. If they are, then we go from this:
inst [dst] [src]
to:
mov rax, [src]
inst [dst] rax
This is okay because rax is never allocated, specifically for this purpose.
-}
(?~>)
:: (VirtualOperand Int, VirtualOperand Int)
-> (HardwareOperand Int -> HardwareOperand Int -> HardwareAsm Int ())
-> HardwareTranslation Int (HardwareAsm Int ())
(v1, v2) ?~> fInst = do
v1' <- translateOp v1
v2' <- translateOp v2
case (v1', v2') of
(Register (Indirect _), Register (Indirect _)) -> do
pure $ do
mov rax v2'
fInst v1' rax
_ -> pure $ fInst v1' v2'
(&~>)
:: (VirtualOperand Int, VirtualOperand Int, VirtualOperand Int)
-> (HardwareOperand Int -> HardwareOperand Int -> HardwareOperand Int -> HardwareAsm Int ())
-> HardwareTranslation Int (HardwareAsm Int ())
(v1, v2, v3) &~> fInst = do
(v1', v2', v3') <- (,,) <$> translateOp v1 <*> translateOp v2 <*> translateOp v3
case (v1, v2, v3) of
(Register (Indirect _), Register (Indirect _), Register (Indirect _)) ->
throwError $ InvariantViolation "triple indirection is impossible"
_ -> pure ()
pure $ fInst v1' v2' v3'
translateOp
:: VirtualOperand label
-> HardwareTranslation label (HardwareOperand label)
translateOp o = case o of
-- Any non-reg operand is just passed as-is. We have to do this boilerplate
-- for typechecking reasons.
Label l -> pure $ Label l
Internal s -> pure $ Internal s
External s -> pure $ External s
Immediate i -> pure $ Immediate i
{- Direct registers: check the translation table. If it got an actual
hardware register, use it. If it got spilled, generate an offset
from rbp. -}
Register d -> case d of
Direct r -> case M.lookup r vToH of
Just loc -> case loc of
Reg r' _ -> pure $ Register $ Direct r'
Mem i ->
pure $ Register $ Indirect $ Offset (fromIntegral i) $
SizedRegister Extended64 $ IntegerHwRegister Rbp
Unassigned -> throwError $ InvariantViolation $
"Register has not been assigned " ++ show r
Nothing -> throwError $ InvariantViolation
"Virtual register with no corresponding hardware location"
{- Indirect registers: normally these should only be generated with
fixed hardware registers. If we end up with an indirect virtual, then
we're in a problematic situation, because that virtual could have been
spilled, which creates a second layer of indirection. There's ways of
dealing with that in instructions with one operand, but when you move up
to two operands, you might end up in a situation where you need to push
another register to make enough room for those operands.
Bottom line: an error is thrown if the register was spilled.
-}
Indirect off -> case off of
Offset disp r -> case M.lookup r vToH of
Just loc -> case loc of
Reg r' _ -> pure $ Register $ Indirect $ Offset disp r'
Mem _ -> throwError $ InvariantViolation
"Spilled virtual indirect register"
Unassigned -> throwError $ InvariantViolation
"Register has not been assigned."
Nothing -> throwError $ InvariantViolation
"Register has no corresponding hardware location"
-- | Given an offset, constructs the operand to access the spill location
-- associated with it.
spillOperand :: Int -> HardwareOperand label
spillOperand i
= Register
$ Indirect
$ Offset (fromIntegral i)
$ SizedRegister Extended64
$ IntegerHwRegister Rbp
-- | Obtains all the unsafe registers that are live at the given program point.
getLiveScratch
:: Int
-> [(SizedHardwareRegister, LifetimeSpan)]
-> [SizedHardwareRegister]
getLiveScratch i = map fst . filter (\(h, l) ->
h `elem` scratchRegisters -- The register must be scratch.
&& i >= _start l && i < _end l) -- Its lifetime must encompass the ip.
-- | Calculates the total offset required for spills, and verifies which safe
-- registers are used throughout the function.
--
-- Returns a new version of the register pairings in which all spills have their
-- proper offset computed.
computeAllocState :: [RegisterPairing] -> HardwareTranslation label [RegisterPairing]
computeAllocState = foldl (\acc (v, h) -> do
acc' <- acc
case h of
Unassigned -> throwError $ InvariantViolation "A hardware location should\
\ have been assigned"
Mem _ -> do
let space = storageSize $ getVRegSize v
off <- gets _currentSpillOffset
modify $ \s -> s { _currentSpillOffset = off - space}
pure $ (v, Mem off):acc'
Reg r _ -> do
when (r `elem` safeRegisters)
$ modify $ \s -> s { _safeRegistersUsed = S.insert r $ _safeRegistersUsed s }
pure $ (v, h):acc'
) (pure [])
getVRegSize :: SizedVirtualRegister -> RegisterSize
getVRegSize (SizedRegister sz _) = sz
-- | Computes how many bytes of padding are needed to reach an alignment goal.
alignmentPadding
:: Int -- ^ Current size
-> Int -- ^ Alignment goal
-> Int -- ^ Number of padding bytes required
alignmentPadding sz g = g - (sz `div` g)
{-# INLINE alignmentPadding #-}
|
djeik/goto
|
libgoto/Language/X86/HwTranslator.hs
|
mit
| 12,525
| 0
| 27
| 4,615
| 3,054
| 1,515
| 1,539
| 216
| 55
|
{-# LANGUAGE MagicHash, UnboxedTuples, CPP, RankNTypes #-}
{-# OPTIONS_GHC -fno-full-laziness #-}
module Data.TrieVector.SmallArrayPrim (
Array
, MArray
, new
, write
, read
, thaw
, index
, freeze
, unsafeFreeze
, unsafeThaw
, sizeof
, sizeofMut
, copy
, copyMut
, clone
, cloneMut
, cas
, sameMut
, run
) where
import GHC.Prim
import GHC.Types
import GHC.Base (realWorld#)
import Prelude hiding (read)
type Array = SmallArray#
type MArray = SmallMutableArray#
new = newSmallArray#
write = writeSmallArray#
read = readSmallArray#
thaw = thawSmallArray#
index = indexSmallArray#
freeze = freezeSmallArray#
unsafeFreeze = unsafeFreezeSmallArray#
unsafeThaw = unsafeThawSmallArray#
sizeof = sizeofSmallArray#
sizeofMut = sizeofSmallMutableArray#
copy = copySmallArray#
copyMut = copySmallMutableArray#
clone = cloneSmallArray#
cloneMut = cloneSmallMutableArray#
cas = casSmallArray#
sameMut = sameSmallMutableArray#
run :: (forall s. State# s -> (# State# s, Array a #)) -> Array a
run strep = case strep realWorld# of
(# _, arr #) -> arr
{-# INLINE [0] run #-}
{-# INLINE new #-}
{-# INLINE write #-}
{-# INLINE read #-}
{-# INLINE thaw #-}
{-# INLINE index #-}
{-# INLINE freeze #-}
{-# INLINE unsafeFreeze #-}
{-# INLINE unsafeThaw #-}
{-# INLINE sizeof #-}
{-# INLINE sizeofMut #-}
{-# INLINE copy #-}
{-# INLINE copyMut #-}
{-# INLINE clone #-}
{-# INLINE cloneMut #-}
{-# INLINE cas #-}
{-# INLINE sameMut #-}
|
AndrasKovacs/trie-vector
|
Data/TrieVector/SmallArrayPrim.hs
|
mit
| 1,508
| 0
| 10
| 312
| 270
| 169
| 101
| 64
| 1
|
{-# LANGUAGE RecordWildCards, LambdaCase #-}
module QuadRenderingAdHoc ( drawQuadImmediate
, drawQuadAdHocVBO
, drawQuadAdHocVBOShader
) where
import qualified Graphics.Rendering.OpenGL as GL
import qualified Data.Vector.Storable.Mutable as VSM
import Data.List
import Data.Maybe
import Control.Monad
import Foreign.Ptr
import Foreign.ForeignPtr
import Foreign.Storable
import GLHelpers
import GLImmediate
import Shaders
import Trace
import QuadTypes
-- Inefficient / obsolete (just used for testing / development) immediate mode and ad-hoc
-- drawing functions. QuadRendering re-exports everything from here, this only exists to
-- get some code out of the way and to make QuadRendering a bit smaller
--
-- Some references for getting basic rendering / shading like this up and running with
-- OpenGL in Haskell:
--
-- https://github.com/ocharles/blog/blob/master/code/2013-12-02-linear-example.hs
-- http://www.arcadianvisions.com/blog/?p=224
-- https://github.com/haskell-opengl/GLUT/blob/master/examples/Misc/SmoothOpenGL3.hs
drawQuadImmediate, drawQuadAdHocVBO, drawQuadAdHocVBOShader
:: Float -> Float -> Float -> Float
-> Float
-> FillColor
-> Transparency
-> Maybe GL.TextureObject
-> IO ()
-- OpenGL 1.0 style immediate mode drawing
drawQuadImmediate x1 y1 x2 y2 depth col trans tex = do
setTransparency trans
setTextureFFP tex
let (pos', cols, texs) = paramToPosColUV x1 y1 x2 y2 col
-- Immediate mode drawing
GL.renderPrimitive GL.Quads . forM_ (zip3 pos' cols texs) $
\((x, y), RGBA r g b a, (u, v)) -> do
color4f r g b a
texCoord2f u v
vertex3f x y (-depth)
-- OpenGL 1.5 style VBO + FFP drawing with ad-hoc buffer creation
drawQuadAdHocVBO x1 y1 x2 y2 depth col trans tex = do
setTransparency trans
setTextureFFP tex
let (pos', cols, texs) = paramToPosColUV x1 y1 x2 y2 col
-- VBO allocation
let szf = sizeOf (0 :: Float)
numvtx = 4
vtxStride = 3
colStride = 4
uvStride = 2
vtxSize = numvtx * vtxStride
colSize = numvtx * colStride
uvSize = numvtx * uvStride
totalSize = vtxSize + colSize + uvSize
vtxOffset = 0
colOffset = vtxOffset + vtxSize
uvOffset = colOffset + colSize
vbo <- mkBindDynamicBO GL.ArrayBuffer $ totalSize * szf
-- Fill mapped VBO with vertex data. We don't interleave the vertex attributes, but
-- rather have the different arrays consecutively in the buffer
GL.withMappedBuffer
GL.ArrayBuffer
GL.WriteOnly
( \ptr -> newForeignPtr_ ptr >>= \fp -> do
let vec = VSM.unsafeFromForeignPtr fp vtxOffset vtxSize in
forM_ (zip [0..] pos') $ \(i, (x, y)) ->
forM_ (zip [0..] [x, y, (-depth)]) $ \(c, f) ->
VSM.write vec (i * vtxStride + c) f
let vec = VSM.unsafeFromForeignPtr fp colOffset colSize in
forM_ (zip [0..] cols) $ \(i, RGBA r g b a) ->
forM_ (zip [0..] [r, g, b, a]) $ \(c, f) ->
VSM.write vec (i * colStride + c) f
let vec = VSM.unsafeFromForeignPtr fp uvOffset uvSize in
forM_ (zip [0..] texs) $ \(i, (u, v)) ->
forM_ (zip [0..] [u, v]) $ \(c, f) ->
VSM.write vec (i * uvStride + c) f
)
( \mf -> traceAndThrow $ "drawQuadAdHocVBO - OpenGL mapping failure: " ++ show mf )
-- Specify and enable vertex arrays
GL.arrayPointer GL.VertexArray GL.$=
GL.VertexArrayDescriptor
(fromIntegral vtxStride)
GL.Float
0
(nullPtr `plusPtr` (vtxOffset * szf))
GL.arrayPointer GL.ColorArray GL.$=
GL.VertexArrayDescriptor
(fromIntegral colStride)
GL.Float
0
(nullPtr `plusPtr` (colOffset * szf))
GL.arrayPointer GL.TextureCoordArray GL.$=
GL.VertexArrayDescriptor
(fromIntegral uvStride)
GL.Float
0
(nullPtr `plusPtr` (uvOffset * szf))
mapM_ (\x -> GL.clientState x GL.$= GL.Enabled)
[GL.VertexArray, GL.ColorArray, GL.TextureCoordArray]
-- Draw
GL.drawArrays GL.Quads 0 $ fromIntegral numvtx
-- Disable vertex arrays
mapM_ (\x -> GL.clientState x GL.$= GL.Disabled)
[GL.VertexArray, GL.ColorArray, GL.TextureCoordArray]
-- Delete VBO
GL.deleteObjectNames [vbo]
-- OpenGL 3.0 style VBA / VBO + shader drawing, also using an index buffer, interleaved
-- arrays and drawing triangles instead of quads. Buffers and shaders are created ad-hoc
drawQuadAdHocVBOShader x1 y1 x2 y2 depth col trans tex = do
setTransparency trans
let (pos', cols, texs) = paramToPosColUV x1 y1 x2 y2 col
-- Create and bind Vertex Array Object (VAO)
vao <- GL.genObjectName
GL.bindVertexArrayObject GL.$= Just vao
-- VBO allocation
let szf = sizeOf (0 :: Float)
numvtx = 4
vtxStride = 3
colStride = 4
uvStride = 2
totalStride = vtxStride + colStride + uvStride
totalSize = totalStride * numvtx
vtxOffset = 0
colOffset = vtxOffset + vtxStride
uvOffset = colOffset + colStride
vbo <- mkBindDynamicBO GL.ArrayBuffer $ totalSize * szf
-- Fill mapped VBO with vertex data, interleaved attribute arrays
GL.withMappedBuffer
GL.ArrayBuffer
GL.WriteOnly
( \ptr -> newForeignPtr_ ptr >>= \fp ->
let vec = VSM.unsafeFromForeignPtr0 fp totalSize
in forM_ (zip4 [0..] pos' cols texs) $
\(i, (x, y), RGBA r g b a, (u, v)) ->
forM_ (zip [0..] [x, y, (-depth), r, g, b, a, u, v]) $
\(offs, f) -> VSM.write vec (i * totalStride + offs) f
)
( \mf -> traceAndThrow $ "drawQuadAdHocVBOShader - VBO mapping failure: " ++ show mf )
-- Specify and enable vertex attribute arrays
vtxAttrib <- setAttribArray 0 vtxStride totalStride vtxOffset
colAttrib <- setAttribArray 1 colStride totalStride colOffset
uvAttrib <- setAttribArray 2 uvStride totalStride uvOffset
-- Allocate element array (index) buffer object (EBO)
let numidx = 2 * 3
szi = sizeOf(0 :: GL.GLuint)
ebo <- mkBindDynamicBO GL.ElementArrayBuffer $ numidx * szi
-- Fill mapped EBO with index data
GL.withMappedBuffer
GL.ElementArrayBuffer
GL.WriteOnly
( \ptr -> newForeignPtr_ ptr >>= \fp ->
let vec = VSM.unsafeFromForeignPtr0 fp numidx :: VSM.IOVector GL.GLuint
in forM_ (zip [0..] [0, 1, 2, 0, 2, 3]) $ \(i, e) -> VSM.write vec i e
)
( \mf -> traceAndThrow $ "drawQuadAdHocVBOShader - EBO mapping failure: " ++ show mf )
-- Create, compile and link shaders
shdProg <- mkShaderProgam vsSrcBasic (if isJust tex
then fsSrcBasic
else fsColOnlySrcBasic) >>= \case
Left err -> traceAndThrow $ "drawQuadAdHocVBOShader - Shader error:\n " ++ err
Right p -> return p
-- Set shader attributes and activate
GL.attribLocation shdProg "in_pos" GL.$= vtxAttrib
GL.attribLocation shdProg "in_col" GL.$= colAttrib
GL.attribLocation shdProg "in_uv" GL.$= uvAttrib
GL.currentProgram GL.$= Just shdProg
-- Projection matrix
{-
let l = 0
r = 100
b = 0
t = 100
n = 0
f = 1000
projection = VS.fromList [ 2 / (r - l), 0, 0, 0,
0, 2 / (t - b), 0, 0,
0, 0, -2 / (f - n), 0,
-(r + l) / (r - l), -(t + b) / (t - b), -(f + n) / (f - n), 1
] :: VS.Vector GL.GLfloat
let projection = VS.fromList [ 1 / 1280, 0, 0, 0
, 0, 1 / 720, 0, 0
, 0, 0, 1 / 1000, 0
, 0, 0, 0, 1
] :: VS.Vector GL.GLfloat
-}
-- TODO: We're setting the shader matrix from FFP projection matrix
setProjMatrixFromFFP shdProg "in_mvp"
-- Textures
when (isJust tex) $
setTextureShader (fromJust tex) 0 shdProg "tex"
-- Draw quad as two triangles
GL.drawElements GL.Triangles (fromIntegral numidx) GL.UnsignedInt nullPtr
-- Delete shaders / EBO / VBO / VAO
disableVAOAndShaders
GL.deleteObjectName shdProg
GL.deleteObjectName ebo
GL.deleteObjectName vbo
GL.deleteObjectName vao
-- Convert rectangle position and draw parameters into a set of render-ready vertex attributes
paramToPosColUV :: Float -> Float -> Float -> Float
-> FillColor
-> ([(Float, Float)], [RGBA], [(Float, Float)])
paramToPosColUV x1 y1 x2 y2 col =
let pos' = [ (x1, y1), (x2, y1), (x2, y2), (x1, y2) ]
cols = case col of FCWhite -> replicate 4 (RGBA 1 1 1 1)
FCBlack -> replicate 4 (RGBA 0 0 0 1)
FCSolid c -> replicate 4 c
FCBottomTopGradient b t -> [b, b, t, t]
FCLeftRightGradient l r -> [l, r, l, r]
texs = [ (0, 0), (1, 0), (1, 1), (0, 1) ]
in (pos', cols, texs)
setTextureFFP :: Maybe GL.TextureObject -> IO ()
setTextureFFP tex = do
-- FFP texture setup
case tex of
Just _ -> do
GL.texture GL.Texture2D GL.$= GL.Enabled
GL.textureBinding GL.Texture2D GL.$= tex
Nothing ->
GL.texture GL.Texture2D GL.$= GL.Disabled
|
blitzcode/jacky
|
src/old_code/QuadRenderingAdHoc.hs
|
mit
| 9,871
| 0
| 24
| 3,260
| 2,443
| 1,283
| 1,160
| 168
| 5
|
module Test where
{
import PopGen;
import Probability;
get_observed_alleles file = map list_from_vector $ list_from_vector $ read_phase_file file;
filename = "/home/bredelings/Reports/Kmar/TwinCays2005a.phase1.infile";
n = 5;
note mean ~ iid(n, gamma(0.5,0.5) );
note sigmaOverMu ~ iid(n, gamma(1.05,0.1) );
alpha = 1.0;
note p ~ symmetric_dirichlet (n, alpha/(intToDouble n));
data1 = get_observed_alleles filename;
n_loci = length data1;
n_individuals = (length (data1!!0))/2;
note category ~ iid(n_loci, categorical p);
note z ~ iid(n_loci, normal(0.0, 1.0));
safe_exp x = if (x < (-20.0)) then
exp (-20.0);
else if (x > 20.0) then
exp 20.0;
else
exp x;
theta = [ mean!!k * safe_exp (z!!i * sigmaOverMu!!k) | i <- take n_loci [0..], let {k=category!!i}];
note p_m ~ uniform (0.0, 1.0);
p_h = 1.0 - p_m;
theta_ewens = map (*(1.0-s*0.5)/( (1.0+s)^2 /(4.0*p_h) + (1.0-s)^2/(4.0*p_m)) ) theta;
note theta_example ~ mixture [ (p!!i, logNormal(log(mean!!i),sigmaOverMu!!i)) | i <- take n [0..] ];
note s ~ uniform(0.0, 1.0);
note t ~ iid(n_individuals, exponential (s/(1.0-s)));
note i ~ iid(n_loci, plate (n_individuals,\k->bernoulli (1.0-0.5**t!!k)) );
note data data1 ~ plate (n_loci, \l -> afs2 (theta_ewens!!l,i!!l));
note data 19 ~ binomial(112, p_m);
note MakeLogger p;
note MakeLogger theta;
note MakeLogger t;
}
|
bredelings/BAli-Phy
|
tests/PartialSelfing/diploid.andro.multi_theta.TCb.hs
|
gpl-2.0
| 1,448
| 34
| 16
| 318
| 669
| 370
| 299
| -1
| -1
|
module GraphTheory.Macro where
import Types
import Macro.Tuple
graph_ :: Note
graph_ = "G"
grph :: Note -> Note -> Note
grph = tuple
grph_ :: Note
grph_ = grph vrt_ edg_
vrt_ :: Note
vrt_ = "V"
edg_ :: Note
edg_ = "E"
|
NorfairKing/the-notes
|
src/GraphTheory/Macro.hs
|
gpl-2.0
| 245
| 0
| 6
| 70
| 77
| 45
| 32
| 13
| 1
|
module Main (main) where
import Data.Bifunctor
import Language.SimplyTyped.Parser
import Language.SimplyTyped.Pretty
import Language.SimplyTyped.Semantics
import Language.SimplyTyped.Interpreter
import System.Console.Haskeline
evalString :: String -> String
evalString input = either id id $ evalString' input where
evalString' :: String -> Either String String
evalString' input = do
term <- first show $ readTerm input
unnamedTerm <- first show $ unname term
first show $ typeof unnamedTerm
value <- first show $ name $ eval unnamedTerm
return $ showTerm value
main :: IO ()
main = runInputT defaultSettings loop
where
loop :: InputT IO ()
loop = do
minput <- getInputLine "> "
case minput of
Nothing -> return ()
Just input -> do outputStrLn $ evalString input
loop
|
robertclancy/tapl
|
simply-typed/src/Main.hs
|
gpl-2.0
| 967
| 0
| 15
| 311
| 264
| 128
| 136
| 25
| 2
|
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, GeneralizedNewtypeDeriving #-}
module Lamdu.Data.DbLayout
( DbM, runDbTransaction
, ViewM, runViewTransaction
, CodeProps, codeProps, codeIRefs
, RevisionProps, revisionProps, revisionIRefs
, module Lamdu.Data.Anchors
) where
import Prelude.Compat
import Control.Monad.IO.Class (MonadIO)
import Data.ByteString.Char8 ()
import Data.Store.Db (Db)
import qualified Data.Store.Db as Db
import Data.Store.IRef (IRef)
import qualified Data.Store.IRef as IRef
import Data.Store.Rev.View (View)
import qualified Data.Store.Rev.View as View
import Data.Store.Transaction (Transaction)
import qualified Data.Store.Transaction as Transaction
import Lamdu.Data.Anchors (Code(..), Revision(..), assocNameRef)
import qualified Lamdu.Data.Anchors as Anchors
type T = Transaction
newtype DbM a = DbM { dbM :: IO a }
deriving (Functor, Applicative, Monad, MonadIO)
newtype ViewM a = ViewM { viewM :: T DbM a }
deriving (Functor, Applicative, Monad)
runDbTransaction :: Db -> T DbM a -> IO a
runDbTransaction db = dbM . Transaction.run (Transaction.onStoreM DbM (Db.store db))
runViewTransaction :: View DbM -> T ViewM a -> T DbM a
runViewTransaction v = viewM . (Transaction.run . Transaction.onStoreM ViewM . View.store) v
codeIRefs :: Code (IRef ViewM) ViewM
codeIRefs = Code
{ repl = IRef.anchor "repl"
, panes = IRef.anchor "panes"
, globals = IRef.anchor "globals"
, preJumps = IRef.anchor "prejumps"
, preCursor = IRef.anchor "precursor"
, postCursor = IRef.anchor "postcursor"
, tags = IRef.anchor "tags"
, tids = IRef.anchor "tids"
}
revisionIRefs :: Revision (IRef DbM) DbM
revisionIRefs = Revision
{ branches = IRef.anchor "branches"
, currentBranch = IRef.anchor "currentBranch"
, cursor = IRef.anchor "cursor"
, redos = IRef.anchor "redos"
, view = IRef.anchor "view"
}
type CodeProps = Anchors.CodeProps ViewM
type RevisionProps = Anchors.RevisionProps DbM
codeProps :: CodeProps
codeProps = Anchors.onCode Transaction.mkPropertyFromIRef codeIRefs
revisionProps :: RevisionProps
revisionProps = Anchors.onRevision Transaction.mkPropertyFromIRef revisionIRefs
|
da-x/lamdu
|
Lamdu/Data/DbLayout.hs
|
gpl-3.0
| 2,291
| 0
| 11
| 452
| 631
| 366
| 265
| 52
| 1
|
{-# LANGUAGE EmptyDataDecls,
MultiParamTypeClasses,
GADTs,
RankNTypes,
FlexibleInstances #-}
module Canon where
import Music (Name(..), Accidental(..), Scale(..), Tuning(..), Timing(..), Metronome(..), Duration(..),
AbstractInt1(..), AbstractPitch1(..), AbstractDur1(..),
AbstractInt2(..), AbstractPitch2(..), AbstractDur2(..),
AbstractInt3(..), AbstractPitch3(..), AbstractDur3(..),
Note(..),
Name(..), Number(..), Accidental(..), Quality(..),
Pitch(..), Interval(..),
Transpose(..),
AbstractNote(..), Note1, Note2, Note3,
AbstractPhrase(..),
Degree(..), Ficta(..), noteToSound,
mapPhrase, absolute, normalise, repeatPhrase, foldPhrase, countDurs,
explodeVoices, splitVoices, mapMusic, apPitch,
Music(..))
import Tuning
import FiveLimit (JustTuning(..), JustPitch(..), JustInt(..), ForceJustTuning(..))
import Scales (minor, major, harmonicminor, melodicminor, infiniteScale)
import Shortcuts
import Output
import LilyPrint
import Data.Ratio
import Data.Semigroup hiding (Min)
----
bassnotes = map (.-^ (2 *^ octave)) $ map (\d -> AbstractPitch1 d Neutral)
[(DUp TO), DO, SM, ME, SD, TO, SD, DO]
p1notes = map (\d -> AbstractPitch1 d Neutral)
[ME, ST, TO, (DDown LN), (DDown SM), (DDown DO), (DDown SM), (DDown LN)]
p2notes = map (.-^ octave) $ map (\d -> AbstractPitch1 d Neutral)
[(DUp TO), LN, SM, DO, SD, ME, SD, ST]
p3notes = map (.-^ octave) $ map (\d -> AbstractPitch1 d Neutral)
[TO, ME, DO, SD, ME, TO, ME, ST, TO, (DDown SM), TO, DO, SD, SM, DO, SD]
p4notes = map (.-^ octave) $ map (\d -> AbstractPitch1 d Neutral)
[ME, TO, ST, LN, (DUp TO), (DUp ME), (DUp DO), DO, SM, SD, DO, ME, TO, (DUp TO), (DUp TO), LN]
p4rhythms = (take 14 $ repeat quaver) ++ [dotted quaver, semiquaver]
p5notes = map (.-^ octave) $ map (\d -> AbstractPitch1 d Neutral)
[(DUp TO), LN, (DUp TO), TO, (DDown LN), DO, ST, ME, TO, (DUp TO), LN, SM, LN, (DUp ME), (DUp DO), (DUp SM), (DUp SD), (DUp ME), (DUp ST), (DUp SD),
(DUp ME), (DUp ST), (DUp TO), LN, SM, DO, SD, ME, ST, SD, ME, ST]
key = major (pitch C Na)
-- key = minor (a .+^ d3 .+^ d3)
bass = AbstractPhrase (zipWith AbstractPitch
(map ((transpose (int Perf ((Negative (Compound Unison))))) . (applyScale key)) bassnotes)
(repeat crotchet))
cphrase p d k = AbstractPhrase (zipWith AbstractPitch (map (applyScale k) p) d)
p1 = cphrase p1notes (repeat crotchet) key
p2 = cphrase p2notes (repeat crotchet) key
p3 = cphrase p3notes (repeat quaver) key
p4 = cphrase p4notes p4rhythms key
p5 = cphrase p5notes (repeat semiquaver) key
v1 = (conn v4) <> p1 <> (conn v2) <> p2 <> p3 <> p4 <> p5
v2 = p1 <> (conn v3) <> p2 <> p3 <> p4
v3 = p1 <> p2 <> p3
v4 = repeatPhrase 5 bass
--et = Equal (a, freq 440)
et = Pythagorean (a, freq 440)
me = Metronome 120
canon = Start v1
voices = explodeVoices canon
|
ejlilley/AbstractMusic
|
Canon.hs
|
gpl-3.0
| 3,116
| 0
| 20
| 804
| 1,341
| 791
| 550
| 60
| 1
|
module StopWatch where
import FRP.Yampa
import Data.IORef
import Data.Time.Clock
data Stopwatch = Stopwatch { zero :: UTCTime
, prev :: UTCTime }
startStopWatch :: UTCTime -> Stopwatch
startStopWatch now = Stopwatch now now
storeStopwatch :: IO (IORef Stopwatch)
storeStopwatch = getCurrentTime >>= (newIORef . startStopWatch)
diffTime :: (IORef Stopwatch) -> IO (DTime,DTime)
diffTime ref = do
now <- getCurrentTime
(Stopwatch zero prev) <- readIORef ref
writeIORef ref (Stopwatch zero now)
let dt = realToFrac (diffUTCTime now prev)
timePassed = realToFrac (diffUTCTime now zero)
return (dt, timePassed)
|
eniac314/aquarium
|
src/StopWatch.hs
|
gpl-3.0
| 676
| 0
| 12
| 156
| 214
| 111
| 103
| 18
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
-- Module : Network.AWS.ElasticFileSystem.DeleteFileSystem
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes a file system, permanently severing access to its contents. Upon
-- return, the file system no longer exists and you will not be able to
-- access any contents of the deleted file system.
--
-- You cannot delete a file system that is in use. That is, if the file
-- system has any mount targets, you must first delete them. For more
-- information, see DescribeMountTargets and DeleteMountTarget.
--
-- The @DeleteFileSystem@ call returns while the file system state is still
-- \"deleting\". You can check the file system deletion status by calling
-- the DescribeFileSystems API, which returns a list of file systems in
-- your account. If you pass file system ID or creation token for the
-- deleted file system, the DescribeFileSystems will return a 404
-- \"FileSystemNotFound\" error.
--
-- This operation requires permission for the
-- @elasticfilesystem:DeleteFileSystem@ action.
--
-- <http://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeleteFileSystem.html>
module Network.AWS.ElasticFileSystem.DeleteFileSystem
(
-- * Request
DeleteFileSystem
-- ** Request constructor
, deleteFileSystem
-- ** Request lenses
, dFileSystemId
-- * Response
, DeleteFileSystemResponse
-- ** Response constructor
, deleteFileSystemResponse
) where
import Network.AWS.ElasticFileSystem.Types
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | /See:/ 'deleteFileSystem' smart constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dFileSystemId'
newtype DeleteFileSystem = DeleteFileSystem'
{ _dFileSystemId :: Text
} deriving (Eq,Read,Show)
-- | 'DeleteFileSystem' smart constructor.
deleteFileSystem :: Text -> DeleteFileSystem
deleteFileSystem pFileSystemId =
DeleteFileSystem'
{ _dFileSystemId = pFileSystemId
}
-- | The ID of the file system you want to delete.
dFileSystemId :: Lens' DeleteFileSystem Text
dFileSystemId = lens _dFileSystemId (\ s a -> s{_dFileSystemId = a});
instance AWSRequest DeleteFileSystem where
type Sv DeleteFileSystem = ElasticFileSystem
type Rs DeleteFileSystem = DeleteFileSystemResponse
request = delete
response = receiveNull DeleteFileSystemResponse'
instance ToHeaders DeleteFileSystem where
toHeaders = const mempty
instance ToPath DeleteFileSystem where
toPath DeleteFileSystem'{..}
= mconcat
["/2015-02-01/file-systems/", toText _dFileSystemId]
instance ToQuery DeleteFileSystem where
toQuery = const mempty
-- | /See:/ 'deleteFileSystemResponse' smart constructor.
data DeleteFileSystemResponse =
DeleteFileSystemResponse'
deriving (Eq,Read,Show)
-- | 'DeleteFileSystemResponse' smart constructor.
deleteFileSystemResponse :: DeleteFileSystemResponse
deleteFileSystemResponse = DeleteFileSystemResponse'
|
fmapfmapfmap/amazonka
|
amazonka-efs/gen/Network/AWS/ElasticFileSystem/DeleteFileSystem.hs
|
mpl-2.0
| 3,611
| 0
| 9
| 704
| 326
| 206
| 120
| 41
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.IAM.UpdateGroup
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Updates the name and/or the path of the specified group.
--
-- You should understand the implications of changing a group's path or name.
-- For more information, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_WorkingWithGroupsAndUsers.html Renaming Users and Groups> in the /Using IAM/ guide. To change a group name the requester must have appropriate permissions on both the source object and the target object. For example, to change Managers to MGRs, the entity making the request must have permission on Managers and MGRs, or must have permission on all (*). For more information about permissions, see
-- Permissions and Policies.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateGroup.html>
module Network.AWS.IAM.UpdateGroup
(
-- * Request
UpdateGroup
-- ** Request constructor
, updateGroup
-- ** Request lenses
, ugGroupName
, ugNewGroupName
, ugNewPath
-- * Response
, UpdateGroupResponse
-- ** Response constructor
, updateGroupResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data UpdateGroup = UpdateGroup
{ _ugGroupName :: Text
, _ugNewGroupName :: Maybe Text
, _ugNewPath :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'UpdateGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'ugGroupName' @::@ 'Text'
--
-- * 'ugNewGroupName' @::@ 'Maybe' 'Text'
--
-- * 'ugNewPath' @::@ 'Maybe' 'Text'
--
updateGroup :: Text -- ^ 'ugGroupName'
-> UpdateGroup
updateGroup p1 = UpdateGroup
{ _ugGroupName = p1
, _ugNewPath = Nothing
, _ugNewGroupName = Nothing
}
-- | Name of the group to update. If you're changing the name of the group, this
-- is the original name.
ugGroupName :: Lens' UpdateGroup Text
ugGroupName = lens _ugGroupName (\s a -> s { _ugGroupName = a })
-- | New name for the group. Only include this if changing the group's name.
ugNewGroupName :: Lens' UpdateGroup (Maybe Text)
ugNewGroupName = lens _ugNewGroupName (\s a -> s { _ugNewGroupName = a })
-- | New path for the group. Only include this if changing the group's path.
ugNewPath :: Lens' UpdateGroup (Maybe Text)
ugNewPath = lens _ugNewPath (\s a -> s { _ugNewPath = a })
data UpdateGroupResponse = UpdateGroupResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'UpdateGroupResponse' constructor.
updateGroupResponse :: UpdateGroupResponse
updateGroupResponse = UpdateGroupResponse
instance ToPath UpdateGroup where
toPath = const "/"
instance ToQuery UpdateGroup where
toQuery UpdateGroup{..} = mconcat
[ "GroupName" =? _ugGroupName
, "NewGroupName" =? _ugNewGroupName
, "NewPath" =? _ugNewPath
]
instance ToHeaders UpdateGroup
instance AWSRequest UpdateGroup where
type Sv UpdateGroup = IAM
type Rs UpdateGroup = UpdateGroupResponse
request = post "UpdateGroup"
response = nullResponse UpdateGroupResponse
|
romanb/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/UpdateGroup.hs
|
mpl-2.0
| 4,083
| 0
| 9
| 898
| 472
| 287
| 185
| 57
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.