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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
-- Mainly provides a kind checker on types
module Language.Granule.Checker.Kinds (
inferKindOfType
, inferKindOfTypeInContext
, hasLub
, joinKind
, mguCoeffectTypesFromCoeffects
, inferCoeffectType
, inferCoeffectTypeInContext
, inferCoeffectTypeAssumption
, promoteTypeToKind
, demoteKindToType
, isEffectType
, isEffectTypeFromKind
, isEffectKind
, isCoeffectKind) where
import Control.Monad.State.Strict
import Language.Granule.Checker.Flatten
import Language.Granule.Checker.KindsHelpers
import Language.Granule.Checker.Monad
import Language.Granule.Checker.Predicates
import Language.Granule.Checker.Primitives (tyOps, setElements)
import Language.Granule.Checker.SubstitutionContexts
import Language.Granule.Checker.Variables
import Language.Granule.Syntax.Identifiers
import Language.Granule.Syntax.Pretty
import Language.Granule.Syntax.Span
import Language.Granule.Syntax.Type
import Language.Granule.Context
import Language.Granule.Utils
import Data.List (partition)
inferKindOfType :: (?globals :: Globals) => Span -> Type -> Checker Kind
inferKindOfType s t = do
checkerState <- get
inferKindOfTypeInContext s (stripQuantifiers $ tyVarContext checkerState) t
inferKindOfTypeInContext :: (?globals :: Globals) => Span -> Ctxt Kind -> Type -> Checker Kind
inferKindOfTypeInContext s quantifiedVariables t =
typeFoldM (TypeFold kFun kCon kBox kDiamond kVar kApp kInt kInfix kSet) t
where
kFun (KPromote (TyCon c)) (KPromote (TyCon c'))
| internalName c == internalName c' = return $ kConstr c
kFun KType KType = return KType
kFun KType (KPromote (TyCon (internalName -> "Protocol"))) = return $ KPromote (TyCon (mkId "Protocol"))
kFun KType y = throw KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = KType, kActual = y }
kFun x _ = throw KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = KType, kActual = x }
kCon (internalName -> "Pure") = do
-- Create a fresh type variable
var <- freshTyVarInContext (mkId $ "eff[" <> pretty (startPos s) <> "]") KEffect
return $ KPromote $ TyVar var
kCon conId = do
st <- get
case lookup conId (typeConstructors st) of
Just (kind,_,_) -> return kind
Nothing -> do
mConstructor <- lookupDataConstructor s conId
case mConstructor of
Just (Forall _ [] [] t, _) -> return $ KPromote t
Just _ -> error $ pretty s <> "I'm afraid I can't yet promote the polymorphic data constructor:" <> pretty conId
Nothing -> throw UnboundTypeConstructor{ errLoc = s, errId = conId }
kBox c KType = do
-- Infer the coeffect (fails if that is ill typed)
_ <- inferCoeffectType s c
return KType
kBox _ x = throw KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = KType, kActual = x }
kDiamond effK KType = do
effTyM <- isEffectTypeFromKind s effK
case effTyM of
Right effTy -> return KType
Left otherk -> throw KindMismatch { errLoc = s, tyActualK = Just t, kExpected = KEffect, kActual = otherk }
kDiamond _ x = throw KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = KType, kActual = x }
kVar tyVar =
case lookup tyVar quantifiedVariables of
Just kind -> return kind
Nothing -> do
st <- get
case lookup tyVar (tyVarContext st) of
Just (kind, _) -> return kind
Nothing -> throw UnboundTypeVariable{ errLoc = s, errId = tyVar }
kApp (KFun k1 k2) kArg = do
kLub <- k1 `hasLub` kArg
if kLub
then return k2
else throw KindMismatch
{ errLoc = s
, tyActualK = Nothing
, kActual = kArg
, kExpected = k1 }
kApp k kArg = throw KindMismatch
{ errLoc = s
, tyActualK = Nothing
, kExpected = (KFun kArg (KVar $ mkId "..."))
, kActual = k
}
kInt _ = return $ kConstr $ mkId "Nat"
kInfix (tyOps -> (k1exp, k2exp, kret)) k1act k2act = do
kLub <- k1act `hasLub` k1exp
if not kLub
then throw
KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = k1exp, kActual = k1act}
else do
kLub' <- k2act `hasLub` k2exp
if not kLub'
then throw
KindMismatch{ errLoc = s, tyActualK = Nothing, kExpected = k2exp, kActual = k2act}
else pure kret
kSet ks =
-- If the set is empty, then it could have any kind, so we need to make
-- a kind which is `KPromote (Set a)` for some type variable `a` of unknown kind
if null ks
then do
-- create fresh polymorphic kind variable for this type
vark <- freshIdentifierBase $ "set_elemk"
-- remember this new kind variable in the kind environment
modify (\st -> st { tyVarContext = (mkId vark, (KType, InstanceQ))
: tyVarContext st })
-- Create a fresh type variable
var <- freshTyVarInContext (mkId $ "set_elem[" <> pretty (startPos s) <> "]") (KPromote $ TyVar $ mkId vark)
return $ KPromote $ TyApp (TyCon $ mkId "Set") (TyVar var)
-- Otherwise, everything in the set has to have the same kind
else
if foldr (\x r -> (x == head ks) && r) True ks
then -- check if there is an alias (name) for sets of this kind
case lookup (head ks) setElements of
-- Lift this alias to the kind level
Just t -> return $ KPromote t
Nothing ->
-- Return a set type lifted to a kind
case demoteKindToType (head ks) of
Just t -> return $ KPromote $ TyApp (TyCon $ mkId "Set") t
-- If the kind cannot be demoted then we shouldn't be making a set
Nothing -> throw $ KindCannotFormSet s (head ks)
-- Find the first occurence of a change in kind:
else throw $ KindMismatch { errLoc = s , tyActualK = Nothing, kExpected = head left, kActual = head right }
where (left, right) = partition (\x -> (head ks) == x) ks
-- | Compute the join of two kinds, if it exists
joinKind :: (?globals :: Globals) => Kind -> Kind -> Checker (Maybe (Kind, Substitution))
joinKind k1 k2 | k1 == k2 = return $ Just (k1, [])
joinKind (KVar v) k = return $ Just (k, [(v, SubstK k)])
joinKind k (KVar v) = return $ Just (k, [(v, SubstK k)])
joinKind (KPromote t1) (KPromote t2) = do
(coeffTy, _) <- mguCoeffectTypes nullSpan t1 t2
return $ Just (KPromote coeffTy, [])
joinKind (KUnion k1 k2) k = do
jK1 <- joinKind k k1
case jK1 of
Nothing -> do
jK2 <- joinKind k k2
case jK2 of
Nothing -> return $ Nothing
Just (k2', u) -> return $ Just (KUnion k1 k2', u)
Just (k1', u) -> return $ Just (KUnion k1' k2, u)
joinKind k (KUnion k1 k2) = joinKind (KUnion k1 k2) k
joinKind _ _ = return $ Nothing
-- | Predicate on whether two kinds have a leasy upper bound
hasLub :: (?globals :: Globals) => Kind -> Kind -> Checker Bool
hasLub k1 k2 = do
jK <- joinKind k1 k2
case jK of
Nothing -> return False
Just _ -> return True
-- | Infer the type of ta coeffect term (giving its span as well)
inferCoeffectType :: (?globals :: Globals) => Span -> Coeffect -> Checker Type
inferCoeffectType s c = do
st <- get
inferCoeffectTypeInContext s (map (\(id, (k, _)) -> (id, k)) (tyVarContext st)) c
inferCoeffectTypeInContext :: (?globals :: Globals) => Span -> Ctxt Kind -> Coeffect -> Checker Type
-- Coeffect constants have an obvious kind
inferCoeffectTypeInContext _ _ (Level _) = return $ TyCon $ mkId "Level"
inferCoeffectTypeInContext _ _ (CNat _) = return $ TyCon $ mkId "Nat"
inferCoeffectTypeInContext _ _ (CFloat _) = return $ TyCon $ mkId "Q"
inferCoeffectTypeInContext _ _ (CSet _) = return $ TyCon $ mkId "Set"
inferCoeffectTypeInContext s ctxt (CProduct c1 c2) = do
k1 <- inferCoeffectTypeInContext s ctxt c1
k2 <- inferCoeffectTypeInContext s ctxt c2
return $ TyApp (TyApp (TyCon $ mkId "×") k1) k2
inferCoeffectTypeInContext s ctxt (CInterval c1 c2) = do
(k, _) <- mguCoeffectTypesFromCoeffects s c1 c2
return $ TyApp (TyCon $ mkId "Interval") k
-- Take the join for compound coeffect epxressions
inferCoeffectTypeInContext s _ (CPlus c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
inferCoeffectTypeInContext s _ (CMinus c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
inferCoeffectTypeInContext s _ (CTimes c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
inferCoeffectTypeInContext s _ (CMeet c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
inferCoeffectTypeInContext s _ (CJoin c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
inferCoeffectTypeInContext s _ (CExpon c c') = fmap fst $ mguCoeffectTypesFromCoeffects s c c'
-- Coeffect variables should have a type in the cvar->kind context
inferCoeffectTypeInContext s ctxt (CVar cvar) = do
st <- get
case lookup cvar ctxt of
Nothing -> do
throw UnboundTypeVariable{ errLoc = s, errId = cvar }
-- state <- get
-- let newType = TyVar $ "ck" <> show (uniqueVarId state)
-- We don't know what it is yet though, so don't update the coeffect kind ctxt
-- put (state { uniqueVarId = uniqueVarId state + 1 })
-- return newType
Just (KVar name) -> return $ TyVar name
Just (KPromote t) -> checkKindIsCoeffect s ctxt t
Just k -> throw
KindMismatch{ errLoc = s, tyActualK = Just $ TyVar cvar, kExpected = KPromote (TyVar $ mkId "coeffectType"), kActual = k }
inferCoeffectTypeInContext s ctxt (CZero t) = checkKindIsCoeffect s ctxt t
inferCoeffectTypeInContext s ctxt (COne t) = checkKindIsCoeffect s ctxt t
inferCoeffectTypeInContext s ctxt (CInfinity (Just t)) = checkKindIsCoeffect s ctxt t
-- Unknown infinity defaults to the interval of extended nats version
inferCoeffectTypeInContext s ctxt (CInfinity Nothing) = return (TyApp (TyCon $ mkId "Interval") extendedNat)
inferCoeffectTypeInContext s ctxt (CSig _ t) = checkKindIsCoeffect s ctxt t
inferCoeffectTypeAssumption :: (?globals :: Globals)
=> Span -> Assumption -> Checker (Maybe Type)
inferCoeffectTypeAssumption _ (Linear _) = return Nothing
inferCoeffectTypeAssumption s (Discharged _ c) = do
t <- inferCoeffectType s c
return $ Just t
checkKindIsCoeffect :: (?globals :: Globals) => Span -> Ctxt Kind -> Type -> Checker Type
checkKindIsCoeffect span ctxt ty = do
kind <- inferKindOfTypeInContext span ctxt ty
case kind of
k | isCoeffectKind k -> return ty
-- Came out as a promoted type, check that this is a coeffect
KPromote k -> do
kind' <- inferKindOfTypeInContext span ctxt k
if isCoeffectKind kind'
then return ty
else throw KindMismatch{ errLoc = span, tyActualK = Just ty, kExpected = KCoeffect, kActual = kind }
KVar v ->
case lookup v ctxt of
Just k | isCoeffectKind k -> return ty
_ -> throw KindMismatch{ errLoc = span, tyActualK = Just ty, kExpected = KCoeffect, kActual = kind }
_ -> throw KindMismatch{ errLoc = span, tyActualK = Just ty, kExpected = KCoeffect, kActual = kind }
-- Find the most general unifier of two coeffects
-- This is an effectful operation which can update the coeffect-kind
-- contexts if a unification resolves a variable
mguCoeffectTypesFromCoeffects :: (?globals :: Globals)
=> Span -> Coeffect -> Coeffect -> Checker (Type, (Coeffect -> Coeffect, Coeffect -> Coeffect))
mguCoeffectTypesFromCoeffects s c1 c2 = do
coeffTy1 <- inferCoeffectType s c1
coeffTy2 <- inferCoeffectType s c2
mguCoeffectTypes s coeffTy1 coeffTy2
-- Given a type term, works out if its kind is actually an effect type (promoted)
-- if so, returns `Right effTy` where `effTy` is the effect type
-- otherwise, returns `Left k` where `k` is the kind of the original type term
isEffectType :: (?globals :: Globals) => Span -> Type -> Checker (Either Kind Type)
isEffectType s ty = do
kind <- inferKindOfType s ty
isEffectTypeFromKind s kind
isEffectTypeFromKind :: (?globals :: Globals) => Span -> Kind -> Checker (Either Kind Type)
isEffectTypeFromKind s kind =
case kind of
KPromote effTy -> do
kind' <- inferKindOfType s effTy
if isEffectKind kind'
then return $ Right effTy
else return $ Left kind
_ -> return $ Left kind | dorchard/gram_lang | frontend/src/Language/Granule/Checker/Kinds.hs | bsd-3-clause | 12,958 | 0 | 20 | 3,617 | 3,710 | 1,914 | 1,796 | -1 | -1 |
import Diagrams.Backend.Cairo.CmdLine
import Diagrams.TwoD.Apollonian
main = defaultMain (apollonianGasket (1/500) 1 1 1) | diagrams/diagrams-test | misc/ApollonianTest.hs | bsd-3-clause | 122 | 1 | 9 | 12 | 44 | 23 | 21 | 3 | 1 |
module Evaluator where
import Tokenizer
import Conversion
import Data.IORef
import Data.Maybe
import Data.List
import Control.Monad.Error
import Control.Monad.Reader
import Control.Monad.Trans.Class
import qualified Data.Traversable as Traversable
import Debug.Trace
data PHPError = UndefinedVariable String
| NotEnoughArguments String
| NotFound String String
| Default String
showPHPError :: PHPError -> String
showPHPError (UndefinedVariable s) = "undefined variable: " ++ s
showPHPError (NotEnoughArguments s) = "Function '" ++ s ++ "' was not passed enough arguments"
showPHPError (NotFound msg name) = msg ++ ": " ++ name
showPHPError (Default s) = "error: " ++ s
instance Show PHPError where
show = showPHPError
instance Error PHPError where
noMsg = Default "Error"
strMsg = Default
type PHPFunctionType = [PHPValue] -> PHPEval PHPValue
type VariableList = [(String, IORef PHPValue)]
type VariableEnv = IORef VariableList
type FunctionList = [(String, PHPFunctionType)]
type FunctionEnv = IORef FunctionList
type IniSetting = (String, IORef String)
type IniSettings = IORef [IniSetting]
type FunctionStatics = [(String, IORef PHPValue)]
type FunctionStaticEnv = IORef [(String, IORef FunctionStatics)]
data EvalConfig = EvalConfig { variableEnv :: VariableEnv
, functionEnv :: FunctionEnv
, globalRef :: Maybe VariableEnv
, outputHandler :: String -> IO ()
, iniSettings :: IniSettings
, functionStaticEnv :: FunctionStaticEnv
, currentFunction :: Maybe String
}
type ErrMonad = ErrorT PHPError IO
type PHPEval = ReaderT EvalConfig ErrMonad
emptyEnv :: IO (IORef [a])
emptyEnv = newIORef []
defaultConfig :: IO EvalConfig
defaultConfig = do
v <- emptyEnv
f <- emptyEnv
i <- emptyEnv
s <- emptyEnv
return $ EvalConfig v f Nothing putStr i s Nothing
output :: String -> PHPEval ()
output s = do
fn <- liftM outputHandler ask
liftIO $ fn s
getRef :: (EvalConfig -> IORef a) -> PHPEval (IORef a)
getRef accessor = liftM accessor ask
readRef :: (EvalConfig -> IORef a) -> PHPEval a
readRef accessor = getRef accessor >>= liftIO . readIORef
pushRef :: IORef [a] -> a -> PHPEval ()
pushRef ref val = liftIO $ do
list <- readIORef ref
writeIORef ref (val : list)
getCurrentFunction :: PHPEval (Maybe String)
getCurrentFunction = liftM currentFunction ask
getFunctionStatics :: String -> PHPEval FunctionStatics
getFunctionStatics fn = do
statics <- readRef functionStaticEnv
case lookup fn statics of
Nothing -> return []
Just ref -> liftIO $ readIORef ref
putFunctionStatics :: String -> StaticVar -> PHPEval (IORef PHPValue)
putFunctionStatics func (StaticVar name mval) = do
mref <- readRef functionStaticEnv >>= return . (lookup name)
valref <- liftIO $ newIORef $ fromMaybe PHPNull mval
case mref of
Just fref -> do
statics <- liftIO $ readIORef fref
case lookup name statics of
Nothing -> do
pushRef fref (name, valref)
return valref
Just _ -> return valref
Nothing -> do
statics <- liftIO $ newIORef [(name, valref)]
fse <- getRef functionStaticEnv
pushRef fse (func, statics)
return valref
lookupIniSetting :: String -> PHPEval (Maybe String)
lookupIniSetting v = do
settings <- readRef iniSettings
r <- liftIO $ Traversable.sequence $ fmap readIORef $ lookup v settings
return r
setIniSetting :: String -> String -> PHPEval ()
setIniSetting s v = do
allRef <- getRef iniSettings
settings <- liftIO $ readIORef allRef
case lookup s settings of
Nothing -> liftIO $ do
newRef <- newIORef v
writeIORef allRef ((s, newRef) : settings)
Just oldRef -> do
liftIO $ writeIORef oldRef v
-- returns reference to local var environment
-- could be global, if variable is at root level execution
varEnvRef :: PHPEval VariableEnv
varEnvRef = liftM variableEnv ask
-- returns reference to global var env even if inside a function
globalVarsRef :: PHPEval VariableEnv
globalVarsRef = do
mref <- liftM globalRef ask
case mref of
Nothing -> varEnvRef
Just ref -> return ref
isInFunctionContext :: PHPEval Bool
isInFunctionContext = liftM globalRef ask >>= return . isJust
globalFunctionsRef :: PHPEval FunctionEnv
globalFunctionsRef = liftM functionEnv ask
varDefs :: PHPEval VariableList
varDefs = varEnvRef >>= liftIO . readIORef
isDefined :: String -> PHPEval Bool
isDefined var = varDefs >>= return . isJust . lookup var
getVar :: String -> PHPEval PHPValue
getVar var = do
e <- varDefs
maybe (throwError $ UndefinedVariable var)
(liftIO . readIORef)
(lookup var e)
setVar :: String -> PHPValue -> PHPEval PHPValue
setVar var val = do
ref <- varEnvRef
e <- liftIO $ readIORef ref
defined <- isDefined var
if defined
then liftIO $ do
writeIORef (fromJust $ lookup var e) val
return val
else liftIO $ do
valueRef <- newIORef val
writeIORef ref ((var, valueRef) : e)
return val
setVarRef :: String -> IORef PHPValue -> PHPEval ()
setVarRef var valref = do
ref <- varEnvRef
e <- liftIO $ readIORef ref
defined <- isDefined var
if defined
then liftIO $ do
writeIORef ref $ (var, valref) : fromMaybe e (find ((== var) . fst) e >>= return . (flip delete) e)
return ()
else liftIO $ do
writeIORef ref ((var, valref) : e)
return ()
lookupFunction :: String -> PHPEval (Maybe PHPFunctionType)
lookupFunction name = do
gref <- globalFunctionsRef
globalFuncs <- liftIO $ readIORef gref
return $ lookup name globalFuncs
defineFunction :: String -> [FunctionArgumentDef] -> PHPStmt -> PHPEval ()
defineFunction name args body = do
gref <- globalFunctionsRef
globalFuncs <- liftIO $ readIORef gref
case lookup name globalFuncs of
Just _ -> throwError $ Default ("Cannot redeclare function " ++ name)
Nothing -> liftIO $ do
writeIORef gref ((name, makeFunction name args body) : globalFuncs)
return ()
makeFunction :: String -> [FunctionArgumentDef] -> PHPStmt -> PHPFunctionType
makeFunction name argDefs body =
let requiredArgsCount = length $ dropWhile (isJust . argDefault) $ reverse argDefs
requiredArgsCheck args = when (length args < requiredArgsCount) (throwError $ Default $ "Not enough arguments to function " ++ name)
applyArgs args = mapM (uncurry setVarOrDef) $ zip argDefs $ concat [map Just args, repeat mzero]
setVarOrDef def val = case val of
Just v -> setVar (argName def) v
Nothing -> setVar (argName def) (fromJust $ argDefault def)
in (\args -> do
requiredArgsCheck args
applyArgs args
result <- evalStmt body
case result of
Nothing -> return PHPNull
Just v -> return v
)
evalExpr :: PHPExpr -> PHPEval PHPExpr
evalExpr (BinaryExpr op a b) = do
av <- liftM exprVal (evalExpr a)
bv <- liftM exprVal (evalExpr b)
return $ Literal $ case op of
Add -> phpSum av bv
Subtract -> phpSubtract av bv
Multiply -> phpMultiply av bv
Divide -> case phpDivide av bv of
PHPBool _ -> error "Division by zero"
v -> v
Modulo -> phpModulo av bv
And -> boolAnd av bv
Or -> boolOr av bv
Greater -> boolGreater av bv
Less -> boolLess av bv
Equals -> boolEquals av bv
StrictEquals -> boolStrictEquals av bv
Concat -> PHPString $ (stringFromPHPValue $ castToString av) ++ (stringFromPHPValue $ castToString bv)
evalExpr a@(Literal _) = return a
evalExpr (Assign (PHPVariable varName) expr) = do
v <- liftM exprVal (evalExpr expr)
setVar varName v
return $ Literal v
evalExpr (Assign (PHPVariableVariable vn) expr) = do
var <- getVar vn
evalExpr $ Assign (PHPVariable $ stringFromPHPValue var) expr
evalExpr (Variable (PHPVariable var)) = do
val <- getVar var
return $ Literal val
evalExpr (Variable (PHPVariableVariable vn)) = do
var <- liftM stringFromPHPValue (getVar vn)
evalExpr $ Variable (PHPVariable var)
evalExpr (Call (FunctionCall n) args) = do
mfn <- lookupFunction n
case mfn of
Nothing -> throwError $ NotFound "Function not found" n
Just fn -> do
locals <- liftIO $ emptyEnv
getFunctionStatics n >>= mapM_ (pushRef locals)
globalRef <- globalVarsRef
args' <- mapM evalExpr args
let vals = map exprVal args'
local (localEnv locals globalRef) $ liftM Literal $ fn vals
where
localEnv locals globals env = env { variableEnv = locals, globalRef = Just globals, currentFunction = Just n }
evalExpr (UnaryExpr utype uop var) = case utype of
Before -> runOp uop var >> evalExpr (Variable var)
After -> do
val <- liftM exprVal $ evalExpr (Variable var)
runOp uop var
return $ Literal val
where
runOp op var = do
vn <- varName var
getVar vn >>= runOp' op >>= setVar vn
runOp' _ b@(PHPBool _) = return b
runOp' Increment PHPNull = return $ PHPInt 1
runOp' Decrement PHPNull = return PHPNull
runOp' _ (PHPString _) = error "undefined behavior for string unary op"
runOp' op (PHPFloat f) = return $ PHPFloat (numOp op f)
runOp' op (PHPInt i) = return $ PHPInt (numOp op i)
numOp op num = case op of
Increment -> num + 1
Decrement -> num - 1
evalExpr (Isset vars) = liftM Literal $ isset vars
where isset [] = return $ PHPBool True
isset ((PHPVariable x):xs) = do
defs <- varDefs
case lookup x defs of
Nothing -> return $ PHPBool False
Just ref -> do
val <- liftIO $ readIORef ref
case val of
PHPNull -> return $ PHPBool False
_ -> isset xs
evalExpr (Print expr) = evalExpr expr >>= phpEcho . (:[]) . exprVal >> (return $ Literal $ PHPInt 1)
varName :: PHPVariable -> PHPEval String
varName (PHPVariable n) = return n
varName (PHPVariableVariable vv) = liftM stringFromPHPValue $ getVar vv
exprVal :: PHPExpr -> PHPValue
exprVal (Literal v) = v
exprVal _ = error "Value that are not literals must be evaluated first"
stmtVal :: PHPStmt -> PHPValue
stmtVal (Expression e) = exprVal e
stmtVal _ = error "Only expressions can be evaluated into values"
stringFromPHPValue :: PHPValue -> String
stringFromPHPValue (PHPString s) = s
stringFromPHPValue _ = error "Non-PHPString values shouldn't be attempted to be converted to plain strings"
evalStmt :: PHPStmt -> PHPEval (Maybe PHPValue)
evalStmt (Seq xs) = foldSeq xs
where foldSeq (x:xs) = do
result <- evalStmt x
case result of
Nothing -> foldSeq xs
Just v -> return $ Just v
foldSeq [] = return Nothing
evalStmt (Expression expr) = evalExpr expr >> return Nothing
evalStmt (Function name argDefs body) = defineFunction name argDefs body >> return Nothing
evalStmt (Return expr) = liftM (Just . exprVal) (evalExpr expr)
evalStmt (Echo exs) = mapM evalExpr exs >>= phpEcho . map exprVal >> return Nothing
evalStmt (Static vars) = mapM makeStatic vars >> return Nothing
where makeStatic var@(StaticVar name mval) = do
mfunc <- getCurrentFunction
case mfunc of
Nothing -> return ()
Just func -> do
statics <- getFunctionStatics func
case lookup name statics of
Nothing -> do
putFunctionStatics func var >>= setVarRef name
return ()
_ -> return ()
evalStmt (Global var) = do
hasCtx <- isInFunctionContext
if hasCtx == False
then return Nothing
else do
name <- varName var
globals <- globalVarsRef >>= liftIO . readIORef
locals <- varDefs
localRef <- varEnvRef
maybe (return Nothing)
(\ref -> do
liftIO $ writeIORef localRef $ (name, ref) : fromMaybe locals (find ((== name) . fst) locals >>= return . (flip delete) locals)
return Nothing)
(lookup name globals)
evalStmt (If condExpr body mElse) = do
condResult <- liftM exprVal $ evalExpr condExpr
if isTruthy condResult
then evalStmt body
else maybe (return Nothing) evalElseExpr mElse
evalStmt w@(While cond body) = do
condResult <- liftM exprVal $ evalExpr cond
if isTruthy condResult
then do
evalStmt body
evalStmt w
else return Nothing
evalStmt (For init cond iter body) = do
mapM_ evalExpr init
forMain cond iter body
return Nothing
where
forMain cond iter body = do
condTrue <- mapM evalExpr cond >>= return . all (isTruthy . exprVal)
when (condTrue || length cond == 0) $ void $ evalStmt body
mapM_ evalExpr iter
when (condTrue || length cond == 0) $ forMain cond iter body
evalElseExpr :: ElseExpr -> PHPEval (Maybe PHPValue)
evalElseExpr (Else stmt) = evalStmt stmt
evalElseExpr (ElseIf condExpr body mElse) = evalStmt $ If condExpr body mElse
evalParseResult :: ParseResult -> PHPEval String
evalParseResult (PlainText t) = output t >> return t
evalParseResult (PHPCode stmt) = do
res <- evalStmt stmt
case res of
Nothing -> return ""
Just v -> return $ stringFromPHPValue $ castToString v
evalParseResults :: [ParseResult] -> PHPEval String
evalParseResults rs = liftM concat $ mapM evalParseResult rs
runPHPEval :: EvalConfig -> (PHPEval a) -> IO (Either PHPError a)
runPHPEval config eval = runErrorT $ runReaderT eval config
phpEcho :: PHPFunctionType
phpEcho xs = mapM (output . stringFromPHPValue . castToString) xs >> return PHPNull
| jhartikainen/hs-language-php | Evaluator.hs | bsd-3-clause | 14,793 | 0 | 23 | 4,563 | 4,699 | 2,251 | 2,448 | 342 | 24 |
{-# LANGUAGE TupleSections #-}
module Day17 where
-- Improvements to Day12
import Control.Monad (when)
import Control.Monad.Gen
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Either
import qualified Data.Map as Map
data Type
= Function Type Type
| RecordT [(String, Type)]
| VariantT [(String, Type)]
deriving (Eq, Show)
data CheckTerm
-- neither a constructor nor change of direction
= Let InferTerm Type (InferTerm -> CheckTerm)
| Gen Int Type
-- switch direction (check -> infer)
| Neutral InferTerm
-- constructors
-- \x -> CheckedTerm
| Abs (CheckTerm -> CheckTerm)
| Record [(String, CheckTerm)]
| Variant String CheckTerm
data InferTerm
-- switch direction (infer -> check)
= Annot CheckTerm Type
-- eliminators
--
-- note that eliminators always take an InferTerm as the inspected term,
-- since that's the neutral position, then CheckTerms for the rest
| App InferTerm CheckTerm
| AccessField InferTerm String
| Case InferTerm Type [(String, CheckTerm -> CheckTerm)]
-- xxx = error "not yet implemented"
-- eval :: InferTerm -> EvalCtx CheckTerm
-- eval t = case t of
-- Annot cTerm _ -> return cTerm
-- App f x -> do
-- f' <- eval f
-- case f' of
-- Neutral _ -> xxx
-- Abs f'' -> return $ f'' x
-- AccessField iTm name _ -> do
-- evaled <- eval iTm
-- case evaled of
-- Neutral _ -> return $ Neutral (AccessField xxx xxx xxx)
-- Record fields -> case Map.lookup name (Map.fromList fields) of
-- Just field -> return field
-- Nothing -> left "didn't find field in record"
-- _ -> left "unexpected"
-- Case iTm _ branches -> do
-- evaled <- eval iTm
-- case evaled of
-- Neutral _ -> xxx
-- Variant name cTm -> case Map.lookup name (Map.fromList branches) of
-- Just branch -> return $ branch evaled
type EvalCtx = EitherT String (Gen Int)
type CheckCtx = EitherT String (Gen Int)
runChecker :: CheckCtx () -> String
runChecker calc = case runGen (runEitherT calc) of
Right () -> "success!"
Left str -> str
unifyTy :: Type -> Type -> CheckCtx Type
unifyTy (Function dom1 codom1) (Function dom2 codom2) =
Function <$> unifyTy dom1 dom2 <*> unifyTy codom1 codom2
unifyTy (RecordT lTy) (RecordT rTy) = do
-- RecordT [(String, Type)]
-- Take the intersection of possible records. Make sure the overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
return $ RecordT (Map.toList isect')
unifyTy (VariantT lTy) (VariantT rTy) = do
-- Take the union of possible variants. Make sure overlap matches!
let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy)
isect' <- mapM (uncurry unifyTy) isect
let union = Map.union (Map.fromList lTy) (Map.fromList rTy)
-- Overwrite with extra data we may have learned from unifying the types in
-- the intersection
let result = Map.union isect' union
return $ VariantT (Map.toList result)
unifyTy l r = left ("failed unification " ++ show (l, r))
check :: CheckTerm -> Type -> CheckCtx ()
check tm ty = case tm of
-- t1: infered, t2: infer -> check
Let t1 ty' body -> do
t1Ty <- infer t1
_ <- unifyTy t1Ty ty'
let bodyVal = body t1
check bodyVal ty
Gen _ ty' -> do
_ <- unifyTy ty ty'
return ()
Neutral iTm -> do
iTy <- infer iTm
_ <- unifyTy ty iTy
return ()
Abs t' -> do
let Function domain codomain = ty
v <- Gen <$> lift gen <*> pure domain
let evaled = t' v
check evaled codomain
Record fields -> do
-- Record [(String, CheckTerm)]
--
-- Here we define our notion of record subtyping -- we check that the
-- record we've been given has at least the fields expected of it and of
-- the right type.
let fieldMap = Map.fromList fields
case ty of
RecordT fieldTys -> mapM_
(\(name, subTy) -> do
case Map.lookup name fieldMap of
Just subTm -> check subTm subTy
Nothing -> left "failed to find required field in record"
)
fieldTys
_ -> left "failed to check a record against a non-record type"
Variant name t' -> do
-- Variant String CheckTerm
--
-- Here we define our notion of variant subtyping -- we check that the
-- variant we've been given is in the row
case ty of
VariantT fieldTys -> case Map.lookup name (Map.fromList fieldTys) of
Just expectedTy -> check t' expectedTy
Nothing -> left "failed to find required field in record"
_ -> left "failed to check a record against a non-record type"
infer :: InferTerm -> CheckCtx Type
infer t = case t of
Annot _ ty -> pure ty
App t1 t2 -> do
Function domain codomain <- infer t1
check t2 domain
return codomain
-- rec.name
AccessField recTm name -> do
inspectTy <- infer recTm
case inspectTy of
RecordT parts -> case Map.lookup name (Map.fromList parts) of
Just subTy -> do
return subTy
Nothing -> left "didn't find the accessed key"
_ -> left "found non-record unexpectedly"
-- (case [varTm] of [cases]) : [ty]
Case varTm ty cases -> do
-- check that the inspected value is a variant,
-- check all of its cases and the branches to see if all are aligned,
-- finally that each typechecks
varTmTy <- infer varTm
case varTmTy of
VariantT tyParts -> do
let tyMap = Map.fromList tyParts
caseMap = Map.fromList cases
bothMatch = (Map.null (tyMap Map.\\ caseMap))
&& (Map.null (caseMap Map.\\ tyMap))
when (not bothMatch) (left "case misalignment")
let mergedMap = Map.mergeWithKey
(\name l r -> Just (name, l, r))
(const (Map.fromList []))
(const (Map.fromList []))
tyMap
caseMap
mapM_
(\(_name, branchTy, rhs) -> do
v <- Gen <$> lift gen <*> pure branchTy
check (rhs v) ty
)
mergedMap
_ -> left "found non-variant in case"
return ty
main :: IO ()
main = do
let unit = Record []
unitTy = RecordT []
xy = Record
[ ("x", unit)
, ("y", unit)
]
xyTy = RecordT
[ ("x", unitTy)
, ("y", unitTy)
]
-- boring
print $ runChecker $
let tm = Abs (\x -> x)
ty = Function unitTy unitTy
in check tm ty
-- standard record
print $ runChecker $
let tm = Let
(Annot xy xyTy)
xyTy
(\x -> Neutral
(AccessField x "x")
)
in check tm unitTy
-- record subtyping
print $ runChecker $
let xRecTy = RecordT [("x", unitTy)]
tm = Let
(Annot xy xRecTy)
xRecTy
(\x -> Neutral
(AccessField x "x")
)
in check tm unitTy
-- variant subtyping
--
-- left () : { left () | right () }
print $ runChecker $
let eitherTy = VariantT
[ ("left", unitTy)
, ("right", unitTy)
]
in check (Variant "left" unit) eitherTy
-- let x = left () : { left : () | right : () }
-- in case x of
-- left y -> y
-- right y -> y
print $ runChecker $
let eitherTy = VariantT
[ ("left", unitTy)
, ("right", unitTy)
]
tm = Let
(Annot (Variant "left" unit) eitherTy)
eitherTy
(\x -> Neutral
(Case x unitTy
[ ("left", \y -> y)
, ("right", \y -> y)
]
)
)
in check tm unitTy
| joelburget/daily-typecheckers | src/Day18.hs | bsd-3-clause | 7,686 | 0 | 23 | 2,367 | 1,998 | 1,016 | 982 | 162 | 10 |
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_scalar_block_layout - device extension
--
-- == VK_EXT_scalar_block_layout
--
-- [__Name String__]
-- @VK_EXT_scalar_block_layout@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 222
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Deprecation state__]
--
-- - /Promoted/ to
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.2-promotions Vulkan 1.2>
--
-- [__Contact__]
--
-- - Tobias Hector
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_scalar_block_layout] @tobski%0A<<Here describe the issue or question you have about the VK_EXT_scalar_block_layout extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2018-11-14
--
-- [__Interactions and External Dependencies__]
--
-- - Promoted to Vulkan 1.2 Core
--
-- [__Contributors__]
--
-- - Jeff Bolz
--
-- - Jan-Harald Fredriksen
--
-- - Graeme Leese
--
-- - Jason Ekstrand
--
-- - John Kessenich
--
-- == Description
--
-- This extension enables C-like structure layout for SPIR-V blocks. It
-- modifies the alignment rules for uniform buffers, storage buffers and
-- push constants, allowing non-scalar types to be aligned solely based on
-- the size of their components, without additional requirements.
--
-- == Promotion to Vulkan 1.2
--
-- Functionality in this extension is included in core Vulkan 1.2, with the
-- EXT suffix omitted. However, if Vulkan 1.2 is supported and this
-- extension is not, the @scalarBlockLayout@ capability is optional. The
-- original type, enum and command names are still available as aliases of
-- the core functionality.
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceFeatures2',
-- 'Vulkan.Core10.Device.DeviceCreateInfo':
--
-- - 'PhysicalDeviceScalarBlockLayoutFeaturesEXT'
--
-- == New Enum Constants
--
-- - 'EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME'
--
-- - 'EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT'
--
-- == Version History
--
-- - Revision 1, 2018-11-14 (Tobias Hector)
--
-- - Initial draft
--
-- == See Also
--
-- 'PhysicalDeviceScalarBlockLayoutFeaturesEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_scalar_block_layout Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_scalar_block_layout ( pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT
, PhysicalDeviceScalarBlockLayoutFeaturesEXT
, EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION
, pattern EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION
, EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME
, pattern EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME
) where
import Data.String (IsString)
import Vulkan.Core12.Promoted_From_VK_EXT_scalar_block_layout (PhysicalDeviceScalarBlockLayoutFeatures)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES))
-- No documentation found for TopLevel "VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT"
pattern STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT = STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES
-- No documentation found for TopLevel "VkPhysicalDeviceScalarBlockLayoutFeaturesEXT"
type PhysicalDeviceScalarBlockLayoutFeaturesEXT = PhysicalDeviceScalarBlockLayoutFeatures
type EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION"
pattern EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION = 1
type EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME = "VK_EXT_scalar_block_layout"
-- No documentation found for TopLevel "VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME"
pattern EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME = "VK_EXT_scalar_block_layout"
| expipiplus1/vulkan | src/Vulkan/Extensions/VK_EXT_scalar_block_layout.hs | bsd-3-clause | 4,846 | 0 | 8 | 925 | 268 | 204 | 64 | -1 | -1 |
module Main where
import System.Environment(getArgs)
import Data.Char (isDigit, digitToInt)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import Data.List (sortBy, groupBy, nub, sort, unfoldr)
import ExactCover
import Test.QuickCheck
import Control.Monad
textToRawSudoku :: String -> [(Int,Int,Int)]
textToRawSudoku = concatMap lineToLists . zip [0..8] . lines
lineToLists :: (Int, String) -> [(Int,Int,Int)]
lineToLists (row, str) = concatMap f (zip [0..8] str)
where f (col, chr)
|isDigit chr = [(row, col, digitToInt chr)]
| otherwise = map (\x -> (row, col, x)) [1..9]
rowConstraints :: (Int,Int,Int) -> [Bool]
rowConstraints (x,y,z) = map f [0..80]
where f num = x*9 + (z-1) == num
colConstraints :: (Int, Int, Int) -> [Bool]
colConstraints (x,y,z) = map f [0..80]
where f num = y*9 + (z-1) == num
blockConstraints :: (Int, Int, Int) -> [Bool]
blockConstraints (x,y,z) = map f [0..80]
where blockNum = cellToBlock x y
f num = blockNum * 9 + (z-1) == num
cellToBlock row col = blockR * 3 + blockC
blockR = div x 3
blockC = div y 3
cellConstraints :: (Int, Int, Int) -> [Bool]
cellConstraints (x,y,z) = map f [0..80]
where f num = x*9 + y == num
constraints x = (rowConstraints x) ++ (colConstraints x) ++ (blockConstraints x) ++ (cellConstraints x)
toExactCover :: [(Int,Int,Int)] -> EC
toExactCover = fromBoolLists . map constraints
solveSudoku text = case textToRawSudoku text of
rawSudoku -> case solve $ toExactCover rawSudoku of
Nothing -> putStrLn "No solution"
Just x -> printSoln $ map (rawSudoku !!) x
sortTriple :: (Int,Int,Int) -> (Int, Int,Int) -> Ordering
sortTriple (x1,y1,_) (x2,y2,_) = compare (x1,y1) (x2, y2)
groupTriple :: (Int, Int,Int) -> (Int,Int,Int) -> Bool
groupTriple (x1,_,_) (x2,_,_) = x1 == x2
showTriple (x,y,z) = show z
printSoln :: [(Int,Int,Int)] -> IO ()
printSoln x = do
mapM_ putStrLn . map (concatMap showTriple) . groupBy groupTriple . sortBy sortTriple $ x
putStrLn "---------"
runFile :: String -> IO ()
runFile fileName = do
putStrLn ("solving " ++ fileName)
text <- readFile fileName
solveSudoku text
main :: IO ()
main = do
args <- getArgs
case args of
[f1,f2,f3,f4,f5] -> do
rawsam <- readFiveFiles (f1,f2,f3,f4,f5)
solveSamuraiCover rawsam
_ -> mapM_ runFile args
data SudokuPos = TL
| TR
| M
| BR
| BL
deriving (Eq, Show)
data SamuraiPos = SamuraiPos !SudokuPos !Int !Int !Int
deriving (Eq, Show)
groupSamuraiPos (SamuraiPos p1 _ _ _) (SamuraiPos p2 _ _ _) = p1 == p2
samuraiPosToTriple (SamuraiPos _ x y z) = (x,y,z)
tripleToSamuraiPos spos (x,y,z) = SamuraiPos spos x y z
type RawSamurai = V.Vector SamuraiPos
textToRawSamurai spos = map (tripleToSamuraiPos spos) . textToRawSudoku
readFiveFiles (f1,f2,f3,f4,f5) = do
p1 <- readFile f1
p2 <- readFile f2
p3 <- readFile f3
p4 <- readFile f4
p5 <- readFile f5
return (V.fromList $ (textToRawSamurai TL p1) ++ (textToRawSamurai TR p2) ++ (filter filterMs $textToRawSamurai M p3) ++ (textToRawSamurai BL p4) ++ (textToRawSamurai BR p5))
spos2Index TL = 0
spos2Index TR = 1
spos2Index M = 2
spos2Index BL = 3
spos2Index BR = 4
isOverLap :: SudokuPos -> Int -> Int -> Bool
isOverLap TL r c = r > 5 && c > 5
isOverLap TR r c = r > 5 && c < 3
isOverLap M r c = or [r < 3 && c < 3, r < 3 && c > 5, r > 5 && c < 3 , r > 5 && c > 5]
isOverLap BL r c = r < 3 && c > 5
isOverLap BR r c = r < 3 && c < 3
mCell :: SudokuPos -> Int -> Int -> (Int,Int)
mCell TL r c = (r - 6, c - 6)
mCell TR r c = (r - 6 , c + 6)
mCell M r c = (r,c)
mCell BL r c = (r + 6, c - 6)
mCell BR r c = (r + 6, c + 6)
filterMs :: SamuraiPos -> Bool
filterMs (SamuraiPos M r c v) = not $ isOverLap M r c
filterMs _ = True
mOverLapRows r c
| r < 3 && c < 3 = [(spos2Index TL) * 81 + r * 9 + (c-1)]
| r < 3 && c > 5 = [(spos2Index TR) * 81 + r * 9 + (c-1)]
| r > 5 && c < 3 = [(spos2Index BL) * 81 + r * 9 + (c-1)]
| r > 5 && c > 5 = [(spos2Index BR) * 81 + r * 9 + (c-1)]
| otherwise = []
mOverLapCols r c v
| c < 3 && c < 3 = [(spos2Index TL) * 81 + c * 9 + (v-1)]
| c < 3 && c > 5 = [(spos2Index TR) * 81 + c * 9 + (v-1)]
| c > 5 && c < 3 = [(spos2Index BL) * 81 + c * 9 + (v-1)]
| c > 5 && c > 5 = [(spos2Index BR) * 81 + c * 9 + (v-1)]
| otherwise = []
withTrueAt1 :: Int -> UV.Vector Bool
withTrueAt1 pos = (UV.replicate 405 False) UV.// [(pos, True)]
withTrueAt :: [Int] -> UV.Vector Bool
withTrueAt poss = (UV.replicate 405 False) UV.// (zip poss $ repeat True)
samuraiRC :: SamuraiPos -> UV.Vector Bool
samuraiRC (SamuraiPos spos r c v) = withTrueAt ((i*81 + r*9 + v-1):rest)
where i = spos2Index spos
m = spos2Index M
(mr,mc) = mCell spos r c
rest = if isOverLap spos r c
then [m*81 + mr*9 + v - 1]
else []
samuraiCC :: SamuraiPos -> UV.Vector Bool
samuraiCC (SamuraiPos spos r c v) = withTrueAt ((i*81 + c*9 + v-1):rest)
where i = spos2Index spos
m = spos2Index M
(mr,mc) = mCell spos r c
rest = if isOverLap spos r c
then [m*81 + mc*9 + v - 1]
else []
samuraiCellCons :: SamuraiPos -> UV.Vector Bool
samuraiCellCons (SamuraiPos spos r c v) = withTrueAt $ (i*81 + r*9 + c):rest
where i = spos2Index spos
m = spos2Index M
(mr,mc) = mCell spos r c
rest = if isOverLap spos r c
then [m*81 + mr*9 + c]
else []
samuraiBC :: SamuraiPos -> UV.Vector Bool
samuraiBC (SamuraiPos spos r c v) = withTrueAt $ (i*81 + blockIndex * 9 + (v - 1)):rest
where i = spos2Index spos
m = spos2Index M
(mr,mc) = mCell spos r c
blockR = div r 3
blockC = div c 3
blockIndex = blockR * 3 + blockC
mBlockIndex = (div mr 3)*3 + (div mc 3)
rest = if isOverLap spos r c
then [m*81 + mBlockIndex*9 + (v-1)]
else []
samuraiConstraints x = (samuraiRC x) UV.++ (samuraiCC x) UV.++ (samuraiBC x) UV.++ (samuraiCellCons x)
toSamuraiCover :: RawSamurai -> EC
toSamuraiCover rawsam = fromTable table rowCount colCount
where table = V.map samuraiConstraints rawsam
colCount = UV.length (table V.! 0)
rowCount = V.length rawsam
solveSamuraiCover rawsam =
case solve $ toSamuraiCover rawsam of
Nothing -> putStrLn "No Solution"
Just x -> printSamuraiSol $ map (rawsam V.!) x
printSamuraiSol :: [SamuraiPos] -> IO ()
printSamuraiSol = mapM_ printSoln . map (map samuraiPosToTriple) . groupBy groupSamuraiPos
-- Tests
newtype Cell = Cell (Int,Int,Int)
deriving Show
arbitraryTriple :: Gen Cell
arbitraryTriple = do
r <- choose (0,8)
c <- choose (0,8)
v <- choose (1,9)
return $ Cell (r,c,v)
instance Arbitrary Cell where
arbitrary = arbitraryTriple
prop_rcLength :: Cell -> Bool
prop_rcLength (Cell x) = (length $ rowConstraints x) == 81
prop_rcTrueCount :: Cell -> Bool
prop_rcTrueCount (Cell x) = (length . filter id $ rowConstraints x) == 1
prop_rcColIndependence :: Cell -> Bool
prop_rcColIndependence (Cell (r,c,v)) =
let
rowcons = rowConstraints (r,c,v)
f x = rowConstraints (r,x,v)
in
case nub $ map f [0..8] of
[h] -> rowcons == h
_ -> False
prop_rcTruePos :: Cell -> Bool
prop_rcTruePos (Cell (r,c,v)) =
let
pos = length . takeWhile (not . id) . rowConstraints $ (r,c,v)
in
pos == r*9 + v - 1
testRowConstraints = do
quickCheck prop_rcLength
quickCheck prop_rcTrueCount
quickCheck prop_rcColIndependence
quickCheck prop_rcTruePos
prop_ccLength :: Cell -> Bool
prop_ccLength (Cell x) = (length $ colConstraints x) == 81
prop_ccTrueCount :: Cell -> Bool
prop_ccTrueCount (Cell x) = (length . filter id $ colConstraints x) == 1
prop_ccRowIndependence :: Cell -> Bool
prop_ccRowIndependence (Cell (r,c,v)) =
let
colcons = colConstraints (r,c,v)
f x = colConstraints (x,c,v)
in
case nub $ map f [0..8] of
[h] -> colcons == h
_ -> False
prop_ccTruePos :: Cell -> Bool
prop_ccTruePos (Cell (r,c,v)) =
let
pos = length . takeWhile (not . id) . colConstraints $ (r,c,v)
in
pos == c*9 + v - 1
testColConstraints = do
quickCheck prop_ccLength
quickCheck prop_ccTrueCount
quickCheck prop_ccRowIndependence
quickCheck prop_ccTruePos
prop_cellConsLength :: Cell -> Bool
prop_cellConsLength (Cell x) = (length $ cellConstraints x) == 81
prop_cellConsTrueCount :: Cell -> Bool
prop_cellConsTrueCount (Cell x) = (length . filter id $ cellConstraints x) == 1
prop_cellConsValIndependence :: Cell -> Bool
prop_cellConsValIndependence (Cell (r,c,v)) =
let
celcons = cellConstraints (r,c,v)
f x = cellConstraints (r,c,x)
in
case nub $ map f [1..9] of
[h] -> celcons == h
_ -> False
prop_cellConsTruePos :: Cell -> Bool
prop_cellConsTruePos (Cell (r,c,v)) =
let
pos = length . takeWhile (not . id) . cellConstraints $ (r,c,v)
in
pos == r*9 + c
testCellConstraints = do
quickCheck prop_cellConsLength
quickCheck prop_cellConsTrueCount
quickCheck prop_cellConsValIndependence
quickCheck prop_cellConsTruePos
prop_bcLength :: Cell -> Bool
prop_bcLength (Cell x) = (length $ blockConstraints x) == 81
prop_bcTrueCount :: Cell -> Bool
prop_bcTrueCount (Cell x) = (length . filter id $ blockConstraints x) == 1
blockIndices :: (Int,Int) -> [(Int,Int)]
blockIndices (x,y)
| x < 3 && y < 3 = [(x,y) | x <- [0,1,2], y <- [0,1,2] ]
| x < 3 && y < 6 = [(x,y) | x <- [0,1,2], y <- [3,4,5] ]
| x < 3 = [(x,y) | x <- [0,1,2], y <- [6,7,8] ]
| x < 6 && y < 3 = [(x,y) | x <- [3,4,5], y <- [0,1,2] ]
| x < 6 && y < 6 = [(x,y) | x <- [3,4,5], y <- [3,4,5] ]
| x < 6 = [(x,y) | x <- [3,4,5], y <- [6,7,8] ]
| y < 3 = [(x,y) | x <- [6,7,8], y <- [0,1,2] ]
| y < 6 = [(x,y) | x <- [6,7,8], y <- [3,4,5] ]
| otherwise = [(x,y) | x <- [6,7,8], y <- [6,7,8] ]
blockId :: (Int,Int) -> Int
blockId (x,y)
| x < 3 && y < 3 = 0
| x < 3 && y < 6 = 1
| x < 3 = 2
| x < 6 && y < 3 = 3
| x < 6 && y < 6 = 4
| x < 6 = 5
| y < 3 = 6
| y < 6 = 7
| otherwise = 8
prop_bcRCIndependence :: Cell -> Bool
prop_bcRCIndependence (Cell (r,c,v)) =
let
colcons = blockConstraints (r,c,v)
f (x,y) = blockConstraints (x,y,v)
in
case nub . map f $ blockIndices (r,c) of
[h] -> colcons == h
_ -> False
prop_bcTruePos :: Cell -> Bool
prop_bcTruePos (Cell (r,c,v)) =
let
pos = length . takeWhile (not . id) . blockConstraints $ (r,c,v)
b = blockId (r,c)
in
pos == b*9 + v - 1
testBlockConstraints = do
quickCheck prop_bcLength
quickCheck prop_bcTrueCount
quickCheck prop_bcRCIndependence
quickCheck prop_bcTruePos
testConstraints = do
testBlockConstraints
testRowConstraints
testColConstraints
testCellConstraints
newtype FilledLine = FilledLine (Int, String)
deriving Show
arbFillLine :: Gen FilledLine
arbFillLine = do
line <- shuffle "123456789"
row <- choose (0,8)
return $ FilledLine (row, line)
instance Arbitrary FilledLine where
arbitrary = arbFillLine
prop_filledLineLength :: FilledLine -> Bool
prop_filledLineLength (FilledLine (r, s)) =
let
list = lineToLists (r,s)
in
length list == 9
prop_filledLineRow :: FilledLine -> Bool
prop_filledLineRow (FilledLine (r, s)) =
let
list = lineToLists (r,s)
f (x,_,_) = x
in
(map f list) == (take 9 (repeat r))
prop_filledLineCol :: FilledLine -> Bool
prop_filledLineCol (FilledLine (r, s)) =
let
list = lineToLists (r,s)
f (_,x,_) = x
in
(sort $ map f list) == [0..8]
prop_filledLineVal :: FilledLine -> Bool
prop_filledLineVal (FilledLine (r,s)) =
let
list = lineToLists (r,s)
f (_,_,v) = v
in
(map f list) == (map digitToInt s)
testFilledLine = do
quickCheck prop_filledLineLength
quickCheck prop_filledLineRow
quickCheck prop_filledLineCol
quickCheck prop_filledLineVal
newtype EmptyLine = EmptyLine (Int, String)
deriving Show
arbEmptyLine :: Gen EmptyLine
arbEmptyLine = do
row <- choose (0,8)
return $ EmptyLine (row, "---------")
instance Arbitrary EmptyLine where
arbitrary = arbEmptyLine
prop_emptyLineLength :: EmptyLine -> Bool
prop_emptyLineLength (EmptyLine (r, s)) =
let
list = lineToLists (r,s)
in
length list == 81
prop_emptyLineRow :: EmptyLine -> Bool
prop_emptyLineRow (EmptyLine (r, s)) =
let
list = lineToLists (r,s)
f (x,_,_) = x
in
(map f list) == (take 81 (repeat r))
prop_emptyLineCol :: EmptyLine -> Bool
prop_emptyLineCol (EmptyLine (r, s)) =
let
list = lineToLists (r,s)
f (_,x,_) = x
in
(sort .nub $ map f list) == [0..8]
prop_emptyLineVal :: EmptyLine -> Bool
prop_emptyLineVal (EmptyLine (r,s)) =
let
list = lineToLists (r,s)
f (_,_,v) = v
in
(sort . nub . map f $ list) == [1,2,3,4,5,6,7,8,9]
testEmptyLine = do
quickCheck prop_emptyLineLength
quickCheck prop_emptyLineRow
quickCheck prop_emptyLineCol
quickCheck prop_emptyLineVal
newtype DummySudoku = DummySudoku String
deriving Show
sudokuLine = vectorOf 9 (elements "123456789-")
genDummySudoku :: Gen DummySudoku
genDummySudoku = do
lines <- vectorOf 9 sudokuLine
return . DummySudoku . unlines $ lines
instance Arbitrary DummySudoku
where arbitrary = genDummySudoku
prop_rawSudokuLength :: DummySudoku -> Bool
prop_rawSudokuLength (DummySudoku str) =
let
rawsudoku = textToRawSudoku str
hyphenCount = length $ filter ('-' ==) str
digitCount = length $ filter isDigit str
in
length rawsudoku == hyphenCount * 9 + digitCount
prop_rawSudokuIndices :: DummySudoku -> Bool
prop_rawSudokuIndices (DummySudoku str) =
let
rawsudoku = textToRawSudoku str
f (x,y,_) = (x,y)
in
(nub . map f $ rawsudoku) == [(x,y) | x <- [0..8], y <- [0..8]]
testSudokuReads = do
quickCheck prop_rawSudokuLength
quickCheck prop_rawSudokuIndices
testFilledLine
testEmptyLine
testConstraints
| kapilash/dc | src/sudokus/hs/ExactCover/app/Main.hs | bsd-3-clause | 14,320 | 1 | 15 | 3,733 | 6,649 | 3,488 | 3,161 | 400 | 2 |
{-# LANGUAGE OverloadedStrings
, ParallelListComp
, ScopedTypeVariables
, TupleSections #-}
-- | Backend interface and CoProc interpreter implementations.
module System.Posix.CoProc.Internals where
import Control.Applicative
import Control.Concurrent
import Control.Concurrent.Async
import Data.Bits
import Data.ByteString.Char8 (ByteString)
import qualified Data.ByteString.Char8 as Bytes
import Data.Monoid
import System.Exit
import System.IO
import System.IO.Error
import System.Process
import System.Process.Internals
import System.Posix.ByteString
import System.Random
import System.IO.Temp
import qualified Text.ShellEscape as Esc
-- | A low-level interface, in terms of handles, for interacting with a
-- running interpreter. This interface is wrapped in the primary module to
-- add thread safety and diagnostic information. To implement a new
-- interpreter, simply implement this interface and use the functions in the
-- public module as before.
class Interpreter interpreter where
start :: interpreter -> IO (Handle, Handle, Handle, ProcessHandle)
query :: interpreter -> (Handle, Handle, Handle, ProcessHandle)
-> ByteString -> IO (ByteString, ByteString)
done :: interpreter -> (Handle, Handle, Handle, ProcessHandle) -> IO ExitCode
-- | Simplest way to shutdown a running interpreter.
close :: (Handle, Handle, Handle, ProcessHandle) -> IO ExitCode
close (i, o, e, p) = hClose' i *> hClose' o *> hClose' e *> waitForProcess p
where hClose' h = catchIOError (hClose h) (const (return ()))
-- | Run an IO action with two FIFOs in scope, which will be removed after it
-- completes.
withFIFOs :: (RawFilePath -> RawFilePath -> IO a) -> IO a
withFIFOs m = do
num :: Int <- randomIO
withSystemTempDirectory ("hs." ++ show num ++ ".coproc.") m'
where m' = (uncurry m =<<) . mk . Bytes.pack
mk d = (o, e) <$ (createNamedPipe o mode >> createNamedPipe e mode)
where (o, e) = (d <> "/o", d <> "/e")
mode = ownerReadMode .|. ownerWriteMode .|. namedPipeMode
-- | Use @bash@+@cat@ to drain the FIFO and terminate when complete.
drainFIFO :: ByteString -> IO ByteString
drainFIFO path = do
(i, o, e, p) <- runInteractiveProcess "bash" [] Nothing (Just [])
Bytes.hPutStrLn i ("exec cat <" <> (Esc.bytes . Esc.bash) path)
hFlush i
hClose i
hClose e
Bytes.hGetContents o <* waitForProcess p
-- | Read several FIFOs in the background, in parallel, returning all of their
-- contents.
backgroundReadFIFOs :: [ByteString] -> IO [ByteString]
backgroundReadFIFOs = mapConcurrently drainFIFO
-- | Retrieve the PID from a process handle. Note that calling this function
-- on a process that one has terimated or called wait for will results in an
-- exception being thrown.
pid :: ProcessHandle -> IO CPid
pid handle = withProcessHandle handle getPID
where getPID (OpenHandle pid) = return pid
getPID _ = error
"System.CoProc.Internal.pid: Called on closed handle! Yikes!"
| solidsnack/coproc | System/Posix/CoProc/Internals.hs | bsd-3-clause | 3,163 | 0 | 13 | 723 | 694 | 378 | 316 | 52 | 2 |
module Rasa.Ext.Views.Internal.Actions
( rotate
, closeInactive
, focusViewLeft
, focusViewRight
, focusViewAbove
, focusViewBelow
, hSplit
, vSplit
, addSplit
, nextBuf
, prevBuf
, focusDo
, focusDo_
, focusedBufs
, isFocused
, scrollBy
) where
import Rasa.Ext
import qualified Rasa.Ext.Views.Internal.Views as V
import Rasa.Ext.Views.Internal.BiTree
import Control.Lens
import Control.Monad
import Data.Maybe
import Data.List
-- | Flip all Horizontal splits to Vertical ones and vice versa.
rotate :: App ()
rotate = V.overWindows V.rotate
-- | Move focus from any viewports one viewport to the left
focusViewLeft :: App ()
focusViewLeft = V.overWindows V.focusViewLeft
-- | Move focus from any viewports one viewport to the right
focusViewRight :: App ()
focusViewRight = V.overWindows V.focusViewRight
-- | Move focus from any viewports one viewport above
focusViewAbove :: App ()
focusViewAbove = V.overWindows V.focusViewAbove
-- | Move focus from any viewports one viewport below
focusViewBelow :: App ()
focusViewBelow = V.overWindows V.focusViewBelow
-- | Close all inactive viewports
closeInactive :: App ()
closeInactive = do
mWindows <- V.getViews
V.setViews $ mWindows >>= V.closeBy (not . view V.active)
-- | Split active views horizontally
hSplit :: App ()
hSplit = V.overWindows V.hSplit
-- | Split active views vertically
vSplit :: App ()
vSplit = V.overWindows V.vSplit
-- | Add a new split at the top level in the given direction containing the given buffer.
addSplit :: BufAdded -> App ()
addSplit (BufAdded bRef) = do
mWin <- V.getViews
case mWin of
Nothing -> V.setViews . Just $ Leaf (V.View True (V.BufView bRef) 0)
Just win -> V.setViews . Just $ V.addSplit V.Vert (V.BufView bRef) win
-- | Select the next buffer in any active viewports
nextBuf :: App ()
nextBuf = V.traverseViews next
where
next vw
| vw ^. V.active = do
newViewable <- getNextBufRef (vw^. V.viewable)
return (vw & V.viewable .~ newViewable)
| otherwise = return vw
getNextBufRef (V.BufView br) = V.BufView <$> nextBufRef br
getNextBufRef v = return v
-- | Select the previous buffer in any active viewports
prevBuf :: App ()
prevBuf = V.traverseViews prev
where
prev vw
| vw ^. V.active = do
newViewable <- getPrevBufRef (vw^. V.viewable)
return (vw & V.viewable .~ newViewable)
| otherwise = return vw
getPrevBufRef (V.BufView br) = V.BufView <$> prevBufRef br
getPrevBufRef v = return v
-- | Get bufRefs for all buffers that are selected in at least one viewport
focusedBufs :: App [BufRef]
focusedBufs = do
mWindows <- V.getViews
case mWindows of
Nothing -> return []
Just win -> return . nub . activeBufRefs $ win
where activeBufRefs = toListOf $ traverse . filtered (view V.active) . V.viewable . V._BufViewRef
-- | Returns whether the current buffer is focused in at least one view.
isFocused :: BufAction Bool
isFocused = do
inFocus <- runApp focusedBufs
br <- getBufRef
return $ br `elem` inFocus
-- | Run a bufAction over all focused buffers and return any results.
focusDo :: BufAction a -> App [a]
focusDo bufAct = do
bufRefs <- focusedBufs
catMaybes <$> mapM (`bufDo` bufAct) bufRefs
-- | 'focusDo' with a void return
focusDo_ :: BufAction a -> App ()
focusDo_ = void . focusDo
-- | Scrolls each focused viewport by the given amount.
scrollBy :: Int -> App ()
scrollBy amt = V.overWindows $ V.scrollBy amt
| samcal/rasa | rasa-ext-views/src/Rasa/Ext/Views/Internal/Actions.hs | gpl-3.0 | 3,492 | 0 | 16 | 717 | 959 | 493 | 466 | 86 | 2 |
module Distribution.AutoUpdate.MenuItem (
autoUpdateMenuItem,
mkUpdateVersionRef,
) where
import Safe
import Data.Version
import Text.Logging
import Control.Monad
import Control.Monad.Trans.Error
import Control.Concurrent.MVar
import Control.Concurrent
import Graphics.Qt
import Utils
import Base
import Distribution.AutoUpdate
-- | Creates the MVar containing the UpdateVersion,
-- but also forks the thread that queries the UpdateVersion from
-- the update server.
mkUpdateVersionRef :: Ptr MainWindow -> Configuration -> IO (MVar UpdateVersions)
mkUpdateVersionRef window config = do
mvar <- newEmptyMVar
ignore $ forkIO $ do
lookupUpdateVersion config >>= putMVar mvar
updateMainWindow window
return mvar
-- | Tries to lookup, if a newer version of the game is available.
-- Runs in the background of the main menu. In case of errors, this
-- operation does not terminate.
lookupUpdateVersion :: Configuration -> IO UpdateVersions
lookupUpdateVersion config = do
let repo = Repo $ update_repo config
v <- io $ runErrorT $ getUpdateVersion config repo
case v of
Left error -> do
mapM_ (logg Error) $ lines error
io $ forever (threadDelay (1 * 10 ^ 6))
Right x -> return x
autoUpdateMenuItem :: AutoUpdateMenuItem
autoUpdateMenuItem = AutoUpdateMenuItem False
data AutoUpdateMenuItem = AutoUpdateMenuItem {selected :: Bool}
instance Renderable AutoUpdateMenuItem where
render ptr app config size (AutoUpdateMenuItem selected) = do
v <- tryReadMVar $ autoUpdateVersion app
let r :: Prose -> IO (Size Double, IO ())
r = render ptr app config size . proseMod v
selectionMod = if selected then select else deselect
proseMod (Just updateVersions) | hasUpdates updateVersions =
colorizeProse yellow . selectionMod
proseMod _ = selectionMod
case v of
-- no information yet
Nothing -> r $ p "online update"
-- no updates available
Just uvs | not (hasUpdates uvs) -> r $
headNote "Distribution.AutoUpdate.MenuItem.render" $
noUpdatesAvailable uvs
-- update available
Just (UpdateVersions Nothing (Right (Just newVersion))) ->
r $ substitute [("version", showVersion newVersion)] $
p "new storymode version available: $version"
Just (UpdateVersions (Just g) (Right (Just sm))) ->
r $ substitute [("gameVersion", showVersion g),
("storyModeVersion", showVersion sm)] $
p "new version available: $gameVersion (Nikki) and $storyModeVersion (storymode)"
Just (UpdateVersions (Just newVersion) _) ->
r $ substitute [("version", showVersion newVersion)] $
p "new game version available: $version"
label = const "AutoUpdateMenuItem"
select = const $ AutoUpdateMenuItem True
deselect = const $ AutoUpdateMenuItem False
| geocurnoff/nikki | src/Distribution/AutoUpdate/MenuItem.hs | lgpl-3.0 | 3,082 | 0 | 18 | 842 | 726 | 361 | 365 | 60 | 2 |
{-# LANGUAGE MultiParamTypeClasses
, FlexibleInstances
, EmptyDataDecls #-}
module Data.FibHeap
#ifndef TESTING
( Heap(..)
, HeapPolicy(..)
, empty
, peek
, insert
, decreaseKey
, datum
, key
, focusElement
)
#endif
where
-- import Control.Arrow ( (&&&) )
import Control.Monad ( MonadPlus(..), guard )
import Prelude hiding ( foldr, min )
-- import Data.Sequence ( Seq, (<|), (|>), (><), ViewL(..), ViewR(..) )
import Data.Foldable
-- import Data.IntMap (IntMap)
import Data.Tree
import Data.Maybe ( isJust )
-- import qualified Data.List as List
import qualified Prelude as Prelude
import qualified Data.Sequence as Seq
import qualified Data.IntMap as IntMap
-- * Forest cursor
data Path a = Point { left :: Forest a -- ^ 1st left thing on front
, right :: Forest a -- ^ 1st right thing on front
, up :: Maybe (a, Path a)
-- ^ The label of the parent and a path up.
}
deriving (Show, Eq)
emptyPath :: Path a
emptyPath = Point [] [] Nothing
data Cursor a = EmptyC
| Cursor { focus :: Tree a
, context :: Path a }
deriving Show
closeCursor :: Cursor a -> Forest a
closeCursor EmptyC = []
closeCursor c@(Cursor t p) =
case up p of
Nothing -> left p ++ [t] ++ right p
_ -> (closeCursor . focusUp) c
focusElement :: Cursor a -> a
focusElement EmptyC = error "focusElement: empty"
focusElement c = (rootLabel . focus) c
focusLeft, focusRight, focusUp, focusDown :: Cursor a -> Cursor a
focusLeft EmptyC = error "focusLeft: empty"
focusLeft c@(Cursor t p) = case p of
Point (l:ls) rs u -> Cursor l (Point ls (t:rs) u)
_ -> c
focusRight EmptyC = error "focusLeft: empty"
focusRight c@(Cursor t p) = case p of
Point ls (r:rs) u -> Cursor r (Point (t:ls) rs u)
_ -> c
focusUp EmptyC = error "focusLeft: empty"
focusUp c@(Cursor t p) = case p of
Point { up = Nothing } -> c
Point ls rs (Just (p', u)) -> Cursor (Node p' (reverse ls ++ t : rs)) u
-- | Focus on the leftmost subtree of current focus. If no such, returns
-- cursor unmodified.
focusDown EmptyC = error "focusLeft: empty"
focusDown c@(Cursor t p) = case t of
Node l (t1:ts) -> Cursor t1 (Point [] ts (Just (l, p)))
_ -> c
-- | Replace the focused tree, creating new if necessary.
frobFocus :: Tree a -> Cursor a -> Cursor a
frobFocus x EmptyC = Cursor x emptyPath
frobFocus x (Cursor _ p) = Cursor x p
modifyFocus :: Cursor a -> (Tree a -> Tree a) -> Cursor a
modifyFocus EmptyC _ = EmptyC
modifyFocus (Cursor t p) f = Cursor (f t) p
-- | Insert a new element at the focus, moving focused element to right. If
-- the initial focus was empty, focuses on the new element.
insertFocus :: Tree a -> Cursor a -> Cursor a
insertFocus x EmptyC = Cursor x emptyPath
insertFocus x (Cursor t p) = case p of
Point ls rs u -> Cursor x (Point ls (t:rs) u)
-- | Insert element at immediate right of focus, or at focus if empty.
insertRight :: Tree a -> Cursor a -> Cursor a
insertRight x EmptyC = Cursor x emptyPath
insertRight x (Cursor t p) = case p of
Point ls rs u -> Cursor t (Point ls (x:rs) u)
insertWithRight :: Tree a
-> (Tree a -> Tree a -> (Tree a, Tree a))
-- ^ /existing/ -> /new/ -> (/focus/, /right/)
-> Cursor a -> Cursor a
insertWithRight x _ EmptyC = Cursor x emptyPath
insertWithRight x f (Cursor t (Point ls rs u)) = Cursor t' (Point ls (r':rs) u)
where (t', r') = f t x
-- | Delete the focus subtree and try to move right, then left, then up, and
-- finally to the empty cursor, in that order.
delete :: Cursor a -> Cursor a
delete EmptyC = error "delete: empty"
delete (Cursor _ p) = case p of
Point ls (r:rs) u -> Cursor r (Point ls rs u)
Point (l:ls) [] u -> Cursor l (Point ls [] u)
Point [] [] (Just (x, p')) -> Cursor (Node x []) p'
Point [] [] Nothing -> EmptyC
-- | Delete focused element and move focus to parent, if any. If no parent,
-- returns empty cursor.
deleteUp :: Cursor a -> Cursor a
deleteUp EmptyC = error "deleteUp: empty"
deleteUp (Cursor t p) = case p of
Point _ _ Nothing -> EmptyC
Point ls rs (Just (p', u)) -> Cursor (Node p' (reverse ls ++ t : rs)) u
-- * Heap implementation
-- | A heap policy indicates which elements are closer to the `min' in the
-- heap. If @x@ is less than @y@ according to `heapCompare', @x@ is closer to
-- the `min' than @y@.
class (Eq a) => HeapPolicy p a where
-- | The minimum possible value. This is used to delete elements (by
-- decreasing their key to the minimum possible value, then extracting the
-- min).
heapMin :: a
-- | Compare elements for the heap. Lesser elements are closer to the
-- `min'.
heapCompare :: p -- ^ /Must not be evaluated./
-> a -> a -> Ordering
-- Convenience for comparing nodes?
instance (HeapPolicy p k) => Ord (Info p k a) where
compare n n' = heapCompare (policy n) (key n) (key n')
data Heap p k a = H
{ min :: Cursor (Info p k a)
, size :: Int -- ^ Number of elements in the heap.
, numMarked :: Int }
deriving Show
-- data Node p k a = N
-- { key :: k
-- , parent :: Zipper (Node p k a) -- ^ Focused on parent node.
-- , child :: Zipper (Node p k a) -- ^ Focused on child node.
-- , mark :: Bool
-- , degree :: Int
-- , datum :: a }
-- deriving Show
-- | Info kept for each node in the tree.
data Info p k a = Info
{ key :: k
, mark :: Bool -- ^ Has this node lost a child since the last
-- time it was made the child of another node?
, datum :: a }
deriving Show
instance (Eq k) => Eq (Info p k a) where
i == i' = key i == key i'
policy :: Info p k a -> p
policy = const undefined
-- * Operations
-- | The empty Fibonacci heap.
empty :: HeapPolicy p k => Heap p k a
empty = H { min = EmptyC
, size = 0
, numMarked = 0 }
peek :: Heap p k a -> a
peek = datum . focusElement . min
-- | Insert given value with given key into the heap.
insert :: HeapPolicy p k => (k, a) -> Heap p k a -> Heap p k a
insert (k, v) heap = heap' { min = insertMinimumFocus infoNode (min heap') }
where heap' = heap{ size = size heap + 1 }
info = Info { key = k, mark = False, datum = v }
infoNode = Node info []
-- | Insert the `Info' into the cursor and focus on a (possibly new) minimum
-- element.
insertMinimumFocus :: Ord a => Tree a -> Cursor a -> Cursor a
insertMinimumFocus node tree = insertWithRight node focusOnMin tree
where
focusOnMin n n' = (argmin rootLabel n n', argmax rootLabel n n')
-- | Extract the minimum node from the heap, as determined by `heapCompare'.
--
-- N.B. This function is /not total/: if the heap is empty, throws an error.
extractMin :: HeapPolicy p k => Heap p k a -> (Cursor (Info p k a), Heap p k a)
extractMin heap = case min heap of
EmptyC -> error "Data.FibHeap.extractMin: empty heap"
c@(Cursor t _) ->
( c
, heap { min = consolidate collapsedCursor
, size = size heap - 1 } )
where
-- Add child trees of min as siblings of `c'.
collapsedCursor = foldl' (flip insertRight) (delete c) (subForest t)
-- In order to use decreaseKey properly, we need to find the cursor for a node
-- that's already in the heap. We can do this with a worst-case-linear-time
-- search of the heap-ordered trees. If in the Heap record we keep around the
-- set of items in the heap, then discovering *that* the item is in the heap
-- takes O(log n) time and then linear time to find it. If we keep a map of
-- unique item identifiers to cursors into the heap, we can recover the
-- cursors in O(log n) time, but we have to update these cursors all the
-- freaking time. Ugh.
-- Cursor must be non-empty.
decreaseKey :: HeapPolicy p k => Heap p k a -> Cursor (Info p k a) -> k
-> Heap p k a
decreaseKey heap nodeCursor newKey =
case newKey `compareKeys` (key . focusElement) nodeCursor of
GT -> error "Data.FibHeap.decreaseKey: newKey too big"
_ -> let (Cursor t _) = nodeCursor
in if (isJust . up . context) nodeCursor then
-- at root level, so focus in the minimum of current & min
case rootLabel t `compare` (focusElement . min) heap of
LT -> heap { min = nodeCursorNewKey }
_ -> heap
else -- not at root level, cut/cascading up to new min
heap { min = (undelayCursor . cascadingCut . cut . delayCursor)
nodeCursorNewKey }
where
compareKeys = heapCompare (policy (focusElement nodeCursor))
nodeCursorNewKey =
frobFocus (focus nodeCursor
`modifyRootLabel` (\info -> info { key = newKey }))
nodeCursor
modifyRootLabel :: Tree a -> (a -> a) -> Tree a
modifyRootLabel t f = t { rootLabel = f (rootLabel t) }
-- | The elements of the forest are elements that belong as siblings of the
-- topmost trees in the tree represented by the cursor.
type DelayedRootlistCursor a = (Forest a, Cursor a)
delayCursor :: Cursor a -> DelayedRootlistCursor a
delayCursor c = ([], c)
undelayCursor :: (Ord a) => DelayedRootlistCursor a -> Cursor a
undelayCursor (roots, c) = foldl' (flip insertMinimumFocus) c roots
-- | @cut c@ removes focus of @c@ and puts it in the (delayed) root list of
-- the tree.
--
-- Precondition: The input cursor focus element must have a parent.
cut :: DelayedRootlistCursor (Info p k a) -> DelayedRootlistCursor (Info p k a)
cut c@(_, EmptyC) = c
cut (roots, c) =
( focus c `modifyRootLabel` (\info -> info { mark = False }) : roots
, deleteUp c )
cascadingCut :: DelayedRootlistCursor (Info p k a)
-> DelayedRootlistCursor (Info p k a)
cascadingCut d@(_, EmptyC) = d
cascadingCut d@(roots, c) =
if (isJust . up . context) c then
if (not . mark . focusElement) c then
( roots
, modifyFocus c (`modifyRootLabel` (\info -> info { mark = True })) )
else cut d
else d
-- ** Heap consolidation
consolidate :: HeapPolicy p k => Cursor (Info p k a) -> Cursor (Info p k a)
consolidate = undefined
-- at the end we want:
-- 1. exactly one tree of each degree in the root list
-- 2. the min to be right
-- consolidate heap = undefined
-- where degMap = foldr (flip linkByDegree) IntMap.empty (min heap)
-- | @linkByDegree map nz@ links @nz@ with node in @map@ which has same degree
-- (if any), and does so recursively, returning a new map.
-- linkByDegree :: HeapPolicy p k =>
-- IntMap (Node p k a) -- ^ Invariant: if @i@ maps to @n@ in this
-- -- map, then @degree n == i@.
-- -> Node p k a
-- -> IntMap (Node p k a)
-- linkByDegree degMap node =
-- if IntMap.member d degMap then
-- linkByDegree degMapLinked linkedNodeZ
-- else IntMap.insert d node degMap
-- where d = degree node
-- -- foci of existingNodeZ and nodeZ have same degree.
-- existingNode = degMap IntMap.! d
-- linkedNodeZ = if node < existingNode then
-- link existingNode node
-- else link node existingNode
-- degMapLinked =
-- (IntMap.insert (degree (focus linkedNodeZ)) linkedNodeZ
-- . IntMap.delete (degree node))
-- degMap
-- ** Helpers
argmax :: (Ord b) => (a -> b) -> a -> a -> a
{-# INLINE argmax #-}
argmax f x y = if f x > f y then x else y
argmin :: (Ord b) => (a -> b) -> a -> a -> a
{-# INLINE argmin #-}
argmin f x y = if f x < f y then x else y
-- | Length of `subForest' of tree.
degree :: Tree a -> Int
degree (Node _ ts) = length ts
findSplit = undefined
-- dfsForest pred [] = Nothing
-- dfsForest pred (t:ts) =
-- if (pred . rootLabel) t then Just t
-- else
dfsCursor _ EmptyC = Nothing
dfsCursor pred c@(Cursor t p@(Point ls rs _)) =
(guard ((pred . rootLabel) t) >> return c)
`mplus` (guard (null (subForest t)) >> dfsCursor pred (focusDown c))
`mplus` foldr mplus mzero (map (dfsCursor pred) (rights c))
where
rights (Cursor { context = (Point { right = [] }) }) = []
rights c = focusRight c : rights (focusRight c)
| rbonifacio/funsat | etc/fiblib/Data/FibHeap.hs | bsd-3-clause | 12,658 | 0 | 17 | 3,718 | 3,386 | 1,807 | 1,579 | 188 | 4 |
module Main where
import Test.Framework
import Test.Compiler
import Test.Property
main :: IO ()
main =
defaultMain
[ compilerTests
, propertyTests
]
| JoeyEremondi/utrecht-apa-p1 | tests/Test.hs | bsd-3-clause | 168 | 0 | 6 | 40 | 43 | 25 | 18 | 9 | 1 |
{-# LANGUAGE TemplateHaskell, ForeignFunctionInterface #-}
module Graphics.Wayland.Internal.SpliceClient where
import Data.Functor
import Language.Haskell.TH
import Foreign.C.Types
import Graphics.Wayland.Scanner.Protocol
import Graphics.Wayland.Scanner
import Graphics.Wayland.Internal.SpliceClientTypes
import qualified Graphics.Wayland.Internal.SpliceClientInternal as Import
$(runIO readProtocol >>= generateClientExports)
| abooij/haskell-wayland | Graphics/Wayland/Internal/SpliceClient.hs | mit | 432 | 0 | 8 | 34 | 70 | 46 | 24 | 10 | 0 |
<?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="ar-SA">
<title>Passive Scan Rules - Alpha | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>بحث</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | 0xkasun/security-tools | src/org/zaproxy/zap/extension/pscanrulesAlpha/resources/help_ar_SA/helpset_ar_SA.hs | apache-2.0 | 988 | 87 | 52 | 163 | 403 | 212 | 191 | -1 | -1 |
-- {-# OPTIONS -fglasgow-exts -XNoMonomorphismRestriction -XOverlappingInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Control.Monatron.Open where
import Control.Monatron.Monatron ()
import Control.Monatron.AutoLift
infixr 9 :+:
infixr 9 <@>
data (:+:) f g a = Inl (f a) | Inr (g a)
newtype Fix f = In {out :: f (Fix f)}
type Open e f r = (e -> r) -> (f e -> r)
(<@>) :: Open e f r -> Open e g r -> Open e (f :+: g) r
evalf <@> evalg = \eval e ->
case e of
Inl el -> evalf eval el
Inr er -> evalg eval er
fix :: Open (Fix f) f r -> (Fix f -> r)
fix f = let this = f this . out
in this
-- Borrowed from Data types \`a la Carte
class (f :<: g) where
inj :: f a -> g a
instance Functor f => (:<:) f f where
inj = id
instance (Functor g, Functor f)
=> (:<:) f (f :+: g) where
inj = Inl
instance (Functor g, Functor h, Functor f, f :<: g)
=> (:<:) f (h :+: g) where
inj = Inr . inj
inject :: (f :<: g) => f (Fix g) -> Fix g
inject = In . inj
instance (Functor f, Functor g) =>
Functor (f :+: g) where
fmap f (Inl x) = Inl (fmap f x)
fmap f (Inr y) = Inr (fmap f y)
foldFix :: Functor f => (f a -> a) -> Fix f -> a
foldFix f = f . fmap (foldFix f) . out
| neothemachine/monadiccp | src/Control/Monatron/Open.hs | bsd-3-clause | 1,419 | 1 | 10 | 392 | 600 | 321 | 279 | 39 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE PatternGuards #-}
{-# OPTIONS_GHC -fno-warn-deprecations #-}
---------------------------------------------------------
--
-- Module : Network.Wai.Handler.Warp
-- Copyright : Michael Snoyman
-- License : BSD3
--
-- Maintainer : Michael Snoyman <michael@snoyman.com>
-- Stability : Stable
-- Portability : portable
--
-- A fast, light-weight HTTP server handler for WAI.
--
---------------------------------------------------------
-- | A fast, light-weight HTTP server handler for WAI.
--
-- HTTP\/1.0, HTTP\/1.1 and HTTP\/2 are supported. For HTTP\/2,
-- Warp supports direct and ALPN (in TLS) but not upgrade.
--
-- Note on slowloris timeouts: to prevent slowloris attacks, timeouts are used
-- at various points in request receiving and response sending. One interesting
-- corner case is partial request body consumption; in that case, Warp's
-- timeout handling is still in effect, and the timeout will not be triggered
-- again. Therefore, it is recommended that once you start consuming the
-- request body, you either:
--
-- * consume the entire body promptly
--
-- * call the 'pauseTimeout' function
--
-- For more information, see <https://github.com/yesodweb/wai/issues/351>.
--
--
module Network.Wai.Handler.Warp (
-- * Run a Warp server
-- | All of these automatically serve the same 'Application' over HTTP\/1,
-- HTTP\/1.1, and HTTP\/2.
run
, runEnv
, runSettings
, runSettingsSocket
-- * Run an HTTP\/2-aware server
-- | Each of these takes an HTTP\/2-aware application as well as a backup
-- 'Application' to be used for HTTP\/1.1 and HTTP\/1 connections. These
-- are only needed if your application needs access to HTTP\/2-specific
-- features such as trailers or pushed streams.
, runHTTP2
, runHTTP2Env
, runHTTP2Settings
, runHTTP2SettingsSocket
-- * Settings
, Settings
, defaultSettings
-- ** Setters
, setPort
, setHost
, setOnException
, setOnExceptionResponse
, setOnOpen
, setOnClose
, setTimeout
, setManager
, setFdCacheDuration
, setBeforeMainLoop
, setNoParsePath
, setInstallShutdownHandler
, setServerName
, setMaximumBodyFlush
, setFork
, setProxyProtocolNone
, setProxyProtocolRequired
, setProxyProtocolOptional
, setSlowlorisSize
, setHTTP2Disabled
-- ** Getters
, getPort
, getHost
, getOnOpen
, getOnClose
, getOnException
-- ** Exception handler
, defaultOnException
, defaultShouldDisplayException
-- ** Exception response handler
, defaultOnExceptionResponse
, exceptionResponseForDebug
-- * Data types
, HostPreference (..)
, Port
, InvalidRequest (..)
-- * Utilities
, pauseTimeout
-- * Internal
-- | The following APIs will be removed in Warp 3.2.0. Please use ones exported from Network.Wai.Handler.Warp.Internal.
-- ** Low level run functions
, runSettingsConnection
, runSettingsConnectionMaker
, runSettingsConnectionMakerSecure
, Transport (..)
-- ** Connection
, Connection (..)
, socketConnection
-- ** Buffer
, Buffer
, BufSize
, bufferSize
, allocateBuffer
, freeBuffer
-- ** Sendfile
, FileId (..)
, SendFile
, sendFile
, readSendFile
-- ** Version
, warpVersion
-- ** Data types
, InternalInfo (..)
, HeaderValue
, IndexedHeader
, requestMaxIndex
-- ** File descriptor cache
, module Network.Wai.Handler.Warp.FdCache
-- ** Date
, module Network.Wai.Handler.Warp.Date
-- ** Request and response
, Source
, recvRequest
, sendResponse
-- ** Time out manager
, module Network.Wai.Handler.Warp.Timeout
) where
import Control.Exception (SomeException)
import Data.ByteString (ByteString)
import Data.Maybe (fromMaybe)
import Data.Streaming.Network (HostPreference)
import qualified Data.Vault.Lazy as Vault
import Network.Socket (SockAddr)
import Network.Wai (Request, Response, vault)
import Network.Wai.Handler.Warp.Buffer
import Network.Wai.Handler.Warp.Date
import Network.Wai.Handler.Warp.FdCache
import Network.Wai.Handler.Warp.Header
import Network.Wai.Handler.Warp.Request
import Network.Wai.Handler.Warp.Response
import Network.Wai.Handler.Warp.Run
import Network.Wai.Handler.Warp.SendFile
import Network.Wai.Handler.Warp.Settings
import Network.Wai.Handler.Warp.Timeout
import Network.Wai.Handler.Warp.Types
-- | Port to listen on. Default value: 3000
--
-- Since 2.1.0
setPort :: Port -> Settings -> Settings
setPort x y = y { settingsPort = x }
-- | Interface to bind to. Default value: HostIPv4
--
-- Since 2.1.0
setHost :: HostPreference -> Settings -> Settings
setHost x y = y { settingsHost = x }
-- | What to do with exceptions thrown by either the application or server.
-- Default: 'defaultOnException'
--
-- Since 2.1.0
setOnException :: (Maybe Request -> SomeException -> IO ()) -> Settings -> Settings
setOnException x y = y { settingsOnException = x }
-- | A function to create a `Response` when an exception occurs.
--
-- Default: 'defaultOnExceptionResponse'
--
-- Since 2.1.0
setOnExceptionResponse :: (SomeException -> Response) -> Settings -> Settings
setOnExceptionResponse x y = y { settingsOnExceptionResponse = x }
-- | What to do when a connection is opened. When 'False' is returned, the
-- connection is closed immediately. Otherwise, the connection is going on.
-- Default: always returns 'True'.
--
-- Since 2.1.0
setOnOpen :: (SockAddr -> IO Bool) -> Settings -> Settings
setOnOpen x y = y { settingsOnOpen = x }
-- | What to do when a connection is closed. Default: do nothing.
--
-- Since 2.1.0
setOnClose :: (SockAddr -> IO ()) -> Settings -> Settings
setOnClose x y = y { settingsOnClose = x }
-- | Timeout value in seconds. Default value: 30
--
-- Since 2.1.0
setTimeout :: Int -> Settings -> Settings
setTimeout x y = y { settingsTimeout = x }
-- | Use an existing timeout manager instead of spawning a new one. If used,
-- 'settingsTimeout' is ignored.
--
-- Since 2.1.0
setManager :: Manager -> Settings -> Settings
setManager x y = y { settingsManager = Just x }
-- | Cache duration time of file descriptors in seconds. 0 means that the cache mechanism is not used.
--
-- The FD cache is an optimization that is useful for servers dealing with
-- static files. However, if files are being modified, it can cause incorrect
-- results in some cases. Therefore, we disable it by default. If you know that
-- your files will be static or you prefer performance to file consistency,
-- it's recommended to turn this on; a reasonable value for those cases is 10.
-- Enabling this cache results in drastic performance improvement for file
-- transfers.
--
-- Default value: since 3.0.13, default value is 0, was previously 10
setFdCacheDuration :: Int -> Settings -> Settings
setFdCacheDuration x y = y { settingsFdCacheDuration = x }
-- | Code to run after the listening socket is ready but before entering
-- the main event loop. Useful for signaling to tests that they can start
-- running, or to drop permissions after binding to a restricted port.
--
-- Default: do nothing.
--
-- Since 2.1.0
setBeforeMainLoop :: IO () -> Settings -> Settings
setBeforeMainLoop x y = y { settingsBeforeMainLoop = x }
-- | Perform no parsing on the rawPathInfo.
--
-- This is useful for writing HTTP proxies.
--
-- Default: False
--
-- Since 2.1.0
setNoParsePath :: Bool -> Settings -> Settings
setNoParsePath x y = y { settingsNoParsePath = x }
-- | Get the listening port.
--
-- Since 2.1.1
getPort :: Settings -> Port
getPort = settingsPort
-- | Get the interface to bind to.
--
-- Since 2.1.1
getHost :: Settings -> HostPreference
getHost = settingsHost
-- | Get the action on opening connection.
getOnOpen :: Settings -> SockAddr -> IO Bool
getOnOpen = settingsOnOpen
-- | Get the action on closeing connection.
getOnClose :: Settings -> SockAddr -> IO ()
getOnClose = settingsOnClose
-- | Get the exception handler.
getOnException :: Settings -> Maybe Request -> SomeException -> IO ()
getOnException = settingsOnException
-- | A code to install shutdown handler.
--
-- For instance, this code should set up a UNIX signal
-- handler. The handler should call the first argument,
-- which close the listen socket, at shutdown.
--
-- Default: does not install any code.
--
-- Since 3.0.1
setInstallShutdownHandler :: (IO () -> IO ()) -> Settings -> Settings
setInstallShutdownHandler x y = y { settingsInstallShutdownHandler = x }
-- | Default server name if application does not set one.
--
-- Since 3.0.2
setServerName :: ByteString -> Settings -> Settings
setServerName x y = y { settingsServerName = x }
-- | The maximum number of bytes to flush from an unconsumed request body.
--
-- By default, Warp does not flush the request body so that, if a large body is
-- present, the connection is simply terminated instead of wasting time and
-- bandwidth on transmitting it. However, some clients do not deal with that
-- situation well. You can either change this setting to @Nothing@ to flush the
-- entire body in all cases, or in your application ensure that you always
-- consume the entire request body.
--
-- Default: 8192 bytes.
--
-- Since 3.0.3
setMaximumBodyFlush :: Maybe Int -> Settings -> Settings
setMaximumBodyFlush x y
| Just x' <- x, x' < 0 = error "setMaximumBodyFlush: must be positive"
| otherwise = y { settingsMaximumBodyFlush = x }
-- | Code to fork a new thread to accept a connection.
--
-- This may be useful if you need OS bound threads, or if
-- you wish to develop an alternative threading model.
--
-- Default: void . forkIOWithUnmask
--
-- Since 3.0.4
setFork :: (((forall a. IO a -> IO a) -> IO ()) -> IO ()) -> Settings -> Settings
setFork fork' s = s { settingsFork = fork' }
-- | Do not use the PROXY protocol.
--
-- Since 3.0.5
setProxyProtocolNone :: Settings -> Settings
setProxyProtocolNone y = y { settingsProxyProtocol = ProxyProtocolNone }
-- | Require PROXY header.
--
-- This is for cases where a "dumb" TCP/SSL proxy is being used, which cannot
-- add an @X-Forwarded-For@ HTTP header field but has enabled support for the
-- PROXY protocol.
--
-- See <http://www.haproxy.org/download/1.5/doc/proxy-protocol.txt> and
-- <http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#proxy-protocol>.
--
-- Only the human-readable header format (version 1) is supported. The binary
-- header format (version 2) is /not/ supported.
--
-- Since 3.0.5
setProxyProtocolRequired :: Settings -> Settings
setProxyProtocolRequired y = y { settingsProxyProtocol = ProxyProtocolRequired }
-- | Use the PROXY header if it exists, but also accept
-- connections without the header. See 'setProxyProtocolRequired'.
--
-- WARNING: This is contrary to the PROXY protocol specification and
-- using it can indicate a security problem with your
-- architecture if the web server is directly accessable
-- to the public, since it would allow easy IP address
-- spoofing. However, it can be useful in some cases,
-- such as if a load balancer health check uses regular
-- HTTP without the PROXY header, but proxied
-- connections /do/ include the PROXY header.
--
-- Since 3.0.5
setProxyProtocolOptional :: Settings -> Settings
setProxyProtocolOptional y = y { settingsProxyProtocol = ProxyProtocolOptional }
-- | Size in bytes read to prevent Slowloris protection. Default value: 2048
--
-- Since 3.1.2
setSlowlorisSize :: Int -> Settings -> Settings
setSlowlorisSize x y = y { settingsSlowlorisSize = x }
-- | Disable HTTP2.
--
-- Since 3.1.7
setHTTP2Disabled :: Settings -> Settings
setHTTP2Disabled y = y { settingsHTTP2Enabled = False }
-- | Explicitly pause the slowloris timeout.
--
-- This is useful for cases where you partially consume a request body. For
-- more information, see <https://github.com/yesodweb/wai/issues/351>
--
-- Since 3.0.10
pauseTimeout :: Request -> IO ()
pauseTimeout = fromMaybe (return ()) . Vault.lookup pauseTimeoutKey . vault
| dylex/wai | warp/Network/Wai/Handler/Warp.hs | mit | 11,989 | 0 | 13 | 2,134 | 1,515 | 966 | 549 | 146 | 1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DeriveGeneric #-}
-- | The sytnax of numeric propositions.
module Cryptol.TypeCheck.Solver.Numeric.AST
( Name(..), ppName
, Prop(..), cryPropExprs, cryPropFVS
, ppProp, ppPropPrec
, Expr(..), zero, one, two, inf, cryAnds, cryOrs
, cryExprExprs, cryRebuildExpr
, cryExprFVS
, ppExpr, ppExprPrec
, Nat'(..)
, IfExpr, IfExpr'(..), ppIf, ppIfExpr
, Subst, HasVars(..), cryLet, composeSubst, doAppSubst
) where
import Cryptol.TypeCheck.AST(TVar)
import Cryptol.TypeCheck.PP(pp)
import Cryptol.TypeCheck.Solver.InfNat ( Nat'(..) )
import Cryptol.Utils.PP ( Doc, text, (<+>), hang, ($$), char, (<>)
, parens, integer, sep )
import Cryptol.Utils.Panic ( panic )
import Cryptol.Utils.Misc ( anyJust )
-- import Data.GenericTrie (TrieKey)
import GHC.Generics(Generic)
import Data.Maybe (fromMaybe)
import Data.Map ( Map )
import qualified Data.Map as Map
import Data.Set ( Set )
import qualified Data.Set as Set
import qualified Control.Applicative as A
import Control.Monad ( liftM, ap )
infixr 2 :||
infixr 3 :&&
infix 4 :==, :>, :>=, :==:, :>:
infixl 6 :+, :-
infixl 7 :*
infixr 8 :^^
data Name = UserName TVar | SysName Int
deriving (Show,Eq,Ord,Generic)
-- | Propopsitions, representing Cryptol's numeric constraints (and a bit more).
data Prop =
-- Preidcates on natural numbers with infinity.
-- After simplification, the only one of these should be `fin x`,
-- where `x` is a variable.
Fin Expr | Expr :== Expr | Expr :>= Expr | Expr :> Expr
-- Predicate on strict natural numbers (i.e., no infinities)
-- Should be introduced by 'cryNatOp', to eliminte 'inf'.
| Expr :==: Expr | Expr :>: Expr
-- Standard logical strucutre>
| Prop :&& Prop | Prop :|| Prop
| Not Prop
| PFalse | PTrue
deriving (Eq,Show,Generic)
-- | Expressions, representing Cryptol's numeric types.
data Expr = K Nat'
| Var Name
| Expr :+ Expr -- total
| Expr :- Expr -- partial: x >= y, fin y
| Expr :* Expr -- total
| Div Expr Expr -- partial: fin x, y >= 1
| Mod Expr Expr -- partial: fin x, y >= 1
| Expr :^^ Expr -- total
| Min Expr Expr -- total
| Max Expr Expr -- total
| Width Expr -- total
| LenFromThen Expr Expr Expr -- partial: x /= y, w >= width x
| LenFromThenTo Expr Expr Expr -- partial: x /= y
deriving (Eq,Show,Generic,Ord)
-- | The constant @0@.
zero :: Expr
zero = K (Nat 0)
-- | The constant @1@.
one :: Expr
one = K (Nat 1)
-- | The constant @2@.
two :: Expr
two = K (Nat 2)
-- | The constant @infinity@.
inf :: Expr
inf = K Inf
-- | Make a conjucntion of the given properties.
cryAnds :: [Prop] -> Prop
cryAnds [] = PTrue
cryAnds ps = foldr1 (:&&) ps
-- | Make a disjunction of the given properties.
cryOrs :: [Prop] -> Prop
cryOrs [] = PFalse
cryOrs ps = foldr1 (:||) ps
-- | Compute all expressions in a property.
cryPropExprs :: Prop -> [Expr]
cryPropExprs = go []
where
go es prop =
case prop of
PTrue -> es
PFalse -> es
Not p -> go es p
p :&& q -> go (go es q) p
p :|| q -> go (go es q) p
Fin x -> x : es
x :== y -> x : y : es
x :> y -> x : y : es
x :>= y -> x : y : es
x :==: y -> x : y : es
x :>: y -> x : y : es
-- | Compute the immediate sub-expressions of an expression.
cryExprExprs :: Expr -> [Expr]
cryExprExprs expr =
case expr of
K _ -> []
Var _ -> []
x :+ y -> [x,y]
x :- y -> [x,y]
x :* y -> [x,y]
Div x y -> [x,y]
Mod x y -> [x,y]
x :^^ y -> [x,y]
Min x y -> [x,y]
Max x y -> [x,y]
Width x -> [x]
LenFromThen x y z -> [x,y,z]
LenFromThenTo x y z -> [x,y,z]
-- | Rebuild an expression, using the top-level strucutre of the first
-- expression, but the second list of expressions as sub-expressions.
cryRebuildExpr :: Expr -> [Expr] -> Expr
cryRebuildExpr expr args =
case (expr,args) of
(K _, []) -> expr
(Var _, []) -> expr
(_ :+ _k, [x,y]) -> x :+ y
(_ :- _ , [x,y]) -> x :- y
(_ :* _ , [x,y]) -> x :* y
(Div _ _, [x,y]) -> Div x y
(Mod _ _, [x,y]) -> Mod x y
(_ :^^ _, [x,y]) -> x :^^ y
(Min _ _, [x,y]) -> Min x y
(Max _ _, [x,y]) -> Max x y
(Width _, [x]) -> Width x
(LenFromThen _ _ _ , [x,y,z]) -> LenFromThen x y z
(LenFromThenTo _ _ _ , [x,y,z]) -> LenFromThenTo x y z
_ -> panic "cryRebuildExpr" $ map show
$ text "expr:" <+> ppExpr expr
: [ text "arg:" <+> ppExpr a | a <- args ]
-- | Compute the free variables in an expression.
cryExprFVS :: Expr -> Set Name
cryExprFVS expr =
case expr of
Var x -> Set.singleton x
_ -> Set.unions (map cryExprFVS (cryExprExprs expr))
-- | Compute the free variables in a proposition.
cryPropFVS :: Prop -> Set Name
cryPropFVS = Set.unions . map cryExprFVS . cryPropExprs
data IfExpr' p a = If p (IfExpr' p a) (IfExpr' p a) | Return a | Impossible
deriving Eq
type IfExpr = IfExpr' Prop
instance Monad (IfExpr' p) where
return = Return
fail _ = Impossible
m >>= k = case m of
Impossible -> Impossible
Return a -> k a
If p t e -> If p (t >>= k) (e >>= k)
instance Functor (IfExpr' p) where
fmap = liftM
instance A.Applicative (IfExpr' p) where
pure = return
(<*>) = ap
--------------------------------------------------------------------------------
-- Substitution
--------------------------------------------------------------------------------
type Subst = Map Name Expr
composeSubst :: Subst -> Subst -> Subst
composeSubst g f = Map.union f' g
where
f' = fmap (\e -> fromMaybe e (apSubst g e)) f
cryLet :: HasVars e => Name -> Expr -> e -> Maybe e
cryLet x e = apSubst (Map.singleton x e)
doAppSubst :: HasVars a => Subst -> a -> a
doAppSubst su a = fromMaybe a (apSubst su a)
-- | Replaces occurances of the name with the expression.
-- Returns 'Nothing' if there were no occurances of the name.
class HasVars ast where
apSubst :: Subst -> ast -> Maybe ast
-- | This is used in the simplification to "apply" substitutions to Props.
instance HasVars Bool where
apSubst _ _ = Nothing
instance HasVars Expr where
apSubst su = go
where
go expr =
case expr of
K _ -> Nothing
Var b -> Map.lookup b su
x :+ y -> bin (:+) x y
x :- y -> bin (:-) x y
x :* y -> bin (:*) x y
x :^^ y -> bin (:^^) x y
Div x y -> bin Div x y
Mod x y -> bin Mod x y
Min x y -> bin Min x y
Max x y -> bin Max x y
Width x -> Width `fmap` go x
LenFromThen x y w -> three LenFromThen x y w
LenFromThenTo x y z -> three LenFromThen x y z
bin f x y = do [x',y'] <- anyJust go [x,y]
return (f x' y')
three f x y z = do [x',y',z'] <- anyJust go [x,y,z]
return (f x' y' z')
instance HasVars Prop where
apSubst su = go
where
go prop =
case prop of
PFalse -> Nothing
PTrue -> Nothing
Not p -> Not `fmap` go p
p :&& q -> bin (:&&) p q
p :|| q -> bin (:||) p q
Fin x -> Fin `fmap` apSubst su x
x :== y -> twoE (:==) x y
x :>= y -> twoE (:>=) x y
x :> y -> twoE (:>) x y
x :==: y -> twoE (:==:) x y
x :>: y -> twoE (:>) x y
bin f x y = do [x',y'] <- anyJust go [x,y]
return (f x' y')
twoE f x y = do [x',y'] <- anyJust (apSubst su) [x,y]
return (f x' y')
--------------------------------------------------------------------------------
-- Tries
--------------------------------------------------------------------------------
-- instance TrieKey Name
-- instance TrieKey Prop
-- instance TrieKey Expr
--------------------------------------------------------------------------------
-- Pretty Printing
--------------------------------------------------------------------------------
-- | Pretty print a name.
ppName :: Name -> Doc
ppName name =
case name of
UserName x -> pp x
SysName x -> char '_' <> text (names !! x)
-- | An infinite list of names, for pretty prinitng.
names :: [String]
names = concatMap gen [ 0 :: Integer .. ]
where
gen x = [ a : suff x | a <- [ 'a' .. 'z' ] ]
suff 0 = ""
suff x = show x
-- | Pretty print a top-level property.
ppProp :: Prop -> Doc
ppProp = ppPropPrec 0
-- | Pretty print a proposition, in the given precedence context.
ppPropPrec :: Int -> Prop -> Doc
ppPropPrec prec prop =
case prop of
Fin x -> fun "fin" ppExprPrec x
x :== y -> bin "==" 4 1 1 ppExprPrec x y
x :>= y -> bin ">=" 4 1 1 ppExprPrec x y
x :> y -> bin ">" 4 1 1 ppExprPrec x y
x :==: y -> bin "==#" 4 1 1 ppExprPrec x y
x :>: y -> bin ">#" 4 1 1 ppExprPrec x y
p :&& q -> bin "&&" 3 1 0 ppPropPrec p q
p :|| q -> bin "||" 2 1 0 ppPropPrec p q
Not p -> fun "not" ppPropPrec p
PTrue -> text "True"
PFalse -> text "False"
where
wrap p d = if prec > p then parens d else d
fun f how x = wrap 10 (text f <+> how 11 x)
bin op opP lMod rMod how x y =
wrap opP (sep [ how (opP + lMod) x, text op, how (opP + rMod) y ])
-- | Pretty print an expression at the top level.
ppExpr :: Expr -> Doc
ppExpr = ppExprPrec 0
-- | Pretty print an expression, in the given precedence context.
ppExprPrec :: Int -> Expr -> Doc
ppExprPrec prec expr =
case expr of
K Inf -> text "inf"
K (Nat n) -> integer n
Var a -> ppName a
x :+ y -> bin "+" 6 0 1 x y
x :- y -> bin "-" 6 0 1 x y
x :* y -> bin "*" 7 0 1 x y
Div x y -> fun "div" [x,y]
Mod x y -> fun "mod" [x,y]
x :^^ y -> bin "^^" 8 1 0 x y
Min x y -> fun "min" [x,y]
Max x y -> fun "max" [x,y]
Width x -> fun "width" [x]
LenFromThen x y w -> fun "lenFromThen" [x,y,w]
LenFromThenTo x y z -> fun "lenFromThenTo" [x,y,z]
where
wrap p d = if prec > p then parens d else d
fun f xs = wrap 10 (text f <+> sep (map (ppExprPrec 11) xs))
bin op opP lMod rMod x y =
wrap opP
(ppExprPrec (opP + lMod) x <+> text op <+> ppExprPrec (opP + rMod) y)
-- | Pretty print an experssion with ifs.
ppIfExpr :: IfExpr Expr -> Doc
ppIfExpr = ppIf ppProp ppExpr
-- | Pretty print an experssion with ifs.
ppIf :: (p -> Doc) -> (a -> Doc) -> IfExpr' p a -> Doc
ppIf ppAtom ppVal = go
where
go expr =
case expr of
If p t e -> hang (text "if" <+> ppAtom p) 2
( (text "then" <+> go t) $$
(text "else" <+> go e)
)
Return e -> ppVal e
Impossible -> text "<impossible>"
| ntc2/cryptol | src/Cryptol/TypeCheck/Solver/Numeric/AST.hs | bsd-3-clause | 11,768 | 0 | 15 | 4,150 | 4,006 | 2,129 | 1,877 | 262 | 15 |
{- $Id: AFRPTestsWFG.hs,v 1.2 2003/11/10 21:28:58 antony Exp $
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsWFG *
* Purpose: Test cases for wave-form generation *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module AFRPTestsWFG (wfg_tr, wfg_trs) where
import FRP.Yampa
import FRP.Yampa.Internals (Event(NoEvent, Event))
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for wave-form generation
------------------------------------------------------------------------------
wfg_inp1 = deltaEncode 1.0 $
[NoEvent, NoEvent, Event 1.0, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
wfg_inp2 = deltaEncode 1.0 $
[Event 1.0, NoEvent, NoEvent, NoEvent,
Event 2.0, NoEvent, NoEvent, NoEvent,
Event 3.0, Event 4.0, Event 4.0, NoEvent,
Event 0.0, NoEvent, NoEvent, NoEvent]
++ repeat NoEvent
wfg_t0 :: [Double]
wfg_t0 = take 16 $ embed (hold 99.99) wfg_inp1
wfg_t0r =
[99.99, 99.99, 1.0, 1.0,
2.0, 2.0, 2.0, 2.0,
3.0, 4.0, 4.0, 4.0,
0.0, 0.0, 0.0, 0.0]
wfg_t1 :: [Double]
wfg_t1 = take 16 $ embed (hold 99.99) wfg_inp2
wfg_t1r =
[1.0, 1.0, 1.0, 1.0,
2.0, 2.0, 2.0, 2.0,
3.0, 4.0, 4.0, 4.0,
0.0, 0.0, 0.0, 0.0]
wfg_inp3 = deltaEncode 1.0 $
[Nothing, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
wfg_inp4 = deltaEncode 1.0 $
[Just 0.0, Nothing, Just 1.0, Just 2.0, Just 3.0,
Just 4.0, Nothing, Nothing, Nothing, Just 3.0,
Just 2.0, Nothing, Just 1.0, Just 0.0, Just 1.0,
Just 2.0, Just 3.0, Nothing, Nothing, Just 4.0]
++ repeat Nothing
wfg_t2 :: [Double]
wfg_t2 = take 25 $ embed (trackAndHold 99.99) wfg_inp3
wfg_t2r =
[99.99, 99.99, 1.0, 2.0, 3.0,
4.0, 4.0, 4.0, 4.0, 3.0,
2.0, 2.0, 1.0, 0.0, 1.0,
2.0, 3.0, 3.0, 3.0, 4.0,
4.0, 4.0, 4.0, 4.0, 4.0]
wfg_t3 :: [Double]
wfg_t3 = take 25 $ embed (trackAndHold 99.99) wfg_inp4
wfg_t3r =
[0.0, 0.0, 1.0, 2.0, 3.0,
4.0, 4.0, 4.0, 4.0, 3.0,
2.0, 2.0, 1.0, 0.0, 1.0,
2.0, 3.0, 3.0, 3.0, 4.0,
4.0, 4.0, 4.0, 4.0, 4.0]
wfg_trs =
[ wfg_t0 ~= wfg_t0r,
wfg_t1 ~= wfg_t1r,
wfg_t2 ~= wfg_t2r,
wfg_t3 ~= wfg_t3r
]
wfg_tr = and wfg_trs
| ony/Yampa-core | tests/AFRPTestsWFG.hs | bsd-3-clause | 3,156 | 0 | 8 | 1,044 | 875 | 509 | 366 | 64 | 1 |
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -O -funbox-strict-fields #-}
-- We always optimise this, otherwise performance of a non-optimised
-- compiler is severely affected
--
-- (c) The University of Glasgow 2002-2006
--
-- Binary I/O library, with special tweaks for GHC
--
-- Based on the nhc98 Binary library, which is copyright
-- (c) Malcolm Wallace and Colin Runciman, University of York, 1998.
-- Under the terms of the license for that software, we must tell you
-- where you can obtain the original version of the Binary library, namely
-- http://www.cs.york.ac.uk/fp/nhc98/
module Binary
( {-type-} Bin,
{-class-} Binary(..),
{-type-} BinHandle,
SymbolTable, Dictionary,
openBinMem,
-- closeBin,
seekBin,
seekBy,
tellBin,
castBin,
writeBinMem,
readBinMem,
fingerprintBinMem,
computeFingerprint,
isEOFBin,
putAt, getAt,
-- for writing instances:
putByte,
getByte,
-- lazy Bin I/O
lazyGet,
lazyPut,
UserData(..), getUserData, setUserData,
newReadState, newWriteState,
putDictionary, getDictionary, putFS,
) where
#include "HsVersions.h"
-- The *host* architecture version:
#include "../includes/MachDeps.h"
import {-# SOURCE #-} Name (Name)
import FastString
import Panic
import UniqFM
import FastMutInt
import Fingerprint
import BasicTypes
import SrcLoc
import Foreign
import Data.Array
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BS
import qualified Data.ByteString.Unsafe as BS
import Data.IORef
import Data.Char ( ord, chr )
import Data.Time
import Data.Typeable
import Control.Monad ( when )
import System.IO as IO
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO.Error ( mkIOError, eofErrorType )
import GHC.Real ( Ratio(..) )
import GHC.Serialized
type BinArray = ForeignPtr Word8
---------------------------------------------------------------
-- BinHandle
---------------------------------------------------------------
data BinHandle
= BinMem { -- binary data stored in an unboxed array
bh_usr :: UserData, -- sigh, need parameterized modules :-)
_off_r :: !FastMutInt, -- the current offset
_sz_r :: !FastMutInt, -- size of the array (cached)
_arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1))
}
-- XXX: should really store a "high water mark" for dumping out
-- the binary data to a file.
getUserData :: BinHandle -> UserData
getUserData bh = bh_usr bh
setUserData :: BinHandle -> UserData -> BinHandle
setUserData bh us = bh { bh_usr = us }
---------------------------------------------------------------
-- Bin
---------------------------------------------------------------
newtype Bin a = BinPtr Int
deriving (Eq, Ord, Show, Bounded)
castBin :: Bin a -> Bin b
castBin (BinPtr i) = BinPtr i
---------------------------------------------------------------
-- class Binary
---------------------------------------------------------------
class Binary a where
put_ :: BinHandle -> a -> IO ()
put :: BinHandle -> a -> IO (Bin a)
get :: BinHandle -> IO a
-- define one of put_, put. Use of put_ is recommended because it
-- is more likely that tail-calls can kick in, and we rarely need the
-- position return value.
put_ bh a = do _ <- put bh a; return ()
put bh a = do p <- tellBin bh; put_ bh a; return p
putAt :: Binary a => BinHandle -> Bin a -> a -> IO ()
putAt bh p x = do seekBin bh p; put_ bh x; return ()
getAt :: Binary a => BinHandle -> Bin a -> IO a
getAt bh p = do seekBin bh p; get bh
openBinMem :: Int -> IO BinHandle
openBinMem size
| size <= 0 = error "Data.Binary.openBinMem: size must be >= 0"
| otherwise = do
arr <- mallocForeignPtrBytes size
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r size
return (BinMem noUserData ix_r sz_r arr_r)
tellBin :: BinHandle -> IO (Bin a)
tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix)
seekBin :: BinHandle -> Bin a -> IO ()
seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do
sz <- readFastMutInt sz_r
if (p >= sz)
then do expandBin h p; writeFastMutInt ix_r p
else writeFastMutInt ix_r p
seekBy :: BinHandle -> Int -> IO ()
seekBy h@(BinMem _ ix_r sz_r _) off = do
sz <- readFastMutInt sz_r
ix <- readFastMutInt ix_r
let ix' = ix + off
if (ix' >= sz)
then do expandBin h ix'; writeFastMutInt ix_r ix'
else writeFastMutInt ix_r ix'
isEOFBin :: BinHandle -> IO Bool
isEOFBin (BinMem _ ix_r sz_r _) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
return (ix >= sz)
writeBinMem :: BinHandle -> FilePath -> IO ()
writeBinMem (BinMem _ ix_r _ arr_r) fn = do
h <- openBinaryFile fn WriteMode
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
withForeignPtr arr $ \p -> hPutBuf h p ix
hClose h
readBinMem :: FilePath -> IO BinHandle
-- Return a BinHandle with a totally undefined State
readBinMem filename = do
h <- openBinaryFile filename ReadMode
filesize' <- hFileSize h
let filesize = fromIntegral filesize'
arr <- mallocForeignPtrBytes (filesize*2)
count <- withForeignPtr arr $ \p -> hGetBuf h p filesize
when (count /= filesize) $
error ("Binary.readBinMem: only read " ++ show count ++ " bytes")
hClose h
arr_r <- newIORef arr
ix_r <- newFastMutInt
writeFastMutInt ix_r 0
sz_r <- newFastMutInt
writeFastMutInt sz_r filesize
return (BinMem noUserData ix_r sz_r arr_r)
fingerprintBinMem :: BinHandle -> IO Fingerprint
fingerprintBinMem (BinMem _ ix_r _ arr_r) = do
arr <- readIORef arr_r
ix <- readFastMutInt ix_r
withForeignPtr arr $ \p -> fingerprintData p ix
computeFingerprint :: Binary a
=> (BinHandle -> Name -> IO ())
-> a
-> IO Fingerprint
computeFingerprint put_name a = do
bh <- openBinMem (3*1024) -- just less than a block
bh <- return $ setUserData bh $ newWriteState put_name putFS
put_ bh a
fingerprintBinMem bh
-- expand the size of the array to include a specified offset
expandBin :: BinHandle -> Int -> IO ()
expandBin (BinMem _ _ sz_r arr_r) off = do
sz <- readFastMutInt sz_r
let sz' = head (dropWhile (<= off) (iterate (* 2) sz))
arr <- readIORef arr_r
arr' <- mallocForeignPtrBytes sz'
withForeignPtr arr $ \old ->
withForeignPtr arr' $ \new ->
copyBytes new old sz
writeFastMutInt sz_r sz'
writeIORef arr_r arr'
-- -----------------------------------------------------------------------------
-- Low-level reading/writing of bytes
putWord8 :: BinHandle -> Word8 -> IO ()
putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
-- double the size of the array if it overflows
if (ix >= sz)
then do expandBin h ix
putWord8 h w
else do arr <- readIORef arr_r
withForeignPtr arr $ \p -> pokeByteOff p ix w
writeFastMutInt ix_r (ix+1)
return ()
getWord8 :: BinHandle -> IO Word8
getWord8 (BinMem _ ix_r sz_r arr_r) = do
ix <- readFastMutInt ix_r
sz <- readFastMutInt sz_r
when (ix >= sz) $
ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing)
arr <- readIORef arr_r
w <- withForeignPtr arr $ \p -> peekByteOff p ix
writeFastMutInt ix_r (ix+1)
return w
putByte :: BinHandle -> Word8 -> IO ()
putByte bh w = put_ bh w
getByte :: BinHandle -> IO Word8
getByte = getWord8
-- -----------------------------------------------------------------------------
-- Primitve Word writes
instance Binary Word8 where
put_ = putWord8
get = getWord8
instance Binary Word16 where
put_ h w = do -- XXX too slow.. inline putWord8?
putByte h (fromIntegral (w `shiftR` 8))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2)
instance Binary Word32 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 24))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 24) .|.
(fromIntegral w2 `shiftL` 16) .|.
(fromIntegral w3 `shiftL` 8) .|.
(fromIntegral w4))
instance Binary Word64 where
put_ h w = do
putByte h (fromIntegral (w `shiftR` 56))
putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff))
putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff))
putByte h (fromIntegral (w .&. 0xff))
get h = do
w1 <- getWord8 h
w2 <- getWord8 h
w3 <- getWord8 h
w4 <- getWord8 h
w5 <- getWord8 h
w6 <- getWord8 h
w7 <- getWord8 h
w8 <- getWord8 h
return $! ((fromIntegral w1 `shiftL` 56) .|.
(fromIntegral w2 `shiftL` 48) .|.
(fromIntegral w3 `shiftL` 40) .|.
(fromIntegral w4 `shiftL` 32) .|.
(fromIntegral w5 `shiftL` 24) .|.
(fromIntegral w6 `shiftL` 16) .|.
(fromIntegral w7 `shiftL` 8) .|.
(fromIntegral w8))
-- -----------------------------------------------------------------------------
-- Primitve Int writes
instance Binary Int8 where
put_ h w = put_ h (fromIntegral w :: Word8)
get h = do w <- get h; return $! (fromIntegral (w::Word8))
instance Binary Int16 where
put_ h w = put_ h (fromIntegral w :: Word16)
get h = do w <- get h; return $! (fromIntegral (w::Word16))
instance Binary Int32 where
put_ h w = put_ h (fromIntegral w :: Word32)
get h = do w <- get h; return $! (fromIntegral (w::Word32))
instance Binary Int64 where
put_ h w = put_ h (fromIntegral w :: Word64)
get h = do w <- get h; return $! (fromIntegral (w::Word64))
-- -----------------------------------------------------------------------------
-- Instances for standard types
instance Binary () where
put_ _ () = return ()
get _ = return ()
instance Binary Bool where
put_ bh b = putByte bh (fromIntegral (fromEnum b))
get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x))
instance Binary Char where
put_ bh c = put_ bh (fromIntegral (ord c) :: Word32)
get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32)))
instance Binary Int where
put_ bh i = put_ bh (fromIntegral i :: Int64)
get bh = do
x <- get bh
return $! (fromIntegral (x :: Int64))
instance Binary a => Binary [a] where
put_ bh l = do
let len = length l
if (len < 0xff)
then putByte bh (fromIntegral len :: Word8)
else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32)
mapM_ (put_ bh) l
get bh = do
b <- getByte bh
len <- if b == 0xff
then get bh
else return (fromIntegral b :: Word32)
let loop 0 = return []
loop n = do a <- get bh; as <- loop (n-1); return (a:as)
loop len
instance (Binary a, Binary b) => Binary (a,b) where
put_ bh (a,b) = do put_ bh a; put_ bh b
get bh = do a <- get bh
b <- get bh
return (a,b)
instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where
put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (a,b,c)
instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where
put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (a,b,c,d)
instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where
put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e;
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
e <- get bh
return (a,b,c,d,e)
instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where
put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f;
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
e <- get bh
f <- get bh
return (a,b,c,d,e,f)
instance Binary a => Binary (Maybe a) where
put_ bh Nothing = putByte bh 0
put_ bh (Just a) = do putByte bh 1; put_ bh a
get bh = do h <- getWord8 bh
case h of
0 -> return Nothing
_ -> do x <- get bh; return (Just x)
instance (Binary a, Binary b) => Binary (Either a b) where
put_ bh (Left a) = do putByte bh 0; put_ bh a
put_ bh (Right b) = do putByte bh 1; put_ bh b
get bh = do h <- getWord8 bh
case h of
0 -> do a <- get bh ; return (Left a)
_ -> do b <- get bh ; return (Right b)
instance Binary UTCTime where
put_ bh u = do put_ bh (utctDay u)
put_ bh (utctDayTime u)
get bh = do day <- get bh
dayTime <- get bh
return $ UTCTime { utctDay = day, utctDayTime = dayTime }
instance Binary Day where
put_ bh d = put_ bh (toModifiedJulianDay d)
get bh = do i <- get bh
return $ ModifiedJulianDay { toModifiedJulianDay = i }
instance Binary DiffTime where
put_ bh dt = put_ bh (toRational dt)
get bh = do r <- get bh
return $ fromRational r
--to quote binary-0.3 on this code idea,
--
-- TODO This instance is not architecture portable. GMP stores numbers as
-- arrays of machine sized words, so the byte format is not portable across
-- architectures with different endianess and word size.
--
-- This makes it hard (impossible) to make an equivalent instance
-- with code that is compilable with non-GHC. Do we need any instance
-- Binary Integer, and if so, does it have to be blazing fast? Or can
-- we just change this instance to be portable like the rest of the
-- instances? (binary package has code to steal for that)
--
-- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.hs
instance Binary Integer where
-- XXX This is hideous
put_ bh i = put_ bh (show i)
get bh = do str <- get bh
case reads str of
[(i, "")] -> return i
_ -> fail ("Binary Integer: got " ++ show str)
{-
-- This code is currently commented out.
-- See https://ghc.haskell.org/trac/ghc/ticket/3379#comment:10 for
-- discussion.
put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#)
put_ bh (J# s# a#) = do
putByte bh 1
put_ bh (I# s#)
let sz# = sizeofByteArray# a# -- in *bytes*
put_ bh (I# sz#) -- in *bytes*
putByteArray bh a# sz#
get bh = do
b <- getByte bh
case b of
0 -> do (I# i#) <- get bh
return (S# i#)
_ -> do (I# s#) <- get bh
sz <- get bh
(BA a#) <- getByteArray bh sz
return (J# s# a#)
putByteArray :: BinHandle -> ByteArray# -> Int# -> IO ()
putByteArray bh a s# = loop 0#
where loop n#
| n# ==# s# = return ()
| otherwise = do
putByte bh (indexByteArray a n#)
loop (n# +# 1#)
getByteArray :: BinHandle -> Int -> IO ByteArray
getByteArray bh (I# sz) = do
(MBA arr) <- newByteArray sz
let loop n
| n ==# sz = return ()
| otherwise = do
w <- getByte bh
writeByteArray arr n w
loop (n +# 1#)
loop 0#
freezeByteArray arr
-}
{-
data ByteArray = BA ByteArray#
data MBA = MBA (MutableByteArray# RealWorld)
newByteArray :: Int# -> IO MBA
newByteArray sz = IO $ \s ->
case newByteArray# sz s of { (# s, arr #) ->
(# s, MBA arr #) }
freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray
freezeByteArray arr = IO $ \s ->
case unsafeFreezeByteArray# arr s of { (# s, arr #) ->
(# s, BA arr #) }
writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO ()
writeByteArray arr i (W8# w) = IO $ \s ->
case writeWord8Array# arr i w s of { s ->
(# s, () #) }
indexByteArray :: ByteArray# -> Int# -> Word8
indexByteArray a# n# = W8# (indexWord8Array# a# n#)
-}
instance (Binary a) => Binary (Ratio a) where
put_ bh (a :% b) = do put_ bh a; put_ bh b
get bh = do a <- get bh; b <- get bh; return (a :% b)
instance Binary (Bin a) where
put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32)
get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32)))
-- -----------------------------------------------------------------------------
-- Instances for Data.Typeable stuff
instance Binary TyCon where
put_ bh tc = do
put_ bh (tyConPackage tc)
put_ bh (tyConModule tc)
put_ bh (tyConName tc)
get bh = do
p <- get bh
m <- get bh
n <- get bh
return (mkTyCon3 p m n)
instance Binary TypeRep where
put_ bh type_rep = do
let (ty_con, child_type_reps) = splitTyConApp type_rep
put_ bh ty_con
put_ bh child_type_reps
get bh = do
ty_con <- get bh
child_type_reps <- get bh
return (mkTyConApp ty_con child_type_reps)
-- -----------------------------------------------------------------------------
-- Lazy reading/writing
lazyPut :: Binary a => BinHandle -> a -> IO ()
lazyPut bh a = do
-- output the obj with a ptr to skip over it:
pre_a <- tellBin bh
put_ bh pre_a -- save a slot for the ptr
put_ bh a -- dump the object
q <- tellBin bh -- q = ptr to after object
putAt bh pre_a q -- fill in slot before a with ptr to q
seekBin bh q -- finally carry on writing at q
lazyGet :: Binary a => BinHandle -> IO a
lazyGet bh = do
p <- get bh -- a BinPtr
p_a <- tellBin bh
a <- unsafeInterleaveIO $ do
-- NB: Use a fresh off_r variable in the child thread, for thread
-- safety.
off_r <- newFastMutInt
getAt bh { _off_r = off_r } p_a
seekBin bh p -- skip over the object for now
return a
-- -----------------------------------------------------------------------------
-- UserData
-- -----------------------------------------------------------------------------
data UserData =
UserData {
-- for *deserialising* only:
ud_get_name :: BinHandle -> IO Name,
ud_get_fs :: BinHandle -> IO FastString,
-- for *serialising* only:
ud_put_name :: BinHandle -> Name -> IO (),
ud_put_fs :: BinHandle -> FastString -> IO ()
}
newReadState :: (BinHandle -> IO Name)
-> (BinHandle -> IO FastString)
-> UserData
newReadState get_name get_fs
= UserData { ud_get_name = get_name,
ud_get_fs = get_fs,
ud_put_name = undef "put_name",
ud_put_fs = undef "put_fs"
}
newWriteState :: (BinHandle -> Name -> IO ())
-> (BinHandle -> FastString -> IO ())
-> UserData
newWriteState put_name put_fs
= UserData { ud_get_name = undef "get_name",
ud_get_fs = undef "get_fs",
ud_put_name = put_name,
ud_put_fs = put_fs
}
noUserData :: a
noUserData = undef "UserData"
undef :: String -> a
undef s = panic ("Binary.UserData: no " ++ s)
---------------------------------------------------------
-- The Dictionary
---------------------------------------------------------
type Dictionary = Array Int FastString -- The dictionary
-- Should be 0-indexed
putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO ()
putDictionary bh sz dict = do
put_ bh sz
mapM_ (putFS bh) (elems (array (0,sz-1) (eltsUFM dict)))
getDictionary :: BinHandle -> IO Dictionary
getDictionary bh = do
sz <- get bh
elems <- sequence (take sz (repeat (getFS bh)))
return (listArray (0,sz-1) elems)
---------------------------------------------------------
-- The Symbol Table
---------------------------------------------------------
-- On disk, the symbol table is an array of IfaceExtName, when
-- reading it in we turn it into a SymbolTable.
type SymbolTable = Array Int Name
---------------------------------------------------------
-- Reading and writing FastStrings
---------------------------------------------------------
putFS :: BinHandle -> FastString -> IO ()
putFS bh fs = putBS bh $ fastStringToByteString fs
getFS :: BinHandle -> IO FastString
getFS bh = do bs <- getBS bh
return $! mkFastStringByteString bs
putBS :: BinHandle -> ByteString -> IO ()
putBS bh bs =
BS.unsafeUseAsCStringLen bs $ \(ptr, l) -> do
put_ bh l
let
go n | n == l = return ()
| otherwise = do
b <- peekElemOff (castPtr ptr) n
putByte bh b
go (n+1)
go 0
{- -- possible faster version, not quite there yet:
getBS bh@BinMem{} = do
(I# l) <- get bh
arr <- readIORef (arr_r bh)
off <- readFastMutInt (off_r bh)
return $! (mkFastSubBytesBA# arr off l)
-}
getBS :: BinHandle -> IO ByteString
getBS bh = do
l <- get bh
fp <- mallocForeignPtrBytes l
withForeignPtr fp $ \ptr -> do
let go n | n == l = return $ BS.fromForeignPtr fp 0 l
| otherwise = do
b <- getByte bh
pokeElemOff ptr n b
go (n+1)
--
go 0
instance Binary ByteString where
put_ bh f = putBS bh f
get bh = getBS bh
instance Binary FastString where
put_ bh f =
case getUserData bh of
UserData { ud_put_fs = put_fs } -> put_fs bh f
get bh =
case getUserData bh of
UserData { ud_get_fs = get_fs } -> get_fs bh
-- Here to avoid loop
instance Binary Fingerprint where
put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2
get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2)
instance Binary FunctionOrData where
put_ bh IsFunction = putByte bh 0
put_ bh IsData = putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> return IsFunction
1 -> return IsData
_ -> panic "Binary FunctionOrData"
instance Binary TupleSort where
put_ bh BoxedTuple = putByte bh 0
put_ bh UnboxedTuple = putByte bh 1
put_ bh ConstraintTuple = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> do return BoxedTuple
1 -> do return UnboxedTuple
_ -> do return ConstraintTuple
instance Binary Activation where
put_ bh NeverActive = do
putByte bh 0
put_ bh AlwaysActive = do
putByte bh 1
put_ bh (ActiveBefore src aa) = do
putByte bh 2
put_ bh src
put_ bh aa
put_ bh (ActiveAfter src ab) = do
putByte bh 3
put_ bh src
put_ bh ab
get bh = do
h <- getByte bh
case h of
0 -> do return NeverActive
1 -> do return AlwaysActive
2 -> do src <- get bh
aa <- get bh
return (ActiveBefore src aa)
_ -> do src <- get bh
ab <- get bh
return (ActiveAfter src ab)
instance Binary InlinePragma where
put_ bh (InlinePragma s a b c d) = do
put_ bh s
put_ bh a
put_ bh b
put_ bh c
put_ bh d
get bh = do
s <- get bh
a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (InlinePragma s a b c d)
instance Binary RuleMatchInfo where
put_ bh FunLike = putByte bh 0
put_ bh ConLike = putByte bh 1
get bh = do
h <- getByte bh
if h == 1 then return ConLike
else return FunLike
instance Binary InlineSpec where
put_ bh EmptyInlineSpec = putByte bh 0
put_ bh Inline = putByte bh 1
put_ bh Inlinable = putByte bh 2
put_ bh NoInline = putByte bh 3
get bh = do h <- getByte bh
case h of
0 -> return EmptyInlineSpec
1 -> return Inline
2 -> return Inlinable
_ -> return NoInline
instance Binary RecFlag where
put_ bh Recursive = do
putByte bh 0
put_ bh NonRecursive = do
putByte bh 1
get bh = do
h <- getByte bh
case h of
0 -> do return Recursive
_ -> do return NonRecursive
instance Binary OverlapMode where
put_ bh (NoOverlap s) = putByte bh 0 >> put_ bh s
put_ bh (Overlaps s) = putByte bh 1 >> put_ bh s
put_ bh (Incoherent s) = putByte bh 2 >> put_ bh s
put_ bh (Overlapping s) = putByte bh 3 >> put_ bh s
put_ bh (Overlappable s) = putByte bh 4 >> put_ bh s
get bh = do
h <- getByte bh
case h of
0 -> (get bh) >>= \s -> return $ NoOverlap s
1 -> (get bh) >>= \s -> return $ Overlaps s
2 -> (get bh) >>= \s -> return $ Incoherent s
3 -> (get bh) >>= \s -> return $ Overlapping s
4 -> (get bh) >>= \s -> return $ Overlappable s
_ -> panic ("get OverlapMode" ++ show h)
instance Binary OverlapFlag where
put_ bh flag = do put_ bh (overlapMode flag)
put_ bh (isSafeOverlap flag)
get bh = do
h <- get bh
b <- get bh
return OverlapFlag { overlapMode = h, isSafeOverlap = b }
instance Binary FixityDirection where
put_ bh InfixL = do
putByte bh 0
put_ bh InfixR = do
putByte bh 1
put_ bh InfixN = do
putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> do return InfixL
1 -> do return InfixR
_ -> do return InfixN
instance Binary Fixity where
put_ bh (Fixity src aa ab) = do
put_ bh src
put_ bh aa
put_ bh ab
get bh = do
src <- get bh
aa <- get bh
ab <- get bh
return (Fixity src aa ab)
instance Binary WarningTxt where
put_ bh (WarningTxt s w) = do
putByte bh 0
put_ bh s
put_ bh w
put_ bh (DeprecatedTxt s d) = do
putByte bh 1
put_ bh s
put_ bh d
get bh = do
h <- getByte bh
case h of
0 -> do s <- get bh
w <- get bh
return (WarningTxt s w)
_ -> do s <- get bh
d <- get bh
return (DeprecatedTxt s d)
instance Binary StringLiteral where
put_ bh (StringLiteral st fs) = do
put_ bh st
put_ bh fs
get bh = do
st <- get bh
fs <- get bh
return (StringLiteral st fs)
instance Binary a => Binary (GenLocated SrcSpan a) where
put_ bh (L l x) = do
put_ bh l
put_ bh x
get bh = do
l <- get bh
x <- get bh
return (L l x)
instance Binary SrcSpan where
put_ bh (RealSrcSpan ss) = do
putByte bh 0
put_ bh (srcSpanFile ss)
put_ bh (srcSpanStartLine ss)
put_ bh (srcSpanStartCol ss)
put_ bh (srcSpanEndLine ss)
put_ bh (srcSpanEndCol ss)
put_ bh (UnhelpfulSpan s) = do
putByte bh 1
put_ bh s
get bh = do
h <- getByte bh
case h of
0 -> do f <- get bh
sl <- get bh
sc <- get bh
el <- get bh
ec <- get bh
return (mkSrcSpan (mkSrcLoc f sl sc)
(mkSrcLoc f el ec))
_ -> do s <- get bh
return (UnhelpfulSpan s)
instance Binary Serialized where
put_ bh (Serialized the_type bytes) = do
put_ bh the_type
put_ bh bytes
get bh = do
the_type <- get bh
bytes <- get bh
return (Serialized the_type bytes)
| oldmanmike/ghc | compiler/utils/Binary.hs | bsd-3-clause | 29,425 | 0 | 19 | 9,755 | 9,202 | 4,440 | 4,762 | 662 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# Language ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS -Wno-noncanonical-monoid-instances #-}
module T13758 where
import Data.Coerce
import GHC.Generics
import Data.Semigroup
-----
class Monoid' f where
mempty' :: f x
mappend' :: f x -> f x -> f x
instance Monoid' U1 where
mempty' = U1
mappend' U1 U1 = U1
instance Monoid a => Monoid' (K1 i a) where
mempty' = K1 mempty
mappend' (K1 x) (K1 y) = K1 (x `mappend` y)
instance Monoid' f => Monoid' (M1 i c f) where
mempty' = M1 mempty'
mappend' (M1 x) (M1 y) = M1 (x `mappend'` y)
instance (Monoid' f, Monoid' h) => Monoid' (f :*: h) where
mempty' = mempty' :*: mempty'
mappend' (x1 :*: y1) (x2 :*: y2) = mappend' x1 x2 :*: mappend' y1 y2
memptydefault :: (Generic a, Monoid' (Rep a)) => a
memptydefault = to mempty'
mappenddefault :: (Generic a, Monoid' (Rep a)) => a -> a -> a
mappenddefault x y = to (mappend' (from x) (from y))
-----
newtype GenericMonoid a = GenericMonoid a
instance (Generic a, Monoid' (Rep a)) => Semigroup (GenericMonoid a) where
(<>) = coerce (mappenddefault :: a -> a -> a)
instance (Generic a, Monoid' (Rep a)) => Monoid (GenericMonoid a) where
mempty = coerce (memptydefault :: a)
mappend = coerce (mappenddefault :: a -> a -> a)
data Urls = Urls String String String
deriving (Show, Generic)
newtype UrlsDeriv = UD (GenericMonoid Urls)
deriving (Semigroup, Monoid)
| sdiehl/ghc | testsuite/tests/deriving/should_compile/T13758.hs | bsd-3-clause | 1,600 | 0 | 9 | 310 | 589 | 314 | 275 | 41 | 1 |
{-# LANGUAGE CPP, FlexibleContexts, QuasiQuotes, DeriveDataTypeable, DeriveGeneric, OverloadedStrings #-}
module Gen2.ClosureInfo where
import Control.DeepSeq
import GHC.Generics
import Data.Array
import Data.Bits ((.|.), shiftL)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Default
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Data.Typeable (Typeable)
import Compiler.JMacro
import Gen2.StgAst ()
import Gen2.Utils
import DynFlags
import StgSyn
import DataCon
import TyCon
import Type
import Id
-- closure types
data CType = Thunk | Fun | Pap | Con | Blackhole | StackFrame
deriving (Show, Eq, Ord, Enum, Bounded)
--
ctNum :: CType -> Int
ctNum Fun = 1
ctNum Con = 2
ctNum Thunk = 0 -- 4
ctNum Pap = 3 -- 8
-- ctNum Ind = 4 -- 16
ctNum Blackhole = 5 -- 32
ctNum StackFrame = -1
instance ToJExpr CType where
toJExpr e = toJExpr (ctNum e)
-- function argument and free variable types
data VarType = PtrV -- pointer = reference to heap object (closure object)
| VoidV -- no fields
-- | FloatV -- one field -- no single precision supported
| DoubleV -- one field
| IntV -- one field
| LongV -- two fields
| AddrV -- a pointer not to the heap: two fields, array + index
| RtsObjV -- some RTS object from GHCJS (for example TVar#, MVar#, MutVar#, Weak#)
| ObjV -- some JS object, user supplied, be careful around these, can be anything
| ArrV -- boxed array
deriving (Eq, Ord, Show, Enum, Bounded, Generic)
instance NFData VarType
-- can we unbox C x to x, only if x is represented as a Number
isUnboxableCon :: DataCon -> Bool
isUnboxableCon dc
| [t] <- dataConRepArgTys dc, [t1] <- typeVt t =
isUnboxable t1 &&
dataConTag dc == 1 &&
length (tyConDataCons $ dataConTyCon dc) == 1
| otherwise = False
-- one-constructor types with one primitive field represented as a JS Number
-- can be unboxed
isUnboxable :: VarType -> Bool
isUnboxable DoubleV = True
isUnboxable IntV = True -- includes Char#
isUnboxable _ = False
varSize :: VarType -> Int
varSize VoidV = 0
varSize LongV = 2 -- hi, low
varSize AddrV = 2 -- obj/array, offset
varSize _ = 1
typeSize :: Type -> Int
typeSize = sum . map varSize . typeVt
isVoid :: VarType -> Bool
isVoid VoidV = True
isVoid _ = False
isPtr :: VarType -> Bool
isPtr PtrV = True
isPtr _ = False
isSingleVar :: VarType -> Bool
isSingleVar v = varSize v == 1
isMultiVar :: VarType -> Bool
isMultiVar v = varSize v > 1
-- can we pattern match on these values in a case?
isMatchable :: [VarType] -> Bool
isMatchable [DoubleV] = True
isMatchable [IntV] = True
isMatchable _ = False
tyConVt :: TyCon -> [VarType]
tyConVt = typeVt . mkTyConTy
idVt :: Id -> [VarType]
idVt = typeVt . idType
typeVt :: Type -> [VarType]
typeVt t = case repType t of
UbxTupleRep uts -> concatMap typeVt uts
UnaryRep ut -> [uTypeVt ut]
-- only use if you know it's not an unboxed tuple
uTypeVt :: UnaryType -> VarType
uTypeVt ut
| isPrimitiveType ut = primTypeVt ut
| otherwise = primRepVt . typePrimRep $ ut
where
primRepVt VoidRep = VoidV
primRepVt PtrRep = PtrV -- fixme does ByteArray# ever map to this?
primRepVt IntRep = IntV
primRepVt WordRep = IntV
primRepVt Int64Rep = LongV
primRepVt Word64Rep = LongV
primRepVt AddrRep = AddrV
primRepVt FloatRep = DoubleV
primRepVt DoubleRep = DoubleV
primRepVt (VecRep{}) = error "uTypeVt: vector types are unsupported"
primTypeVt :: Type -> VarType
primTypeVt t = case repType t of
UnaryRep ut -> case tyConAppTyCon_maybe ut of
Nothing -> error "primTypeVt: not a TyCon"
Just tc -> go (show tc)
_ -> error "primTypeVt: non-unary type found"
where
pr xs = "ghc-prim:GHC.Prim." ++ xs
go st
| st == pr "Addr#" = AddrV
| st == pr "Int#" = IntV
| st == pr "Int64#" = LongV
| st == pr "Char#" = IntV
| st == pr "Word#" = IntV
| st == pr "Word64#" = LongV
| st == pr "Double#" = DoubleV
| st == pr "Float#" = DoubleV
| st == pr "Array#" = ArrV
| st == pr "MutableArray#" = ArrV
| st == pr "ByteArray#" = ObjV -- can contain any JS reference, used for JSRef
| st == pr "MutableByteArray#" = ObjV -- can contain any JS reference, used for JSRef
| st == pr "ArrayArray#" = ArrV
| st == pr "MutableArrayArray#" = ArrV
| st == pr "MutVar#" = RtsObjV
| st == pr "TVar#" = RtsObjV
| st == pr "MVar#" = RtsObjV
| st == pr "State#" = VoidV
| st == pr "RealWorld" = VoidV
| st == pr "ThreadId#" = RtsObjV
| st == pr "Weak#" = RtsObjV
| st == pr "StablePtr#" = AddrV
| st == pr "StableName#" = RtsObjV
| st == pr "Void#" = VoidV
| st == pr "Proxy#" = VoidV
| st == pr "MutVar#" = RtsObjV
| st == pr "BCO#" = RtsObjV -- fixme what do we need here?
| st == pr "~#" = VoidV -- coercion token?
| st == pr "~R#" = VoidV -- role
| st == pr "Any" = PtrV
#if __GLASGOW_HASKELL__ >= 709
| st == pr "SmallMutableArray#" = ArrV
| st == pr "SmallArray#" = ArrV
#endif
| st == "Data.Dynamic.Obj" = PtrV -- ?
| otherwise = error ("primTypeVt: unrecognized primitive type: " ++ st)
argVt :: StgArg -> VarType
argVt = uTypeVt . stgArgType
instance ToJExpr VarType where
toJExpr = toJExpr . fromEnum
data ClosureInfo = ClosureInfo
{ ciVar :: Text -- ^ object being infod
, ciRegs :: CIRegs -- ^ things in registers when this is the next closure to enter
, ciName :: Text -- ^ friendly name for printing
, ciLayout :: CILayout -- ^ heap/stack layout of the object
, ciType :: CIType -- ^ type of the object, with extra info where required
, ciStatic :: CIStatic -- ^ static references of this object
}
deriving (Eq, Ord, Show, Generic)
instance NFData ClosureInfo
data CIType = CIFun { citArity :: Int -- ^ function arity
, citRegs :: Int -- ^ number of registers for the args
}
| CIThunk
| CICon { citConstructor :: Int }
| CIPap
| CIBlackhole
| CIStackFrame
deriving (Eq, Ord, Show, Generic)
instance NFData CIType
data CIRegs = CIRegsUnknown
| CIRegs { ciRegsSkip :: Int -- ^ unused registers before actual args start
, ciRegsTypes :: [VarType] -- ^ args
}
deriving (Eq, Ord, Show, Generic)
instance NFData CIRegs
data CIStatic = -- CIStaticParent { staticParent :: Ident } -- ^ static refs are stored in parent in fungroup
CIStaticRefs { staticRefs :: [Text] } -- ^ list of refs that need to be kept alive
deriving (Eq, Ord, Show, Generic)
instance NFData CIStatic
noStatic :: CIStatic
noStatic = CIStaticRefs []
-- | static refs: array = references, null = nothing to report
-- note: only works after all top-level objects have been created
instance ToJExpr CIStatic where
toJExpr (CIStaticRefs []) = [je| null |]
toJExpr (CIStaticRefs rs) = toJExpr (map TxtI rs)
data CILayout = CILayoutVariable -- layout stored in object itself, first position from the start
| CILayoutUnknown -- fixed size, but content unknown (for example stack apply frame)
{ layoutSize :: !Int
}
| CILayoutFixed -- whole layout known
{ layoutSize :: !Int -- closure size in array positions, including entry
, layout :: [VarType]
}
deriving (Eq, Ord, Show, Generic)
instance NFData CILayout
-- standard fixed layout: payload types
-- payload starts at .d1 for heap objects, entry closest to Sp for stack frames
fixedLayout :: [VarType] -> CILayout
fixedLayout vts = CILayoutFixed (sum (map varSize vts)) vts
layoutSizeMaybe :: CILayout -> Maybe Int
layoutSizeMaybe (CILayoutUnknown n) = Just n
layoutSizeMaybe (CILayoutFixed n _) = Just n
layoutSizeMaybe _ = Nothing
{-
Some stack frames don't need explicit information, since the
frame size can be determined from inspecting the types on the stack
requirements:
- stack frame
- fixed size, known layout
- one register value
- no ObjV (the next function on the stack should be the start of the next frame, not something in this frame)
- no static references
-}
implicitLayout :: ClosureInfo -> Bool
implicitLayout ci
| CILayoutFixed _ layout <- ciLayout ci
, CIStaticRefs [] <- ciStatic ci
, CIStackFrame <- ciType ci
, CIRegs 0 rs <- ciRegs ci =
sum (map varSize rs) == 1 &&
null (filter (==ObjV) layout)
| otherwise = False
-- | note: the statements only work after all top-level objects have been created
instance ToStat ClosureInfo where
toStat = closureInfoStat False
closureInfoStat :: Bool -> ClosureInfo -> JStat
closureInfoStat debug (ClosureInfo obj rs name layout CIThunk srefs) =
setObjInfoL debug obj rs layout Thunk name 0 srefs
closureInfoStat debug (ClosureInfo obj rs name layout (CIFun arity nregs) srefs) =
setObjInfoL debug obj rs layout Fun name (mkArityTag arity nregs) srefs
closureInfoStat debug (ClosureInfo obj rs name layout (CICon con) srefs) =
setObjInfoL debug obj rs layout Con name con srefs
closureInfoStat debug (ClosureInfo obj rs name layout CIBlackhole srefs) =
setObjInfoL debug obj rs layout Blackhole name 0 srefs
closureInfoStat debug (ClosureInfo obj rs name layout CIPap srefs) =
setObjInfoL debug obj rs layout Pap name 0 srefs
closureInfoStat debug (ClosureInfo obj rs name layout CIStackFrame srefs) =
setObjInfoL debug obj rs layout StackFrame name 0 srefs
mkArityTag :: Int -> Int -> Int
mkArityTag arity registers = arity .|. (registers `shiftL` 8)
setObjInfoL :: Bool -- ^ debug: output symbol names
-> Text -- ^ the object name
-> CIRegs -- ^ things in registers
-> CILayout -- ^ layout of the object
-> CType -- ^ closure type
-> Text -- ^ object name, for printing
-> Int -- ^ `a' argument, depends on type (arity, conid)
-> CIStatic -- ^ static refs
-> JStat
setObjInfoL debug obj rs CILayoutVariable t n a =
setObjInfo debug obj t n [] a (-1) rs
setObjInfoL debug obj rs (CILayoutUnknown size) t n a =
setObjInfo debug obj t n xs a size rs
where
xs = toTypeList (replicate size ObjV)
setObjInfoL debug obj rs (CILayoutFixed size layout) t n a =
setObjInfo debug obj t n xs a size rs
where
xs = toTypeList layout
toTypeList :: [VarType] -> [Int]
toTypeList = concatMap (\x -> replicate (varSize x) (fromEnum x))
setObjInfo :: Bool -- ^ debug: output all symbol names
-> Text -- ^ the thing to modify
-> CType -- ^ closure type
-> Text -- ^ object name, for printing
-> [Int] -- ^ list of item types in the object, if known (free variables, datacon fields)
-> Int -- ^ extra 'a' parameter, for constructor tag or arity
-> Int -- ^ object size, -1 (number of vars) for unknown
-> CIRegs -- ^ things in registers [VarType] -- ^ things in registers
-> CIStatic -- ^ static refs
-> JStat
setObjInfo debug obj t name fields a size regs static
| debug = [j| h$setObjInfo(`TxtI obj`, `t`, `name`, `fields`, `a`, `size`, `regTag regs`, `static`); |]
| otherwise = [j| h$o(`TxtI obj`,`t`,`a`,`size`,`regTag regs`,`static`); |]
where
regTag CIRegsUnknown = -1
regTag (CIRegs skip types) =
let nregs = sum $ map varSize types
in skip + (nregs `shiftL` 8)
data StaticInfo = StaticInfo { siVar :: !Text -- ^ global object
, siVal :: !StaticVal -- ^ static initialization
, siCC :: !(Maybe Ident) -- ^ optional CCS name
}
deriving (Eq, Ord, Show, Typeable, Generic)
instance NFData StaticInfo
data StaticVal = StaticFun !Text -- ^ heap object for function
| StaticThunk !(Maybe Text) -- ^ heap object for CAF (field is Nothing when thunk is initialized in an alternative way, like string thunks through h$str)
| StaticUnboxed !StaticUnboxed -- ^ unboxed constructor (Bool, Int, Double etc)
| StaticData !Text [StaticArg] -- ^ regular datacon app
| StaticList [StaticArg] (Maybe Text) -- ^ list initializer (with optional tail)
deriving (Eq, Ord, Show, Typeable, Generic)
instance NFData StaticVal
data StaticUnboxed = StaticUnboxedBool !Bool
| StaticUnboxedInt !Integer
| StaticUnboxedDouble !SaneDouble
deriving (Eq, Ord, Show, Typeable, Generic)
instance NFData StaticUnboxed
data StaticArg = StaticObjArg !Text -- ^ reference to a heap object
| StaticLitArg !StaticLit -- ^ literal
| StaticConArg !Text [StaticArg] -- ^ unfloated constructor
deriving (Eq, Ord, Show, Typeable, Generic)
instance NFData StaticArg
data StaticLit = BoolLit !Bool
| IntLit !Integer
| NullLit
| DoubleLit !SaneDouble -- should we actually use double here?
| StringLit !Text
| BinLit !ByteString
| LabelLit !Bool !Text -- ^ is function pointer, label (also used for string / binary init)
deriving (Eq, Ord, Show, Typeable, Generic)
instance NFData StaticLit
instance ToJExpr StaticArg where
toJExpr (StaticLitArg l) = toJExpr l
toJExpr (StaticObjArg t) = ValExpr (JVar (TxtI t))
toJExpr (StaticConArg c args) =
-- FIXME: cost-centre stack
allocDynamicE def (ValExpr . JVar . TxtI $ c) (map toJExpr args) Nothing
instance ToJExpr StaticLit where
toJExpr (BoolLit b) = toJExpr b
toJExpr (IntLit i) = toJExpr i
toJExpr NullLit = jnull
toJExpr (DoubleLit d) = toJExpr (unSaneDouble d)
toJExpr (StringLit t) = [je| h$str(`t`)() |] -- fixme this duplicates the string!
toJExpr (BinLit b) = [je| h$rstr(`map toInteger (B.unpack b)`)() |] -- fixme this duplicates the string
toJExpr (LabelLit _isFun lbl) = [je| `JVar (TxtI lbl)` |]
-- | declare and do first-pass init of a global object (create JS object for heap objects)
staticDeclStat :: StaticInfo
-> JStat
staticDeclStat (StaticInfo si sv _) =
let si' = TxtI si
ssv (StaticUnboxed u) = Just (ssu u)
ssv (StaticThunk Nothing) = Nothing
ssv _ = Just [je| h$d() |]
ssu (StaticUnboxedBool b) = [je| h$p(`b`) |]
ssu (StaticUnboxedInt i) = [je| h$p(`i`) |]
ssu (StaticUnboxedDouble d) = [je| h$p(`unSaneDouble d`) |]
-- fixme, we shouldn't do h$di, we need to record the statement to init the thunks
in maybe [j| h$di(`si'`); |] (\v -> DeclStat si' <> [j| `si'` = `v`; |]) (ssv sv)
-- | initialize a global object. all global objects have to be declared (staticInfoDecl) first
-- (this is only used with -debug, normal init would go through the static data table)
staticInitStat :: Bool -- ^ profiling enabled
-> StaticInfo
-> JStat
staticInitStat _prof (StaticInfo i sv cc) =
case sv of
StaticData con args -> ApplStat (jvar "h$sti") $ [jvar i, jvar con, toJExpr args] ++ ccArg
StaticFun f -> ApplStat (jvar "h$sti") $ [jvar i, jvar f, [je| [] |]] ++ ccArg
StaticList args mt ->
ApplStat (jvar "h$stl") $ [jvar i, toJExpr args, toJExpr $ maybe jnull (toJExpr . TxtI) mt] ++ ccArg
StaticThunk (Just f) -> ApplStat (jvar "h$stc") $ [jvar i, jvar f] ++ ccArg
_ -> mempty
where
ccArg = maybeToList (fmap toJExpr cc)
allocDynamicE :: CgSettings -> JExpr -> [JExpr] -> Maybe JExpr -> JExpr
allocDynamicE s entry free cc
| csInlineAlloc s || length free > 24 =
ValExpr . jhFromList $ [("f", entry), ("d1", fillObj1), ("d2", fillObj2), ("m", ji 0)]
++ maybe [] (\cid -> [("cc", cid)]) cc
| otherwise = ApplExpr allocFun (toJExpr entry : free ++ maybeToList cc)
where
allocFun = allocClsA ! length free
(fillObj1,fillObj2)
= case free of
[] -> (jnull, jnull)
[x] -> (x,jnull)
[x,y] -> (x,y)
(x:xs) -> (x,toJExpr (JHash $ M.fromList (zip dataFields xs)))
dataFields = map (T.pack . ('d':) . show) [(1::Int)..]
allocClsA :: Array Int JExpr
allocClsA = listArray (0, 1024) (toJExpr (TxtI "h$c") : map f [(1::Int)..1024])
where
f n = toJExpr . TxtI . T.pack $ "h$c" ++ show n
allocData :: Array Int JExpr
allocData = listArray (1, 1024) (map f [(1::Int)..1024])
where
f n = toJExpr . TxtI . T.pack $ "h$d" ++ show n
data CgSettings = CgSettings
{ csInlinePush :: Bool
, csInlineBlackhole :: Bool
, csInlineLoadRegs :: Bool
, csInlineEnter :: Bool
, csInlineAlloc :: Bool
, csTraceRts :: Bool
, csAssertRts :: Bool
, csTraceForeign :: Bool
, csProf :: Bool
}
instance Default CgSettings where
def = CgSettings False False False False False False False False False
dfCgSettings :: DynFlags -> CgSettings
dfCgSettings df = def { csTraceRts = "-DGHCJS_TRACE_RTS" `elem` opt_P df
, csAssertRts = "-DGHCJS_ASSERT_RTS" `elem` opt_P df
, csProf = WayProf `elem` ways df
-- FIXME: this part is inlined from Settings.hs to avoid circular imports
}
| beni55/ghcjs | src/Gen2/ClosureInfo.hs | mit | 18,755 | 0 | 16 | 5,920 | 4,656 | 2,445 | 2,211 | 399 | 10 |
module FoldingsOneMoreTime where
-- Yep, traditinal dig into why foldr works with infinite list
-- and foldl does not.
-- This definition might support incorrect intuition about
-- the fact that foldl works with infinite collection.
-- Because we create newInit right now and go to the next
-- iteration.
-- Left folding looks like this, if we write
-- how it works explicitly:
-- f (... (f ( f (f z x1) x2) x3) ...) xn
-- foldl use (\acc elem -> ...) as f
myFoldl f init [] = init
myFoldl f init (x:xs) = myFoldl f newInit xs
where newInit = f init x
-- Right folding looks like this:
-- f x1 (f x2 (f x3 (...(f xn z) ...)))
-- foldr use (\elem acc -> ...) as f
myFoldr f init [] = init
myFoldr f init (x:xs) = f x rightResult
where rightResult = myFoldr f init xs
| raventid/coursera_learning | haskell/will_kurt/9.5_myfoldl_myfoldr.hs | mit | 780 | 0 | 7 | 168 | 121 | 68 | 53 | 7 | 1 |
-- List
n = [1, 2, 3] -- List holds multiple values of the same type
b = [True, False, True]
c = ['H', 'e', 'l', 'l', 'o']
arr = 'A': ['B', 'C', 'D'] -- : operator append a value at the beginning of the list 'ABCD'
-- Tuples: They hold a fixed number of values, which can have different types
tp = (1, True)
z = zip [1 .. 5] ['a' .. 'e']
main = print z
| domenicosolazzo/practice-haskell | basics/data-structures.hs | mit | 356 | 6 | 6 | 81 | 130 | 70 | 60 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module WebserverInternalSpec (spec) where
import BasicPrelude
import qualified Data.Text.Lazy as TL
import qualified DynamoDbEventStore.Webserver as W
import Test.Tasty.Hspec
import Test.Tasty.QuickCheck
import Text.Read (readMaybe)
showText :: Show a => a -> LText
showText = TL.fromStrict . tshow
spec :: Spec
spec = do
describe "parseInt64" $ do
let run = W.runParser W.positiveInt64Parser ()
it "can parse any positive int64" $ property $
\x -> x >= 0 ==> run (showText (x :: Int64)) === Right x
it "will not parse negative numbers" $ property $
\x -> x < 0 ==> run (showText (x :: Int64)) === Left ()
it "will not parse anything that read cannot convert read" $ property $
\x -> (Text.Read.readMaybe x :: Maybe Int64) == Nothing ==> run (showText x) === Left ()
it "will not parse numbers that are too large" $ do
let tooLarge = toInteger (maxBound :: Int64) + 1
run (showText tooLarge) == Left ()
describe "global feed position" $ do
it "can round trip any position" $ property $
\position -> W.parseGlobalFeedPosition(W.globalFeedPositionToText(position)) === Just position
| adbrowne/dynamodb-eventstore | dynamodb-eventstore-web/tests/WebserverInternalSpec.hs | mit | 1,262 | 0 | 18 | 324 | 384 | 195 | 189 | 26 | 1 |
{-# htermination lookupFM :: FiniteMap Ordering b -> Ordering -> Maybe b #-}
import FiniteMap
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/FiniteMap_lookupFM_11.hs | mit | 94 | 0 | 3 | 15 | 5 | 3 | 2 | 1 | 0 |
import LSys
import LSys.LSys
import LSys.Sierpinski
main = (\p -> _display p (_state p)) . (!! 8) . iterate nextGen $ sierpinski
| lesguillemets/lsyst.hs | examples/sierpinski.hs | mit | 129 | 0 | 12 | 22 | 57 | 31 | 26 | 4 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Main where
--Gets the structure of the Database before compiling main program
import HLINQ
$(createDB "../test.db" "test")
| juventietis/HLINQ | main.hs | mit | 168 | 0 | 7 | 26 | 21 | 12 | 9 | 4 | 0 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLDataListElement
(js_getOptions, getOptions, HTMLDataListElement,
castToHTMLDataListElement, gTypeHTMLDataListElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"options\"]" js_getOptions ::
HTMLDataListElement -> IO (Nullable HTMLCollection)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLDataListElement.options Mozilla HTMLDataListElement.options documentation>
getOptions ::
(MonadIO m) => HTMLDataListElement -> m (Maybe HTMLCollection)
getOptions self
= liftIO (nullableToMaybe <$> (js_getOptions (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/HTMLDataListElement.hs | mit | 1,430 | 6 | 10 | 164 | 371 | 236 | 135 | 24 | 1 |
{-# OPTIONS -Wall #-}
import Data.Functor (($>))
import qualified Data.List as List
import Data.Map.Lazy (Map, (!))
import qualified Data.Map.Lazy as Map
import qualified Data.Maybe as Maybe
import Data.Set (Set)
import qualified Data.Set as Set
import Helpers.Numbers
import Helpers.Parse
import Text.Parsec
type Item = ([Set Segment], [Set Segment])
type Input = [Item]
data Segment = A | B | C | D | E | F | G
deriving (Eq, Ord, Enum, Bounded, Show)
allSegments :: [Segment]
allSegments = [minBound .. maxBound]
numbers :: [Set Segment]
numbers =
map
Set.fromList
[ [A, B, C, E, F, G],
[C, F],
[A, C, D, E, G],
[A, C, D, F, G],
[B, C, D, F],
[A, B, D, F, G],
[A, B, D, E, F, G],
[A, C, F],
[A, B, C, D, E, F, G],
[A, B, C, D, F, G]
]
numbersSet :: Set (Set Segment)
numbersSet = Set.fromList numbers
main :: IO ()
main = do
input <- parseInput
let outputNumbers = map solve input
print $ sum outputNumbers
solve :: Item -> Int
solve (signalPatterns, outputValue) =
let mapping = findMapping signalPatterns
outputPatterns = map (applyMapping mapping) outputValue
outputDigits = map (Maybe.fromJust . (`List.elemIndex` numbers)) outputPatterns
in digitsToIntegral outputDigits
findMapping :: [Set Segment] -> Map Segment Segment
findMapping signalPatterns =
let possibleMappings = map (Map.fromList . zip allSegments) (List.permutations allSegments)
mappedNumbers = List.find (\mapping -> Set.fromList (map (applyMapping mapping) signalPatterns) == numbersSet) possibleMappings
in Maybe.fromJust mappedNumbers
applyMapping :: Map Segment Segment -> Set Segment -> Set Segment
applyMapping mapping = Set.map (mapping !)
parseInput :: IO Input
parseInput = parseLinesIO $ do
signalPatterns <- filter (not . Set.null) <$> sepBy segments (string " ")
_ <- string "| "
outputValue <- sepBy segments (string " ")
return (signalPatterns, outputValue)
where
segments = Set.fromList <$> many segment
segment =
choice
[ char 'a' $> A,
char 'b' $> B,
char 'c' $> C,
char 'd' $> D,
char 'e' $> E,
char 'f' $> F,
char 'g' $> G
]
| SamirTalwar/advent-of-code | 2021/AOC_08_2.hs | mit | 2,233 | 1 | 17 | 546 | 878 | 492 | 386 | 67 | 1 |
-- file: ch04/SplitLines.hs
-- re-implementation of "lines" (?)
splitLines [] = []
splitLines cs =
let (pre, suf) = break isLineTerminator cs
in pre : case suf of
('\r':'\n':rest) -> splitLines rest
('\r':rest) -> splitLines rest
('\n':rest) -> splitLines rest
_ -> []
isLineTerminator c = c == '\r' || c == '\n'
| imrehg/rwhaskell | ch04/SplitLines.hs | mit | 347 | 0 | 12 | 87 | 130 | 65 | 65 | 9 | 4 |
module Nunavut.NeuralNet.Internal where
import Prelude hiding (reverse)
import Control.Lens (Lens', lens, to, views)
import Data.List (intercalate)
import Data.List.NonEmpty (NonEmpty, toList)
import Nunavut.Layer (Layer)
import Nunavut.Util (SizedOperator (..), _head, _last)
{--------------------------------------------------------------------------
- Types -
--------------------------------------------------------------------------}
data FFNet = FFNet {
_layers :: NonEmpty Layer
}
{--------------------------------------------------------------------------
- Lenses -
--------------------------------------------------------------------------}
layers :: Lens' FFNet (NonEmpty Layer)
layers = lens _layers (\net ls -> net { _layers = ls })
{--------------------------------------------------------------------------
- Instances -
--------------------------------------------------------------------------}
instance Show FFNet where
show (FFNet ls) = intercalate "\n" . toList $ fmap show ls
instance SizedOperator FFNet where
inSize = to $ views (layers . _last . inSize) pred
outSize = to $ views (layers . _head . outSize) pred
| markcwhitfield/nunavut | src/Nunavut/NeuralNet/Internal.hs | mit | 1,561 | 0 | 10 | 540 | 250 | 142 | 108 | 16 | 1 |
-- |
--
-- Checks that namespaces and sources can be on the "same" level of the hierarchy
module Main where
import Control.Biegunka
import Control.Biegunka.Source.Git
main :: IO ()
main = do
biegunka id run $
namespace "outer" $ do
namespace "inner" $
git (url "git@github.com:ghc/ghc" . path "ghc") pass
git (url "git@github.com:ghc/ghc" . path "ghc") pass
pass
| biegunka/biegunka | test/typecheck/should_compile/OK7.hs | mit | 394 | 0 | 14 | 89 | 105 | 52 | 53 | 11 | 1 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings, PostfixOperators, NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts, LambdaCase #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-partial-type-signatures #-}
{-# OPTIONS_GHC -O0 -fno-cse -fno-full-laziness #-} -- preserve "lexical" sharing for observed sharing
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Commands.Plugins.Spiros.Correct.Grammar where
import Commands.Plugins.Spiros.Digit.Grammar
import Commands.Plugins.Spiros.Phrase
import Commands.Server.Types(Correction(..))
import Commands.Mixins.DNS13OSX9
import Digit
import Control.Applicative
correctionGrammar :: R Correction -- TODO, upon grammatical contexts
correctionGrammar = 'correctionGrammar <=> empty
<|> ChosenCorrection <$> digit_
<|> (SpokenCorrection . letters2dictation) <$ "spell" <*> letters
<|> SpokenCorrection <$> dictation
<|> EditedCorrection <$ "edit" <*> digit_
runCorrection = \case
ChosenCorrection i -> runDigit i
SpokenCorrection d -> runDictation d
EditedCorrection _i -> error "runCorrection" --TODO Must live in some CommandsServerT monad, Not just a Workflow. This lets the user configure their own correction UI, without changing the server source.
where
runDigit = insertD . digit2dictation
digit2dictation :: Digit -> Dictation
digit2dictation (Digit d) = words2dictation . show $ d
| sboosali/commands-spiros | config/Commands/Plugins/Spiros/Correct/Grammar.hs | gpl-2.0 | 1,375 | 0 | 15 | 166 | 211 | 120 | 91 | 25 | 3 |
{-|
Module : $Header$
Copyright : (c) 2015 Edward O'Callaghan
License : GPL2
Maintainer : eocallaghan@alterapraxis.com
Stability : provisional
Portability : portable
This module contains various misc actions,
such as for example, generic error handling
and cleanups.
-}
module Misc ( checkAndcleanup
, bsToHexString
) where
import qualified Data.ByteString as BS
import Data.List.Split (chunksOf)
import System.Exit (exitFailure)
import Text.Printf (printf)
import LibFtdi
-- | Check that we are able to receive bytes
-- and if things are bad clean up and exit.
checkAndcleanup :: Maybe DeviceHandle -> IO ()
checkAndcleanup dev = do
putStrLn "ABORT"
case dev of
Nothing -> putStrLn "No device connected"
Just dev' -> do checkRx dev'
ftdiUSBClose dev'
ftdiDeInit dev'
exitFailure
checkRx :: DeviceHandle -> IO ()
checkRx = loop
where loop dev = do
d <- ftdiReadData dev 1
case d of
Nothing -> do putStrLn $ "unexpected rx byte: " ++ show d
loop dev
Just _ -> return ()
-- | Given a ByteString return a String of bytes in the hex representation
bsToHexString :: BS.ByteString -> String
bsToHexString x = unlines $ fmap (concatMap (printf "0x%.2X ")) ls
where ls = chunksOf 32 (BS.unpack x)
| victoredwardocallaghan/haskflash | src/Misc.hs | gpl-2.0 | 1,418 | 0 | 15 | 422 | 283 | 141 | 142 | 27 | 2 |
module Postructures where
import qualified Prelude
data Bool =
True
| False
andb :: Bool -> Bool -> Bool
andb b1 b2 =
case b1 of {
True -> b2;
False -> False}
orb :: Bool -> Bool -> Bool
orb b1 b2 =
case b1 of {
True -> True;
False -> b2}
negb :: Bool -> Bool
negb b =
case b of {
True -> False;
False -> True}
data Nat =
O
| S Nat
data Option a =
Some a
| None
data Prod a b =
Pair a b
snd :: (Prod a1 a2) -> a2
snd p =
case p of {
Pair x y -> y}
data List a =
Nil
| Cons a (List a)
app :: (List a1) -> (List a1) -> List a1
app l m =
case l of {
Nil -> m;
Cons a l1 -> Cons a (app l1 m)}
plus :: Nat -> Nat -> Nat
plus n m =
case n of {
O -> m;
S p -> S (plus p m)}
tl :: (List a1) -> List a1
tl l =
case l of {
Nil -> Nil;
Cons a m -> m}
nth :: Nat -> (List a1) -> a1 -> a1
nth n l default0 =
case n of {
O ->
case l of {
Nil -> default0;
Cons x l' -> x};
S m ->
case l of {
Nil -> default0;
Cons x t -> nth m t default0}}
map :: (a1 -> a2) -> (List a1) -> List a2
map f l =
case l of {
Nil -> Nil;
Cons a t -> Cons (f a) (map f t)}
fold_left :: (a1 -> a2 -> a1) -> (List a2) -> a1 -> a1
fold_left f l a0 =
case l of {
Nil -> a0;
Cons b t -> fold_left f t (f a0 b)}
filter :: (a1 -> Bool) -> (List a1) -> List a1
filter f l =
case l of {
Nil -> Nil;
Cons x l0 ->
case f x of {
True -> Cons x (filter f l0);
False -> filter f l0}}
partition :: (a1 -> Bool) -> (List a1) -> Prod (List a1) (List a1)
partition f l =
case l of {
Nil -> Pair Nil Nil;
Cons x tl0 ->
case partition f tl0 of {
Pair g d ->
case f x of {
True -> Pair (Cons x g) d;
False -> Pair g (Cons x d)}}}
combine :: (List a1) -> (List a2) -> List (Prod a1 a2)
combine l l' =
case l of {
Nil -> Nil;
Cons x tl0 ->
case l' of {
Nil -> Nil;
Cons y tl' -> Cons (Pair x y) (combine tl0 tl')}}
beq_nat :: Nat -> Nat -> Bool
beq_nat n m =
case n of {
O ->
case m of {
O -> True;
S n0 -> False};
S n1 ->
case m of {
O -> False;
S m1 -> beq_nat n1 m1}}
data Hex =
H0
| H1
| H2
| H3
| H4
| H5
| H6
| H7
| H8
| H9
| HA
| HB
| HC
| HD
| HE
| HF
hex2nat :: Hex -> Nat
hex2nat h =
case h of {
H0 -> O;
H1 -> S O;
H2 -> S (S O);
H3 -> S (S (S O));
H4 -> S (S (S (S O)));
H5 -> S (S (S (S (S O))));
H6 -> S (S (S (S (S (S O)))));
H7 -> S (S (S (S (S (S (S O))))));
H8 -> S (S (S (S (S (S (S (S O)))))));
H9 -> S (S (S (S (S (S (S (S (S O))))))));
HA -> S (S (S (S (S (S (S (S (S (S O)))))))));
HB -> S (S (S (S (S (S (S (S (S (S (S O))))))))));
HC -> S (S (S (S (S (S (S (S (S (S (S (S O)))))))))));
HD -> S (S (S (S (S (S (S (S (S (S (S (S (S O))))))))))));
HE -> S (S (S (S (S (S (S (S (S (S (S (S (S (S O)))))))))))));
HF -> S (S (S (S (S (S (S (S (S (S (S (S (S (S (S O))))))))))))))}
succH :: Hex -> Hex
succH h =
case h of {
H0 -> H1;
H1 -> H2;
H2 -> H3;
H3 -> H4;
H4 -> H5;
H5 -> H6;
H6 -> H7;
H7 -> H8;
H8 -> H9;
H9 -> HA;
HA -> HB;
HB -> HC;
HC -> HD;
HD -> HE;
HE -> HF;
HF -> H0}
type HexN = List Hex
eqb_hex :: Hex -> Hex -> Bool
eqb_hex h1 h2 =
beq_nat (hex2nat h1) (hex2nat h2)
eqb_hexs :: HexN -> HexN -> Bool
eqb_hexs bs1 bs2 =
case bs1 of {
Nil ->
case bs2 of {
Nil -> True;
Cons h l -> False};
Cons x xs ->
case bs2 of {
Nil -> False;
Cons y ys ->
case eqb_hex x y of {
True -> eqb_hexs xs ys;
False -> False}}}
data LTree x =
Tgen x
| Tcons x (LTree x)
| Tfork (LBranch x) (LTree x)
data LBranch x =
Tbranch (LTree x)
lastnode :: (LTree a1) -> a1
lastnode t =
case t of {
Tgen a -> a;
Tcons a l -> a;
Tfork l t1 -> lastnode t1}
lastforknodes :: (LTree a1) -> List a1
lastforknodes t =
case t of {
Tgen x -> Nil;
Tcons x l -> lastforknodes l;
Tfork l t1 ->
case l of {
Tbranch t2 -> app (lastforknodes t1) (lastnodes t2)}}
lastnodes :: (LTree a1) -> List a1
lastnodes t =
case t of {
Tgen x -> Cons x Nil;
Tcons x l -> Cons x (lastforknodes l);
Tfork l t1 ->
case l of {
Tbranch t2 -> app (lastnodes t1) (lastnodes t2)}}
ltree_map :: (a1 -> a2) -> (LTree a1) -> LTree a2
ltree_map f t =
case t of {
Tgen a -> Tgen (f a);
Tcons a l -> Tcons (f a) (ltree_map f l);
Tfork l l' ->
case l of {
Tbranch l'' -> Tfork (Tbranch (ltree_map f l'')) (ltree_map f l')}}
ltree_list_map :: (a1 -> a2) -> (LTree a1) -> List a2
ltree_list_map f t =
case t of {
Tgen a -> Cons (f a) Nil;
Tcons a l -> app (ltree_list_map f l) (Cons (f a) Nil);
Tfork l t1 -> ltree_list_map f t1}
ltree_foldl :: (a2 -> a1 -> a2) -> (LTree a1) -> a2 -> a2
ltree_foldl f t y0 =
case t of {
Tgen a -> f y0 a;
Tcons a l -> ltree_foldl f l (f y0 a);
Tfork l t1 -> ltree_foldl f t1 y0}
fold1 :: (a1 -> a1 -> a1) -> (List a1) -> List a1
fold1 f l =
let {tl0 = tl l} in
let {cmbl = combine tl0 l} in
map (\z ->
case z of {
Pair x y -> f x y}) cmbl
ltree2list :: (LTree a1) -> List a1
ltree2list t =
case t of {
Tgen a -> Cons a Nil;
Tcons a t' -> app (ltree2list t') (Cons a Nil);
Tfork l t' -> ltree2list t'}
ltreelen :: (LTree a1) -> Nat
ltreelen t =
case t of {
Tgen x -> S O;
Tcons x t' -> S (ltreelen t');
Tfork l t' -> ltreelen t'}
forks :: (List (LTree a1)) -> (LTree a1) -> LTree a1
forks ff t =
case ff of {
Nil -> t;
Cons fx fs -> Tfork (Tbranch fx) (forks fs t)}
ltree_grow20 :: a1 -> a1 -> (a1 -> a1 -> Bool) -> (LTree a1) -> Bool -> (List
(LTree a1)) -> Prod (Option a1) (LTree a1)
ltree_grow20 x y eqX t bfork lbr =
case t of {
Tgen a ->
case eqX x a of {
True ->
case bfork of {
True -> Pair (Some a) (forks (Cons (Tgen y) lbr) t);
False -> Pair (Some a) (Tcons y (forks lbr t))};
False -> Pair None (forks lbr t)};
Tcons a l ->
case eqX x a of {
True ->
let {r = Some a} in
case bfork of {
True -> Pair r (forks (Cons (Tgen y) lbr) (Tcons a l));
False -> Pair r (Tcons y (forks lbr (Tcons a l)))};
False ->
case ltree_grow20 x y eqX l True Nil of {
Pair mx l' -> Pair mx (forks lbr (Tcons a l'))}};
Tfork l t' ->
case l of {
Tbranch t'' ->
case ltree_grow20 x y eqX t'' False Nil of {
Pair mx'' l'' ->
case mx'' of {
Some x'' -> Pair (Some (lastnode t')) (forks (Cons l'' lbr) t');
None -> ltree_grow20 x y eqX t' bfork (Cons l'' lbr)}}}}
ltree_grow2 :: a1 -> a1 -> (a1 -> a1 -> Bool) -> (LTree a1) -> Prod
(Option a1) (LTree a1)
ltree_grow2 x y eqX t =
ltree_grow20 x y eqX t False Nil
merge_trees :: (LTree a1) -> (LTree a1) -> LTree a1
merge_trees t1 t2 =
case t2 of {
Tgen a2 -> Tcons a2 t1;
Tcons a2 l2 -> Tcons a2 (merge_trees t1 l2);
Tfork l l2' -> Tfork l (merge_trees t1 l2')}
merge_node_forks2 :: a1 -> a1 -> (a1 -> a1 -> Bool) -> (LTree a1) -> (Prod
(Option (LTree a1)) (List (LTree a1))) -> Bool -> (List
(LTree a1)) -> Prod Bool (LTree a1)
merge_node_forks2 x y eqX t lbt bfork lbr =
case t of {
Tgen a ->
case lbt of {
Pair o lb ->
case o of {
Some lt ->
case eqX x a of {
True ->
case bfork of {
True -> Pair True
(forks (Cons (merge_trees (forks lb (Tgen y)) lt) lbr) t);
False -> Pair True
(merge_trees (forks lb (Tcons y (forks lbr t))) lt)};
False -> Pair False (forks lbr t)};
None ->
case eqX x a of {
True ->
case bfork of {
True -> Pair True (forks (Cons (forks lb (Tgen y)) lbr) t);
False -> Pair True (forks lb (Tcons y (forks lbr t)))};
False -> Pair False (forks lbr t)}}};
Tcons a l ->
case merge_node_forks2 x y eqX l lbt True Nil of {
Pair b l' ->
case lbt of {
Pair o lb ->
case o of {
Some lt ->
case eqX x a of {
True ->
case bfork of {
True -> Pair True
(forks (Cons (merge_trees (forks lb (Tgen y)) lt) lbr) (Tcons a
l));
False -> Pair True
(merge_trees (forks lb (Tcons y (forks lbr (Tcons a l)))) lt)};
False -> Pair b (forks lbr (Tcons a l'))};
None ->
case eqX x a of {
True ->
case bfork of {
True -> Pair True
(forks (Cons (forks lb (Tgen y)) lbr) (Tcons a l));
False -> Pair True (forks lb (Tcons y (forks lbr (Tcons a l))))};
False -> Pair b (forks lbr (Tcons a l'))}}}};
Tfork l t' ->
case l of {
Tbranch t'' ->
case merge_node_forks2 x y eqX t'' lbt False Nil of {
Pair b l'' ->
case b of {
True -> Pair True (forks (Cons l'' lbr) t');
False -> merge_node_forks2 x y eqX t' lbt bfork (Cons l'' lbr)}}}}
rebalanceS :: (a1 -> a2) -> (a1 -> a1 -> Bool) -> a2 -> (a2 -> a2 -> Bool) ->
(a2 -> a2 -> a2) -> a2 -> (LTree a1) -> (Prod
(Option (LTree a1)) (List (LTree a1))) -> Prod (Prod a2 a1)
(LTree a1)
rebalanceS w eqX s0 geS plusS s t lbr =
case t of {
Tgen a ->
case lbr of {
Pair o lb ->
case o of {
Some lt -> Pair (Pair (plusS s (w a)) a) (merge_trees (forks lb t) lt);
None -> Pair (Pair (plusS s (w a)) a) (forks lb t)}};
Tcons a t' ->
case rebalanceS w eqX s0 geS plusS (plusS s (w a)) t' (Pair None Nil) of {
Pair mx t'b ->
case mx of {
Pair m x -> Pair (Pair m a)
(snd (merge_node_forks2 x a eqX t'b lbr False Nil))}};
Tfork l t' ->
case l of {
Tbranch t'' ->
case rebalanceS w eqX s0 geS plusS s0 t'' (Pair None Nil) of {
Pair px'' t''b ->
case px'' of {
Pair p'' x'' ->
case geS s p'' of {
True ->
case lbr of {
Pair o lb ->
rebalanceS w eqX s0 geS plusS s t' (Pair o (Cons t''b lb))};
False ->
case lbr of {
Pair o lb ->
case o of {
Some lt ->
rebalanceS w eqX s0 geS plusS p'' t' (Pair (Some t''b) (Cons
lt lb));
None ->
rebalanceS w eqX s0 geS plusS p'' t' (Pair (Some t''b) lb)}}}}}}}
ltree_split_till :: a1 -> (a1 -> a1 -> Bool) -> (LTree a1) -> Prod
(Option (LTree a1)) (Option (LTree a1))
ltree_split_till x eqX t =
case t of {
Tgen a ->
case eqX a x of {
True -> Pair None (Some (Tgen a));
False -> Pair (Some (Tgen a)) None};
Tcons a l ->
case eqX a x of {
True -> Pair (Some l) (Some (Tgen a));
False ->
case ltree_split_till x eqX l of {
Pair o o0 ->
case o of {
Some l1 ->
case o0 of {
Some l2 -> Pair (Some l1) (Some (Tcons a l2));
None -> Pair (Some (Tcons a l1)) None};
None ->
case o0 of {
Some l2 -> Pair None (Some (Tcons a l2));
None -> Pair None None}}}};
Tfork l t1 ->
case ltree_split_till x eqX t1 of {
Pair o o0 ->
case o of {
Some l1 ->
case o0 of {
Some l2 -> Pair (Some l1) (Some (Tfork l l2));
None -> Pair (Some (Tfork l l1)) None};
None ->
case o0 of {
Some l2 -> Pair None (Some (Tfork l l2));
None -> Pair None None}}}}
rebalanceS_till :: a1 -> (a1 -> a2) -> (a1 -> a1 -> Bool) -> a2 -> (a2 -> a2
-> Bool) -> (a2 -> a2 -> a2) -> a2 -> (LTree a1) -> LTree
a1
rebalanceS_till x w eqX s0 geS plusS s t =
case ltree_split_till x eqX t of {
Pair t1 t2 ->
case t1 of {
Some t3 ->
case t2 of {
Some t4 ->
merge_trees t3
(snd (rebalanceS w eqX s0 geS plusS s t4 (Pair None Nil)));
None -> t3};
None ->
case t2 of {
Some t3 -> snd (rebalanceS w eqX s0 geS plusS s t3 (Pair None Nil));
None -> t}}}
type Nattable v = List (Prod Nat v)
search_table :: Nat -> (Nattable a1) -> Option a1
search_table k t =
case t of {
Nil -> None;
Cons p t' ->
case p of {
Pair k' v ->
case beq_nat k k' of {
True -> Some v;
False -> search_table k t'}}}
search_place_table0 :: Nat -> (Nattable a1) -> (Nattable a1) -> Option
(Prod a1 (Nattable a1))
search_place_table0 k t t' =
case t of {
Nil -> None;
Cons p t'' ->
case p of {
Pair k' v ->
case beq_nat k k' of {
True -> Some (Pair v (app t' t''));
False -> search_place_table0 k t'' (app t' (Cons (Pair k' v) Nil))}}}
search_place_table :: Nat -> (Nattable a1) -> Option (Prod a1 (Nattable a1))
search_place_table k t =
search_place_table0 k t Nil
modify_key :: Nat -> a1 -> (Nattable a1) -> Nattable a1
modify_key k v t =
case search_place_table k t of {
Some p ->
case p of {
Pair v0 tb -> Cons (Pair k v) tb};
None -> t}
is_nilb :: (List a1) -> Bool
is_nilb l =
case l of {
Nil -> True;
Cons x l0 -> False}
type Timestamp bN = bN
type Currency bN = bN
type HexSPK = Hex
data Account0 bN =
Account bN (Currency bN) Bool Bool Bool Bool Bool (Option Nat) HexSPK
balance_weight :: (Account0 a1) -> a1
balance_weight a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 ->
balance_weight0}
balance :: (Account0 a1) -> Currency a1
balance a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> balance0}
isForging :: (Account0 a1) -> Bool
isForging a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> isForging0}
isPublishing :: (Account0 a1) -> Bool
isPublishing a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> isPublishing0}
isMarkable :: (Account0 a1) -> Bool
isMarkable a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> isMarkable0}
isMarkFollowing :: (Account0 a1) -> Bool
isMarkFollowing a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 ->
isMarkFollowing0}
isMarkUnfollowing :: (Account0 a1) -> Bool
isMarkUnfollowing a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 ->
isMarkUnfollowing0}
tfdepth :: (Account0 a1) -> Option Nat
tfdepth a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> tfdepth0}
publicKey :: (Account0 a1) -> HexSPK
publicKey a =
case a of {
Account balance_weight0 balance0 isForging0 isPublishing0 isMarkable0
isMarkFollowing0 isMarkUnfollowing0 tfdepth0 publicKey0 -> publicKey0}
data Transaction0 bN =
Transaction (Account0 bN) (Account0 bN) (Currency bN) (Currency bN)
(Timestamp bN)
type BS = HexN
data Block0 bN =
Block (List (Transaction0 bN)) Nat bN bN (Account0 bN) BS (Timestamp bN)
transactions :: (Block0 a1) -> List (Transaction0 a1)
transactions b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> transactions0}
nMarked :: (Block0 a1) -> Nat
nMarked b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> nMarked0}
baseTarget :: (Block0 a1) -> a1
baseTarget b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> baseTarget0}
totalDifficulty :: (Block0 a1) -> a1
totalDifficulty b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> totalDifficulty0}
generator :: (Block0 a1) -> Account0 a1
generator b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> generator0}
generationSignature :: (Block0 a1) -> BS
generationSignature b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> generationSignature0}
btimestamp :: (Block0 a1) -> Timestamp a1
btimestamp b =
case b of {
Block transactions0 nMarked0 baseTarget0 totalDifficulty0 generator0
generationSignature0 btimestamp0 -> btimestamp0}
eqb_block :: (Block0 a1) -> (Block0 a1) -> Bool
eqb_block b1 b2 =
eqb_hexs (generationSignature b1) (generationSignature b2)
calcGenerationSignature :: (a2 -> BS) -> (HexN -> a2) -> (Block0 a1) ->
(Account0 a1) -> BS
calcGenerationSignature dig2string hashfun pb acc =
dig2string
(hashfun (app (generationSignature pb) (Cons (publicKey acc) Nil)))
type Blockchain bN =
LTree (Block0 bN)
-- singleton inductive, whose constructor was blocktree
blocks :: (Blockchain a1) -> LTree (Block0 a1)
blocks b =
b
lastblocks :: (Blockchain a1) -> List (Block0 a1)
lastblocks bc =
Cons (lastnode bc) Nil
pushBlock :: (Block0 a1) -> (Blockchain a1) -> (Block0 a1) -> Prod
(Option (Block0 a1)) (Blockchain a1)
pushBlock pb bc b =
case ltree_grow2 pb b eqb_block bc of {
Pair parb newbs -> Pair parb newbs}
markBlock :: Nat -> (Block0 a1) -> Block0 a1
markBlock n b =
Block (transactions b) (S n) (baseTarget b) (totalDifficulty b)
(generator b) (generationSignature b) (btimestamp b)
isnatpos :: Nat -> Bool
isnatpos n =
case n of {
O -> False;
S n0 -> True}
generateBlock :: ((Block0 a1) -> (Account0 a1) -> (Timestamp a1) -> (List
(Transaction0 a1)) -> HexSPK -> Block0 a1) -> (a1 -> a1 ->
Bool) -> (Timestamp a1) -> (Blockchain a1) -> (Block0
a1) -> (Account0 a1) -> (Timestamp a1) -> (List
(Transaction0 a1)) -> HexSPK -> Prod
(Prod (Block0 a1) (Option (Block0 a1))) (Blockchain a1)
generateBlock formBlock geN markTimestamp bc pb acc ts txs pk =
let {newblock' = formBlock pb acc ts txs pk} in
let {bMark = isnatpos (nMarked pb)} in
let {bTimeMore = geN ts markTimestamp} in
let {bBlockOld = negb (geN (btimestamp pb) markTimestamp)} in
let {
newblock = case orb bMark
(andb (isMarkable acc) (andb bTimeMore bBlockOld)) of {
True -> markBlock (nMarked pb) newblock';
False -> newblock'}}
in
case pushBlock pb bc newblock of {
Pair parb newbc -> Pair (Pair newblock parb) newbc}
data Node0 bN =
Node (Blockchain bN) (Option (Block0 bN)) (List (Transaction0 bN))
(List (Prod (Block0 bN) (Block0 bN))) (List (Block0 bN)) (Account0 bN)
nodechain :: (Node0 a1) -> Blockchain a1
nodechain n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> nodechain0}
changedBlock :: (Node0 a1) -> Option (Block0 a1)
changedBlock n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> changedBlock0}
unconfirmedTxs :: (Node0 a1) -> List (Transaction0 a1)
unconfirmedTxs n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> unconfirmedTxs0}
pending_blocks :: (Node0 a1) -> List (Prod (Block0 a1) (Block0 a1))
pending_blocks n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> pending_blocks0}
open_blocks :: (Node0 a1) -> List (Block0 a1)
open_blocks n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> open_blocks0}
node_account :: (Node0 a1) -> Account0 a1
node_account n =
case n of {
Node nodechain0 changedBlock0 unconfirmedTxs0 pending_blocks0 open_blocks0
node_account0 -> node_account0}
effectiveBalance :: (Account0 a1) -> Currency a1
effectiveBalance =
balance
addSortedBlock :: (a1 -> a1 -> Bool) -> (Block0 a1) -> (List (Block0 a1)) ->
List (Block0 a1)
addSortedBlock geN b lb =
case lb of {
Nil -> Cons b Nil;
Cons b' bs ->
case geN (totalDifficulty b) (totalDifficulty b') of {
True -> Cons b lb;
False -> Cons b' (addSortedBlock geN b bs)}}
earlierBlock :: (a1 -> a1 -> Bool) -> (Option (Block0 a1)) -> (Option
(Block0 a1)) -> Option (Block0 a1)
earlierBlock geN mb1 mb2 =
case mb1 of {
Some b1 ->
case mb2 of {
Some b2 ->
case geN (btimestamp b1) (btimestamp b2) of {
True -> mb2;
False -> mb1};
None -> Some b1};
None -> mb2}
forge_block :: ((Block0 a1) -> (Account0 a1) -> (Timestamp a1) -> (List
(Transaction0 a1)) -> HexSPK -> Block0 a1) -> (a1 -> a1 ->
Bool) -> (Timestamp a1) -> ((Node0 a1) -> (Timestamp a1) ->
(Block0 a1) -> Bool) -> (Node0 a1) -> (Timestamp a1) ->
(Block0 a1) -> Node0 a1
forge_block formBlock geN markTimestamp canforge nd ts pb =
let {txs = unconfirmedTxs nd} in
let {acct = node_account nd} in
let {bc = nodechain nd} in
let {pk = publicKey acct} in
let {canf = canforge nd ts pb} in
let {pendb = pending_blocks nd} in
let {openb = open_blocks nd} in
let {chb = changedBlock nd} in
case canf of {
True ->
case generateBlock formBlock geN markTimestamp bc pb acct ts txs pk of {
Pair newbp newbc ->
case newbp of {
Pair newb parb -> Node newbc (earlierBlock geN chb parb) Nil (Cons
(Pair pb newb) pendb) (addSortedBlock geN newb openb) acct}};
False -> Node bc chb Nil pendb (addSortedBlock geN pb openb) acct}
splitn :: Nat -> (List a1) -> Prod (List a1) (List a1)
splitn n l =
case n of {
O -> Pair Nil l;
S n' ->
case l of {
Nil -> Pair Nil Nil;
Cons x xs ->
case splitn n' xs of {
Pair l1 l2 -> Pair (Cons x l1) l2}}}
blt_nat :: Nat -> Nat -> Bool
blt_nat n m =
case n of {
O ->
case m of {
O -> False;
S n0 -> True};
S n' ->
case m of {
O -> False;
S m' -> blt_nat n' m'}}
markedBlocks :: Nat -> (Block0 a1) -> Bool
markedBlocks lengthConfirmation b =
andb (blt_nat (nMarked b) lengthConfirmation) (blt_nat O (nMarked b))
unmarkedBlocks :: (Block0 a1) -> Bool
unmarkedBlocks b =
negb (isnatpos (nMarked b))
getOpenBlocks :: (Option Nat) -> (List (Block0 a1)) -> (List (Block0 a1)) ->
Prod (List (Block0 a1)) (List (Block0 a1))
getOpenBlocks tfdepth0 opb defl =
case tfdepth0 of {
Some tfd ->
case tfd of {
O -> Pair defl Nil;
S n -> splitn tfd opb};
None -> Pair opb Nil}
forge_blocks :: ((Block0 a1) -> (Account0 a1) -> (Timestamp a1) -> (List
(Transaction0 a1)) -> HexSPK -> Block0 a1) -> (a1 -> a1 ->
Bool) -> (Timestamp a1) -> ((Node0 a1) -> (Timestamp
a1) -> (Block0 a1) -> Bool) -> Nat -> (Node0 a1) ->
(Timestamp a1) -> Node0 a1
forge_blocks formBlock geN markTimestamp canforge lengthConfirmation nd ts =
let {acc = node_account nd} in
let {bc = nodechain nd} in
let {opb = open_blocks nd} in
case getOpenBlocks (tfdepth acc) opb (lastblocks bc) of {
Pair blocks' rb' ->
case isMarkFollowing acc of {
True ->
case partition (markedBlocks lengthConfirmation) blocks' of {
Pair l l' ->
let {rb = app l' rb'} in
let {
bConfirmed = case opb of {
Nil -> False;
Cons b l0 -> blt_nat lengthConfirmation (nMarked b)}}
in
let {
acc' = Account (balance_weight acc) (balance acc) (isForging acc)
(isPublishing acc) (isMarkable acc)
(andb (isMarkFollowing acc) (negb bConfirmed))
(orb (isMarkUnfollowing acc)
(andb bConfirmed (isMarkFollowing acc))) (tfdepth acc)
(publicKey acc)}
in
let {
nd' = Node (nodechain nd) (changedBlock nd) (unconfirmedTxs nd)
(pending_blocks nd) rb acc'}
in
fold_left (\n pb ->
forge_block formBlock geN markTimestamp canforge n ts pb) l nd'};
False ->
case isMarkUnfollowing acc of {
True ->
case partition unmarkedBlocks blocks' of {
Pair l l' ->
let {rb = app l' rb'} in
let {
bConfirmed = case opb of {
Nil -> False;
Cons b l0 -> blt_nat lengthConfirmation (nMarked b)}}
in
let {
acc' = Account (balance_weight acc) (balance acc) (isForging acc)
(isPublishing acc) (isMarkable acc)
(andb (isMarkFollowing acc) (negb bConfirmed))
(orb (isMarkUnfollowing acc)
(andb bConfirmed (isMarkFollowing acc))) (tfdepth acc)
(publicKey acc)}
in
let {
nd' = Node (nodechain nd) (changedBlock nd) (unconfirmedTxs nd)
(pending_blocks nd) rb acc'}
in
fold_left (\n pb ->
forge_block formBlock geN markTimestamp canforge n ts pb) l nd'};
False ->
let {
bConfirmed = case opb of {
Nil -> False;
Cons b l -> blt_nat lengthConfirmation (nMarked b)}}
in
let {
acc' = Account (balance_weight acc) (balance acc) (isForging acc)
(isPublishing acc) (isMarkable acc)
(andb (isMarkFollowing acc) (negb bConfirmed))
(orb (isMarkUnfollowing acc)
(andb bConfirmed (isMarkFollowing acc))) (tfdepth acc)
(publicKey acc)}
in
let {
nd' = Node (nodechain nd) (changedBlock nd) (unconfirmedTxs nd)
(pending_blocks nd) rb' acc'}
in
fold_left (\n pb ->
forge_block formBlock geN markTimestamp canforge n ts pb) blocks'
nd'}}}
defaultAccount :: a1 -> a1 -> HexSPK -> Account0 a1
defaultAccount bN0 bN1 pk =
Account bN1 bN0 True True False False False (Some O) pk
fixAccounts :: a1 -> a1 -> HexSPK -> Nat -> (List
(Prod (Prod (Prod (Prod a1 Bool) Bool) Bool) (Option Nat))) ->
List (Account0 a1)
fixAccounts bN0 bN1 h n l =
case n of {
O -> Nil;
S n' ->
case l of {
Nil -> Cons (defaultAccount bN0 bN1 h)
(fixAccounts bN0 bN1 (succH h) n' l);
Cons ap l' ->
case ap of {
Pair f1 tfd ->
case f1 of {
Pair f2 iMF ->
case f2 of {
Pair f3 iMA ->
case f3 of {
Pair w iP -> Cons (Account w bN0 True iP iMA iMF False tfd h)
(fixAccounts bN0 bN1 (succH h) n' l')}}}}}}
sysAccounts :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> a1
-> a1 -> Nat -> (List
(Prod (Prod (Prod (Prod a1 Bool) Bool) Bool) (Option Nat))) ->
(Currency a1) -> List (Account0 a1)
sysAccounts multN divN plusN bN0 bN1 nFixAccounts accountParams systemBalance =
let {accs0 = fixAccounts bN0 bN1 H1 nFixAccounts accountParams} in
let {w = fold_left plusN (map balance_weight accs0) bN0} in
map (\acc -> Account (balance_weight acc)
(divN (multN (balance_weight acc) systemBalance) w) (isForging acc)
(isPublishing acc) (isMarkable acc) (isMarkFollowing acc)
(isMarkUnfollowing acc) (tfdepth acc) (publicKey acc)) accs0
data Connection0 bN =
Connection (Node0 bN) (Node0 bN)
data System0 bN =
System (List (Node0 bN)) (List (Connection0 bN)) (List (Account0 bN))
(Timestamp bN)
nodes :: (System0 a1) -> List (Node0 a1)
nodes s =
case s of {
System nodes0 connections0 accounts0 timestamp0 -> nodes0}
connections :: (System0 a1) -> List (Connection0 a1)
connections s =
case s of {
System nodes0 connections0 accounts0 timestamp0 -> connections0}
accounts :: (System0 a1) -> List (Account0 a1)
accounts s =
case s of {
System nodes0 connections0 accounts0 timestamp0 -> accounts0}
timestamp :: (System0 a1) -> Timestamp a1
timestamp s =
case s of {
System nodes0 connections0 accounts0 timestamp0 -> timestamp0}
godAccount :: a1 -> Account0 a1
godAccount bN0 =
Account bN0 bN0 False False False False False None H0
initialBaseTarget :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) ->
(Currency a1) -> a1 -> a1 -> a1
initialBaseTarget multN divN doubleN systemBalance goalBlockTime maxRand =
divN maxRand (doubleN (multN systemBalance goalBlockTime))
maxBaseTarget :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) ->
(Currency a1) -> a1 -> a1 -> a1
maxBaseTarget multN divN doubleN systemBalance goalBlockTime maxRand =
multN
(initialBaseTarget multN divN doubleN systemBalance goalBlockTime
maxRand) systemBalance
genesisBlock :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) -> a1 ->
(Currency a1) -> a1 -> a1 -> Block0 a1
genesisBlock multN divN doubleN bN0 systemBalance goalBlockTime maxRand =
Block Nil O
(initialBaseTarget multN divN doubleN systemBalance goalBlockTime
maxRand)
(initialBaseTarget multN divN doubleN systemBalance goalBlockTime
maxRand) (godAccount bN0) (Cons H0 Nil) bN0
genesisState :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) -> (a1 ->
a1 -> a1) -> a1 -> a1 -> Nat -> (List
(Prod (Prod (Prod (Prod a1 Bool) Bool) Bool) (Option Nat)))
-> (Currency a1) -> a1 -> a1 -> System0 a1
genesisState multN divN doubleN plusN bN0 bN1 nFixAccounts accountParams systemBalance goalBlockTime maxRand =
let {
accs = sysAccounts multN divN plusN bN0 bN1 nFixAccounts accountParams
systemBalance}
in
let {
chain = Tgen
(genesisBlock multN divN doubleN bN0 systemBalance goalBlockTime maxRand)}
in
let {
nodes0 = map (\acc -> Node chain None Nil Nil (Cons
(genesisBlock multN divN doubleN bN0 systemBalance
goalBlockTime maxRand) Nil) acc) accs}
in
System nodes0 Nil (Cons (godAccount bN0) accs) bN0
sendBlock :: (a2 -> BS) -> (HexN -> a2) -> (a1 -> a1 -> Bool) -> (Node0
a1) -> (Node0 a1) -> (Prod (Block0 a1) (Block0 a1)) -> Node0
a1
sendBlock dig2string hashfun geN sender receiver bseq =
case bseq of {
Pair prevb newb ->
let {rcvr_bc = nodechain receiver} in
let {gen = node_account sender} in
let {gs = calcGenerationSignature dig2string hashfun prevb gen} in
let {chb = changedBlock receiver} in
case eqb_hexs gs (generationSignature newb) of {
True ->
case pushBlock prevb rcvr_bc newb of {
Pair parb newbc -> Node newbc (earlierBlock geN chb parb)
(unconfirmedTxs receiver) (pending_blocks receiver)
(addSortedBlock geN newb (open_blocks receiver))
(node_account receiver)};
False -> receiver}}
eqbAccounts :: (Account0 a1) -> (Account0 a1) -> Bool
eqbAccounts a1 a2 =
eqb_hex (publicKey a1) (publicKey a2)
sendBlocks :: (a2 -> BS) -> (HexN -> a2) -> (a1 -> a1 -> Bool) -> (Node0
a1) -> (Node0 a1) -> Node0 a1
sendBlocks dig2string hashfun geN sender receiver =
case andb
(negb (eqbAccounts (node_account sender) (node_account receiver)))
(isPublishing (node_account sender)) of {
True ->
fold_left (\n pbb -> sendBlock dig2string hashfun geN sender n pbb)
(pending_blocks sender) receiver;
False -> receiver}
postforge :: (a1 -> a1 -> a1) -> ((Block0 a1) -> a1) -> a1 -> (a1 -> a1 ->
Bool) -> (Node0 a1) -> Node0 a1
postforge plusN block_difficulty bN0 geN n =
let {bc = nodechain n} in
let {txs = unconfirmedTxs n} in
let {acc = node_account n} in
let {chb = changedBlock n} in
let {
newbc = case tfdepth acc of {
Some tfd ->
case tfd of {
O ->
case chb of {
Some chb' ->
rebalanceS_till chb' block_difficulty eqb_block bN0 geN
plusN bN0 bc;
None -> bc};
S n0 -> bc};
None -> bc}}
in
Node newbc None txs Nil (open_blocks n) acc
rebalance_chain :: (a1 -> a1 -> a1) -> ((Block0 a1) -> a1) -> a1 -> (a1 -> a1
-> Bool) -> (Node0 a1) -> Node0 a1
rebalance_chain plusN block_difficulty bN0 geN n =
let {bc = nodechain n} in
let {txs = unconfirmedTxs n} in
let {acc = node_account n} in
let {
newbc = snd
(rebalanceS block_difficulty eqb_block bN0 geN plusN bN0 bc
(Pair None Nil))}
in
Node newbc None txs Nil (open_blocks n) acc
rebalance_sys :: (a1 -> a1 -> a1) -> ((Block0 a1) -> a1) -> a1 -> (a1 -> a1
-> Bool) -> (System0 a1) -> System0 a1
rebalance_sys plusN block_difficulty bN0 geN s =
System (map (rebalance_chain plusN block_difficulty bN0 geN) (nodes s))
(connections s) (accounts s) (timestamp s)
systemEvents :: (a1 -> a1 -> a1) -> (a2 -> BS) -> (HexN -> a2) -> ((Block0
a1) -> (Account0 a1) -> (Timestamp a1) -> (List
(Transaction0 a1)) -> HexSPK -> Block0 a1) -> ((Block0
a1) -> a1) -> a1 -> (a1 -> a1 -> Bool) -> (Timestamp
a1) -> ((Node0 a1) -> (Timestamp a1) -> (Block0 a1) -> Bool)
-> Nat -> (Timestamp a1) -> (System0 a1) -> System0 a1
systemEvents plusN dig2string hashfun formBlock block_difficulty bN0 geN markTimestamp canforge lengthConfirmation ts sys0 =
let {
nodes' = map (\n ->
forge_blocks formBlock geN markTimestamp canforge
lengthConfirmation n ts) (nodes sys0)}
in
case partition (\n -> is_nilb (pending_blocks n)) nodes' of {
Pair nonForgers forgers ->
let {
alteredNodes = map (\n_to ->
fold_left (\n_to' n_from ->
sendBlocks dig2string hashfun geN n_from n_to')
forgers n_to) nodes'}
in
System (map (postforge plusN block_difficulty bN0 geN) alteredNodes)
(connections sys0) (accounts sys0) ts}
systemTransform :: (a1 -> a1 -> a1) -> (a1 -> a1) -> (a2 -> BS) -> (HexN ->
a2) -> ((Block0 a1) -> (Account0 a1) -> (Timestamp
a1) -> (List (Transaction0 a1)) -> HexSPK -> Block0
a1) -> ((Block0 a1) -> a1) -> a1 -> (a1 -> a1 -> Bool) ->
(Timestamp a1) -> ((Node0 a1) -> (Timestamp a1) -> (Block0
a1) -> Bool) -> Nat -> (System0 a1) -> Nat -> System0
a1
systemTransform plusN succN dig2string hashfun formBlock block_difficulty bN0 geN markTimestamp canforge lengthConfirmation sys0 count =
let {t = timestamp sys0} in
case count of {
O -> sys0;
S c' ->
systemTransform plusN succN dig2string hashfun formBlock block_difficulty
bN0 geN markTimestamp canforge lengthConfirmation
(systemEvents plusN dig2string hashfun formBlock block_difficulty bN0
geN markTimestamp canforge lengthConfirmation (succN t) sys0) c'}
sys :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) -> (a1 -> a1 -> a1)
-> (a1 -> a1) -> (a2 -> BS) -> (HexN -> a2) -> ((Block0 a1) ->
(Account0 a1) -> (Timestamp a1) -> (List (Transaction0 a1)) -> HexSPK
-> Block0 a1) -> ((Block0 a1) -> a1) -> a1 -> a1 -> (a1 -> a1 -> Bool)
-> (Timestamp a1) -> ((Node0 a1) -> (Timestamp a1) -> (Block0
a1) -> Bool) -> Nat -> Nat -> (List
(Prod (Prod (Prod (Prod a1 Bool) Bool) Bool) (Option Nat))) ->
(Currency a1) -> a1 -> a1 -> Nat -> System0 a1
sys multN divN doubleN plusN succN dig2string hashfun formBlock block_difficulty bN0 bN1 geN markTimestamp canforge lengthConfirmation nFixAccounts accountParams systemBalance goalBlockTime maxRand n =
systemTransform plusN succN dig2string hashfun formBlock block_difficulty
bN0 geN markTimestamp canforge lengthConfirmation
(genesisState multN divN doubleN plusN bN0 bN1 nFixAccounts accountParams
systemBalance goalBlockTime maxRand) n
sysblocks :: (System0 a1) -> List (LTree (Block0 a1))
sysblocks s =
map blocks (map nodechain (nodes s))
data Mhex =
N0
| N1
| N2
| N3
| N4
| N5
| N6
| N7
| N8
| N9
| NA
| NB
| NC
| ND
| NE
| NF
| M0
| M1
| M2
| M3
| M4
| M5
| M6
| M7
| M8
| M9
| MA
| MB
| MC
| MD
| ME
| MF
hex2mhex :: Bool -> Hex -> Mhex
hex2mhex m h =
case m of {
True ->
case h of {
H0 -> M0;
H1 -> M1;
H2 -> M2;
H3 -> M3;
H4 -> M4;
H5 -> M5;
H6 -> M6;
H7 -> M7;
H8 -> M8;
H9 -> M9;
HA -> MA;
HB -> MB;
HC -> MC;
HD -> MD;
HE -> ME;
HF -> MF};
False ->
case h of {
H0 -> N0;
H1 -> N1;
H2 -> N2;
H3 -> N3;
H4 -> N4;
H5 -> N5;
H6 -> N6;
H7 -> N7;
H8 -> N8;
H9 -> N9;
HA -> NA;
HB -> NB;
HC -> NC;
HD -> ND;
HE -> NE;
HF -> NF}}
showblock :: (Block0 a1) -> Mhex
showblock b =
hex2mhex (isnatpos (nMarked b)) (publicKey (generator b))
signs :: (a1 -> a1 -> a1) -> (a1 -> a1 -> a1) -> (a1 -> a1) -> (a1 -> a1 ->
a1) -> (a1 -> a1) -> (a2 -> BS) -> (HexN -> a2) -> ((Block0
a1) -> (Account0 a1) -> (Timestamp a1) -> (List (Transaction0 a1))
-> HexSPK -> Block0 a1) -> ((Block0 a1) -> a1) -> a1 -> a1 -> (a1 ->
a1 -> Bool) -> (Timestamp a1) -> ((Node0 a1) -> (Timestamp a1) ->
(Block0 a1) -> Bool) -> Nat -> Nat -> (List
(Prod (Prod (Prod (Prod a1 Bool) Bool) Bool) (Option Nat))) ->
(Currency a1) -> a1 -> a1 -> Nat -> List (LTree Mhex)
signs multN divN doubleN plusN succN dig2string hashfun formBlock block_difficulty bN0 bN1 geN markTimestamp canforge lengthConfirmation nFixAccounts accountParams systemBalance goalBlockTime maxRand n =
map (\tb -> ltree_map (\b -> showblock b) tb)
(map blocks
(map nodechain
(nodes
(sys multN divN doubleN plusN succN dig2string hashfun formBlock
block_difficulty bN0 bN1 geN markTimestamp canforge
lengthConfirmation nFixAccounts accountParams systemBalance
goalBlockTime maxRand n))))
sysigns :: (System0 a1) -> List (LTree Mhex)
sysigns s =
map (\tb -> ltree_map (\b -> showblock b) tb) (sysblocks s)
sysaccs :: (System0 a1) -> List (Account0 a1)
sysaccs s =
map node_account (nodes s)
addsucc :: (Nattable Nat) -> Nat -> Nattable Nat
addsucc ht k =
case search_table k ht of {
Some v -> modify_key k (plus v (S O)) ht;
None -> Cons (Pair k (S O)) ht}
generators :: (System0 a1) -> List (Nattable Nat)
generators s =
map (\tb ->
ltree_foldl (\ht b -> addsucc ht (hex2nat (publicKey (generator b)))) tb
Nil) (sysblocks s)
| ConsensusResearch/MultiBranch | postructures.hs | gpl-2.0 | 39,308 | 77 | 38 | 11,980 | 16,481 | 8,534 | 7,947 | 1,125 | 32 |
{-# LANGUAGE LambdaCase #-}
{-|
Module : Voogie.FOOL.Traverse
Description : Helper functions for traversing FOOL formulas.
Copyright : (c) Evgenii Kotelnikov, 2019
License : GPL-3
Maintainer : evgeny.kotelnikov@gmail.com
Stability : provisional
-}
module Voogie.FOOL.Traverse (
traverseProblem,
traverseType,
traverseTyped,
traverseTerm,
traverseBinding,
traverseDefinition
) where
import Voogie.FOOL
traverseProblem :: Applicative f
=> (Term -> f Term)
-> (Type -> f Type)
-> Problem -> f Problem
traverseProblem termF typeF (Problem ts ss as c) =
Problem ts <$> traverse (traverseTyped typeF) ss
<*> traverse termF as
<*> termF c
traverseType :: Applicative f
=> (Type -> f Type)
-> Type -> f Type
traverseType typeF = \case
Array ts t -> Array <$> traverse typeF ts <*> typeF t
Tuple ts -> Tuple <$> traverse typeF ts
Functional ts t -> Functional <$> traverse typeF ts <*> typeF t
t -> pure t
traverseTyped :: Applicative f
=> (Type -> f Type)
-> Typed a -> f (Typed a)
traverseTyped typeF (Typed t a) = Typed <$> typeF t <*> pure a
traverseTerm :: Applicative f
=> (Term -> f Term)
-> (Type -> f Type)
-> Term -> f Term
traverseTerm termF typeF = \case
Variable v -> Variable <$> typedF v
Constant i -> Constant <$> typedF i
Application f ts -> Application <$> typedF f <*> traverse termF ts
Binary op f g -> Binary op <$> termF f <*> termF g
Unary op f -> Unary op <$> termF f
Quantify q vs f -> Quantify q <$> traverse typedF vs <*> termF f
Equals s a b -> Equals s <$> termF a <*> termF b
Let b t -> Let <$> traverseBinding termF typeF b <*> termF t
IfElse c a b -> IfElse <$> termF c <*> termF a <*> termF b
Select a i -> Select <$> termF a <*> traverse termF i
Store a i v -> Store <$> termF a <*> traverse termF i <*> termF v
TupleLiteral es -> TupleLiteral <$> traverse termF es
t -> pure t
where
typedF = traverseTyped typeF
traverseBinding :: Applicative f
=> (Term -> f Term)
-> (Type -> f Type)
-> Binding -> f Binding
traverseBinding termF typeF (Binding d b) =
Binding <$> traverseDefinition typeF d <*> termF b
traverseDefinition :: Applicative f
=> (Type -> f Type)
-> Definition -> f Definition
traverseDefinition typeF = \case
ConstantSymbol i -> ConstantSymbol <$> typedF i
Function i vs -> Function <$> typedF i <*> traverse typedF vs
TupleD is -> TupleD <$> traverse typedF is
where
typedF = traverseTyped typeF
| aztek/voogie | src/Voogie/FOOL/Traverse.hs | gpl-3.0 | 2,863 | 0 | 11 | 952 | 928 | 435 | 493 | 62 | 13 |
module P05MathsSpec (main,spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import P05Maths hiding (main)
main :: IO ()
main = hspec spec
x, y :: Float
x = 120
y = 9
spec :: Spec
spec = do
describe "plus" $ do
it "is the same as adding 2 floats and calling show" $
x `plus` y `shouldBe` 129.0
prop "has the property of commutativity" $
\a b -> a `plus` b `shouldBe` b `plus` a
prop "has the property of associativity [up to 2 decimal places] (a+b)+c==a+(b+c) " $
\a b c -> ((a `plus` b) `plus` c) - (a `plus` (b `plus` c)) < 0.01
describe "minus" $
it "is the same as subtracting 1 floats from another and calling show on the result" $
x `minus` y `shouldBe` 111.0
describe "divBy" $ do
it "is the same as dividing 1 float by another and calling show on the result" $
x `divBy` y `shouldBe` 13.333333
it "is the same as dividing 1 float by another and calling show on the result" $
y `divBy` x `shouldBe` 7.5e-2
describe "times" $ do
it "is the same as multiplying 1 float by another and calling show on the result" $
x `times` y `shouldBe` 1080.0
prop "has the property of commutativity" $
\a b -> a `times` b `shouldBe` b `times` a
| ciderpunx/57-exercises-for-programmers | test/P05MathsSpec.hs | gpl-3.0 | 1,235 | 0 | 17 | 313 | 357 | 199 | 158 | 31 | 1 |
{- hmatrix-labeled: matrices with row and column headers.
Copyright 2014 Nikita Karetnikov <nikita@karetnikov.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 3 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Data.Packed.LMatrix
( LMatrix(..)
, lab, pos
, row, col, row',col'
, rowLabels, colLabels
, lRows, lCols
, elem, elem'
, label, unlabel
, rows, cols
, (><)
, trans
, reshape
, flatten
, fromLists
, toLists
, buildMatrix
, (@@>)
, asRow, asCol
, fromRows, toRows
, fromCols, toCols
-- , fromBlocks, diagBlock, toBlocks, toBlocksEvery, repmat
, reverseRows, reverseCols
, subMatrix
, takeRows, dropRows
, takeCols, dropCols
-- , extractRows, diagRect
, takeDiag
, map
-- , mapMatrixWithIndex, mapMatrixWithIndexM, mapMatrixWithIndexM_
-- , liftMatrix, liftMatrix2, liftMatrix2Auto
-- , fromArray2D
) where
import Prelude hiding (reverse, map, elem)
import qualified Data.Packed as P
import qualified Data.List as L hiding (elem)
type Row = String
type Col = String
-- | A pair containing the label and the corresponding position. Both
-- must be unique for this module to work properly.
data Pair = Pair { _lab :: String
, _pos :: Int
} deriving Show
type LRows = [Pair]
type LCols = [Pair]
-- | Labeled matrix.
data LMatrix a = LMatrix LRows LCols (P.Matrix a)
-- | Find the label matching 'n'.
lab :: Int -> [Pair] -> Maybe String
lab n xs = if null xs'
then Nothing
else Just . _lab $ head xs'
where xs' = flip filter xs $ \p -> _pos p == n
-- | Find the position matching 's'.
pos :: String -> [Pair] -> Maybe Int
pos s xs = if null xs'
then Nothing
else Just . _pos $ head xs'
where xs' = flip filter xs $ \p -> _lab p == s
instance (Show a, P.Element a) => Show (LMatrix a) where
show lm@(LMatrix _ _ m) =
"(" ++ show (P.rows m) ++ "><" ++ show (P.cols m) ++ ")\n" ++
concatMap ((++ "\n") . unwords) m'''
where maximum' xs = L.maximumBy cmp xs
cmp x y
| length x > length y = GT
| length x < length y = LT
| otherwise = compare x y
rowH = rowLabels lm
colH = colLabels lm
m' = L.map (L.map show) (L.transpose $ P.toLists m)
m'' = ("" : rowH) : (zipWith (:) colH m')
maxes = L.map (length . maximum') m''
lens = L.map (L.map length) m''
offsets = zipWith (\m l -> (L.map (flip replicate ' ' . (m-)) l))
maxes lens
m''' = L.transpose $ zipWith (zipWith (++)) offsets m''
row :: P.Element a => Row -> LMatrix a -> [a]
row s lm@(LMatrix r _ m) =
case pos s r of
Nothing -> []
Just n -> row' n lm
col :: P.Element a => Col -> LMatrix a -> [a]
col s lm@(LMatrix _ c m) =
case pos s c of
Nothing -> []
Just n -> col' n lm
row' :: P.Element a => Int -> LMatrix a -> [a]
row' n (LMatrix _ _ m) =
concat . P.toLists . P.dropRows n $ P.takeRows (n+1) m
col' :: P.Element a => Int -> LMatrix a -> [a]
col' n (LMatrix _ _ m) =
concat . P.toLists . P.dropColumns n $ P.takeColumns (n+1) m
rowLabels :: LMatrix a -> [String]
rowLabels (LMatrix r _ _) = L.map _lab r
colLabels :: LMatrix a -> [String]
colLabels (LMatrix _ c _) = L.map _lab c
lRows :: LMatrix a -> LRows
lRows (LMatrix r _ _) = r
lCols :: LMatrix a -> LCols
lCols (LMatrix _ c _) = c
elem :: P.Element a => (Row, Col) -> LMatrix a -> Maybe a
elem (r,c) m = case pos c $ lCols m of
Nothing -> Nothing
Just n -> let xs = row r m in
if n > length xs - 1
then Nothing
else Just $ xs !! n
elem' :: P.Element a => (Int, Int) -> LMatrix a -> Maybe a
elem' (r,c) m = let xs = col' c m in
if r > length xs - 1
then Nothing
else Just $ xs !! r
-- | Label the matrix.
label :: [Row] -> [Col] -> P.Matrix a -> LMatrix a
label rs cs m
| length rs /= P.rows m = error "label: wrong number of rows"
| length cs /= P.cols m = error "label: wrong number of columns"
| otherwise = LMatrix (index rs) (index cs) m
where index xs = zipWith Pair xs $ [0..length xs]
-- | Drop the labels.
unlabel :: LMatrix a -> P.Matrix a
unlabel (LMatrix _ _ m) = m
rows :: LMatrix a -> Int
rows = P.rows . unlabel
cols :: LMatrix a -> Int
cols = P.cols . unlabel
(><) :: P.Element a => Int -> Int -> [Row] -> [Col] -> [a] -> LMatrix a
(><) r c rs cs = label rs cs . (r P.>< c)
trans :: LMatrix a -> LMatrix a
trans (LMatrix r c m) = LMatrix c r $ P.trans m
reshape :: P.Element a => Int -> [Row] -> [Col] -> P.Vector a -> LMatrix a
reshape n rs cs = label rs cs . P.reshape n
flatten :: P.Element a => LMatrix a -> P.Vector a
flatten = P.flatten . unlabel
fromLists :: P.Element a => [Row] -> [Col] -> [[a]] -> LMatrix a
fromLists rs cs = label rs cs . P.fromLists
toLists :: P.Element a => LMatrix a -> [[a]]
toLists = P.toLists . unlabel
buildMatrix :: P.Element a => Int -> Int -> ((Int, Int) -> a)
-> [Row] -> [Col] -> LMatrix a
buildMatrix r c f rs cs = label rs cs $ P.buildMatrix r c f
(@@>) :: P.Element a => LMatrix a -> (Int,Int) -> a
(@@>) m p = unlabel m P.@@> p
asRow :: P.Element a => P.Vector a -> [Row] -> [Col] -> LMatrix a
asRow v rs cs = label rs cs $ P.asRow v
asCol :: P.Element a => P.Vector a -> [Row] -> [Col] -> LMatrix a
asCol v rs cs = label rs cs $ P.asColumn v
fromRows :: P.Element a => [P.Vector a] -> [Row] -> [Col] -> LMatrix a
fromRows v rs cs = label rs cs $ P.fromRows v
toRows :: P.Element a => LMatrix a -> [P.Vector a]
toRows = P.toRows . unlabel
fromCols :: P.Element a => [P.Vector a] -> [Row] -> [Col] -> LMatrix a
fromCols v rs cs = label rs cs $ P.fromColumns v
toCols :: P.Element a => LMatrix a -> [P.Vector a]
toCols = P.toColumns . unlabel
reverse :: [Pair] -> [Pair]
reverse xs = zipWith Pair (L.map _lab $ L.reverse xs) [0..length xs]
reverseRows :: P.Element a => LMatrix a -> LMatrix a
reverseRows (LMatrix r c m) = LMatrix (reverse r) c $ P.flipud m
reverseCols :: P.Element a => LMatrix a -> LMatrix a
reverseCols (LMatrix r c m) = LMatrix r (reverse c) $ P.fliprl m
subMatrix :: P.Element a => (Int, Int) -> (Int, Int) -> LMatrix a -> LMatrix a
subMatrix (rs,cs) (rd,cd) (LMatrix r c m) =
LMatrix r' c' $ P.subMatrix (rs,cs) (rd,cd) m
where renumber ps = zipWith Pair (L.map _lab ps) [0..length ps]
r' = renumber . drop rs $ take (rs+rd) r
c' = renumber . drop cs $ take (cs+cd) c
takeRows :: P.Element a => Int -> LMatrix a -> LMatrix a
takeRows n m = subMatrix (0,0) (n,cols m) m
dropRows :: P.Element a => Int -> LMatrix a -> LMatrix a
dropRows n m = subMatrix (n,0) (rows m - n, cols m) m
takeCols :: P.Element a => Int -> LMatrix a -> LMatrix a
takeCols n m = subMatrix (0,0) (rows m,n) m
dropCols :: P.Element a => Int -> LMatrix a -> LMatrix a
dropCols n m = subMatrix (0,n) (rows m, cols m - n) m
takeDiag :: P.Element a => LMatrix a -> P.Vector a
takeDiag (LMatrix _ _ m) = P.takeDiag m
map :: (P.Element a, P.Element b) => (a -> b) -> LMatrix a -> LMatrix b
map f (LMatrix r c m) = LMatrix r c $ P.mapMatrix f m
| nkaretnikov/hmatrix-labeled | src/Data/Packed/LMatrix.hs | gpl-3.0 | 7,791 | 0 | 15 | 2,159 | 3,295 | 1,688 | 1,607 | 166 | 3 |
module Jumpie.Bresenham(bresenham) where
import Data.List(sort,unfoldr,map)
import Data.Function((.),($),id)
import Prelude(abs,(-),(+),(*),Num)
import Data.Ord((>),(<),(>=),Ord)
import Data.Maybe(Maybe(..))
import Data.Bool(otherwise)
import Jumpie.Geometry.Point(Point2(..),pX,pY,pointToTuple)
import Jumpie.Geometry.LineSegment(LineSegment(..))
bresenham :: (Num a,Ord a) => LineSegment (Point2 a) -> [Point2 a]
bresenham (LineSegment pa pb) = map maySwitch . unfoldr go $ (x1,y1,0)
where
steep = abs ((pY pb) - (pY pa)) > abs ((pX pb) - (pX pa))
maySwitch = if steep then (\(Point2 x y) -> Point2 y x) else id
[(x1,y1),(x2,y2)] = (sort . map pointToTuple) [maySwitch pa, maySwitch pb]
deltax = x2 - x1
deltay = abs (y2 - y1)
ystep = if y1 < y2 then 1 else -1
go (xTemp, yTemp, error)
| xTemp > x2 = Nothing
| otherwise = Just (Point2 xTemp yTemp, (xTemp + 1, newY, newError))
where
tempError = error + deltay
(newY, newError) = if (2*tempError) >= deltax
then (yTemp+ystep,tempError-deltax)
else (yTemp,tempError)
| pmiddend/jumpie | lib/Jumpie/Bresenham.hs | gpl-3.0 | 1,151 | 2 | 12 | 276 | 545 | 316 | 229 | 24 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.MachineLearning.Types
-- 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)
--
module Network.Google.MachineLearning.Types
(
-- * Service Configuration
machineLearningService
-- * OAuth Scopes
, cloudPlatformReadOnlyScope
, cloudPlatformScope
-- * GoogleIAMV1__AuditConfig
, GoogleIAMV1__AuditConfig
, googleIAMV1__AuditConfig
, givacService
, givacAuditLogConfigs
-- * GoogleCloudMlV1__Measurement
, GoogleCloudMlV1__Measurement
, googleCloudMlV1__Measurement
, gcmvmMetrics
, gcmvmElapsedTime
, gcmvmStepCount
-- * GoogleCloudMlV1__Version
, GoogleCloudMlV1__Version
, googleCloudMlV1__Version
, gcmvvFramework
, gcmvvEtag
, gcmvvState
, gcmvvRoutes
, gcmvvAutoScaling
, gcmvvPythonVersion
, gcmvvRuntimeVersion
, gcmvvExplanationConfig
, gcmvvLastMigrationModelId
, gcmvvLastUseTime
, gcmvvServiceAccount
, gcmvvName
, gcmvvPackageURIs
, gcmvvContainer
, gcmvvDeploymentURI
, gcmvvManualScaling
, gcmvvAcceleratorConfig
, gcmvvMachineType
, gcmvvLabels
, gcmvvRequestLoggingConfig
, gcmvvPredictionClass
, gcmvvLastMigrationTime
, gcmvvErrorMessage
, gcmvvDescription
, gcmvvCreateTime
, gcmvvIsDefault
-- * GoogleCloudMlV1_AutomatedStoppingConfig_MedianAutomatedStoppingConfig
, GoogleCloudMlV1_AutomatedStoppingConfig_MedianAutomatedStoppingConfig
, googleCloudMlV1_AutomatedStoppingConfig_MedianAutomatedStoppingConfig
, gcmvascmascUseElapsedTime
-- * GoogleCloudMlV1__PredictionOutput
, GoogleCloudMlV1__PredictionOutput
, googleCloudMlV1__PredictionOutput
, gcmvpoNodeHours
, gcmvpoErrorCount
, gcmvpoPredictionCount
, gcmvpoOutputPath
-- * GoogleCloudMlV1__StudyConfigAlgorithm
, GoogleCloudMlV1__StudyConfigAlgorithm (..)
-- * GoogleCloudMlV1__SampledShapleyAttribution
, GoogleCloudMlV1__SampledShapleyAttribution
, googleCloudMlV1__SampledShapleyAttribution
, gcmvssaNumPaths
-- * GoogleCloudMlV1__HyperparameterOutputWebAccessURIs
, GoogleCloudMlV1__HyperparameterOutputWebAccessURIs
, googleCloudMlV1__HyperparameterOutputWebAccessURIs
, gcmvhowauAddtional
-- * GoogleCloudMlV1__BuiltInAlgorithmOutput
, GoogleCloudMlV1__BuiltInAlgorithmOutput
, googleCloudMlV1__BuiltInAlgorithmOutput
, gcmvbiaoFramework
, gcmvbiaoPythonVersion
, gcmvbiaoRuntimeVersion
, gcmvbiaoModelPath
-- * GoogleCloudMlV1_StudyConfig_ParameterSpecType
, GoogleCloudMlV1_StudyConfig_ParameterSpecType (..)
-- * GoogleCloudMlV1__HyperparameterOutputHyperparameters
, GoogleCloudMlV1__HyperparameterOutputHyperparameters
, googleCloudMlV1__HyperparameterOutputHyperparameters
, gcmvhohAddtional
-- * GoogleCloudMlV1__AutomatedStoppingConfig
, GoogleCloudMlV1__AutomatedStoppingConfig
, googleCloudMlV1__AutomatedStoppingConfig
, gcmvascDecayCurveStoppingConfig
, gcmvascMedianAutomatedStoppingConfig
-- * GoogleCloudMlV1__PredictRequest
, GoogleCloudMlV1__PredictRequest
, googleCloudMlV1__PredictRequest
, gcmvprHTTPBody
-- * GoogleCloudMlV1__SuggestTrialsRequest
, GoogleCloudMlV1__SuggestTrialsRequest
, googleCloudMlV1__SuggestTrialsRequest
, gcmvstrClientId
, gcmvstrSuggestionCount
-- * GoogleCloudMlV1__ParameterSpecType
, GoogleCloudMlV1__ParameterSpecType (..)
-- * GoogleCloudMlV1_StudyConfigParameterSpec_DiscreteValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_DiscreteValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_DiscreteValueSpec
, gcmvscpsdvsValues
-- * GoogleCloudMlV1_StudyConfig_MetricSpec
, GoogleCloudMlV1_StudyConfig_MetricSpec
, googleCloudMlV1_StudyConfig_MetricSpec
, gcmvscmsMetric
, gcmvscmsGoal
-- * GoogleCloudMlV1__TrainingInputScaleTier
, GoogleCloudMlV1__TrainingInputScaleTier (..)
-- * GoogleLongrunning__OperationResponse
, GoogleLongrunning__OperationResponse
, googleLongrunning__OperationResponse
, glorAddtional
-- * GoogleCloudMlV1__ParameterSpecScaleType
, GoogleCloudMlV1__ParameterSpecScaleType (..)
-- * GoogleCloudMlV1__XraiAttribution
, GoogleCloudMlV1__XraiAttribution
, googleCloudMlV1__XraiAttribution
, gcmvxaNumIntegralSteps
-- * GoogleCloudMlV1__CheckTrialEarlyStoppingStateResponse
, GoogleCloudMlV1__CheckTrialEarlyStoppingStateResponse
, googleCloudMlV1__CheckTrialEarlyStoppingStateResponse
, gcmvctessrStartTime
, gcmvctessrShouldStop
, gcmvctessrEndTime
-- * GoogleIAMV1__AuditLogConfig
, GoogleIAMV1__AuditLogConfig
, googleIAMV1__AuditLogConfig
, givalcLogType
, givalcExemptedMembers
-- * GoogleCloudMlV1__VersionFramework
, GoogleCloudMlV1__VersionFramework (..)
-- * GoogleCloudMlV1__SuggestTrialsResponse
, GoogleCloudMlV1__SuggestTrialsResponse
, googleCloudMlV1__SuggestTrialsResponse
, gcmvstrStartTime
, gcmvstrStudyState
, gcmvstrEndTime
, gcmvstrTrials
-- * GoogleCloudMlV1__MetricSpecName
, GoogleCloudMlV1__MetricSpecName (..)
-- * GoogleCloudMlV1__SuggestTrialsResponseStudyState
, GoogleCloudMlV1__SuggestTrialsResponseStudyState (..)
-- * GoogleCloudMlV1_Measurement_Metric
, GoogleCloudMlV1_Measurement_Metric
, googleCloudMlV1_Measurement_Metric
, gcmvmmValue
, gcmvmmMetric
-- * GoogleCloudMlV1__ExplainRequest
, GoogleCloudMlV1__ExplainRequest
, googleCloudMlV1__ExplainRequest
, gcmverHTTPBody
-- * GoogleCloudMlV1__ListModelsResponse
, GoogleCloudMlV1__ListModelsResponse
, googleCloudMlV1__ListModelsResponse
, gcmvlmrNextPageToken
, gcmvlmrModels
-- * GoogleCloudMlV1__VersionState
, GoogleCloudMlV1__VersionState (..)
-- * GoogleCloudMlV1_AutomatedStoppingConfig_DecayCurveAutomatedStoppingConfig
, GoogleCloudMlV1_AutomatedStoppingConfig_DecayCurveAutomatedStoppingConfig
, googleCloudMlV1_AutomatedStoppingConfig_DecayCurveAutomatedStoppingConfig
, gcmvascdcascUseElapsedTime
-- * GoogleLongrunning__ListOperationsResponse
, GoogleLongrunning__ListOperationsResponse
, googleLongrunning__ListOperationsResponse
, gllorNextPageToken
, gllorOperations
-- * GoogleCloudMlV1__AcceleratorConfig
, GoogleCloudMlV1__AcceleratorConfig
, googleCloudMlV1__AcceleratorConfig
, gcmvacCount
, gcmvacType
-- * GoogleIAMV1__Policy
, GoogleIAMV1__Policy
, googleIAMV1__Policy
, givpAuditConfigs
, givpEtag
, givpVersion
, givpBindings
-- * GoogleIAMV1__TestIAMPermissionsResponse
, GoogleIAMV1__TestIAMPermissionsResponse
, googleIAMV1__TestIAMPermissionsResponse
, givtiprPermissions
-- * GoogleCloudMlV1__EncryptionConfig
, GoogleCloudMlV1__EncryptionConfig
, googleCloudMlV1__EncryptionConfig
, gcmvecKmsKeyName
-- * GoogleCloudMlV1__HyperparameterSpecAlgorithm
, GoogleCloudMlV1__HyperparameterSpecAlgorithm (..)
-- * GoogleCloudMlV1__ListJobsResponse
, GoogleCloudMlV1__ListJobsResponse
, googleCloudMlV1__ListJobsResponse
, gcmvljrNextPageToken
, gcmvljrJobs
-- * GoogleCloudMlV1__StudyConfig
, GoogleCloudMlV1__StudyConfig
, googleCloudMlV1__StudyConfig
, gcmvscMetrics
, gcmvscAutomatedStoppingConfig
, gcmvscAlgorithm
, gcmvscParameters
-- * GoogleCloudMlV1__SuggestTrialsMetadata
, GoogleCloudMlV1__SuggestTrialsMetadata
, googleCloudMlV1__SuggestTrialsMetadata
, gcmvstmClientId
, gcmvstmSuggestionCount
, gcmvstmStudy
, gcmvstmCreateTime
-- * GoogleCloudMlV1__ListVersionsResponse
, GoogleCloudMlV1__ListVersionsResponse
, googleCloudMlV1__ListVersionsResponse
, gcmvlvrNextPageToken
, gcmvlvrVersions
-- * GoogleCloudMlV1__CapabilityAvailableAcceleratorsItem
, GoogleCloudMlV1__CapabilityAvailableAcceleratorsItem (..)
-- * GoogleType__Expr
, GoogleType__Expr
, googleType__Expr
, gteLocation
, gteExpression
, gteTitle
, gteDescription
-- * GoogleCloudMlV1__ListOptimalTrialsRequest
, GoogleCloudMlV1__ListOptimalTrialsRequest
, googleCloudMlV1__ListOptimalTrialsRequest
-- * GoogleCloudMlV1__JobState
, GoogleCloudMlV1__JobState (..)
-- * GoogleCloudMlV1__PredictionInputDataFormat
, GoogleCloudMlV1__PredictionInputDataFormat (..)
-- * GoogleCloudMlV1__ListStudiesResponse
, GoogleCloudMlV1__ListStudiesResponse
, googleCloudMlV1__ListStudiesResponse
, gcmvlsrStudies
-- * GoogleCloudMlV1__CapabilityType
, GoogleCloudMlV1__CapabilityType (..)
-- * GoogleCloudMlV1__HyperparameterOutput
, GoogleCloudMlV1__HyperparameterOutput
, googleCloudMlV1__HyperparameterOutput
, gcmvhoState
, gcmvhoIsTrialStoppedEarly
, gcmvhoStartTime
, gcmvhoAllMetrics
, gcmvhoHyperparameters
, gcmvhoTrialId
, gcmvhoEndTime
, gcmvhoFinalMetric
, gcmvhoBuiltInAlgorithmOutput
, gcmvhoWebAccessURIs
-- * GoogleCloudMlV1__StudyState
, GoogleCloudMlV1__StudyState (..)
-- * GoogleCloudMlV1__GetConfigResponse
, GoogleCloudMlV1__GetConfigResponse
, googleCloudMlV1__GetConfigResponse
, gcmvgcrConfig
, gcmvgcrServiceAccount
, gcmvgcrServiceAccountProject
-- * GoogleCloudMlV1__PredictionInputOutputDataFormat
, GoogleCloudMlV1__PredictionInputOutputDataFormat (..)
-- * GoogleCloudMlV1__Study
, GoogleCloudMlV1__Study
, googleCloudMlV1__Study
, gcmvsState
, gcmvsName
, gcmvsInactiveReason
, gcmvsStudyConfig
, gcmvsCreateTime
-- * GoogleCloudMlV1__ManualScaling
, GoogleCloudMlV1__ManualScaling
, googleCloudMlV1__ManualScaling
, gcmvmsNodes
-- * GoogleLongrunning__Operation
, GoogleLongrunning__Operation
, googleLongrunning__Operation
, gloDone
, gloError
, gloResponse
, gloName
, gloMetadata
-- * GoogleCloudMlV1__Model
, GoogleCloudMlV1__Model
, googleCloudMlV1__Model
, gcmvmEtag
, gcmvmRegions
, gcmvmDefaultVersion
, gcmvmName
, gcmvmLabels
, gcmvmOnlinePredictionConsoleLogging
, gcmvmDescription
, gcmvmOnlinePredictionLogging
-- * GoogleCloudMlV1__Job
, GoogleCloudMlV1__Job
, googleCloudMlV1__Job
, gcmvjEtag
, gcmvjState
, gcmvjTrainingOutput
, gcmvjJobId
, gcmvjStartTime
, gcmvjPredictionInput
, gcmvjEndTime
, gcmvjPredictionOutput
, gcmvjLabels
, gcmvjErrorMessage
, gcmvjTrainingInput
, gcmvjCreateTime
-- * GoogleCloudMlV1__HyperparameterSpecGoal
, GoogleCloudMlV1__HyperparameterSpecGoal (..)
-- * GoogleCloudMlV1__SetDefaultVersionRequest
, GoogleCloudMlV1__SetDefaultVersionRequest
, googleCloudMlV1__SetDefaultVersionRequest
-- * GoogleCloudMlV1__ModelLabels
, GoogleCloudMlV1__ModelLabels
, googleCloudMlV1__ModelLabels
, gcmvmlAddtional
-- * GoogleIAMV1__AuditLogConfigLogType
, GoogleIAMV1__AuditLogConfigLogType (..)
-- * GoogleCloudMlV1__JobLabels
, GoogleCloudMlV1__JobLabels
, googleCloudMlV1__JobLabels
, gcmvjlAddtional
-- * GoogleCloudMlV1__ListOptimalTrialsResponse
, GoogleCloudMlV1__ListOptimalTrialsResponse
, googleCloudMlV1__ListOptimalTrialsResponse
, gcmvlotrTrials
-- * GoogleRpc__Status
, GoogleRpc__Status
, googleRpc__Status
, grsDetails
, grsCode
, grsMessage
-- * GoogleCloudMlV1__ReplicaConfig
, GoogleCloudMlV1__ReplicaConfig
, googleCloudMlV1__ReplicaConfig
, gcmvrcDiskConfig
, gcmvrcContainerCommand
, gcmvrcImageURI
, gcmvrcAcceleratorConfig
, gcmvrcContainerArgs
, gcmvrcTpuTfVersion
-- * GoogleCloudMlV1__Config
, GoogleCloudMlV1__Config
, googleCloudMlV1__Config
, gcmvcTpuServiceAccount
-- * GoogleCloudMlV1__HyperparameterSpec
, GoogleCloudMlV1__HyperparameterSpec
, googleCloudMlV1__HyperparameterSpec
, gcmvhsResumePreviousJobId
, gcmvhsParams
, gcmvhsAlgorithm
, gcmvhsGoal
, gcmvhsMaxTrials
, gcmvhsEnableTrialEarlyStopping
, gcmvhsMaxParallelTrials
, gcmvhsMaxFailedTrials
, gcmvhsHyperparameterMetricTag
-- * GoogleCloudMlV1__CompleteTrialRequest
, GoogleCloudMlV1__CompleteTrialRequest
, googleCloudMlV1__CompleteTrialRequest
, gcmvctrFinalMeasurement
, gcmvctrInfeasibleReason
, gcmvctrTrialInfeasible
-- * GoogleCloudMlV1__Trial
, GoogleCloudMlV1__Trial
, googleCloudMlV1__Trial
, gcmvtClientId
, gcmvtState
, gcmvtStartTime
, gcmvtFinalMeasurement
, gcmvtMeasurements
, gcmvtName
, gcmvtEndTime
, gcmvtParameters
, gcmvtInfeasibleReason
, gcmvtTrialInfeasible
-- * GoogleCloudMlV1__AutoScaling
, GoogleCloudMlV1__AutoScaling
, googleCloudMlV1__AutoScaling
, gcmvasMetrics
, gcmvasMinNodes
, gcmvasMaxNodes
-- * GoogleCloudMlV1_StudyConfigParameterSpec_DoubleValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_DoubleValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_DoubleValueSpec
, gcmvscpsdvsMaxValue
, gcmvscpsdvsMinValue
-- * GoogleCloudMlV1__ContainerSpec
, GoogleCloudMlV1__ContainerSpec
, googleCloudMlV1__ContainerSpec
, gcmvcsImage
, gcmvcsCommand
, gcmvcsArgs
, gcmvcsEnv
, gcmvcsPorts
-- * GoogleLongrunning__OperationMetadata
, GoogleLongrunning__OperationMetadata
, googleLongrunning__OperationMetadata
, glomAddtional
-- * GoogleCloudMlV1__CheckTrialEarlyStoppingStateRequest
, GoogleCloudMlV1__CheckTrialEarlyStoppingStateRequest
, googleCloudMlV1__CheckTrialEarlyStoppingStateRequest
-- * GoogleCloudMlV1_StudyConfig_ParameterSpecScaleType
, GoogleCloudMlV1_StudyConfig_ParameterSpecScaleType (..)
-- * GoogleCloudMlV1__CheckTrialEarlyStoppingStateMetatData
, GoogleCloudMlV1__CheckTrialEarlyStoppingStateMetatData
, googleCloudMlV1__CheckTrialEarlyStoppingStateMetatData
, gcmvctessmdTrial
, gcmvctessmdStudy
, gcmvctessmdCreateTime
-- * GoogleCloudMlV1_StudyConfigParameterSpec_CategoricalValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_CategoricalValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_CategoricalValueSpec
, gcmvscpscvsValues
-- * GoogleCloudMlV1_StudyConfig_ParameterSpec
, GoogleCloudMlV1_StudyConfig_ParameterSpec
, googleCloudMlV1_StudyConfig_ParameterSpec
, gcmvscpsParentCategoricalValues
, gcmvscpsDoubleValueSpec
, gcmvscpsParentIntValues
, gcmvscpsParentDiscreteValues
, gcmvscpsChildParameterSpecs
, gcmvscpsDiscreteValueSpec
, gcmvscpsScaleType
, gcmvscpsIntegerValueSpec
, gcmvscpsCategoricalValueSpec
, gcmvscpsType
, gcmvscpsParameter
-- * GoogleCloudMlV1_StudyConfig_MetricSpecGoal
, GoogleCloudMlV1_StudyConfig_MetricSpecGoal (..)
-- * GoogleCloudMlV1_StudyConfigParameterSpec_IntegerValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_IntegerValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_IntegerValueSpec
, gcmvscpsivsMaxValue
, gcmvscpsivsMinValue
-- * GoogleCloudMlV1__ExplanationConfig
, GoogleCloudMlV1__ExplanationConfig
, googleCloudMlV1__ExplanationConfig
, gcmvecIntegratedGradientsAttribution
, gcmvecXraiAttribution
, gcmvecSampledShapleyAttribution
-- * GoogleCloudMlV1__MetricSpec
, GoogleCloudMlV1__MetricSpec
, googleCloudMlV1__MetricSpec
, gcmvmsName
, gcmvmsTarget
-- * GoogleCloudMlV1__ParameterSpec
, GoogleCloudMlV1__ParameterSpec
, googleCloudMlV1__ParameterSpec
, gcmvpsMaxValue
, gcmvpsScaleType
, gcmvpsType
, gcmvpsDiscreteValues
, gcmvpsParameterName
, gcmvpsCategoricalValues
, gcmvpsMinValue
-- * Xgafv
, Xgafv (..)
-- * GoogleIAMV1__Binding
, GoogleIAMV1__Binding
, googleIAMV1__Binding
, givbMembers
, givbRole
, givbCondition
-- * GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentDiscreteValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentDiscreteValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_MatchingParentDiscreteValueSpec
, gcmvscpsmpdvsValues
-- * GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric
, GoogleCloudMlV1_HyperparameterOutput_HyperparameterMetric
, googleCloudMlV1_HyperparameterOutput_HyperparameterMetric
, gcmvhohmTrainingStep
, gcmvhohmObjectiveValue
-- * GoogleCloudMlV1__StopTrialRequest
, GoogleCloudMlV1__StopTrialRequest
, googleCloudMlV1__StopTrialRequest
-- * GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentIntValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentIntValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_MatchingParentIntValueSpec
, gcmvscpsmpivsValues
-- * GoogleCloudMlV1_Trial_Parameter
, GoogleCloudMlV1_Trial_Parameter
, googleCloudMlV1_Trial_Parameter
, gcmvtpIntValue
, gcmvtpStringValue
, gcmvtpFloatValue
, gcmvtpParameter
-- * GoogleIAMV1__SetIAMPolicyRequest
, GoogleIAMV1__SetIAMPolicyRequest
, googleIAMV1__SetIAMPolicyRequest
, givsiprUpdateMask
, givsiprPolicy
-- * GoogleCloudMlV1__PredictionInput
, GoogleCloudMlV1__PredictionInput
, googleCloudMlV1__PredictionInput
, gcmvpiVersionName
, gcmvpiModelName
, gcmvpiDataFormat
, gcmvpiURI
, gcmvpiRuntimeVersion
, gcmvpiBatchSize
, gcmvpiMaxWorkerCount
, gcmvpiOutputDataFormat
, gcmvpiOutputPath
, gcmvpiRegion
, gcmvpiInputPaths
, gcmvpiSignatureName
-- * GoogleCloudMlV1__IntegratedGradientsAttribution
, GoogleCloudMlV1__IntegratedGradientsAttribution
, googleCloudMlV1__IntegratedGradientsAttribution
, gcmvigaNumIntegralSteps
-- * GoogleCloudMlV1__TrainingOutputWebAccessURIs
, GoogleCloudMlV1__TrainingOutputWebAccessURIs
, googleCloudMlV1__TrainingOutputWebAccessURIs
, gcmvtowauAddtional
-- * GoogleCloudMlV1__ContainerPort
, GoogleCloudMlV1__ContainerPort
, googleCloudMlV1__ContainerPort
, gcmvcpContainerPort
-- * GoogleCloudMlV1__TrainingInput
, GoogleCloudMlV1__TrainingInput
, googleCloudMlV1__TrainingInput
, gcmvtiMasterType
, gcmvtiWorkerConfig
, gcmvtiParameterServerCount
, gcmvtiArgs
, gcmvtiEnableWebAccess
, gcmvtiUseChiefInTfConfig
, gcmvtiWorkerCount
, gcmvtiJobDir
, gcmvtiEvaluatorCount
, gcmvtiEvaluatorType
, gcmvtiNetwork
, gcmvtiPythonVersion
, gcmvtiRuntimeVersion
, gcmvtiWorkerType
, gcmvtiMasterConfig
, gcmvtiPythonModule
, gcmvtiParameterServerType
, gcmvtiServiceAccount
, gcmvtiHyperparameters
, gcmvtiPackageURIs
, gcmvtiScaleTier
, gcmvtiEncryptionConfig
, gcmvtiRegion
, gcmvtiScheduling
, gcmvtiParameterServerConfig
, gcmvtiEvaluatorConfig
-- * GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentCategoricalValueSpec
, GoogleCloudMlV1_StudyConfigParameterSpec_MatchingParentCategoricalValueSpec
, googleCloudMlV1_StudyConfigParameterSpec_MatchingParentCategoricalValueSpec
, gcmvscpsmpcvsValues
-- * GoogleCloudMlV1__RouteMap
, GoogleCloudMlV1__RouteMap
, googleCloudMlV1__RouteMap
, gcmvrmHealth
, gcmvrmPredict
-- * GoogleRpc__StatusDetailsItem
, GoogleRpc__StatusDetailsItem
, googleRpc__StatusDetailsItem
, grsdiAddtional
-- * GoogleCloudMlV1__OperationMetadataOperationType
, GoogleCloudMlV1__OperationMetadataOperationType (..)
-- * GoogleProtobuf__Empty
, GoogleProtobuf__Empty
, googleProtobuf__Empty
-- * GoogleCloudMlV1__TrialState
, GoogleCloudMlV1__TrialState (..)
-- * GoogleCloudMlV1__Location
, GoogleCloudMlV1__Location
, googleCloudMlV1__Location
, gcmvlName
, gcmvlCapabilities
-- * GoogleCloudMlV1__OperationMetadataLabels
, GoogleCloudMlV1__OperationMetadataLabels
, googleCloudMlV1__OperationMetadataLabels
, gcmvomlAddtional
-- * GoogleCloudMlV1__AcceleratorConfigType
, GoogleCloudMlV1__AcceleratorConfigType (..)
-- * GoogleCloudMlV1__Capability
, GoogleCloudMlV1__Capability
, googleCloudMlV1__Capability
, gcmvcAvailableAccelerators
, gcmvcType
-- * GoogleCloudMlV1__OperationMetadata
, GoogleCloudMlV1__OperationMetadata
, googleCloudMlV1__OperationMetadata
, gcmvomStartTime
, gcmvomModelName
, gcmvomProjectNumber
, gcmvomVersion
, gcmvomEndTime
, gcmvomIsCancellationRequested
, gcmvomLabels
, gcmvomOperationType
, gcmvomCreateTime
-- * GoogleCloudMlV1__EnvVar
, GoogleCloudMlV1__EnvVar
, googleCloudMlV1__EnvVar
, gcmvevValue
, gcmvevName
-- * GoogleCloudMlV1__ListTrialsResponse
, GoogleCloudMlV1__ListTrialsResponse
, googleCloudMlV1__ListTrialsResponse
, gcmvltrTrials
-- * GoogleCloudMlV1__AddTrialMeasurementRequest
, GoogleCloudMlV1__AddTrialMeasurementRequest
, googleCloudMlV1__AddTrialMeasurementRequest
, gcmvatmrMeasurement
-- * GoogleCloudMlV1__RequestLoggingConfig
, GoogleCloudMlV1__RequestLoggingConfig
, googleCloudMlV1__RequestLoggingConfig
, gcmvrlcSamplingPercentage
, gcmvrlcBigQueryTableName
-- * GoogleAPI__HTTPBodyExtensionsItem
, GoogleAPI__HTTPBodyExtensionsItem
, googleAPI__HTTPBodyExtensionsItem
, gahttpbeiAddtional
-- * GoogleCloudMlV1__CancelJobRequest
, GoogleCloudMlV1__CancelJobRequest
, googleCloudMlV1__CancelJobRequest
-- * GoogleCloudMlV1__Scheduling
, GoogleCloudMlV1__Scheduling
, googleCloudMlV1__Scheduling
, gcmvsMaxWaitTime
, gcmvsPriority
, gcmvsMaxRunningTime
-- * GoogleCloudMlV1__TrainingOutput
, GoogleCloudMlV1__TrainingOutput
, googleCloudMlV1__TrainingOutput
, gcmvtoIsHyperparameterTuningJob
, gcmvtoIsBuiltInAlgorithmJob
, gcmvtoCompletedTrialCount
, gcmvtoConsumedMLUnits
, gcmvtoBuiltInAlgorithmOutput
, gcmvtoHyperparameterMetricTag
, gcmvtoWebAccessURIs
, gcmvtoTrials
-- * GoogleAPI__HTTPBody
, GoogleAPI__HTTPBody
, googleAPI__HTTPBody
, gahttpbExtensions
, gahttpbData
, gahttpbContentType
-- * GoogleIAMV1__TestIAMPermissionsRequest
, GoogleIAMV1__TestIAMPermissionsRequest
, googleIAMV1__TestIAMPermissionsRequest
, giamvtiamprPermissions
-- * GoogleCloudMlV1__ListLocationsResponse
, GoogleCloudMlV1__ListLocationsResponse
, googleCloudMlV1__ListLocationsResponse
, gcmvllrNextPageToken
, gcmvllrLocations
-- * GoogleCloudMlV1__DiskConfig
, GoogleCloudMlV1__DiskConfig
, googleCloudMlV1__DiskConfig
, gcmvdcBootDiskType
, gcmvdcBootDiskSizeGb
-- * GoogleCloudMlV1__VersionLabels
, GoogleCloudMlV1__VersionLabels
, googleCloudMlV1__VersionLabels
, gcmvvlAddtional
-- * GoogleCloudMlV1__HyperparameterOutputState
, GoogleCloudMlV1__HyperparameterOutputState (..)
) where
import Network.Google.MachineLearning.Types.Product
import Network.Google.MachineLearning.Types.Sum
import Network.Google.Prelude
-- | Default request referring to version 'v1' of the AI Platform Training & Prediction API. This contains the host and root path used as a starting point for constructing service requests.
machineLearningService :: ServiceConfig
machineLearningService
= defaultService (ServiceId "ml:v1")
"ml.googleapis.com"
-- | View your data across Google Cloud Platform services
cloudPlatformReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform.read-only"]
cloudPlatformReadOnlyScope = Proxy
-- | See, edit, configure, and delete your Google Cloud Platform data
cloudPlatformScope :: Proxy '["https://www.googleapis.com/auth/cloud-platform"]
cloudPlatformScope = Proxy
| brendanhay/gogol | gogol-ml/gen/Network/Google/MachineLearning/Types.hs | mpl-2.0 | 24,426 | 0 | 7 | 4,431 | 1,935 | 1,340 | 595 | 554 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Cloudbuild.Projects.Builds.Retry
-- 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)
--
-- Creates a new build based on the specified build. This method creates a
-- new build using the original build request, which may or may not result
-- in an identical build. For triggered builds: * Triggered builds resolve
-- to a precise revision; therefore a retry of a triggered build will
-- result in a build that uses the same revision. For non-triggered builds
-- that specify \`RepoSource\`: * If the original build built from the tip
-- of a branch, the retried build will build from the tip of that branch,
-- which may not be the same revision as the original build. * If the
-- original build specified a commit sha or revision ID, the retried build
-- will use the identical source. For builds that specify
-- \`StorageSource\`: * If the original build pulled source from Google
-- Cloud Storage without specifying the generation of the object, the new
-- build will use the current object, which may be different from the
-- original build source. * If the original build pulled source from Cloud
-- Storage and specified the generation of the object, the new build will
-- attempt to use the same object, which may or may not be available
-- depending on the bucket\'s lifecycle management settings.
--
-- /See:/ <https://cloud.google.com/cloud-build/docs/ Cloud Build API Reference> for @cloudbuild.projects.builds.retry@.
module Network.Google.Resource.Cloudbuild.Projects.Builds.Retry
(
-- * REST Resource
ProjectsBuildsRetryResource
-- * Creating a Request
, projectsBuildsRetry
, ProjectsBuildsRetry
-- * Request Lenses
, pbrXgafv
, pbrUploadProtocol
, pbrAccessToken
, pbrUploadType
, pbrPayload
, pbrId
, pbrProjectId
, pbrCallback
) where
import Network.Google.ContainerBuilder.Types
import Network.Google.Prelude
-- | A resource alias for @cloudbuild.projects.builds.retry@ method which the
-- 'ProjectsBuildsRetry' request conforms to.
type ProjectsBuildsRetryResource =
"v1" :>
"projects" :>
Capture "projectId" Text :>
"builds" :>
CaptureMode "id" "retry" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] RetryBuildRequest :>
Post '[JSON] Operation
-- | Creates a new build based on the specified build. This method creates a
-- new build using the original build request, which may or may not result
-- in an identical build. For triggered builds: * Triggered builds resolve
-- to a precise revision; therefore a retry of a triggered build will
-- result in a build that uses the same revision. For non-triggered builds
-- that specify \`RepoSource\`: * If the original build built from the tip
-- of a branch, the retried build will build from the tip of that branch,
-- which may not be the same revision as the original build. * If the
-- original build specified a commit sha or revision ID, the retried build
-- will use the identical source. For builds that specify
-- \`StorageSource\`: * If the original build pulled source from Google
-- Cloud Storage without specifying the generation of the object, the new
-- build will use the current object, which may be different from the
-- original build source. * If the original build pulled source from Cloud
-- Storage and specified the generation of the object, the new build will
-- attempt to use the same object, which may or may not be available
-- depending on the bucket\'s lifecycle management settings.
--
-- /See:/ 'projectsBuildsRetry' smart constructor.
data ProjectsBuildsRetry =
ProjectsBuildsRetry'
{ _pbrXgafv :: !(Maybe Xgafv)
, _pbrUploadProtocol :: !(Maybe Text)
, _pbrAccessToken :: !(Maybe Text)
, _pbrUploadType :: !(Maybe Text)
, _pbrPayload :: !RetryBuildRequest
, _pbrId :: !Text
, _pbrProjectId :: !Text
, _pbrCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsBuildsRetry' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pbrXgafv'
--
-- * 'pbrUploadProtocol'
--
-- * 'pbrAccessToken'
--
-- * 'pbrUploadType'
--
-- * 'pbrPayload'
--
-- * 'pbrId'
--
-- * 'pbrProjectId'
--
-- * 'pbrCallback'
projectsBuildsRetry
:: RetryBuildRequest -- ^ 'pbrPayload'
-> Text -- ^ 'pbrId'
-> Text -- ^ 'pbrProjectId'
-> ProjectsBuildsRetry
projectsBuildsRetry pPbrPayload_ pPbrId_ pPbrProjectId_ =
ProjectsBuildsRetry'
{ _pbrXgafv = Nothing
, _pbrUploadProtocol = Nothing
, _pbrAccessToken = Nothing
, _pbrUploadType = Nothing
, _pbrPayload = pPbrPayload_
, _pbrId = pPbrId_
, _pbrProjectId = pPbrProjectId_
, _pbrCallback = Nothing
}
-- | V1 error format.
pbrXgafv :: Lens' ProjectsBuildsRetry (Maybe Xgafv)
pbrXgafv = lens _pbrXgafv (\ s a -> s{_pbrXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pbrUploadProtocol :: Lens' ProjectsBuildsRetry (Maybe Text)
pbrUploadProtocol
= lens _pbrUploadProtocol
(\ s a -> s{_pbrUploadProtocol = a})
-- | OAuth access token.
pbrAccessToken :: Lens' ProjectsBuildsRetry (Maybe Text)
pbrAccessToken
= lens _pbrAccessToken
(\ s a -> s{_pbrAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pbrUploadType :: Lens' ProjectsBuildsRetry (Maybe Text)
pbrUploadType
= lens _pbrUploadType
(\ s a -> s{_pbrUploadType = a})
-- | Multipart request metadata.
pbrPayload :: Lens' ProjectsBuildsRetry RetryBuildRequest
pbrPayload
= lens _pbrPayload (\ s a -> s{_pbrPayload = a})
-- | Required. Build ID of the original build.
pbrId :: Lens' ProjectsBuildsRetry Text
pbrId = lens _pbrId (\ s a -> s{_pbrId = a})
-- | Required. ID of the project.
pbrProjectId :: Lens' ProjectsBuildsRetry Text
pbrProjectId
= lens _pbrProjectId (\ s a -> s{_pbrProjectId = a})
-- | JSONP
pbrCallback :: Lens' ProjectsBuildsRetry (Maybe Text)
pbrCallback
= lens _pbrCallback (\ s a -> s{_pbrCallback = a})
instance GoogleRequest ProjectsBuildsRetry where
type Rs ProjectsBuildsRetry = Operation
type Scopes ProjectsBuildsRetry =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsBuildsRetry'{..}
= go _pbrProjectId _pbrId _pbrXgafv
_pbrUploadProtocol
_pbrAccessToken
_pbrUploadType
_pbrCallback
(Just AltJSON)
_pbrPayload
containerBuilderService
where go
= buildClient
(Proxy :: Proxy ProjectsBuildsRetryResource)
mempty
| brendanhay/gogol | gogol-containerbuilder/gen/Network/Google/Resource/Cloudbuild/Projects/Builds/Retry.hs | mpl-2.0 | 7,736 | 0 | 19 | 1,733 | 892 | 532 | 360 | 125 | 1 |
{-|
Module : Data.JustParse.Language
Description : Regular expressions
Copyright : Copyright Waived
License : PublicDomain
Maintainer : grantslatton@gmail.com
Stability : experimental
Portability : portable
Allows for conversion from a regular expression and a 'Parser'.
-}
{-# LANGUAGE Safe #-}
module Data.JustParse.Language (
Match (..)
, regex
, regex_
, regex'
, regex_'
) where
import Data.JustParse
import Data.JustParse.Combinator
import Data.JustParse.Numeric
import Data.JustParse.Char
import Control.Monad ( liftM, void )
import Data.Monoid ( Monoid, mconcat, mempty, mappend )
import Control.Applicative ( (<*), (<$) )
-- | @regex@ takes a regular expression in the form of a 'String' and,
-- if the regex is valid, returns a greedy 'Parser' that parses that regex.
-- If the regex is invalid, it returns Nothing.
regex :: Stream s Char => String -> Maybe (Parser s Match)
regex = liftM greedy . regex_
{-# INLINE regex #-}
-- | Like 'regex', but returns a branching (non-greedy) parser.
regex_ :: Stream s Char => String -> Maybe (Parser s Match)
regex_ = parseOnly (regular <* eof)
{-# INLINE regex_ #-}
-- | The same as 'regex', but only returns the full matched text.
regex' :: Stream s Char => String -> Maybe (Parser s String)
regex' = liftM (liftM matched) . regex
{-# INLINE regex' #-}
-- | The same as 'regex_', but only returns the full matched text.
regex_' :: Stream s Char => String -> Maybe (Parser s String)
regex_' = liftM (liftM matched) . regex_
{-# INLINE regex_' #-}
-- | The result of a 'regex'
data Match =
Match {
-- | The complete text matched within the regex
matched :: String
-- | Any submatches created by using capture groups
, groups :: [Match]
} deriving (Show, Eq)
-- mconcat makes things very nice for concatenating the results of subregexes
instance Monoid Match where
mempty = Match "" []
mappend (Match m g) (Match m' g') = Match { matched = m ++ m', groups = g ++ g' }
regular :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
regular = liftM (liftM mconcat . sequence) (many parser)
{-# INLINE regular #-}
-- all parsers
parser :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
parser = choice [
asterisk
, mn
, pipe
, plus
, question
, lookAheadAssert
, lookAheadAssertNot
, group
, character
, charClass
, negCharClass
, period
, endOfLine
]
{-# INLINE parser #-}
-- parsers with no pipe
parserNP :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
parserNP = choice [
asterisk
, mn
, plus
, question
, lookAheadAssert
, lookAheadAssertNot
, group
, character
, charClass
, negCharClass
, period
]
{-# INLINE parserNP #-}
-- parsers that can be followed by special operators (i.e. to prevent a
-- regex like "a???*?" which would be hazardous)
restricted :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
restricted = choice [
character
, charClass
, negCharClass
, lookAheadAssert
, lookAheadAssertNot
, group
, period
]
{-# INLINE restricted #-}
unreserved :: Stream s Char => Parser s Char
unreserved = (char '\\' >> anyChar ) <|> noneOf "()[]\\*+{}^?|.$"
{-# INLINE unreserved #-}
character :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
character = do
c <- unreserved
return $ do
char c
return $ Match [c] []
{-# INLINE character #-}
charClass :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
charClass = do
char '['
c <- many1 unreserved
char ']'
return $ do
c' <- oneOf c
return $ Match [c'] []
{-# INLINE charClass #-}
negCharClass :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
negCharClass = do
string "[^"
c <- many1 unreserved
char ']'
return $ do
c' <- noneOf c
return $ Match [c'] []
{-# INLINE negCharClass #-}
period :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
period = do
char '.'
return $ do
c <- noneOf "\n\r"
return $ Match [c] []
{-# INLINE period #-}
question :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
question = do
p <- restricted
char '?'
return $ liftM mconcat (mN_ 0 1 p)
{-# INLINE question #-}
group :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
group = do
char '('
p <- regular
char ')'
return $ do
r <- p
return $ r { groups = [r] }
{-# INLINE group #-}
asterisk :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
asterisk = do
p <- restricted
char '*'
return $ liftM mconcat (many_ p)
{-# INLINE asterisk #-}
plus :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
plus = do
p <- restricted
char '+'
return $ liftM mconcat (many1_ p)
{-# INLINE plus #-}
mn :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
mn = do
p <- restricted
char '{'
l <- option 0 decInt
char ','
r <- option (-1) decInt
char '}'
return $ liftM mconcat (mN_ l r p)
{-# INLINE mn #-}
pipe :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
pipe = do
p <- parserNP
char '|'
p' <- parser
return $ p <||> p'
{-# INLINE pipe #-}
-- (?=pattern) : positive look-ahead assertion
lookAheadAssert :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
lookAheadAssert = do
string "(?="
p <- regular
char ')'
return $ do
lookAhead p
return $ Match "" []
{-# INLINE lookAheadAssert #-}
-- (?!pattern) : negative look-ahead assertion
lookAheadAssertNot :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
lookAheadAssertNot = do
string "(?!"
p <- regular
char ')'
return $ do
assertNotP $ lookAhead p
return $ Match "" []
{-# INLINE lookAheadAssertNot #-}
endOfLine :: (Stream s0 Char, Stream s1 Char) => Parser s0 (Parser s1 Match)
endOfLine = do
char '$' >> eof
return $ Match "" [] <$ (void eol <|> eof)
{-# INLINE endOfLine #-}
| grantslatton/JustParse | src/Data/JustParse/Language.hs | unlicense | 6,216 | 0 | 13 | 1,590 | 1,878 | 963 | 915 | -1 | -1 |
primes :: Integral a => [a]
primes = map fromIntegral $ [2, 3] ++ primes'
where
primes' = [5] ++ f 1 7 primes'
f m s (p:ps) = [n | n <- ns, gcd m n == 1] ++ f (m * p) (p * p) ps
where ns = [x + y | x <- [s, s + 6 .. p * p - 2], y <- [0, 4]]
ans (p1:p2:ps) n =
if n < p1
then []
else if n == p1
then []
else if n < p2
then [p1, p2]
else if n == p2
then [p1, head ps]
else ans (p2:ps) n
main = do
l <- getContents
let i = map read $ lines l :: [Int]
o = map (ans primes) i
mapM_ putStrLn $ map unwords $ map (map show) o
| a143753/AOJ | 0044.hs | apache-2.0 | 684 | 2 | 12 | 306 | 379 | 193 | 186 | 20 | 5 |
import Network.Eureka (withEureka,
EurekaConfig(eurekaInstanceInfoReplicationInterval, eurekaRegion,
eurekaServerServiceUrls), InstanceConfig(instanceAppName,
instanceLeaseRenewalInterval, instanceMetadata),
InstanceStatus(OutOfService), def, discoverDataCenterAmazon,
lookupByAppName, setStatus, DataCenterInfo(DataCenterAmazon))
import Control.Concurrent (threadDelay)
import Control.Monad (replicateM_)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Logger (runNoLoggingT)
import Network.HTTP.Client (defaultManagerSettings, newManager)
import System.Environment (getArgs)
import qualified Data.Map as Map
main :: IO ()
main = do
args <- getArgs
let [commandLineServer] = args
dataCenterInfo <- newManager defaultManagerSettings >>= discoverDataCenterAmazon
runNoLoggingT $ withEureka
(myEurekaConfig commandLineServer)
myInstanceConfig
(DataCenterAmazon dataCenterInfo)
(\eConn -> runNoLoggingT $ do
result <- lookupByAppName eConn "FITBIT-SYNC-WORKER"
liftIO $ print result
replicateM_ 10 delay
setStatus eConn OutOfService
replicateM_ 10 delay
)
where
delay = liftIO $ threadDelay (1000 * 1000)
myEurekaConfig serverUrl = def {
eurekaInstanceInfoReplicationInterval = 1,
eurekaServerServiceUrls = Map.fromList [("default", [serverUrl])],
eurekaRegion = "default"
}
myInstanceConfig = def {
instanceLeaseRenewalInterval = 1,
instanceAppName = "haskell_eureka_test_app",
instanceMetadata = Map.fromList [("testKey", "testValue")]
}
| SumAll/haskell-eureka-client | src/test.hs | apache-2.0 | 1,669 | 1 | 15 | 353 | 378 | 213 | 165 | 37 | 1 |
module Text.Nagato.Models
( Freqs
,Probs
)where
import Data.Map
type Freqs a = Map a Int
type Probs a = Map a Float
| haru2036/nagato | Text/Nagato/Models.hs | apache-2.0 | 119 | 0 | 5 | 25 | 44 | 27 | 17 | 6 | 0 |
module HaskHOL.Lib.Arith.Base where
import HaskHOL.Core
import HaskHOL.Deductive hiding (getDefinition, getSpecification,
newSpecification, newDefinition)
import HaskHOL.Lib.Nums
import HaskHOL.Lib.Recursion
defPRE :: HOL cls thry HOLThm
defPRE = unsafeCacheProof "defPRE" $ getRecursiveDefinition "PRE"
defADD :: HOL cls thry HOLThm
defADD = unsafeCacheProof "defADD" $ getRecursiveDefinition "+"
defMULT :: HOL cls thry HOLThm
defMULT = unsafeCacheProof "defMULT" $ getRecursiveDefinition "*"
defLE :: HOL cls thry HOLThm
defLE = unsafeCacheProof "defLE" $ getRecursiveDefinition "<="
defLT :: HOL cls thry HOLThm
defLT = unsafeCacheProof "defLT" $ getRecursiveDefinition "<"
thmADD_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_0 = unsafeCacheProof "thmADD_0" .
prove [txt| !m. m + 0 = m |] $
tacINDUCT `_THEN` tacASM_REWRITE [defADD]
thmADD_SUC :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_SUC = unsafeCacheProof "thmADD_SUC" .
prove [txt| !m n. m + (SUC n) = SUC (m + n) |] $
tacINDUCT `_THEN` tacASM_REWRITE [defADD]
thmLE_SUC_LT :: NumsCtxt thry => HOL cls thry HOLThm
thmLE_SUC_LT = unsafeCacheProof "thmLE_SUC_LT" .
prove [txt| !m n. (SUC m <= n) <=> (m < n) |] $
tacGEN `_THEN` tacINDUCT `_THEN`
tacASM_REWRITE [ defLE , defLT, thmNOT_SUC, thmSUC_INJ ]
thmLT_SUC_LE :: NumsCtxt thry => HOL cls thry HOLThm
thmLT_SUC_LE = unsafeCacheProof "thmLT_SUC_LE" .
prove [txt| !m n. (m < SUC n) <=> (m <= n) |] $
tacGEN `_THEN` tacINDUCT `_THEN`
tacONCE_REWRITE [ defLT, defLE ] `_THEN`
tacASM_REWRITE_NIL `_THEN` tacREWRITE [defLT]
thmLE_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmLE_0 = unsafeCacheProof "thmLE_0" .
prove [txt| !n. 0 <= n |] $
tacINDUCT `_THEN` tacASM_REWRITE [defLE]
wfNUM_PRIM :: NumsCtxt thry => HOL cls thry HOLThm
wfNUM_PRIM = unsafeCacheProof "wfNUM_PRIM" .
prove [txt| !P. (!n. (!m. m < n ==> P m) ==> P n) ==> !n. P n |] $
tacGEN `_THEN`
tacMP (ruleSPEC [txt| \n. !m. m < n ==> P m |] inductionNUM) `_THEN`
tacREWRITE [defLT, thmBETA] `_THEN`
tacMESON [defLT]
thmADD_CLAUSES :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_CLAUSES = unsafeCacheProof "thmADD_CLAUSES" .
prove [txt| (!n. 0 + n = n) /\
(!m. m + 0 = m) /\
(!m n. (SUC m) + n = SUC(m + n)) /\
(!m n. m + (SUC n) = SUC(m + n)) |] $
tacREWRITE [defADD, thmADD_0, thmADD_SUC]
thmLE_SUC :: NumsCtxt thry => HOL cls thry HOLThm
thmLE_SUC = unsafeCacheProof "thmLE_SUC" .
prove [txt| !m n. (SUC m <= SUC n) <=> (m <= n) |] $
tacREWRITE [thmLE_SUC_LT, thmLT_SUC_LE]
thmLT_SUC :: NumsCtxt thry => HOL cls thry HOLThm
thmLT_SUC = unsafeCacheProof "thmLT_SUC" .
prove [txt| !m n. (SUC m < SUC n) <=> (m < n) |] $
tacREWRITE [thmLT_SUC_LE, thmLE_SUC_LT]
wopNUM :: NumsCtxt thry => HOL cls thry HOLThm
wopNUM = unsafeCacheProof "wopNUM" .
prove [txt| !P. (?n. P n) <=> (?n. P(n) /\ !m. m < n ==> ~P(m)) |] $
tacGEN `_THEN` tacEQ `_THENL` [_ALL, tacMESON_NIL] `_THEN`
tacCONV convCONTRAPOS `_THEN` tacREWRITE [thmNOT_EXISTS] `_THEN`
tacDISCH `_THEN` tacMATCH_MP wfNUM_PRIM `_THEN` tacASM_MESON_NIL
thmADD_SYM :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_SYM = unsafeCacheProof "thmADD_SYM" .
prove [txt| !m n. m + n = n + m |] $
tacINDUCT `_THEN` tacASM_REWRITE [thmADD_CLAUSES]
thmEQ_ADD_LCANCEL :: NumsCtxt thry => HOL cls thry HOLThm
thmEQ_ADD_LCANCEL = unsafeCacheProof "thmEQ_ADD_LCANCEL" .
prove [txt| !m n p. (m + n = m + p) <=> (n = p) |] $
tacINDUCT `_THEN` tacASM_REWRITE [thmADD_CLAUSES, thmSUC_INJ]
thmBIT0 :: NumsCtxt thry => HOL cls thry HOLThm
thmBIT0 = unsafeCacheProof "thmBIT0" .
prove [txt| !n. BIT0 n = n + n |] $
tacINDUCT `_THEN` tacASM_REWRITE [defBIT0, thmADD_CLAUSES]
thmMULT_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmMULT_0 = unsafeCacheProof "thmMULT_0" .
prove [txt| !m. m * 0 = 0 |] $
tacINDUCT `_THEN`
tacASM_REWRITE [defMULT, thmADD_CLAUSES]
thmADD_ASSOC :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_ASSOC = unsafeCacheProof "thmADD_ASSOC" .
prove [txt| !m n p. m + (n + p) = (m + n) + p |] $
tacINDUCT `_THEN` tacASM_REWRITE [thmADD_CLAUSES]
thmADD_EQ_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmADD_EQ_0 = unsafeCacheProof "thmADD_EQ_0" .
prove [txt| !m n. (m + n = 0) <=> (m = 0) /\ (n = 0) |] $
_REPEAT tacINDUCT `_THEN` tacREWRITE [thmADD_CLAUSES, thmNOT_SUC]
thmLT_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmLT_0 = unsafeCacheProof "thmLT_0" .
prove [txt| !n. 0 < SUC n |] $
tacREWRITE [thmLT_SUC_LE, thmLE_0]
thmLT_ADD :: NumsCtxt thry => HOL cls thry HOLThm
thmLT_ADD = unsafeCacheProof "thmLT_ADD" .
prove [txt| !m n. (m < m + n) <=> (0 < n) |] $
tacINDUCT `_THEN` tacASM_REWRITE [thmADD_CLAUSES, thmLT_SUC]
thmBIT1 :: NumsCtxt thry => HOL cls thry HOLThm
thmBIT1 = unsafeCacheProof "thmBIT1" .
prove [txt| !n. BIT1 n = SUC(n + n) |] $
tacREWRITE [defBIT1, thmBIT0]
thmMULT_SUC :: NumsCtxt thry => HOL cls thry HOLThm
thmMULT_SUC = unsafeCacheProof "thmMULT_SUC" .
prove [txt| !m n. m * (SUC n) = m + (m * n) |] $
tacINDUCT `_THEN`
tacASM_REWRITE [defMULT, thmADD_CLAUSES, thmADD_ASSOC]
thmNOT_LE :: NumsCtxt thry => HOL cls thry HOLThm
thmNOT_LE = unsafeCacheProof "thmNOT_LE" .
prove [txt| !m n. ~(m <= n) <=> (n < m) |] $
_REPEAT tacINDUCT `_THEN`
tacASM_REWRITE [thmLE_SUC, thmLT_SUC] `_THEN`
tacREWRITE [ defLE, defLT, thmNOT_SUC
, ruleGSYM thmNOT_SUC, thmLE_0 ] `_THEN`
(\ g@(Goal _ asl) -> let a = head $ frees asl in
tacSPEC (a, a) g) `_THEN`
tacINDUCT `_THEN` tacREWRITE [thmLT_0]
thmNOT_LT :: NumsCtxt thry => HOL cls thry HOLThm
thmNOT_LT = unsafeCacheProof "thmNOT_LT" .
prove [txt| !m n. ~(m < n) <=> n <= m |] $
_REPEAT tacINDUCT `_THEN`
tacASM_REWRITE [thmLE_SUC, thmLT_SUC] `_THEN`
tacREWRITE [ defLE, defLT, thmNOT_SUC
, ruleGSYM thmNOT_SUC, thmLE_0 ] `_THEN`
(\ g@(Goal _ asl) -> let a = head $ frees asl in
tacSPEC (a, a) g) `_THEN`
tacINDUCT `_THEN` tacREWRITE [thmLT_0]
thmLE_EXISTS :: NumsCtxt thry => HOL cls thry HOLThm
thmLE_EXISTS = unsafeCacheProof "thmLE_EXISTS" .
prove [txt| !m n. (m <= n) <=> (?d. n = m + d) |] $
tacGEN `_THEN` tacINDUCT `_THEN`
tacASM_REWRITE [defLE] `_THENL`
[ tacREWRITE [ruleCONV (convLAND convSYM) =<<
ruleSPEC_ALL thmADD_EQ_0] `_THEN`
tacREWRITE [thmRIGHT_EXISTS_AND, thmEXISTS_REFL]
, tacEQ `_THENL`
[ _DISCH_THEN (_DISJ_CASES_THEN2 tacSUBST1 tacMP) `_THENL`
[ tacEXISTS [txt| 0 |] `_THEN` tacREWRITE [thmADD_CLAUSES]
, _DISCH_THEN (_X_CHOOSE_THEN [txt| d:num |] tacSUBST1) `_THEN`
tacEXISTS [txt| SUC d |] `_THEN` tacREWRITE [thmADD_CLAUSES]
]
, tacONCE_REWRITE [thmLEFT_IMP_EXISTS] `_THEN`
tacINDUCT `_THEN` tacREWRITE [thmADD_CLAUSES, thmSUC_INJ] `_THEN`
_DISCH_THEN tacSUBST1 `_THEN` tacREWRITE_NIL `_THEN`
tacDISJ2 `_THEN`
tacREWRITE [thmEQ_ADD_LCANCEL, ruleGSYM thmEXISTS_REFL]
]
]
thmLT_ADDR :: NumsCtxt thry => HOL cls thry HOLThm
thmLT_ADDR = unsafeCacheProof "thmLT_ADDR" .
prove [txt| !m n. (n < m + n) <=> (0 < m) |] $
tacONCE_REWRITE [thmADD_SYM] `_THEN` tacMATCH_ACCEPT thmLT_ADD
thmBIT1_THM :: NumsCtxt thry => HOL cls thry HOLThm
thmBIT1_THM = unsafeCacheProof "thmBIT1_THM" .
prove [txt| !n. NUMERAL (BIT1 n) = SUC(NUMERAL n + NUMERAL n) |] $
tacREWRITE [defNUMERAL, thmBIT1]
thmMULT_CLAUSES :: NumsCtxt thry => HOL cls thry HOLThm
thmMULT_CLAUSES = unsafeCacheProof "thmMULT_CLAUSES" .
prove [txt| (!n. 0 * n = 0) /\
(!m. m * 0 = 0) /\
(!n. 1 * n = n) /\
(!m. m * 1 = m) /\
(!m n. (SUC m) * n = (m * n) + n) /\
(!m n. m * (SUC n) = m + (m * n)) |] $
tacREWRITE [ thmBIT1_THM, defMULT, thmMULT_0
, thmMULT_SUC, thmADD_CLAUSES ]
thmMULT_SYM :: NumsCtxt thry => HOL cls thry HOLThm
thmMULT_SYM = unsafeCacheProof "thmMULT_SYM" .
prove [txt| !m n. m * n = n * m |] $
tacINDUCT `_THEN`
tacASM_REWRITE [ thmMULT_CLAUSES
, ruleEQT_INTRO =<< ruleSPEC_ALL thmADD_SYM ]
thmLEFT_ADD_DISTRIB :: NumsCtxt thry => HOL cls thry HOLThm
thmLEFT_ADD_DISTRIB = unsafeCacheProof "thmLEFT_ADD_DISTRIB" .
prove [txt| !m n p. m * (n + p) = (m * n) + (m * p) |] $
tacGEN `_THEN` tacINDUCT `_THEN`
tacASM_REWRITE [defADD, thmMULT_CLAUSES, thmADD_ASSOC]
thmRIGHT_ADD_DISTRIB :: NumsCtxt thry => HOL cls thry HOLThm
thmRIGHT_ADD_DISTRIB = unsafeCacheProof "thmRIGHT_ADD_DISTRIB" .
prove [txt| !m n p. (m + n) * p = (m * p) + (n * p) |] $
tacONCE_REWRITE [thmMULT_SYM] `_THEN` tacMATCH_ACCEPT thmLEFT_ADD_DISTRIB
thmDIVMOD_EXIST :: NumsCtxt thry => HOL cls thry HOLThm
thmDIVMOD_EXIST = unsafeCacheProof "thmDIVMOD_EXIST" .
prove [txt| !m n. ~(n = 0) ==> ?q r. (m = q * n + r) /\ r < n |] $
_REPEAT tacSTRIP `_THEN`
tacMP (ruleSPEC [txt| \r. ?q. m = q * n + r |] wopNUM) `_THEN`
tacBETA `_THEN` _DISCH_THEN (tacMP . liftM fst . ruleEQ_IMP) `_THEN`
tacREWRITE [thmLEFT_IMP_EXISTS] `_THEN`
_DISCH_THEN (tacMP . ruleSPECL [[txt| m:num |], [txt| 0 |]]) `_THEN`
tacREWRITE [thmMULT_CLAUSES, thmADD_CLAUSES] `_THEN`
_DISCH_THEN (_X_CHOOSE_THEN [txt| r:num |] tacMP) `_THEN`
_DISCH_THEN (_CONJUNCTS_THEN2 (tacX_CHOOSE [txt| q:num |]) tacMP) `_THEN`
_DISCH_THEN (\ th -> _MAP_EVERY tacEXISTS [ [txt| q:num |]
, [txt| r:num |] ] `_THEN`
tacMP th) `_THEN`
tacCONV convCONTRAPOS `_THEN` tacASM_REWRITE [thmNOT_LT] `_THEN`
_DISCH_THEN (_X_CHOOSE_THEN [txt| d:num |] tacSUBST_ALL .
ruleREWRITE [thmLE_EXISTS]) `_THEN`
tacREWRITE [thmNOT_FORALL] `_THEN` tacEXISTS [txt| d:num |] `_THEN`
tacREWRITE [thmNOT_IMP, thmRIGHT_AND_EXISTS] `_THEN`
tacEXISTS [txt| q + 1 |] `_THEN` tacREWRITE [thmRIGHT_ADD_DISTRIB] `_THEN`
tacREWRITE [thmMULT_CLAUSES, thmADD_ASSOC, thmLT_ADDR] `_THEN`
tacASM_REWRITE [ruleGSYM thmNOT_LE, defLE]
thmDIVMOD_EXIST_0 :: NumsCtxt thry => HOL cls thry HOLThm
thmDIVMOD_EXIST_0 = unsafeCacheProof "thmDIVMOD_EXIST_0" .
prove [txt| !m n. ?q r. if n = 0 then q = 0 /\ r = m
else m = q * n + r /\ r < n |] $
_REPEAT tacGEN `_THEN` tacASM_CASES [txt| n = 0 |] `_THEN`
tacASM_SIMP [thmDIVMOD_EXIST, thmRIGHT_EXISTS_AND, thmEXISTS_REFL]
| ecaustin/haskhol-math | src/HaskHOL/Lib/Arith/Base.hs | bsd-2-clause | 10,771 | 0 | 26 | 2,689 | 2,817 | 1,568 | 1,249 | -1 | -1 |
-- 5537376230
import Euler(fromDigits, readGrid, toDigitsBase)
nn = 10
calcSum n xs = fromDigits $ take n $ toDigitsBase 10 $ sum $ head xs
main = putStrLn $ show $ calcSum nn $ readGrid ss
ss = "\
\37107287533902102798797998220837590246510135740250 \
\46376937677490009712648124896970078050417018260538 \
\74324986199524741059474233309513058123726617309629 \
\91942213363574161572522430563301811072406154908250 \
\23067588207539346171171980310421047513778063246676 \
\89261670696623633820136378418383684178734361726757 \
\28112879812849979408065481931592621691275889832738 \
\44274228917432520321923589422876796487670272189318 \
\47451445736001306439091167216856844588711603153276 \
\70386486105843025439939619828917593665686757934951 \
\62176457141856560629502157223196586755079324193331 \
\64906352462741904929101432445813822663347944758178 \
\92575867718337217661963751590579239728245598838407 \
\58203565325359399008402633568948830189458628227828 \
\80181199384826282014278194139940567587151170094390 \
\35398664372827112653829987240784473053190104293586 \
\86515506006295864861532075273371959191420517255829 \
\71693888707715466499115593487603532921714970056938 \
\54370070576826684624621495650076471787294438377604 \
\53282654108756828443191190634694037855217779295145 \
\36123272525000296071075082563815656710885258350721 \
\45876576172410976447339110607218265236877223636045 \
\17423706905851860660448207621209813287860733969412 \
\81142660418086830619328460811191061556940512689692 \
\51934325451728388641918047049293215058642563049483 \
\62467221648435076201727918039944693004732956340691 \
\15732444386908125794514089057706229429197107928209 \
\55037687525678773091862540744969844508330393682126 \
\18336384825330154686196124348767681297534375946515 \
\80386287592878490201521685554828717201219257766954 \
\78182833757993103614740356856449095527097864797581 \
\16726320100436897842553539920931837441497806860984 \
\48403098129077791799088218795327364475675590848030 \
\87086987551392711854517078544161852424320693150332 \
\59959406895756536782107074926966537676326235447210 \
\69793950679652694742597709739166693763042633987085 \
\41052684708299085211399427365734116182760315001271 \
\65378607361501080857009149939512557028198746004375 \
\35829035317434717326932123578154982629742552737307 \
\94953759765105305946966067683156574377167401875275 \
\88902802571733229619176668713819931811048770190271 \
\25267680276078003013678680992525463401061632866526 \
\36270218540497705585629946580636237993140746255962 \
\24074486908231174977792365466257246923322810917141 \
\91430288197103288597806669760892938638285025333403 \
\34413065578016127815921815005561868836468420090470 \
\23053081172816430487623791969842487255036638784583 \
\11487696932154902810424020138335124462181441773470 \
\63783299490636259666498587618221225225512486764533 \
\67720186971698544312419572409913959008952310058822 \
\95548255300263520781532296796249481641953868218774 \
\76085327132285723110424803456124867697064507995236 \
\37774242535411291684276865538926205024910326572967 \
\23701913275725675285653248258265463092207058596522 \
\29798860272258331913126375147341994889534765745501 \
\18495701454879288984856827726077713721403798879715 \
\38298203783031473527721580348144513491373226651381 \
\34829543829199918180278916522431027392251122869539 \
\40957953066405232632538044100059654939159879593635 \
\29746152185502371307642255121183693803580388584903 \
\41698116222072977186158236678424689157993532961922 \
\62467957194401269043877107275048102390895523597457 \
\23189706772547915061505504953922979530901129967519 \
\86188088225875314529584099251203829009407770775672 \
\11306739708304724483816533873502340845647058077308 \
\82959174767140363198008187129011875491310547126581 \
\97623331044818386269515456334926366572897563400500 \
\42846280183517070527831839425882145521227251250327 \
\55121603546981200581762165212827652751691296897789 \
\32238195734329339946437501907836945765883352399886 \
\75506164965184775180738168837861091527357929701337 \
\62177842752192623401942399639168044983993173312731 \
\32924185707147349566916674687634660915035914677504 \
\99518671430235219628894890102423325116913619626622 \
\73267460800591547471830798392868535206946944540724 \
\76841822524674417161514036427982273348055556214818 \
\97142617910342598647204516893989422179826088076852 \
\87783646182799346313767754307809363333018982642090 \
\10848802521674670883215120185883543223812876952786 \
\71329612474782464538636993009049310363619763878039 \
\62184073572399794223406235393808339651327408011116 \
\66627891981488087797941876876144230030984490851411 \
\60661826293682836764744779239180335110989069790714 \
\85786944089552990653640447425576083659976645795096 \
\66024396409905389607120198219976047599490197230297 \
\64913982680032973156037120041377903785566085089252 \
\16730939319872750275468906903707539413042652315011 \
\94809377245048795150954100921645863754710598436791 \
\78639167021187492431995700641917969777599028300699 \
\15368713711936614952811305876380278410754449733078 \
\40789923115535562561142322423255033685442488917353 \
\44889911501440648020369068063960672322193204149535 \
\41503128880339536053299340368006977710650566631954 \
\81234880673210146739058568557934581403627822703280 \
\82616570773948327592232845941706525094512325230608 \
\22918802058777319719839450180888072429661980811197 \
\77158542502016545090413245809786882778948721859617 \
\72107838435069186155435662884062257473692284509516 \
\20849603980134001723930671666823555245252804609722 \
\53503534226472524250874054075591789781264330331690"
| higgsd/euler | hs/13.hs | bsd-2-clause | 5,601 | 0 | 9 | 242 | 84 | 43 | 41 | 5 | 1 |
module Problem301 where
import Data.Bits
main :: IO ()
main = print $ length $ filter (\n -> f (1 * n) (2 * n) (3 * n)) [1 .. 2 ^ 30]
f :: Int -> Int -> Int -> Bool
f a b c = a `xor` b `xor` c == 0
| adityagupta1089/Project-Euler-Haskell | src/problems/Problem301.hs | bsd-3-clause | 201 | 0 | 11 | 57 | 128 | 71 | 57 | 6 | 1 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UndecidableInstances #-}
-- | A continuation-based error monad.
module Control.Monad.EitherK (
EitherKT
, runEitherKT
) where
import Control.Applicative
import Control.Monad.Error
import Control.Monad.State
newtype EitherKT e m a =
EitherKT { runEitherKT :: forall r. (e -> m r) -> (a -> m r) -> m r }
deriving (Functor)
instance Applicative (EitherKT e m) where
pure x = EitherKT $ \_ sk -> sk x
EitherKT f <*> EitherKT g = EitherKT $
\ek sk -> f ek (\h -> g ek (\x -> sk $ h x))
instance Alternative (EitherKT String m) where
empty = throwError "zero"
EitherKT f <|> EitherKT f' = EitherKT $ \ek sk -> f (\_ -> f' ek sk) sk
instance Monad (EitherKT e m) where
return = pure
EitherKT f >>= m = EitherKT $ \ek sk ->
f ek (\x -> runEitherKT (m x) ek sk)
instance MonadError e (EitherKT e m) where
throwError e = EitherKT $ \ek _ -> ek e
catchError (EitherKT f) handler = EitherKT $ \ek sk ->
f (\e -> runEitherKT (handler e) ek sk) sk
instance (MonadState s m) => MonadState s (EitherKT e m) where
get = EitherKT $ \_ sk -> get >>= sk
put x = EitherKT $ \_ sk -> put x >>= sk
| osa1/fast-tags | src/Control/Monad/EitherK.hs | bsd-3-clause | 1,332 | 0 | 15 | 342 | 506 | 266 | 240 | 32 | 0 |
-- Lib.hs
module Lib
( symbol
, readExp
, spaces
) where
import Text.ParserCombinators.Parsec hiding (spaces)
import Numeric (readHex, readOct, readFloat)
import Data.Char (digitToInt)
import qualified Data.Complex as C
import Data.Ratio ((%))
data LispVal = Atom String
| List [LispVal]
| DottedList [LispVal] LispVal
| Complex (C.Complex Double)
| Integer Integer
| Real Double
| Rational Rational
| String String
| Char Char
| Bool Bool
readExp :: String -> String
readExp input =
case parse parseExpr "lisp" input of
Left err -> "No match: " ++ show err
Right _ -> "Found value"
parseExpr :: Parser LispVal
parseExpr = parseAtom
<|> parseString
<|> parseNumber
<|> try parseChar
<|> parseQuoted
<|> do _ <- char '('
x <- try parseList <|> try parseDottedList
_ <- char ')'
return x
<|> parseQuasiQuoted
<|> parseUnquote
parseAtom :: Parser LispVal
parseAtom =
do first <- letter <|> symbol
rest <- many $ letter <|> digit <|> symbol
let atom = first:rest
return $ case atom of
"#t" -> Bool True
"#f" -> Bool False
_ -> Atom atom
parseString :: Parser LispVal
parseString =
do _ <- char '"'
x <- many $ escapedChars <|> noneOf "\""
_ <- char '"'
return $ String x
parseNumber :: Parser LispVal
parseNumber = try parseComplex
<|> try parseReal
<|> try parseRational
<|> try parseInteger
parseInteger :: Parser LispVal
parseInteger = parseDec
<|> parseDec2
<|> parseOct
<|> parseHex
<|> parseBin
parseOct :: Parser LispVal
parseOct = try (string "#o") >> many1 octDigit >>= return . Integer . octToDig
where octToDig = fst . head . readOct
parseDec :: Parser LispVal
parseDec = Integer . read <$> many1 digit
parseDec2 :: Parser LispVal
parseDec2 = try (string "#d") >> Integer . read <$> many1 digit
parseHex :: Parser LispVal
parseHex = try (string "#x") >> many1 hexDigit >>= return . Integer . hexToDig
where hexToDig = fst . head . readHex
parseBin :: Parser LispVal
parseBin =
try (string "#b") >>
many1 (oneOf "10") >>=
return . Integer . binToDig
-- x0 + 2 * (x1 + 2 * (x2 + 2 * (x3 + 2 * x4)))
where binToDig "" = 0
binToDig s = foldr f 0 ds
where ds = (toInteger . digitToInt) <$> reverse s
f x acc = x + 2 * acc
parseChar :: Parser LispVal
parseChar = parseChar1 <|> parseChar2
parseChar1 :: Parser LispVal
parseChar1 =
do _ <- try (string "#\\")
x <- anyChar >>= \c -> notFollowedBy alphaNum >> return c
return . Char $ x
parseChar2 :: Parser LispVal
parseChar2 =
try (string "#\\") >>
try (string "newline" <|> string "space") >>= \x ->
return . Char $ case x of
"newline" -> '\n'
"space" -> ' '
parseReal :: Parser LispVal
parseReal =
do x <- many1 digit
_ <- char '.'
y <- many1 digit
return . Real . fst . head . readFloat $ x ++ ['.'] ++ y
parseRational :: Parser LispVal
parseRational =
do n <- many1 digit
_ <- char '/'
d <- many1 digit
return . Rational $ read d % read n
parseComplex :: Parser LispVal
parseComplex =
do r <- try $ parseReal <|> parseDec
_ <- char '+'
i <- try $ parseReal <|> parseDec
_ <- char 'i'
return . Complex $ (toDouble r) C.:+ (toDouble i)
where toDouble (Real f) = realToFrac f
toDouble (Integer f) = fromIntegral f
parseList :: Parser LispVal
parseList = List <$> sepBy parseExpr spaces
parseDottedList :: Parser LispVal
parseDottedList =
do h <- endBy parseExpr spaces
t <- char '.' >> spaces >> parseExpr
return $ DottedList h t
parseQuoted :: Parser LispVal
parseQuoted =
do _ <- char '\''
x <- parseExpr
return $ List [Atom "quote", x]
parseQuasiQuoted :: Parser LispVal
parseQuasiQuoted =
do _ <- char '`'
e <- parseExpr
return $ List [Atom "quasiquote", e]
parseUnquote :: Parser LispVal
parseUnquote =
do _ <- char ','
e <- parseExpr
return $ List [Atom "unquote", e]
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
spaces :: Parser ()
spaces = skipMany1 space
escapedChars :: Parser Char
escapedChars = char '\\' >>
oneOf "\\\"\n\r\t" >>= \x ->
return $ case x of
'\\' -> x
'"' -> x
'n' -> '\n'
'r' -> '\r'
| edgarlepe/scheme | src/Lib.hs | bsd-3-clause | 4,673 | 0 | 13 | 1,504 | 1,537 | 753 | 784 | 150 | 4 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Duration.SV.Rules
( rules
) where
import Control.Monad (join)
import Data.String
import Prelude
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Duration.Helpers
import Duckling.Numeral.Helpers (parseInteger)
import Duckling.Numeral.Types (NumeralData(..))
import Duckling.Regex.Types
import Duckling.Types
import qualified Duckling.Numeral.Types as TNumeral
import qualified Duckling.TimeGrain.Types as TG
ruleHalfAnHour :: Rule
ruleHalfAnHour = Rule
{ name = "half an hour"
, pattern =
[ regex "(1/2|en halv) timme"
]
, prod = \_ -> Just . Token Duration $ duration TG.Minute 30
}
ruleIntegerMoreUnitofduration :: Rule
ruleIntegerMoreUnitofduration = Rule
{ name = "<integer> more <unit-of-duration>"
, pattern =
[ Predicate isNatural
, dimension TimeGrain
, regex "fler|mer"
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v}:
Token TimeGrain grain:
_) -> Just . Token Duration . duration grain $ floor v
_ -> Nothing
}
ruleNumeralnumberHours :: Rule
ruleNumeralnumberHours = Rule
{ name = "number.number hours"
, pattern =
[ regex "(\\d+)\\,(\\d+)"
, regex "timm(e|ar)?"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (h:m:_)):_) -> do
hh <- parseInteger h
mnum <- parseInteger m
let mden = 10 ^ Text.length m
Just . Token Duration $ minutesFromHourMixedFraction hh mnum mden
_ -> Nothing
}
ruleIntegerAndAnHalfHours :: Rule
ruleIntegerAndAnHalfHours = Rule
{ name = "<integer> and an half hours"
, pattern =
[ Predicate isNatural
, regex "och (en )?halv timme?"
]
, prod = \tokens -> case tokens of
(Token Numeral NumeralData{TNumeral.value = v}:_) ->
Just . Token Duration . duration TG.Minute $ 30 + 60 * floor v
_ -> Nothing
}
ruleAUnitofduration :: Rule
ruleAUnitofduration = Rule
{ name = "a <unit-of-duration>"
, pattern =
[ regex "en|ett?"
, dimension TimeGrain
]
, prod = \tokens -> case tokens of
(_:Token TimeGrain grain:_) ->
Just . Token Duration $ duration grain 1
_ -> Nothing
}
ruleAboutDuration :: Rule
ruleAboutDuration = Rule
{ name = "about <duration>"
, pattern =
[ regex "(omkring|cirka|ca\\.?|c:a|runt|ungefär)"
, dimension Duration
]
, prod = \tokens -> case tokens of
(_:token:_) -> Just token
_ -> Nothing
}
ruleExactlyDuration :: Rule
ruleExactlyDuration = Rule
{ name = "exactly <duration>"
, pattern =
[ regex "(precis|exakt)"
, dimension Duration
]
, prod = \tokens -> case tokens of
(_:token:_) -> Just token
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleAUnitofduration
, ruleAboutDuration
, ruleExactlyDuration
, ruleHalfAnHour
, ruleIntegerAndAnHalfHours
, ruleIntegerMoreUnitofduration
, ruleNumeralnumberHours
]
| facebookincubator/duckling | Duckling/Duration/SV/Rules.hs | bsd-3-clause | 3,226 | 0 | 18 | 745 | 845 | 473 | 372 | 94 | 2 |
-- |
-- This module defines how to lex the language
module Language.Pureli.Lexer where
import Text.Parsec.String (Parser)
import Text.Parsec.Language (emptyDef)
import Text.ParserCombinators.Parsec ((<|>))
import qualified Text.Parsec as P
import qualified Text.Parsec.Token as Tok
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser style
where
style =
emptyDef
{ Tok.commentLine = ";"
, Tok.reservedNames = ["nil", "define", "require", "module", "(define", "(require", "(module", "#t", "#f"]
, Tok.caseSensitive = True
, Tok.commentStart = "{~"
, Tok.commentEnd = "~}"
, Tok.nestedComments = True
, Tok.identStart = P.oneOf "&!$#%*+./<=>?@\\^|-~" <|> P.letter
, Tok.identLetter = P.oneOf "!:$#%*+./<=>?@\\^|-~" <|> P.alphaNum
}
symbol :: String -> Parser String
symbol = Tok.symbol lexer
char :: Parser Char
char = Tok.charLiteral lexer
parens :: Parser a -> Parser a
parens = Tok.parens lexer
brackets :: Parser a -> Parser a
brackets = Tok.brackets lexer
commaSep :: Parser a -> Parser [a]
commaSep = Tok.commaSep lexer
semiSep :: Parser a -> Parser [a]
semiSep = Tok.semiSep lexer
identifier :: Parser String
identifier = Tok.identifier lexer
reserved :: String -> Parser ()
reserved = Tok.reserved lexer
reservedOp :: String -> Parser ()
reservedOp = Tok.reservedOp lexer
| soupi/pureli | src/Language/Pureli/Lexer.hs | bsd-3-clause | 1,405 | 0 | 11 | 304 | 417 | 232 | 185 | 36 | 1 |
module Numeric.LinearAlgebra.Matrix.Class where
-- import Numeric.LinearAlgebra.Vector
class Functor m => Matrix m where
mDim :: m a -> Int
mElement :: m a -> Int -> Int -> a
mIndexOf :: (Ord a) => (a -> a -> Bool) -> m a -> (Int, Int)
mZip :: (a -> b -> c) -> m a -> m b -> m c
-- | mFold is foldl1'
mFold :: (a -> a -> a) -> m a -> a
det :: Num a => m a -> a
{-# INLINE mApply #-}
mApply :: Functor f => f (a -> b) -> a -> f b
mApply f m = fmap ($ m) f
(.+.) :: (Num k, Matrix m) => m k -> m k -> m k
(.+.) = mZip (+)
(.-.) :: (Num k, Matrix m) => m k -> m k -> m k
(.-.) = mZip (-)
{-
(.*.) :: (k ~ Element m, Num k, Matrix m) => m -> m -> m
m .*. n = mIdxMap m $ \i j -> sum [ mElement m i k * mElement n k j | k <- [ 0 .. 3 ] ]
-}
{-
(.*>) :: (k ~ Element m, k ~ Scalar v, Num k, Matrix m, Vector v)
=> m -> v -> v
m .*> v | vDim v == mDim m = flip vIdxMap v $ \k -> sum [ mElement m i k * vElement v k | i <- [ 0 .. mDim m ] ]
| otherwise = error "Dimensions do not match"
-}
-- (*.) :: (k ~ Element m, Num k, Matrix m) => m -> k -> m
-- m *. k = mMap (k*) m
{-
transpose :: Matrix m => m -> m
transpose m = flip mIdxMap m $ \i j -> mElement j i m
-}
| dagit/lin-alg | src/Numeric/LinearAlgebra/Matrix/Class.hs | bsd-3-clause | 1,214 | 0 | 11 | 373 | 343 | 183 | 160 | 15 | 1 |
import Control.Arrow(second)
import Distribution.Simple
import Distribution.PackageDescription
import Distribution.Text (display)
import qualified Distribution.Simple.LocalBuildInfo as LBI
import qualified Distribution.Simple.Compiler as Compiler
import qualified Distribution.Simple.Configure as Configure
main :: IO ()
main = defaultMainWithHooks simpleUserHooks { confHook = myConfHook }
myConfHook gpdhbi flg = do
lbi <- Configure.configure gpdhbi flg
let compiler = showCompiler $ LBI.compiler lbi
pkgDescr = LBI.localPkgDescr lbi
([so], exes) = span ((== "library.so") . exeName) (executables pkgDescr)
opts = map (second (("-lHSrts-" ++ compiler):)) . options $ buildInfo so
so' = so { buildInfo = (buildInfo so) { options = opts } }
return lbi { LBI.localPkgDescr = pkgDescr {executables = so':exes }}
showCompiler c =
let Compiler.CompilerId f v = Compiler.compilerId c
in display f ++ display v
| philopon/hassistant.vim | Setup.hs | bsd-3-clause | 996 | 0 | 17 | 211 | 306 | 166 | 140 | 20 | 1 |
module Language.Mojito.Inference.Context where
import Data.List (union)
import Language.Mojito.Syntax.Types (Type, showType)
-- Typing context Gamma.
-- Each element is a pair (term variable,s) called 'typing'.
-- Multiple typings can be given to let-bound variable.
data Context = Context {
ctxAssoc :: [(String,Type)]
}
showContext :: Context -> String
showContext g = unlines $ map (\(a,b) -> a ++ " : " ++ showType b) (ctxAssoc g)
types :: Context -> String -> [Type]
types g x = map snd $ filter ((== x) . fst) (ctxAssoc g)
unionContexts :: [Context] -> Context
unionContexts gs = Context (foldl union [] $ map ctxAssoc gs)
| noteed/mojito | Language/Mojito/Inference/Context.hs | bsd-3-clause | 641 | 0 | 10 | 114 | 214 | 120 | 94 | 11 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Data.BerkeleyDB.IO
( new
, insert
-- , Data.BerkeleyDB.IO.lookup
, lookupMany
, getAllObjects
, serialise
, Db(..)
, module Data.BerkeleyDB.Internal
) where
import Data.Binary
import qualified Data.ByteString.Lazy as Lazy
import qualified Data.ByteString.Unsafe as Strict
import qualified Data.ByteString as Strict
import qualified Data.BerkeleyDB.Internal as D
import Data.BerkeleyDB.Internal (DbType(..),DbFlag(..))
import Foreign.C
import Foreign (ForeignPtr, Ptr, FunPtr, newForeignPtr, withForeignPtr, castPtr)
import Control.Monad
import System.IO.Unsafe
import Foreign.ForeignPtr
newtype Db key value = Db (ForeignPtr D.DB)
newtype Cursor key value = Cursor (Ptr D.DBC)
new :: (Binary key, Binary value) => DbType -> IO (Db key value)
new dbType
= do --putStrLn "newdb"
ptr <- D.open Nothing Nothing dbType [D.Create,D.Thread]
liftM Db $ newForeignPtr D.closePtr ptr
insert :: (Binary key, Binary value) => Db key value -> key -> value -> IO ()
insert (Db db) key val
= withForeignPtr db $ \dbPtr ->
do D.put dbPtr (serialise key) (serialise val) []
{-
{-# INLINE lookup #-}
lookup :: (Binary key, Binary value) => Db key value -> key -> IO (Maybe value)
lookup (Db db) key
= withForeignPtr db $ \dbPtr ->
do mbObject <- D.get dbPtr (serialise key) []
case mbObject of
Just object -> return $ Just (deserialise object)
Nothing -> return Nothing
-}
{-# INLINE lookupMany #-}
lookupMany :: (Binary key, Binary value) => Db key value -> key -> IO [value]
lookupMany (Db db) key
= withForeignPtr db $ \dbPtr ->
do objects <- D.getMany dbPtr (serialise key) []
return $ map deserialise objects
{-
setFlags :: Db key value -> [DbFlag] -> IO ()
setFlags (Db db) flags
= withForeignPtr db $ \dbPtr ->
D.setFlags dbPtr flags
-}
newCursor :: Db key value -> IO (Cursor key value)
newCursor (Db db)
= withForeignPtr db $ \dbPtr ->
do dbc <- D.newCursor dbPtr
return $ Cursor dbc
getAtCursor :: (Binary key, Binary value) => Cursor key value -> IO (Maybe (key, [value]))
getAtCursor (Cursor ptr)
= do ret <- D.getAtCursor ptr [Next]
case ret of
Nothing -> return Nothing
Just (key, vals) -> return $ Just (deserialise key, map deserialise vals)
closeCursor :: Cursor key value -> IO ()
closeCursor (Cursor ptr)
= D.closeCursor ptr
getAllObjects :: (Binary key, Binary value) => Db key value -> IO [(key,[value])]
getAllObjects db@(Db fptr)
= do cursor <- newCursor db
let loop = unsafeInterleaveIO $
do mbPair <- getAtCursor cursor
case mbPair of
Nothing -> do closeCursor cursor
touchForeignPtr fptr
return []
Just pair -> liftM (pair:) loop
loop
serialise :: Binary val => val -> D.Object
serialise val
= case Lazy.toChunks (encode val) of
[chunk] -> chunk
ls -> Strict.concat ls
deserialise :: Binary val => D.Object -> val
deserialise bs
= decode $ Lazy.fromChunks [bs]
| dmjio/BerkeleyDB | src/Data/BerkeleyDB/IO.hs | bsd-3-clause | 3,261 | 0 | 19 | 891 | 965 | 505 | 460 | 70 | 2 |
--
-- VectorTest: test of Vector type definitions
--
module VectorTest3 where
import Test.QuickCheck
nearlyZero = 0.00000001 :: Double
class Vector a where
vadd :: a -> a -> a
vsub :: a -> a -> a
vscale :: Double -> a -> a
-- vdiv :: a -> Double -> Maybe a
-- vdiv a s
-- |s == 0 = Nothing
-- |otherwise = Just (vscale (1.0 / s) a)
-- norm :: a -> Double
dot :: a -> a -> Double
-- normalize :: a -> Maybe a
-- normalize a = a `vdiv` (norm a)
-- square :: a -> Double
-- square a = a `dot` a
(.=.) :: a -> a -> Bool
data Vector3 = Vector3 Double Double Double
instance Show Vector3 where
show (ax, ay, az) = "[" ++ (show ax) ++ "," ++ (show ay) ++ "," ++ (show az) ++ "]"
instance Eq Vector3 where
(==) (ax, ay, az) (bx, by, bz) = ax == bx && ay == by && az == bz
instance Arbitrary Vector3 where
arbitrary = do
x <- arbitrary
y <- arbitrary
z <- arbitrary
return $ (x, y, z)
-- |
-- initialize Vector
--
initVec :: Double -> Double -> Double -> Vector3
initVec x y z = Vector3 x y z
-- |
-- element X axis of vector
--
-- >>> elemX $ initVec 1.0 2.0 3.0
-- 1.0
-- >>> elemY $ initVec 1.0 2.0 3.0
-- 2.0
-- >>> elemZ $ initVec 1.0 2.0 3.0
-- 3.0
--
elemX :: Vector3 -> Double
elemX (Vector3 ax _ _) = ax
elemY :: Vector3 -> Double
elemY (Vector3 _ ay _) = ay
elemZ :: Vector3 -> Double
elemZ (Vector3 _ _ az) = az
-- |
-- cross vector
--
cross :: Vector3 -> Vector3 -> Vector3
cross (Vector3 ax ay az:_) (bx:by:bz:_) = Vector3 [ay * bz - by * az, az * bx - bz * ax, ax * by - ay * bx]
instance Vector Vector3 where
-- |
-- nearly equal Zero
--
(.=.) :: Vector3 -> Vector3 -> Bool
(.=.) a b = not $ any (> nearlyZero) (zipWith (-) a b)
-- |
-- vector addition
--
-- >>> vadd (initVec 1 2 3) (initVec 4 5 6)
-- [5.0,7.0,9.0]
--
vadd :: Vector3 -> Vector3 -> Vector3
vadd a b = zipWith (+) a b
-- |
-- vector substract
--
-- >>> vsub (initVec 1 2 3) (initVec 4 5 6)
-- [-3.0,-3.0,-3.0]
--
vsub :: Vector3 -> Vector3 -> Vector3
vsub a b = zipWith (-) a b
-- |
-- vector scaling
--
-- >>> vscale 4.0 (initVec 1.1 2.1 3.1)
-- [4.4,8.4,12.4]
--
vscale :: Double -> Vector3 -> Vector3
vscale s a = map (* s) a
-- |
-- dot vector
--
dot :: Vector3 -> Vector3 -> Double
dot a b = sum $ zipWith (*) a b
-- |
-- QuickCheck
--
-- prop> \a b -> vsub (vadd a b) b .=. a
-- prop> \a b -> vadd (vsub a b) b .=. a
-- -- prop> \a s -> elemX (vscale s a) == s * elemX a
-- prop> dot [ax, ay, az] [bx, by, bz] == ax * bx + ay * by + az * bz
-- prop> elemX (cross [ax, ay, az] [bx, by, bz]) == ay * bz - az * by
-- prop> elemY (cross [ax, ay, az] [bx, by, bz]) == az * bx - ax * bz
-- prop> elemZ (cross [ax, ay, az] [bx, by, bz]) == ax * by - ay * bx
| eijian/raytracer | test/VectorTest4.hs | bsd-3-clause | 2,767 | 0 | 13 | 750 | 752 | 430 | 322 | -1 | -1 |
module Hydra.Stages.BuildEvents (buildEvents) where
import Hydra.Data
buildEvents :: SymTab -> SymTab
buildEvents st = buildEvs 0 (st {events = []}) (model st)
buildEvs :: Int -> SymTab -> [Equation] -> SymTab
buildEvs _ acc [] = acc
buildEvs i acc (eq : eqs) = case eq of
App (SR f1) s1 -> buildEvs i acc (f1 s1 ++ eqs)
App (Switch sr1 (SF sf1) _) s1 ->
let acc1 = acc {events = (sf1 s1, (eventNumber acc,False)) : (events acc)}
in buildEvs i acc1 ((App sr1 s1) : eqs)
Local f1 -> buildEvs (i + 1) acc (f1 (Var i) ++ eqs)
Equal _ _ -> buildEvs i acc eqs
Init _ _ -> buildEvs i acc eqs | giorgidze/Hydra | src/Hydra/Stages/BuildEvents.hs | bsd-3-clause | 626 | 0 | 17 | 158 | 322 | 164 | 158 | 14 | 5 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Dimensions.Common
( allDimensions
) where
import Duckling.Dimensions.Types
allDimensions :: [Seal Dimension]
allDimensions =
[ Seal AmountOfMoney
, Seal CreditCardNumber
, Seal Email
, Seal Numeral
, Seal PhoneNumber
, Seal Url
]
| facebookincubator/duckling | Duckling/Dimensions/Common.hs | bsd-3-clause | 473 | 0 | 6 | 90 | 75 | 44 | 31 | 11 | 1 |
module Language.SimPOL.Template.Retention where
import Prelude hiding ( until )
import Language.SimPOL
import Language.SimPOL.Template.Option
import Language.SimPOL.Template.Obs
retain :: Time -> Contract -> Universe Contract
retain t c = (\present ->
until (at (present + t)) (option c)
) `fmap` now
-- vim: ft=haskell:sts=2:sw=2:et:nu:ai
| ZjMNZHgG5jMXw/privacy-option-simpol | Language/SimPOL/Template/Retention.hs | bsd-3-clause | 346 | 0 | 12 | 48 | 101 | 60 | 41 | 9 | 1 |
{-|
Module : GHC.Hs.Utils
Description : Generic helpers for the HsSyn type.
Copyright : (c) The University of Glasgow, 1992-2006
Here we collect a variety of helper functions that construct or
analyse HsSyn. All these functions deal with generic HsSyn; functions
which deal with the instantiated versions are located elsewhere:
Parameterised by Module
---------------- -------------
GhcPs/RdrName parser/RdrHsSyn
GhcRn/Name rename/RnHsSyn
GhcTc/Id typecheck/TcHsSyn
The @mk*@ functions attempt to construct a not-completely-useless SrcSpan
from their components, compared with the @nl*@ functions which
just attach noSrcSpan to everything.
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -Wno-incomplete-record-updates #-}
module GHC.Hs.Utils(
-- * Terms
mkHsPar, mkHsApp, mkHsAppType, mkHsAppTypes, mkHsCaseAlt,
mkSimpleMatch, unguardedGRHSs, unguardedRHS,
mkMatchGroup, mkMatch, mkPrefixFunRhs, mkHsLam, mkHsIf,
mkHsWrap, mkLHsWrap, mkHsWrapCo, mkHsWrapCoR, mkLHsWrapCo,
mkHsDictLet, mkHsLams,
mkHsOpApp, mkHsDo, mkHsComp, mkHsWrapPat, mkHsWrapPatCo,
mkLHsPar, mkHsCmdWrap, mkLHsCmdWrap,
mkHsCmdIf,
nlHsTyApp, nlHsTyApps, nlHsVar, nlHsDataCon,
nlHsLit, nlHsApp, nlHsApps, nlHsSyntaxApps,
nlHsIntLit, nlHsVarApps,
nlHsDo, nlHsOpApp, nlHsLam, nlHsPar, nlHsIf, nlHsCase, nlList,
mkLHsTupleExpr, mkLHsVarTuple, missingTupArg,
typeToLHsType,
-- * Constructing general big tuples
-- $big_tuples
mkChunkified, chunkify,
-- * Bindings
mkFunBind, mkVarBind, mkHsVarBind, mkSimpleGeneratedFunBind, mkTopFunBind,
mkPatSynBind,
isInfixFunBind,
-- * Literals
mkHsIntegral, mkHsFractional, mkHsIsString, mkHsString, mkHsStringPrimLit,
-- * Patterns
mkNPat, mkNPlusKPat, nlVarPat, nlLitPat, nlConVarPat, nlConVarPatName, nlConPat,
nlConPatName, nlInfixConPat, nlNullaryConPat, nlWildConPat, nlWildPat,
nlWildPatName, nlTuplePat, mkParPat, nlParPat,
mkBigLHsVarTup, mkBigLHsTup, mkBigLHsVarPatTup, mkBigLHsPatTup,
-- * Types
mkHsAppTy, mkHsAppKindTy,
mkLHsSigType, mkLHsSigWcType, mkClassOpSigs, mkHsSigEnv,
nlHsAppTy, nlHsAppKindTy, nlHsTyVar, nlHsFunTy, nlHsParTy, nlHsTyConApp,
-- * Stmts
mkTransformStmt, mkTransformByStmt, mkBodyStmt, mkBindStmt, mkTcBindStmt,
mkLastStmt,
emptyTransStmt, mkGroupUsingStmt, mkGroupByUsingStmt,
emptyRecStmt, emptyRecStmtName, emptyRecStmtId, mkRecStmt,
unitRecStmtTc,
-- * Template Haskell
mkUntypedSplice, mkTypedSplice,
mkHsQuasiQuote, unqualQuasiQuote,
-- * Collecting binders
isUnliftedHsBind, isBangedHsBind,
collectLocalBinders, collectHsValBinders, collectHsBindListBinders,
collectHsIdBinders,
collectHsBindsBinders, collectHsBindBinders, collectMethodBinders,
collectPatBinders, collectPatsBinders,
collectLStmtsBinders, collectStmtsBinders,
collectLStmtBinders, collectStmtBinders,
hsLTyClDeclBinders, hsTyClForeignBinders,
hsPatSynSelectors, getPatSynBinds,
hsForeignDeclsBinders, hsGroupBinders, hsDataFamInstBinders,
-- * Collecting implicit binders
lStmtsImplicits, hsValBindsImplicits, lPatImplicits
) where
#include "HsVersions.h"
import GhcPrelude
import GHC.Hs.Decls
import GHC.Hs.Binds
import GHC.Hs.Expr
import GHC.Hs.Pat
import GHC.Hs.Types
import GHC.Hs.Lit
import GHC.Hs.PlaceHolder
import GHC.Hs.Extension
import TcEvidence
import RdrName
import Var
import TyCoRep
import Type ( appTyArgFlags, splitAppTys, tyConArgFlags, tyConAppNeedsKindSig )
import TysWiredIn ( unitTy )
import TcType
import DataCon
import ConLike
import Id
import Name
import NameSet hiding ( unitFV )
import NameEnv
import BasicTypes
import SrcLoc
import FastString
import Util
import Bag
import Outputable
import Constants
import Data.Either
import Data.Function
import Data.List
{-
************************************************************************
* *
Some useful helpers for constructing syntax
* *
************************************************************************
These functions attempt to construct a not-completely-useless 'SrcSpan'
from their components, compared with the @nl*@ functions below which
just attach 'noSrcSpan' to everything.
-}
-- | @e => (e)@
mkHsPar :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkHsPar e = L (getLoc e) (HsPar noExtField e)
mkSimpleMatch :: HsMatchContext (NameOrRdrName (IdP (GhcPass p)))
-> [LPat (GhcPass p)] -> Located (body (GhcPass p))
-> LMatch (GhcPass p) (Located (body (GhcPass p)))
mkSimpleMatch ctxt pats rhs
= L loc $
Match { m_ext = noExtField, m_ctxt = ctxt, m_pats = pats
, m_grhss = unguardedGRHSs rhs }
where
loc = case pats of
[] -> getLoc rhs
(pat:_) -> combineSrcSpans (getLoc pat) (getLoc rhs)
unguardedGRHSs :: Located (body (GhcPass p))
-> GRHSs (GhcPass p) (Located (body (GhcPass p)))
unguardedGRHSs rhs@(L loc _)
= GRHSs noExtField (unguardedRHS loc rhs) (noLoc emptyLocalBinds)
unguardedRHS :: SrcSpan -> Located (body (GhcPass p))
-> [LGRHS (GhcPass p) (Located (body (GhcPass p)))]
unguardedRHS loc rhs = [L loc (GRHS noExtField [] rhs)]
mkMatchGroup :: (XMG name (Located (body name)) ~ NoExtField)
=> Origin -> [LMatch name (Located (body name))]
-> MatchGroup name (Located (body name))
mkMatchGroup origin matches = MG { mg_ext = noExtField
, mg_alts = mkLocatedList matches
, mg_origin = origin }
mkLocatedList :: [Located a] -> Located [Located a]
mkLocatedList [] = noLoc []
mkLocatedList ms = L (combineLocs (head ms) (last ms)) ms
mkHsApp :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkHsApp e1 e2 = addCLoc e1 e2 (HsApp noExtField e1 e2)
mkHsAppType :: (NoGhcTc (GhcPass id) ~ GhcRn)
=> LHsExpr (GhcPass id) -> LHsWcType GhcRn -> LHsExpr (GhcPass id)
mkHsAppType e t = addCLoc e t_body (HsAppType noExtField e paren_wct)
where
t_body = hswc_body t
paren_wct = t { hswc_body = parenthesizeHsType appPrec t_body }
mkHsAppTypes :: LHsExpr GhcRn -> [LHsWcType GhcRn] -> LHsExpr GhcRn
mkHsAppTypes = foldl' mkHsAppType
mkHsLam :: (XMG (GhcPass p) (LHsExpr (GhcPass p)) ~ NoExtField) =>
[LPat (GhcPass p)] -> LHsExpr (GhcPass p) -> LHsExpr (GhcPass p)
mkHsLam pats body = mkHsPar (L (getLoc body) (HsLam noExtField matches))
where
matches = mkMatchGroup Generated
[mkSimpleMatch LambdaExpr pats' body]
pats' = map (parenthesizePat appPrec) pats
mkHsLams :: [TyVar] -> [EvVar] -> LHsExpr GhcTc -> LHsExpr GhcTc
mkHsLams tyvars dicts expr = mkLHsWrap (mkWpTyLams tyvars
<.> mkWpLams dicts) expr
-- |A simple case alternative with a single pattern, no binds, no guards;
-- pre-typechecking
mkHsCaseAlt :: LPat (GhcPass p) -> (Located (body (GhcPass p)))
-> LMatch (GhcPass p) (Located (body (GhcPass p)))
mkHsCaseAlt pat expr
= mkSimpleMatch CaseAlt [pat] expr
nlHsTyApp :: IdP (GhcPass id) -> [Type] -> LHsExpr (GhcPass id)
nlHsTyApp fun_id tys
= noLoc (mkHsWrap (mkWpTyApps tys) (HsVar noExtField (noLoc fun_id)))
nlHsTyApps :: IdP (GhcPass id) -> [Type] -> [LHsExpr (GhcPass id)]
-> LHsExpr (GhcPass id)
nlHsTyApps fun_id tys xs = foldl' nlHsApp (nlHsTyApp fun_id tys) xs
--------- Adding parens ---------
-- | Wrap in parens if @'hsExprNeedsParens' appPrec@ says it needs them
-- So @f x@ becomes @(f x)@, but @3@ stays as @3@.
mkLHsPar :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkLHsPar le@(L loc e)
| hsExprNeedsParens appPrec e = L loc (HsPar noExtField le)
| otherwise = le
mkParPat :: LPat (GhcPass name) -> LPat (GhcPass name)
mkParPat lp@(L loc p)
| patNeedsParens appPrec p = L loc (ParPat noExtField lp)
| otherwise = lp
nlParPat :: LPat (GhcPass name) -> LPat (GhcPass name)
nlParPat p = noLoc (ParPat noExtField p)
-------------------------------
-- These are the bits of syntax that contain rebindable names
-- See GHC.Rename.Env.lookupSyntaxName
mkHsIntegral :: IntegralLit -> HsOverLit GhcPs
mkHsFractional :: FractionalLit -> HsOverLit GhcPs
mkHsIsString :: SourceText -> FastString -> HsOverLit GhcPs
mkHsDo :: HsStmtContext Name -> [ExprLStmt GhcPs] -> HsExpr GhcPs
mkHsComp :: HsStmtContext Name -> [ExprLStmt GhcPs] -> LHsExpr GhcPs
-> HsExpr GhcPs
mkNPat :: Located (HsOverLit GhcPs) -> Maybe (SyntaxExpr GhcPs)
-> Pat GhcPs
mkNPlusKPat :: Located RdrName -> Located (HsOverLit GhcPs) -> Pat GhcPs
mkLastStmt :: Located (bodyR (GhcPass idR))
-> StmtLR (GhcPass idL) (GhcPass idR) (Located (bodyR (GhcPass idR)))
mkBodyStmt :: Located (bodyR GhcPs)
-> StmtLR (GhcPass idL) GhcPs (Located (bodyR GhcPs))
mkBindStmt :: (XBindStmt (GhcPass idL) (GhcPass idR)
(Located (bodyR (GhcPass idR))) ~ NoExtField)
=> LPat (GhcPass idL) -> Located (bodyR (GhcPass idR))
-> StmtLR (GhcPass idL) (GhcPass idR) (Located (bodyR (GhcPass idR)))
mkTcBindStmt :: LPat GhcTc -> Located (bodyR GhcTc)
-> StmtLR GhcTc GhcTc (Located (bodyR GhcTc))
emptyRecStmt :: StmtLR (GhcPass idL) GhcPs bodyR
emptyRecStmtName :: StmtLR GhcRn GhcRn bodyR
emptyRecStmtId :: StmtLR GhcTc GhcTc bodyR
mkRecStmt :: [LStmtLR (GhcPass idL) GhcPs bodyR]
-> StmtLR (GhcPass idL) GhcPs bodyR
mkHsIntegral i = OverLit noExtField (HsIntegral i) noExpr
mkHsFractional f = OverLit noExtField (HsFractional f) noExpr
mkHsIsString src s = OverLit noExtField (HsIsString src s) noExpr
mkHsDo ctxt stmts = HsDo noExtField ctxt (mkLocatedList stmts)
mkHsComp ctxt stmts expr = mkHsDo ctxt (stmts ++ [last_stmt])
where
last_stmt = L (getLoc expr) $ mkLastStmt expr
mkHsIf :: LHsExpr (GhcPass p) -> LHsExpr (GhcPass p) -> LHsExpr (GhcPass p)
-> HsExpr (GhcPass p)
mkHsIf c a b = HsIf noExtField (Just noSyntaxExpr) c a b
mkHsCmdIf :: LHsExpr (GhcPass p) -> LHsCmd (GhcPass p) -> LHsCmd (GhcPass p)
-> HsCmd (GhcPass p)
mkHsCmdIf c a b = HsCmdIf noExtField (Just noSyntaxExpr) c a b
mkNPat lit neg = NPat noExtField lit neg noSyntaxExpr
mkNPlusKPat id lit
= NPlusKPat noExtField id lit (unLoc lit) noSyntaxExpr noSyntaxExpr
mkTransformStmt :: [ExprLStmt GhcPs] -> LHsExpr GhcPs
-> StmtLR GhcPs GhcPs (LHsExpr GhcPs)
mkTransformByStmt :: [ExprLStmt GhcPs] -> LHsExpr GhcPs
-> LHsExpr GhcPs -> StmtLR GhcPs GhcPs (LHsExpr GhcPs)
mkGroupUsingStmt :: [ExprLStmt GhcPs] -> LHsExpr GhcPs
-> StmtLR GhcPs GhcPs (LHsExpr GhcPs)
mkGroupByUsingStmt :: [ExprLStmt GhcPs] -> LHsExpr GhcPs
-> LHsExpr GhcPs
-> StmtLR GhcPs GhcPs (LHsExpr GhcPs)
emptyTransStmt :: StmtLR GhcPs GhcPs (LHsExpr GhcPs)
emptyTransStmt = TransStmt { trS_ext = noExtField
, trS_form = panic "emptyTransStmt: form"
, trS_stmts = [], trS_bndrs = []
, trS_by = Nothing, trS_using = noLoc noExpr
, trS_ret = noSyntaxExpr, trS_bind = noSyntaxExpr
, trS_fmap = noExpr }
mkTransformStmt ss u = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u }
mkTransformByStmt ss u b = emptyTransStmt { trS_form = ThenForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkGroupUsingStmt ss u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u }
mkGroupByUsingStmt ss b u = emptyTransStmt { trS_form = GroupForm, trS_stmts = ss, trS_using = u, trS_by = Just b }
mkLastStmt body = LastStmt noExtField body False noSyntaxExpr
mkBodyStmt body
= BodyStmt noExtField body noSyntaxExpr noSyntaxExpr
mkBindStmt pat body
= BindStmt noExtField pat body noSyntaxExpr noSyntaxExpr
mkTcBindStmt pat body = BindStmt unitTy pat body noSyntaxExpr noSyntaxExpr
-- don't use placeHolderTypeTc above, because that panics during zonking
emptyRecStmt' :: forall idL idR body.
XRecStmt (GhcPass idL) (GhcPass idR) body
-> StmtLR (GhcPass idL) (GhcPass idR) body
emptyRecStmt' tyVal =
RecStmt
{ recS_stmts = [], recS_later_ids = []
, recS_rec_ids = []
, recS_ret_fn = noSyntaxExpr
, recS_mfix_fn = noSyntaxExpr
, recS_bind_fn = noSyntaxExpr
, recS_ext = tyVal }
unitRecStmtTc :: RecStmtTc
unitRecStmtTc = RecStmtTc { recS_bind_ty = unitTy
, recS_later_rets = []
, recS_rec_rets = []
, recS_ret_ty = unitTy }
emptyRecStmt = emptyRecStmt' noExtField
emptyRecStmtName = emptyRecStmt' noExtField
emptyRecStmtId = emptyRecStmt' unitRecStmtTc
-- a panic might trigger during zonking
mkRecStmt stmts = emptyRecStmt { recS_stmts = stmts }
-------------------------------
-- | A useful function for building @OpApps@. The operator is always a
-- variable, and we don't know the fixity yet.
mkHsOpApp :: LHsExpr GhcPs -> IdP GhcPs -> LHsExpr GhcPs -> HsExpr GhcPs
mkHsOpApp e1 op e2 = OpApp noExtField e1 (noLoc (HsVar noExtField (noLoc op))) e2
unqualSplice :: RdrName
unqualSplice = mkRdrUnqual (mkVarOccFS (fsLit "splice"))
mkUntypedSplice :: SpliceDecoration -> LHsExpr GhcPs -> HsSplice GhcPs
mkUntypedSplice hasParen e = HsUntypedSplice noExtField hasParen unqualSplice e
mkTypedSplice :: SpliceDecoration -> LHsExpr GhcPs -> HsSplice GhcPs
mkTypedSplice hasParen e = HsTypedSplice noExtField hasParen unqualSplice e
mkHsQuasiQuote :: RdrName -> SrcSpan -> FastString -> HsSplice GhcPs
mkHsQuasiQuote quoter span quote
= HsQuasiQuote noExtField unqualSplice quoter span quote
unqualQuasiQuote :: RdrName
unqualQuasiQuote = mkRdrUnqual (mkVarOccFS (fsLit "quasiquote"))
-- A name (uniquified later) to
-- identify the quasi-quote
mkHsString :: String -> HsLit (GhcPass p)
mkHsString s = HsString NoSourceText (mkFastString s)
mkHsStringPrimLit :: FastString -> HsLit (GhcPass p)
mkHsStringPrimLit fs = HsStringPrim NoSourceText (bytesFS fs)
{-
************************************************************************
* *
Constructing syntax with no location info
* *
************************************************************************
-}
nlHsVar :: IdP (GhcPass id) -> LHsExpr (GhcPass id)
nlHsVar n = noLoc (HsVar noExtField (noLoc n))
-- | NB: Only for 'LHsExpr' 'Id'.
nlHsDataCon :: DataCon -> LHsExpr GhcTc
nlHsDataCon con = noLoc (HsConLikeOut noExtField (RealDataCon con))
nlHsLit :: HsLit (GhcPass p) -> LHsExpr (GhcPass p)
nlHsLit n = noLoc (HsLit noExtField n)
nlHsIntLit :: Integer -> LHsExpr (GhcPass p)
nlHsIntLit n = noLoc (HsLit noExtField (HsInt noExtField (mkIntegralLit n)))
nlVarPat :: IdP (GhcPass id) -> LPat (GhcPass id)
nlVarPat n = noLoc (VarPat noExtField (noLoc n))
nlLitPat :: HsLit GhcPs -> LPat GhcPs
nlLitPat l = noLoc (LitPat noExtField l)
nlHsApp :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsApp f x = noLoc (HsApp noExtField f (mkLHsPar x))
nlHsSyntaxApps :: SyntaxExpr (GhcPass id) -> [LHsExpr (GhcPass id)]
-> LHsExpr (GhcPass id)
nlHsSyntaxApps (SyntaxExpr { syn_expr = fun
, syn_arg_wraps = arg_wraps
, syn_res_wrap = res_wrap }) args
| [] <- arg_wraps -- in the noSyntaxExpr case
= ASSERT( isIdHsWrapper res_wrap )
foldl' nlHsApp (noLoc fun) args
| otherwise
= mkLHsWrap res_wrap (foldl' nlHsApp (noLoc fun) (zipWithEqual "nlHsSyntaxApps"
mkLHsWrap arg_wraps args))
nlHsApps :: IdP (GhcPass id) -> [LHsExpr (GhcPass id)] -> LHsExpr (GhcPass id)
nlHsApps f xs = foldl' nlHsApp (nlHsVar f) xs
nlHsVarApps :: IdP (GhcPass id) -> [IdP (GhcPass id)] -> LHsExpr (GhcPass id)
nlHsVarApps f xs = noLoc (foldl' mk (HsVar noExtField (noLoc f))
(map ((HsVar noExtField) . noLoc) xs))
where
mk f a = HsApp noExtField (noLoc f) (noLoc a)
nlConVarPat :: RdrName -> [RdrName] -> LPat GhcPs
nlConVarPat con vars = nlConPat con (map nlVarPat vars)
nlConVarPatName :: Name -> [Name] -> LPat GhcRn
nlConVarPatName con vars = nlConPatName con (map nlVarPat vars)
nlInfixConPat :: RdrName -> LPat GhcPs -> LPat GhcPs -> LPat GhcPs
nlInfixConPat con l r = noLoc (ConPatIn (noLoc con)
(InfixCon (parenthesizePat opPrec l)
(parenthesizePat opPrec r)))
nlConPat :: RdrName -> [LPat GhcPs] -> LPat GhcPs
nlConPat con pats =
noLoc (ConPatIn (noLoc con) (PrefixCon (map (parenthesizePat appPrec) pats)))
nlConPatName :: Name -> [LPat GhcRn] -> LPat GhcRn
nlConPatName con pats =
noLoc (ConPatIn (noLoc con) (PrefixCon (map (parenthesizePat appPrec) pats)))
nlNullaryConPat :: IdP (GhcPass p) -> LPat (GhcPass p)
nlNullaryConPat con = noLoc (ConPatIn (noLoc con) (PrefixCon []))
nlWildConPat :: DataCon -> LPat GhcPs
nlWildConPat con = noLoc (ConPatIn (noLoc (getRdrName con))
(PrefixCon (replicate (dataConSourceArity con)
nlWildPat)))
-- | Wildcard pattern - after parsing
nlWildPat :: LPat GhcPs
nlWildPat = noLoc (WildPat noExtField )
-- | Wildcard pattern - after renaming
nlWildPatName :: LPat GhcRn
nlWildPatName = noLoc (WildPat noExtField )
nlHsDo :: HsStmtContext Name -> [LStmt GhcPs (LHsExpr GhcPs)]
-> LHsExpr GhcPs
nlHsDo ctxt stmts = noLoc (mkHsDo ctxt stmts)
nlHsOpApp :: LHsExpr GhcPs -> IdP GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
nlHsOpApp e1 op e2 = noLoc (mkHsOpApp e1 op e2)
nlHsLam :: LMatch GhcPs (LHsExpr GhcPs) -> LHsExpr GhcPs
nlHsPar :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsIf :: LHsExpr (GhcPass id) -> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id)
nlHsCase :: LHsExpr GhcPs -> [LMatch GhcPs (LHsExpr GhcPs)]
-> LHsExpr GhcPs
nlList :: [LHsExpr GhcPs] -> LHsExpr GhcPs
nlHsLam match = noLoc (HsLam noExtField (mkMatchGroup Generated [match]))
nlHsPar e = noLoc (HsPar noExtField e)
-- | Note [Rebindable nlHsIf]
-- nlHsIf should generate if-expressions which are NOT subject to
-- RebindableSyntax, so the first field of HsIf is Nothing. (#12080)
nlHsIf cond true false = noLoc (HsIf noExtField Nothing cond true false)
nlHsCase expr matches
= noLoc (HsCase noExtField expr (mkMatchGroup Generated matches))
nlList exprs = noLoc (ExplicitList noExtField Nothing exprs)
nlHsAppTy :: LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar :: IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsFunTy :: LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsParTy :: LHsType (GhcPass p) -> LHsType (GhcPass p)
nlHsAppTy f t = noLoc (HsAppTy noExtField f (parenthesizeHsType appPrec t))
nlHsTyVar x = noLoc (HsTyVar noExtField NotPromoted (noLoc x))
nlHsFunTy a b = noLoc (HsFunTy noExtField (parenthesizeHsType funPrec a) b)
nlHsParTy t = noLoc (HsParTy noExtField t)
nlHsTyConApp :: IdP (GhcPass p) -> [LHsType (GhcPass p)] -> LHsType (GhcPass p)
nlHsTyConApp tycon tys = foldl' nlHsAppTy (nlHsTyVar tycon) tys
nlHsAppKindTy ::
LHsType (GhcPass p) -> LHsKind (GhcPass p) -> LHsType (GhcPass p)
nlHsAppKindTy f k
= noLoc (HsAppKindTy noSrcSpan f (parenthesizeHsType appPrec k))
{-
Tuples. All these functions are *pre-typechecker* because they lack
types on the tuple.
-}
mkLHsTupleExpr :: [LHsExpr (GhcPass a)] -> LHsExpr (GhcPass a)
-- Makes a pre-typechecker boxed tuple, deals with 1 case
mkLHsTupleExpr [e] = e
mkLHsTupleExpr es
= noLoc $ ExplicitTuple noExtField (map (noLoc . (Present noExtField)) es) Boxed
mkLHsVarTuple :: [IdP (GhcPass a)] -> LHsExpr (GhcPass a)
mkLHsVarTuple ids = mkLHsTupleExpr (map nlHsVar ids)
nlTuplePat :: [LPat GhcPs] -> Boxity -> LPat GhcPs
nlTuplePat pats box = noLoc (TuplePat noExtField pats box)
missingTupArg :: HsTupArg GhcPs
missingTupArg = Missing noExtField
mkLHsPatTup :: [LPat GhcRn] -> LPat GhcRn
mkLHsPatTup [] = noLoc $ TuplePat noExtField [] Boxed
mkLHsPatTup [lpat] = lpat
mkLHsPatTup lpats = L (getLoc (head lpats)) $ TuplePat noExtField lpats Boxed
-- | The Big equivalents for the source tuple expressions
mkBigLHsVarTup :: [IdP (GhcPass id)] -> LHsExpr (GhcPass id)
mkBigLHsVarTup ids = mkBigLHsTup (map nlHsVar ids)
mkBigLHsTup :: [LHsExpr (GhcPass id)] -> LHsExpr (GhcPass id)
mkBigLHsTup = mkChunkified mkLHsTupleExpr
-- | The Big equivalents for the source tuple patterns
mkBigLHsVarPatTup :: [IdP GhcRn] -> LPat GhcRn
mkBigLHsVarPatTup bs = mkBigLHsPatTup (map nlVarPat bs)
mkBigLHsPatTup :: [LPat GhcRn] -> LPat GhcRn
mkBigLHsPatTup = mkChunkified mkLHsPatTup
-- $big_tuples
-- #big_tuples#
--
-- GHCs built in tuples can only go up to 'mAX_TUPLE_SIZE' in arity, but
-- we might conceivably want to build such a massive tuple as part of the
-- output of a desugaring stage (notably that for list comprehensions).
--
-- We call tuples above this size \"big tuples\", and emulate them by
-- creating and pattern matching on >nested< tuples that are expressible
-- by GHC.
--
-- Nesting policy: it's better to have a 2-tuple of 10-tuples (3 objects)
-- than a 10-tuple of 2-tuples (11 objects), so we want the leaves of any
-- construction to be big.
--
-- If you just use the 'mkBigCoreTup', 'mkBigCoreVarTupTy', 'mkTupleSelector'
-- and 'mkTupleCase' functions to do all your work with tuples you should be
-- fine, and not have to worry about the arity limitation at all.
-- | Lifts a \"small\" constructor into a \"big\" constructor by recursive decomposition
mkChunkified :: ([a] -> a) -- ^ \"Small\" constructor function, of maximum input arity 'mAX_TUPLE_SIZE'
-> [a] -- ^ Possible \"big\" list of things to construct from
-> a -- ^ Constructed thing made possible by recursive decomposition
mkChunkified small_tuple as = mk_big_tuple (chunkify as)
where
-- Each sub-list is short enough to fit in a tuple
mk_big_tuple [as] = small_tuple as
mk_big_tuple as_s = mk_big_tuple (chunkify (map small_tuple as_s))
chunkify :: [a] -> [[a]]
-- ^ Split a list into lists that are small enough to have a corresponding
-- tuple arity. The sub-lists of the result all have length <= 'mAX_TUPLE_SIZE'
-- But there may be more than 'mAX_TUPLE_SIZE' sub-lists
chunkify xs
| n_xs <= mAX_TUPLE_SIZE = [xs]
| otherwise = split xs
where
n_xs = length xs
split [] = []
split xs = take mAX_TUPLE_SIZE xs : split (drop mAX_TUPLE_SIZE xs)
{-
************************************************************************
* *
LHsSigType and LHsSigWcType
* *
********************************************************************* -}
mkLHsSigType :: LHsType GhcPs -> LHsSigType GhcPs
mkLHsSigType ty = mkHsImplicitBndrs ty
mkLHsSigWcType :: LHsType GhcPs -> LHsSigWcType GhcPs
mkLHsSigWcType ty = mkHsWildCardBndrs (mkHsImplicitBndrs ty)
mkHsSigEnv :: forall a. (LSig GhcRn -> Maybe ([Located Name], a))
-> [LSig GhcRn]
-> NameEnv a
mkHsSigEnv get_info sigs
= mkNameEnv (mk_pairs ordinary_sigs)
`extendNameEnvList` (mk_pairs gen_dm_sigs)
-- The subtlety is this: in a class decl with a
-- default-method signature as well as a method signature
-- we want the latter to win (#12533)
-- class C x where
-- op :: forall a . x a -> x a
-- default op :: forall b . x b -> x b
-- op x = ...(e :: b -> b)...
-- The scoped type variables of the 'default op', namely 'b',
-- scope over the code for op. The 'forall a' does not!
-- This applies both in the renamer and typechecker, both
-- of which use this function
where
(gen_dm_sigs, ordinary_sigs) = partition is_gen_dm_sig sigs
is_gen_dm_sig (L _ (ClassOpSig _ True _ _)) = True
is_gen_dm_sig _ = False
mk_pairs :: [LSig GhcRn] -> [(Name, a)]
mk_pairs sigs = [ (n,a) | Just (ns,a) <- map get_info sigs
, L _ n <- ns ]
mkClassOpSigs :: [LSig GhcPs] -> [LSig GhcPs]
-- ^ Convert 'TypeSig' to 'ClassOpSig'.
-- The former is what is parsed, but the latter is
-- what we need in class/instance declarations
mkClassOpSigs sigs
= map fiddle sigs
where
fiddle (L loc (TypeSig _ nms ty))
= L loc (ClassOpSig noExtField False nms (dropWildCards ty))
fiddle sig = sig
typeToLHsType :: Type -> LHsType GhcPs
-- ^ Converting a Type to an HsType RdrName
-- This is needed to implement GeneralizedNewtypeDeriving.
--
-- Note that we use 'getRdrName' extensively, which
-- generates Exact RdrNames rather than strings.
typeToLHsType ty
= go ty
where
go :: Type -> LHsType GhcPs
go ty@(FunTy { ft_af = af, ft_arg = arg, ft_res = res })
= case af of
VisArg -> nlHsFunTy (go arg) (go res)
InvisArg | (theta, tau) <- tcSplitPhiTy ty
-> noLoc (HsQualTy { hst_ctxt = noLoc (map go theta)
, hst_xqual = noExtField
, hst_body = go tau })
go ty@(ForAllTy (Bndr _ argf) _)
| (tvs, tau) <- tcSplitForAllTysSameVis argf ty
= noLoc (HsForAllTy { hst_fvf = argToForallVisFlag argf
, hst_bndrs = map go_tv tvs
, hst_xforall = noExtField
, hst_body = go tau })
go (TyVarTy tv) = nlHsTyVar (getRdrName tv)
go (LitTy (NumTyLit n))
= noLoc $ HsTyLit noExtField (HsNumTy NoSourceText n)
go (LitTy (StrTyLit s))
= noLoc $ HsTyLit noExtField (HsStrTy NoSourceText s)
go ty@(TyConApp tc args)
| tyConAppNeedsKindSig True tc (length args)
-- We must produce an explicit kind signature here to make certain
-- programs kind-check. See Note [Kind signatures in typeToLHsType].
= nlHsParTy $ noLoc $ HsKindSig noExtField ty' (go (tcTypeKind ty))
| otherwise = ty'
where
ty' :: LHsType GhcPs
ty' = go_app (nlHsTyVar (getRdrName tc)) args (tyConArgFlags tc args)
go ty@(AppTy {}) = go_app (go head) args (appTyArgFlags head args)
where
head :: Type
args :: [Type]
(head, args) = splitAppTys ty
go (CastTy ty _) = go ty
go (CoercionTy co) = pprPanic "toLHsSigWcType" (ppr co)
-- Source-language types have _invisible_ kind arguments,
-- so we must remove them here (#8563)
go_app :: LHsType GhcPs -- The type being applied
-> [Type] -- The argument types
-> [ArgFlag] -- The argument types' visibilities
-> LHsType GhcPs
go_app head args arg_flags =
foldl' (\f (arg, flag) ->
let arg' = go arg in
case flag of
Inferred -> f
Specified -> f `nlHsAppKindTy` arg'
Required -> f `nlHsAppTy` arg')
head (zip args arg_flags)
go_tv :: TyVar -> LHsTyVarBndr GhcPs
go_tv tv = noLoc $ KindedTyVar noExtField (noLoc (getRdrName tv))
(go (tyVarKind tv))
{-
Note [Kind signatures in typeToLHsType]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are types that typeToLHsType can produce which require explicit kind
signatures in order to kind-check. Here is an example from #14579:
-- type P :: forall {k} {t :: k}. Proxy t
type P = 'Proxy
-- type Wat :: forall a. Proxy a -> *
newtype Wat (x :: Proxy (a :: Type)) = MkWat (Maybe a)
deriving Eq
-- type Wat2 :: forall {a}. Proxy a -> *
type Wat2 = Wat
-- type Glurp :: * -> *
newtype Glurp a = MkGlurp (Wat2 (P :: Proxy a))
deriving Eq
The derived Eq instance for Glurp (without any kind signatures) would be:
instance Eq a => Eq (Glurp a) where
(==) = coerce @(Wat2 P -> Wat2 P -> Bool)
@(Glurp a -> Glurp a -> Bool)
(==) :: Glurp a -> Glurp a -> Bool
(Where the visible type applications use types produced by typeToLHsType.)
The type P (in Wat2 P) has an underspecified kind, so we must ensure that
typeToLHsType ascribes it with its kind: Wat2 (P :: Proxy a). To accomplish
this, whenever we see an application of a tycon to some arguments, we use
the tyConAppNeedsKindSig function to determine if it requires an explicit kind
signature to resolve some ambiguity. (See Note
Note [When does a tycon application need an explicit kind signature?] for a
more detailed explanation of how this works.)
Note that we pass True to tyConAppNeedsKindSig since we are generated code with
visible kind applications, so even specified arguments count towards injective
positions in the kind of the tycon.
-}
{- *********************************************************************
* *
--------- HsWrappers: type args, dict args, casts ---------
* *
********************************************************************* -}
mkLHsWrap :: HsWrapper -> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkLHsWrap co_fn (L loc e) = L loc (mkHsWrap co_fn e)
-- | Avoid @'HsWrap' co1 ('HsWrap' co2 _)@.
-- See Note [Detecting forced eta expansion] in "DsExpr"
mkHsWrap :: HsWrapper -> HsExpr (GhcPass id) -> HsExpr (GhcPass id)
mkHsWrap co_fn e | isIdHsWrapper co_fn = e
mkHsWrap co_fn (HsWrap _ co_fn' e) = mkHsWrap (co_fn <.> co_fn') e
mkHsWrap co_fn e = HsWrap noExtField co_fn e
mkHsWrapCo :: TcCoercionN -- A Nominal coercion a ~N b
-> HsExpr (GhcPass id) -> HsExpr (GhcPass id)
mkHsWrapCo co e = mkHsWrap (mkWpCastN co) e
mkHsWrapCoR :: TcCoercionR -- A Representational coercion a ~R b
-> HsExpr (GhcPass id) -> HsExpr (GhcPass id)
mkHsWrapCoR co e = mkHsWrap (mkWpCastR co) e
mkLHsWrapCo :: TcCoercionN -> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
mkLHsWrapCo co (L loc e) = L loc (mkHsWrapCo co e)
mkHsCmdWrap :: HsWrapper -> HsCmd (GhcPass p) -> HsCmd (GhcPass p)
mkHsCmdWrap w cmd | isIdHsWrapper w = cmd
| otherwise = HsCmdWrap noExtField w cmd
mkLHsCmdWrap :: HsWrapper -> LHsCmd (GhcPass p) -> LHsCmd (GhcPass p)
mkLHsCmdWrap w (L loc c) = L loc (mkHsCmdWrap w c)
mkHsWrapPat :: HsWrapper -> Pat (GhcPass id) -> Type -> Pat (GhcPass id)
mkHsWrapPat co_fn p ty | isIdHsWrapper co_fn = p
| otherwise = CoPat noExtField co_fn p ty
mkHsWrapPatCo :: TcCoercionN -> Pat (GhcPass id) -> Type -> Pat (GhcPass id)
mkHsWrapPatCo co pat ty | isTcReflCo co = pat
| otherwise = CoPat noExtField (mkWpCastN co) pat ty
mkHsDictLet :: TcEvBinds -> LHsExpr GhcTc -> LHsExpr GhcTc
mkHsDictLet ev_binds expr = mkLHsWrap (mkWpLet ev_binds) expr
{-
l
************************************************************************
* *
Bindings; with a location at the top
* *
************************************************************************
-}
mkFunBind :: Origin -> Located RdrName -> [LMatch GhcPs (LHsExpr GhcPs)]
-> HsBind GhcPs
-- ^ Not infix, with place holders for coercion and free vars
mkFunBind origin fn ms
= FunBind { fun_id = fn
, fun_matches = mkMatchGroup origin ms
, fun_co_fn = idHsWrapper
, fun_ext = noExtField
, fun_tick = [] }
mkTopFunBind :: Origin -> Located Name -> [LMatch GhcRn (LHsExpr GhcRn)]
-> HsBind GhcRn
-- ^ In Name-land, with empty bind_fvs
mkTopFunBind origin fn ms = FunBind { fun_id = fn
, fun_matches = mkMatchGroup origin ms
, fun_co_fn = idHsWrapper
, fun_ext = emptyNameSet -- NB: closed
-- binding
, fun_tick = [] }
mkHsVarBind :: SrcSpan -> RdrName -> LHsExpr GhcPs -> LHsBind GhcPs
mkHsVarBind loc var rhs = mkSimpleGeneratedFunBind loc var [] rhs
mkVarBind :: IdP (GhcPass p) -> LHsExpr (GhcPass p) -> LHsBind (GhcPass p)
mkVarBind var rhs = L (getLoc rhs) $
VarBind { var_ext = noExtField,
var_id = var, var_rhs = rhs, var_inline = False }
mkPatSynBind :: Located RdrName -> HsPatSynDetails (Located RdrName)
-> LPat GhcPs -> HsPatSynDir GhcPs -> HsBind GhcPs
mkPatSynBind name details lpat dir = PatSynBind noExtField psb
where
psb = PSB{ psb_ext = noExtField
, psb_id = name
, psb_args = details
, psb_def = lpat
, psb_dir = dir }
-- |If any of the matches in the 'FunBind' are infix, the 'FunBind' is
-- considered infix.
isInfixFunBind :: HsBindLR id1 id2 -> Bool
isInfixFunBind (FunBind _ _ (MG _ matches _) _ _)
= any (isInfixMatch . unLoc) (unLoc matches)
isInfixFunBind _ = False
------------
-- | Convenience function using 'mkFunBind'.
-- This is for generated bindings only, do not use for user-written code.
mkSimpleGeneratedFunBind :: SrcSpan -> RdrName -> [LPat GhcPs]
-> LHsExpr GhcPs -> LHsBind GhcPs
mkSimpleGeneratedFunBind loc fun pats expr
= L loc $ mkFunBind Generated (L loc fun)
[mkMatch (mkPrefixFunRhs (L loc fun)) pats expr
(noLoc emptyLocalBinds)]
-- | Make a prefix, non-strict function 'HsMatchContext'
mkPrefixFunRhs :: Located id -> HsMatchContext id
mkPrefixFunRhs n = FunRhs { mc_fun = n
, mc_fixity = Prefix
, mc_strictness = NoSrcStrict }
------------
mkMatch :: HsMatchContext (NameOrRdrName (IdP (GhcPass p)))
-> [LPat (GhcPass p)] -> LHsExpr (GhcPass p)
-> Located (HsLocalBinds (GhcPass p))
-> LMatch (GhcPass p) (LHsExpr (GhcPass p))
mkMatch ctxt pats expr lbinds
= noLoc (Match { m_ext = noExtField
, m_ctxt = ctxt
, m_pats = map paren pats
, m_grhss = GRHSs noExtField (unguardedRHS noSrcSpan expr) lbinds })
where
paren lp@(L l p)
| patNeedsParens appPrec p = L l (ParPat noExtField lp)
| otherwise = lp
{-
************************************************************************
* *
Collecting binders
* *
************************************************************************
Get all the binders in some HsBindGroups, IN THE ORDER OF APPEARANCE. eg.
...
where
(x, y) = ...
f i j = ...
[a, b] = ...
it should return [x, y, f, a, b] (remember, order important).
Note [Collect binders only after renaming]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
These functions should only be used on HsSyn *after* the renamer,
to return a [Name] or [Id]. Before renaming the record punning
and wild-card mechanism makes it hard to know what is bound.
So these functions should not be applied to (HsSyn RdrName)
Note [Unlifted id check in isUnliftedHsBind]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The function isUnliftedHsBind is used to complain if we make a top-level
binding for a variable of unlifted type.
Such a binding is illegal if the top-level binding would be unlifted;
but also if the local letrec generated by desugaring AbsBinds would be.
E.g.
f :: Num a => (# a, a #)
g :: Num a => a -> a
f = ...g...
g = ...g...
The top-level bindings for f,g are not unlifted (because of the Num a =>),
but the local, recursive, monomorphic bindings are:
t = /\a \(d:Num a).
letrec fm :: (# a, a #) = ...g...
gm :: a -> a = ...f...
in (fm, gm)
Here the binding for 'fm' is illegal. So generally we check the abe_mono types.
BUT we have a special case when abs_sig is true;
see Note [The abs_sig field of AbsBinds] in GHC.Hs.Binds
-}
----------------- Bindings --------------------------
-- | Should we treat this as an unlifted bind? This will be true for any
-- bind that binds an unlifted variable, but we must be careful around
-- AbsBinds. See Note [Unlifted id check in isUnliftedHsBind]. For usage
-- information, see Note [Strict binds check] is DsBinds.
isUnliftedHsBind :: HsBind GhcTc -> Bool -- works only over typechecked binds
isUnliftedHsBind bind
| AbsBinds { abs_exports = exports, abs_sig = has_sig } <- bind
= if has_sig
then any (is_unlifted_id . abe_poly) exports
else any (is_unlifted_id . abe_mono) exports
-- If has_sig is True we wil never generate a binding for abe_mono,
-- so we don't need to worry about it being unlifted. The abe_poly
-- binding might not be: e.g. forall a. Num a => (# a, a #)
| otherwise
= any is_unlifted_id (collectHsBindBinders bind)
where
is_unlifted_id id = isUnliftedType (idType id)
-- | Is a binding a strict variable or pattern bind (e.g. @!x = ...@)?
isBangedHsBind :: HsBind GhcTc -> Bool
isBangedHsBind (AbsBinds { abs_binds = binds })
= anyBag (isBangedHsBind . unLoc) binds
isBangedHsBind (FunBind {fun_matches = matches})
| [L _ match] <- unLoc $ mg_alts matches
, FunRhs{mc_strictness = SrcStrict} <- m_ctxt match
= True
isBangedHsBind (PatBind {pat_lhs = pat})
= isBangedLPat pat
isBangedHsBind _
= False
collectLocalBinders :: HsLocalBindsLR (GhcPass idL) (GhcPass idR)
-> [IdP (GhcPass idL)]
collectLocalBinders (HsValBinds _ binds) = collectHsIdBinders binds
-- No pattern synonyms here
collectLocalBinders (HsIPBinds {}) = []
collectLocalBinders (EmptyLocalBinds _) = []
collectLocalBinders (XHsLocalBindsLR _) = []
collectHsIdBinders, collectHsValBinders
:: HsValBindsLR (GhcPass idL) (GhcPass idR) -> [IdP (GhcPass idL)]
-- ^ Collect 'Id' binders only, or 'Id's + pattern synonyms, respectively
collectHsIdBinders = collect_hs_val_binders True
collectHsValBinders = collect_hs_val_binders False
collectHsBindBinders :: XRec pass Pat ~ Located (Pat pass) =>
HsBindLR pass idR -> [IdP pass]
-- ^ Collect both 'Id's and pattern-synonym binders
collectHsBindBinders b = collect_bind False b []
collectHsBindsBinders :: LHsBindsLR (GhcPass p) idR -> [IdP (GhcPass p)]
collectHsBindsBinders binds = collect_binds False binds []
collectHsBindListBinders :: [LHsBindLR (GhcPass p) idR] -> [IdP (GhcPass p)]
-- ^ Same as 'collectHsBindsBinders', but works over a list of bindings
collectHsBindListBinders = foldr (collect_bind False . unLoc) []
collect_hs_val_binders :: Bool -> HsValBindsLR (GhcPass idL) (GhcPass idR)
-> [IdP (GhcPass idL)]
collect_hs_val_binders ps (ValBinds _ binds _) = collect_binds ps binds []
collect_hs_val_binders ps (XValBindsLR (NValBinds binds _))
= collect_out_binds ps binds
collect_out_binds :: Bool -> [(RecFlag, LHsBinds (GhcPass p))] ->
[IdP (GhcPass p)]
collect_out_binds ps = foldr (collect_binds ps . snd) []
collect_binds :: Bool -> LHsBindsLR (GhcPass p) idR ->
[IdP (GhcPass p)] -> [IdP (GhcPass p)]
-- ^ Collect 'Id's, or 'Id's + pattern synonyms, depending on boolean flag
collect_binds ps binds acc = foldr (collect_bind ps . unLoc) acc binds
collect_bind :: XRec pass Pat ~ Located (Pat pass) =>
Bool -> HsBindLR pass idR ->
[IdP pass] -> [IdP pass]
collect_bind _ (PatBind { pat_lhs = p }) acc = collect_lpat p acc
collect_bind _ (FunBind { fun_id = L _ f }) acc = f : acc
collect_bind _ (VarBind { var_id = f }) acc = f : acc
collect_bind _ (AbsBinds { abs_exports = dbinds }) acc = map abe_poly dbinds ++ acc
-- I don't think we want the binders from the abe_binds
-- binding (hence see AbsBinds) is in zonking in TcHsSyn
collect_bind omitPatSyn (PatSynBind _ (PSB { psb_id = L _ ps })) acc
| omitPatSyn = acc
| otherwise = ps : acc
collect_bind _ (PatSynBind _ (XPatSynBind _)) acc = acc
collect_bind _ (XHsBindsLR _) acc = acc
collectMethodBinders :: LHsBindsLR idL idR -> [Located (IdP idL)]
-- ^ Used exclusively for the bindings of an instance decl which are all
-- 'FunBinds'
collectMethodBinders binds = foldr (get . unLoc) [] binds
where
get (FunBind { fun_id = f }) fs = f : fs
get _ fs = fs
-- Someone else complains about non-FunBinds
----------------- Statements --------------------------
collectLStmtsBinders :: [LStmtLR (GhcPass idL) (GhcPass idR) body]
-> [IdP (GhcPass idL)]
collectLStmtsBinders = concatMap collectLStmtBinders
collectStmtsBinders :: [StmtLR (GhcPass idL) (GhcPass idR) body]
-> [IdP (GhcPass idL)]
collectStmtsBinders = concatMap collectStmtBinders
collectLStmtBinders :: LStmtLR (GhcPass idL) (GhcPass idR) body
-> [IdP (GhcPass idL)]
collectLStmtBinders = collectStmtBinders . unLoc
collectStmtBinders :: StmtLR (GhcPass idL) (GhcPass idR) body
-> [IdP (GhcPass idL)]
-- Id Binders for a Stmt... [but what about pattern-sig type vars]?
collectStmtBinders (BindStmt _ pat _ _ _) = collectPatBinders pat
collectStmtBinders (LetStmt _ binds) = collectLocalBinders (unLoc binds)
collectStmtBinders (BodyStmt {}) = []
collectStmtBinders (LastStmt {}) = []
collectStmtBinders (ParStmt _ xs _ _) = collectLStmtsBinders
$ [s | ParStmtBlock _ ss _ _ <- xs, s <- ss]
collectStmtBinders (TransStmt { trS_stmts = stmts }) = collectLStmtsBinders stmts
collectStmtBinders (RecStmt { recS_stmts = ss }) = collectLStmtsBinders ss
collectStmtBinders (ApplicativeStmt _ args _) = concatMap collectArgBinders args
where
collectArgBinders (_, ApplicativeArgOne { app_arg_pattern = pat }) = collectPatBinders pat
collectArgBinders (_, ApplicativeArgMany { bv_pattern = pat }) = collectPatBinders pat
collectArgBinders _ = []
collectStmtBinders (XStmtLR nec) = noExtCon nec
----------------- Patterns --------------------------
collectPatBinders :: LPat (GhcPass p) -> [IdP (GhcPass p)]
collectPatBinders pat = collect_lpat pat []
collectPatsBinders :: [LPat (GhcPass p)] -> [IdP (GhcPass p)]
collectPatsBinders pats = foldr collect_lpat [] pats
-------------
collect_lpat :: XRec pass Pat ~ Located (Pat pass) =>
LPat pass -> [IdP pass] -> [IdP pass]
collect_lpat p bndrs
= go (unLoc p)
where
go (VarPat _ var) = unLoc var : bndrs
go (WildPat _) = bndrs
go (LazyPat _ pat) = collect_lpat pat bndrs
go (BangPat _ pat) = collect_lpat pat bndrs
go (AsPat _ a pat) = unLoc a : collect_lpat pat bndrs
go (ViewPat _ _ pat) = collect_lpat pat bndrs
go (ParPat _ pat) = collect_lpat pat bndrs
go (ListPat _ pats) = foldr collect_lpat bndrs pats
go (TuplePat _ pats _) = foldr collect_lpat bndrs pats
go (SumPat _ pat _ _) = collect_lpat pat bndrs
go (ConPatIn _ ps) = foldr collect_lpat bndrs (hsConPatArgs ps)
go (ConPatOut {pat_args=ps}) = foldr collect_lpat bndrs (hsConPatArgs ps)
-- See Note [Dictionary binders in ConPatOut]
go (LitPat _ _) = bndrs
go (NPat {}) = bndrs
go (NPlusKPat _ n _ _ _ _) = unLoc n : bndrs
go (SigPat _ pat _) = collect_lpat pat bndrs
go (SplicePat _ (HsSpliced _ _ (HsSplicedPat pat)))
= go pat
go (SplicePat _ _) = bndrs
go (CoPat _ _ pat _) = go pat
go (XPat {}) = bndrs
{-
Note [Dictionary binders in ConPatOut] See also same Note in DsArrows
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Do *not* gather (a) dictionary and (b) dictionary bindings as binders
of a ConPatOut pattern. For most calls it doesn't matter, because
it's pre-typechecker and there are no ConPatOuts. But it does matter
more in the desugarer; for example, DsUtils.mkSelectorBinds uses
collectPatBinders. In a lazy pattern, for example f ~(C x y) = ...,
we want to generate bindings for x,y but not for dictionaries bound by
C. (The type checker ensures they would not be used.)
Desugaring of arrow case expressions needs these bindings (see DsArrows
and arrowcase1), but SPJ (Jan 2007) says it's safer for it to use its
own pat-binder-collector:
Here's the problem. Consider
data T a where
C :: Num a => a -> Int -> T a
f ~(C (n+1) m) = (n,m)
Here, the pattern (C (n+1)) binds a hidden dictionary (d::Num a),
and *also* uses that dictionary to match the (n+1) pattern. Yet, the
variables bound by the lazy pattern are n,m, *not* the dictionary d.
So in mkSelectorBinds in DsUtils, we want just m,n as the variables bound.
-}
hsGroupBinders :: HsGroup GhcRn -> [Name]
hsGroupBinders (HsGroup { hs_valds = val_decls, hs_tyclds = tycl_decls,
hs_fords = foreign_decls })
= collectHsValBinders val_decls
++ hsTyClForeignBinders tycl_decls foreign_decls
hsGroupBinders (XHsGroup nec) = noExtCon nec
hsTyClForeignBinders :: [TyClGroup GhcRn]
-> [LForeignDecl GhcRn]
-> [Name]
-- We need to look at instance declarations too,
-- because their associated types may bind data constructors
hsTyClForeignBinders tycl_decls foreign_decls
= map unLoc (hsForeignDeclsBinders foreign_decls)
++ getSelectorNames
(foldMap (foldMap hsLTyClDeclBinders . group_tyclds) tycl_decls
`mappend`
foldMap (foldMap hsLInstDeclBinders . group_instds) tycl_decls)
where
getSelectorNames :: ([Located Name], [LFieldOcc GhcRn]) -> [Name]
getSelectorNames (ns, fs) = map unLoc ns ++ map (extFieldOcc . unLoc) fs
-------------------
hsLTyClDeclBinders :: Located (TyClDecl (GhcPass p))
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
-- ^ Returns all the /binding/ names of the decl. The first one is
-- guaranteed to be the name of the decl. The first component
-- represents all binding names except record fields; the second
-- represents field occurrences. For record fields mentioned in
-- multiple constructors, the SrcLoc will be from the first occurrence.
--
-- Each returned (Located name) has a SrcSpan for the /whole/ declaration.
-- See Note [SrcSpan for binders]
hsLTyClDeclBinders (L loc (FamDecl { tcdFam = FamilyDecl
{ fdLName = (L _ name) } }))
= ([L loc name], [])
hsLTyClDeclBinders (L _ (FamDecl { tcdFam = XFamilyDecl nec }))
= noExtCon nec
hsLTyClDeclBinders (L loc (SynDecl
{ tcdLName = (L _ name) }))
= ([L loc name], [])
hsLTyClDeclBinders (L loc (ClassDecl
{ tcdLName = (L _ cls_name)
, tcdSigs = sigs
, tcdATs = ats }))
= (L loc cls_name :
[ L fam_loc fam_name | (L fam_loc (FamilyDecl
{ fdLName = L _ fam_name })) <- ats ]
++
[ L mem_loc mem_name | (L mem_loc (ClassOpSig _ False ns _)) <- sigs
, (L _ mem_name) <- ns ]
, [])
hsLTyClDeclBinders (L loc (DataDecl { tcdLName = (L _ name)
, tcdDataDefn = defn }))
= (\ (xs, ys) -> (L loc name : xs, ys)) $ hsDataDefnBinders defn
hsLTyClDeclBinders (L _ (XTyClDecl nec)) = noExtCon nec
-------------------
hsForeignDeclsBinders :: [LForeignDecl pass] -> [Located (IdP pass)]
-- ^ See Note [SrcSpan for binders]
hsForeignDeclsBinders foreign_decls
= [ L decl_loc n
| L decl_loc (ForeignImport { fd_name = L _ n })
<- foreign_decls]
-------------------
hsPatSynSelectors :: HsValBinds (GhcPass p) -> [IdP (GhcPass p)]
-- ^ Collects record pattern-synonym selectors only; the pattern synonym
-- names are collected by 'collectHsValBinders'.
hsPatSynSelectors (ValBinds _ _ _) = panic "hsPatSynSelectors"
hsPatSynSelectors (XValBindsLR (NValBinds binds _))
= foldr addPatSynSelector [] . unionManyBags $ map snd binds
addPatSynSelector:: LHsBind p -> [IdP p] -> [IdP p]
addPatSynSelector bind sels
| PatSynBind _ (PSB { psb_args = RecCon as }) <- unLoc bind
= map (unLoc . recordPatSynSelectorId) as ++ sels
| otherwise = sels
getPatSynBinds :: [(RecFlag, LHsBinds id)] -> [PatSynBind id id]
getPatSynBinds binds
= [ psb | (_, lbinds) <- binds
, L _ (PatSynBind _ psb) <- bagToList lbinds ]
-------------------
hsLInstDeclBinders :: LInstDecl (GhcPass p)
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
hsLInstDeclBinders (L _ (ClsInstD
{ cid_inst = ClsInstDecl
{ cid_datafam_insts = dfis }}))
= foldMap (hsDataFamInstBinders . unLoc) dfis
hsLInstDeclBinders (L _ (DataFamInstD { dfid_inst = fi }))
= hsDataFamInstBinders fi
hsLInstDeclBinders (L _ (TyFamInstD {})) = mempty
hsLInstDeclBinders (L _ (ClsInstD _ (XClsInstDecl nec)))
= noExtCon nec
hsLInstDeclBinders (L _ (XInstDecl nec))
= noExtCon nec
-------------------
-- | the 'SrcLoc' returned are for the whole declarations, not just the names
hsDataFamInstBinders :: DataFamInstDecl (GhcPass p)
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
hsDataFamInstBinders (DataFamInstDecl { dfid_eqn = HsIB { hsib_body =
FamEqn { feqn_rhs = defn }}})
= hsDataDefnBinders defn
-- There can't be repeated symbols because only data instances have binders
hsDataFamInstBinders (DataFamInstDecl
{ dfid_eqn = HsIB { hsib_body = XFamEqn nec}})
= noExtCon nec
hsDataFamInstBinders (DataFamInstDecl (XHsImplicitBndrs nec))
= noExtCon nec
-------------------
-- | the 'SrcLoc' returned are for the whole declarations, not just the names
hsDataDefnBinders :: HsDataDefn (GhcPass p)
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
hsDataDefnBinders (HsDataDefn { dd_cons = cons })
= hsConDeclsBinders cons
-- See Note [Binders in family instances]
hsDataDefnBinders (XHsDataDefn nec) = noExtCon nec
-------------------
type Seen p = [LFieldOcc (GhcPass p)] -> [LFieldOcc (GhcPass p)]
-- Filters out ones that have already been seen
hsConDeclsBinders :: [LConDecl (GhcPass p)]
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
-- See hsLTyClDeclBinders for what this does
-- The function is boringly complicated because of the records
-- And since we only have equality, we have to be a little careful
hsConDeclsBinders cons
= go id cons
where
go :: Seen p -> [LConDecl (GhcPass p)]
-> ([Located (IdP (GhcPass p))], [LFieldOcc (GhcPass p)])
go _ [] = ([], [])
go remSeen (r:rs)
-- Don't re-mangle the location of field names, because we don't
-- have a record of the full location of the field declaration anyway
= let loc = getLoc r
in case unLoc r of
-- remove only the first occurrence of any seen field in order to
-- avoid circumventing detection of duplicate fields (#9156)
ConDeclGADT { con_names = names, con_args = args }
-> (map (L loc . unLoc) names ++ ns, flds ++ fs)
where
(remSeen', flds) = get_flds remSeen args
(ns, fs) = go remSeen' rs
ConDeclH98 { con_name = name, con_args = args }
-> ([L loc (unLoc name)] ++ ns, flds ++ fs)
where
(remSeen', flds) = get_flds remSeen args
(ns, fs) = go remSeen' rs
XConDecl nec -> noExtCon nec
get_flds :: Seen p -> HsConDeclDetails (GhcPass p)
-> (Seen p, [LFieldOcc (GhcPass p)])
get_flds remSeen (RecCon flds)
= (remSeen', fld_names)
where
fld_names = remSeen (concatMap (cd_fld_names . unLoc) (unLoc flds))
remSeen' = foldr (.) remSeen
[deleteBy ((==) `on` unLoc . rdrNameFieldOcc . unLoc) v
| v <- fld_names]
get_flds remSeen _
= (remSeen, [])
{-
Note [SrcSpan for binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~
When extracting the (Located RdrNme) for a binder, at least for the
main name (the TyCon of a type declaration etc), we want to give it
the @SrcSpan@ of the whole /declaration/, not just the name itself
(which is how it appears in the syntax tree). This SrcSpan (for the
entire declaration) is used as the SrcSpan for the Name that is
finally produced, and hence for error messages. (See #8607.)
Note [Binders in family instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a type or data family instance declaration, the type
constructor is an *occurrence* not a binding site
type instance T Int = Int -> Int -- No binders
data instance S Bool = S1 | S2 -- Binders are S1,S2
************************************************************************
* *
Collecting binders the user did not write
* *
************************************************************************
The job of this family of functions is to run through binding sites and find the set of all Names
that were defined "implicitly", without being explicitly written by the user.
The main purpose is to find names introduced by record wildcards so that we can avoid
warning the user when they don't use those names (#4404)
Since the addition of -Wunused-record-wildcards, this function returns a pair
of [(SrcSpan, [Name])]. Each element of the list is one set of implicit
binders, the first component of the tuple is the document describes the possible
fix to the problem (by removing the ..).
This means there is some unfortunate coupling between this function and where it
is used but it's only used for one specific purpose in one place so it seemed
easier.
-}
lStmtsImplicits :: [LStmtLR GhcRn (GhcPass idR) (Located (body (GhcPass idR)))]
-> [(SrcSpan, [Name])]
lStmtsImplicits = hs_lstmts
where
hs_lstmts :: [LStmtLR GhcRn (GhcPass idR) (Located (body (GhcPass idR)))]
-> [(SrcSpan, [Name])]
hs_lstmts = concatMap (hs_stmt . unLoc)
hs_stmt :: StmtLR GhcRn (GhcPass idR) (Located (body (GhcPass idR)))
-> [(SrcSpan, [Name])]
hs_stmt (BindStmt _ pat _ _ _) = lPatImplicits pat
hs_stmt (ApplicativeStmt _ args _) = concatMap do_arg args
where do_arg (_, ApplicativeArgOne { app_arg_pattern = pat }) = lPatImplicits pat
do_arg (_, ApplicativeArgMany { app_stmts = stmts }) = hs_lstmts stmts
do_arg (_, XApplicativeArg nec) = noExtCon nec
hs_stmt (LetStmt _ binds) = hs_local_binds (unLoc binds)
hs_stmt (BodyStmt {}) = []
hs_stmt (LastStmt {}) = []
hs_stmt (ParStmt _ xs _ _) = hs_lstmts [s | ParStmtBlock _ ss _ _ <- xs
, s <- ss]
hs_stmt (TransStmt { trS_stmts = stmts }) = hs_lstmts stmts
hs_stmt (RecStmt { recS_stmts = ss }) = hs_lstmts ss
hs_stmt (XStmtLR nec) = noExtCon nec
hs_local_binds (HsValBinds _ val_binds) = hsValBindsImplicits val_binds
hs_local_binds (HsIPBinds {}) = []
hs_local_binds (EmptyLocalBinds _) = []
hs_local_binds (XHsLocalBindsLR _) = []
hsValBindsImplicits :: HsValBindsLR GhcRn (GhcPass idR) -> [(SrcSpan, [Name])]
hsValBindsImplicits (XValBindsLR (NValBinds binds _))
= concatMap (lhsBindsImplicits . snd) binds
hsValBindsImplicits (ValBinds _ binds _)
= lhsBindsImplicits binds
lhsBindsImplicits :: LHsBindsLR GhcRn idR -> [(SrcSpan, [Name])]
lhsBindsImplicits = foldBag (++) (lhs_bind . unLoc) []
where
lhs_bind (PatBind { pat_lhs = lpat }) = lPatImplicits lpat
lhs_bind _ = []
lPatImplicits :: LPat GhcRn -> [(SrcSpan, [Name])]
lPatImplicits = hs_lpat
where
hs_lpat lpat = hs_pat (unLoc lpat)
hs_lpats = foldr (\pat rest -> hs_lpat pat ++ rest) []
hs_pat (LazyPat _ pat) = hs_lpat pat
hs_pat (BangPat _ pat) = hs_lpat pat
hs_pat (AsPat _ _ pat) = hs_lpat pat
hs_pat (ViewPat _ _ pat) = hs_lpat pat
hs_pat (ParPat _ pat) = hs_lpat pat
hs_pat (ListPat _ pats) = hs_lpats pats
hs_pat (TuplePat _ pats _) = hs_lpats pats
hs_pat (SigPat _ pat _) = hs_lpat pat
hs_pat (CoPat _ _ pat _) = hs_pat pat
hs_pat (ConPatIn n ps) = details n ps
hs_pat (ConPatOut {pat_con=con, pat_args=ps}) = details (fmap conLikeName con) ps
hs_pat _ = []
details :: Located Name -> HsConPatDetails GhcRn -> [(SrcSpan, [Name])]
details _ (PrefixCon ps) = hs_lpats ps
details n (RecCon fs) =
[(err_loc, collectPatsBinders implicit_pats) | Just{} <- [rec_dotdot fs] ]
++ hs_lpats explicit_pats
where implicit_pats = map (hsRecFieldArg . unLoc) implicit
explicit_pats = map (hsRecFieldArg . unLoc) explicit
(explicit, implicit) = partitionEithers [if pat_explicit then Left fld else Right fld
| (i, fld) <- [0..] `zip` rec_flds fs
, let pat_explicit =
maybe True ((i<) . unLoc)
(rec_dotdot fs)]
err_loc = maybe (getLoc n) getLoc (rec_dotdot fs)
details _ (InfixCon p1 p2) = hs_lpat p1 ++ hs_lpat p2
| sdiehl/ghc | compiler/GHC/Hs/Utils.hs | bsd-3-clause | 58,828 | 0 | 18 | 15,395 | 14,954 | 7,692 | 7,262 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
#ifndef MIN_VERSION_base
#define MIN_VERSION_base(x,y,z) 1
#endif
-----------------------------------------------------------------------------
-- |
-- Module : Control.Lens.Each
-- Copyright : (C) 2012-14 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Control.Lens.Each
(
-- * Each
Each(..)
) where
import Control.Applicative
import Control.Lens.Iso
import Control.Lens.Type
import Control.Lens.Traversal
import Data.Array.Unboxed as Unboxed
import Data.Array.IArray as IArray
import Data.ByteString as StrictB
import Data.ByteString.Lazy as LazyB
import Data.Complex
import Data.Functor.Identity
import Data.HashMap.Lazy as HashMap
import Data.IntMap as IntMap
import Data.List.NonEmpty
import Data.Map as Map
import Data.Sequence as Seq
import Data.Text as StrictT
import Data.Text.Lazy as LazyT
import Data.Tree as Tree
import qualified Data.Vector as Vector
import qualified Data.Vector.Primitive as Prim
import Data.Vector.Primitive (Prim)
import qualified Data.Vector.Storable as Storable
import Data.Vector.Storable (Storable)
import qualified Data.Vector.Unboxed as Unboxed
import Data.Vector.Unboxed (Unbox)
import Data.Word
-- $setup
-- >>> :set -XNoOverloadedStrings
-- >>> import Control.Lens
-- >>> import Data.Text.Strict.Lens as Text
-- >>> import Data.Char as Char
-- | Extract 'each' element of a (potentially monomorphic) container.
--
-- Notably, when applied to a tuple, this generalizes 'Control.Lens.Traversal.both' to arbitrary homogeneous tuples.
--
-- >>> (1,2,3) & each *~ 10
-- (10,20,30)
--
-- It can also be used on monomorphic containers like 'StrictT.Text' or 'StrictB.ByteString'.
--
-- >>> over each Char.toUpper ("hello"^.Text.packed)
-- "HELLO"
--
-- >>> ("hello","world") & each.each %~ Char.toUpper
-- ("HELLO","WORLD")
class Each s t a b | s -> a, t -> b, s b -> t, t a -> s where
each :: Traversal s t a b
#ifndef HLINT
default each :: (Applicative f, Traversable g, s ~ g a, t ~ g b) => LensLike f s t a b
each = traverse
{-# INLINE each #-}
#endif
-- | @'each' :: 'Traversal' (a,a) (b,b) a b@
instance (a~a', b~b') => Each (a,a') (b,b') a b where
each f ~(a,b) = (,) <$> f a <*> f b
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a) (b,b,b) a b@
instance (a~a2, a~a3, b~b2, b~b3) => Each (a,a2,a3) (b,b2,b3) a b where
each f ~(a,b,c) = (,,) <$> f a <*> f b <*> f c
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a) (b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, b~b2, b~b3, b~b4) => Each (a,a2,a3,a4) (b,b2,b3,b4) a b where
each f ~(a,b,c,d) = (,,,) <$> f a <*> f b <*> f c <*> f d
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a,a) (b,b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, a~a5, b~b2, b~b3, b~b4, b~b5) => Each (a,a2,a3,a4,a5) (b,b2,b3,b4,b5) a b where
each f ~(a,b,c,d,e) = (,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a,a,a) (b,b,b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, a~a5, a~a6, b~b2, b~b3, b~b4, b~b5, b~b6) => Each (a,a2,a3,a4,a5,a6) (b,b2,b3,b4,b5,b6) a b where
each f ~(a,b,c,d,e,g) = (,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a) (b,b,b,b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7) => Each (a,a2,a3,a4,a5,a6,a7) (b,b2,b3,b4,b5,b6,b7) a b where
each f ~(a,b,c,d,e,g,h) = (,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a,a) (b,b,b,b,b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7, b~b8) => Each (a,a2,a3,a4,a5,a6,a7,a8) (b,b2,b3,b4,b5,b6,b7,b8) a b where
each f ~(a,b,c,d,e,g,h,i) = (,,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h <*> f i
{-# INLINE each #-}
-- | @'each' :: 'Traversal' (a,a,a,a,a,a,a,a,a) (b,b,b,b,b,b,b,b,b) a b@
instance (a~a2, a~a3, a~a4, a~a5, a~a6, a~a7, a~a8, a~a9, b~b2, b~b3, b~b4, b~b5, b~b6, b~b7, b~b8, b~b9) => Each (a,a2,a3,a4,a5,a6,a7,a8,a9) (b,b2,b3,b4,b5,b6,b7,b8,b9) a b where
each f ~(a,b,c,d,e,g,h,i,j) = (,,,,,,,,) <$> f a <*> f b <*> f c <*> f d <*> f e <*> f g <*> f h <*> f i <*> f j
{-# INLINE each #-}
#if MIN_VERSION_base(4,4,0)
-- | @'each' :: ('RealFloat' a, 'RealFloat' b) => 'Traversal' ('Complex' a) ('Complex' b) a b@
instance Each (Complex a) (Complex b) a b where
each f (a :+ b) = (:+) <$> f a <*> f b
{-# INLINE each #-}
#else
-- | @'each' :: 'Traversal' ('Complex' a) ('Complex' b) a b@
instance (RealFloat a, RealFloat b) => Each (Complex a) (Complex b) a b where
each f (a :+ b) = (:+) <$> f a <*> f b
{-# INLINE each #-}
#endif
-- | @'each' :: 'Traversal' ('Map' c a) ('Map' c b) a b@
instance (c ~ d) => Each (Map c a) (Map d b) a b
-- | @'each' :: 'Traversal' ('Map' c a) ('Map' c b) a b@
instance Each (IntMap a) (IntMap b) a b
-- | @'each' :: 'Traversal' ('HashMap' c a) ('HashMap' c b) a b@
instance (c ~ d) => Each (HashMap c a) (HashMap d b) a b
-- | @'each' :: 'Traversal' [a] [b] a b@
instance Each [a] [b] a b
-- | @'each' :: 'Traversal' (NonEmpty a) (NonEmpty b) a b@
instance Each (NonEmpty a) (NonEmpty b) a b
-- | @'each' :: 'Traversal' ('Identity' a) ('Identity' b) a b@
instance Each (Identity a) (Identity b) a b
-- | @'each' :: 'Traversal' ('Maybe' a) ('Maybe' b) a b@
instance Each (Maybe a) (Maybe b) a b
-- | @'each' :: 'Traversal' ('Seq' a) ('Seq' b) a b@
instance Each (Seq a) (Seq b) a b
-- | @'each' :: 'Traversal' ('Tree' a) ('Tree' b) a b@
instance Each (Tree a) (Tree b) a b
-- | @'each' :: 'Traversal' ('Vector.Vector' a) ('Vector.Vector' b) a b@
instance Each (Vector.Vector a) (Vector.Vector b) a b
-- | @'each' :: ('Prim' a, 'Prim' b) => 'Traversal' ('Prim.Vector' a) ('Prim.Vector' b) a b@
instance (Prim a, Prim b) => Each (Prim.Vector a) (Prim.Vector b) a b where
each f v = Prim.fromListN (Prim.length v) <$> traverse f (Prim.toList v)
{-# INLINE each #-}
-- | @'each' :: ('Storable' a, 'Storable' b) => 'Traversal' ('Storable.Vector' a) ('Storable.Vector' b) a b@
instance (Storable a, Storable b) => Each (Storable.Vector a) (Storable.Vector b) a b where
each f v = Storable.fromListN (Storable.length v) <$> traverse f (Storable.toList v)
{-# INLINE each #-}
-- | @'each' :: ('Unbox' a, 'Unbox' b) => 'Traversal' ('Unboxed.Vector' a) ('Unboxed.Vector' b) a b@
instance (Unbox a, Unbox b) => Each (Unboxed.Vector a) (Unboxed.Vector b) a b where
each f v = Unboxed.fromListN (Unboxed.length v) <$> traverse f (Unboxed.toList v)
{-# INLINE each #-}
-- | @'each' :: 'Traversal' 'StrictT.Text' 'StrictT.Text' 'Char' 'Char'@
instance (a ~ Char, b ~ Char) => Each StrictT.Text StrictT.Text a b where
each = iso StrictT.unpack StrictT.pack . traversed
{-# INLINE each #-}
-- | @'each' :: 'Traversal' 'LazyT.Text' 'LazyT.Text' 'Char' 'Char'@
instance (a ~ Char, b ~ Char) => Each LazyT.Text LazyT.Text a b where
each = iso LazyT.unpack LazyT.pack . traverse
{-# INLINE each #-}
-- | @'each' :: 'Traversal' 'StrictB.ByteString' 'StrictB.ByteString' 'Word8' 'Word8'@
instance (a ~ Word8, b ~ Word8) => Each StrictB.ByteString StrictB.ByteString a b where
each = iso StrictB.unpack StrictB.pack . traverse
{-# INLINE each #-}
-- | @'each' :: 'Traversal' 'LazyB.ByteString' 'LazyB.ByteString' 'Word8' 'Word8'@
instance (a ~ Word8, b ~ Word8) => Each LazyB.ByteString LazyB.ByteString a b where
each = iso LazyB.unpack LazyB.pack . traverse
{-# INLINE each #-}
-- | @'each' :: 'Ix' i => 'Traversal' ('Array' i a) ('Array' i b) a b@
instance (Ix i, i ~ j) => Each (Array i a) (Array j b) a b where
each f arr = array (bounds arr) <$> traverse (\(i,a) -> (,) i <$> f a) (IArray.assocs arr)
{-# INLINE each #-}
-- | @'each' :: ('Ix' i, 'IArray' 'UArray' a, 'IArray' 'UArray' b) => 'Traversal' ('Array' i a) ('Array' i b) a b@
instance (Ix i, IArray UArray a, IArray UArray b, i ~ j) => Each (UArray i a) (UArray j b) a b where
each f arr = array (bounds arr) <$> traverse (\(i,a) -> (,) i <$> f a) (IArray.assocs arr)
{-# INLINE each #-}
| hvr/lens | src/Control/Lens/Each.hs | bsd-3-clause | 8,574 | 0 | 15 | 1,575 | 3,021 | 1,668 | 1,353 | 107 | 0 |
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving, RecordWildCards,
MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances #-}
module Database.Redis.Core (
Connection, connect,
ConnectInfo(..), defaultConnectInfo,
Redis(),runRedis,
RedisCtx(..), MonadRedis(..),
send, recv, sendRequest,
auth, select
) where
import Prelude hiding (catch)
import Control.Applicative
import Control.Monad.Reader
import qualified Data.ByteString as B
import Data.Pool
import Data.Time
import Network
import Database.Redis.Protocol
import qualified Database.Redis.ProtocolPipelining as PP
import Database.Redis.Types
--------------------------------------------------------------------------------
-- The Redis Monad
--
-- |Context for normal command execution, outside of transactions. Use
-- 'runRedis' to run actions of this type.
--
-- In this context, each result is wrapped in an 'Either' to account for the
-- possibility of Redis returning an 'Error' reply.
newtype Redis a = Redis (ReaderT (PP.Connection Reply) IO a)
deriving (Monad, MonadIO, Functor, Applicative)
-- |This class captures the following behaviour: In a context @m@, a command
-- will return it's result wrapped in a \"container\" of type @f@.
--
-- Please refer to the Command Type Signatures section of this page for more
-- information.
class (MonadRedis m) => RedisCtx m f | m -> f where
returnDecode :: RedisResult a => Reply -> m (f a)
instance RedisCtx Redis (Either Reply) where
returnDecode = return . decode
class (Monad m) => MonadRedis m where
liftRedis :: Redis a -> m a
instance MonadRedis Redis where
liftRedis = id
-- |Interact with a Redis datastore specified by the given 'Connection'.
--
-- Each call of 'runRedis' takes a network connection from the 'Connection'
-- pool and runs the given 'Redis' action. Calls to 'runRedis' may thus block
-- while all connections from the pool are in use.
runRedis :: Connection -> Redis a -> IO a
runRedis (Conn pool) redis =
withResource pool $ \conn -> runRedisInternal conn redis
-- |Internal version of 'runRedis' that does not depend on the 'Connection'
-- abstraction. Used to run the AUTH command when connecting.
runRedisInternal :: PP.Connection Reply -> Redis a -> IO a
runRedisInternal env (Redis redis) = runReaderT redis env
recv :: (MonadRedis m) => m Reply
recv = liftRedis $ Redis $ ask >>= liftIO . PP.recv
send :: (MonadRedis m) => [B.ByteString] -> m ()
send req = liftRedis $ Redis $ do
conn <- ask
liftIO $ PP.send conn (renderRequest req)
-- |'sendRequest' can be used to implement commands from experimental
-- versions of Redis. An example of how to implement a command is given
-- below.
--
-- @
-- -- |Redis DEBUG OBJECT command
-- debugObject :: ByteString -> 'Redis' (Either 'Reply' ByteString)
-- debugObject key = 'sendRequest' [\"DEBUG\", \"OBJECT\", key]
-- @
--
sendRequest :: (RedisCtx m f, RedisResult a)
=> [B.ByteString] -> m (f a)
sendRequest req = do
r <- liftRedis $ Redis $ do
conn <- ask
liftIO $ PP.request conn (renderRequest req)
returnDecode r
--------------------------------------------------------------------------------
-- Connection
--
-- |A threadsafe pool of network connections to a Redis server. Use the
-- 'connect' function to create one.
newtype Connection = Conn (Pool (PP.Connection Reply))
-- |Information for connnecting to a Redis server.
--
-- It is recommended to not use the 'ConnInfo' data constructor directly.
-- Instead use 'defaultConnectInfo' and update it with record syntax. For
-- example to connect to a password protected Redis server running on localhost
-- and listening to the default port:
--
-- @
-- myConnectInfo :: ConnectInfo
-- myConnectInfo = defaultConnectInfo {connectAuth = Just \"secret\"}
-- @
--
data ConnectInfo = ConnInfo
{ connectHost :: HostName
, connectPort :: PortID
, connectAuth :: Maybe B.ByteString
-- ^ When the server is protected by a password, set 'connectAuth' to 'Just'
-- the password. Each connection will then authenticate by the 'auth'
-- command.
, connectDatabase :: Integer
-- ^ Each connection will 'select' the database with the given index.
, connectMaxConnections :: Int
-- ^ Maximum number of connections to keep open. The smallest acceptable
-- value is 1.
, connectMaxIdleTime :: NominalDiffTime
-- ^ Amount of time for which an unused connection is kept open. The
-- smallest acceptable value is 0.5 seconds. If the @timeout@ value in
-- your redis.conf file is non-zero, it should be larger than
-- 'connectMaxIdleTime'.
}
-- |Default information for connecting:
--
-- @
-- connectHost = \"localhost\"
-- connectPort = PortNumber 6379 -- Redis default port
-- connectAuth = Nothing -- No password
-- connectDatabase = 0 -- SELECT database 0
-- connectMaxConnections = 50 -- Up to 50 connections
-- connectMaxIdleTime = 30 -- Keep open for 30 seconds
-- @
--
defaultConnectInfo :: ConnectInfo
defaultConnectInfo = ConnInfo
{ connectHost = "localhost"
, connectPort = PortNumber 6379
, connectAuth = Nothing
, connectDatabase = 0
, connectMaxConnections = 50
, connectMaxIdleTime = 30
}
-- |Opens a 'Connection' to a Redis server designated by the given
-- 'ConnectInfo'.
connect :: ConnectInfo -> IO Connection
connect ConnInfo{..} = Conn <$>
createPool create destroy 1 connectMaxIdleTime connectMaxConnections
where
create = do
conn <- PP.connect connectHost connectPort reply
runRedisInternal conn $ do
-- AUTH
case connectAuth of
Nothing -> return ()
Just pass -> void $ auth pass
-- SELECT
when (connectDatabase /= 0) (void $ select connectDatabase)
return conn
destroy = PP.disconnect
-- The AUTH command. It has to be here because it is used in 'connect'.
auth
:: B.ByteString -- ^ password
-> Redis (Either Reply Status)
auth password = sendRequest ["AUTH", password]
-- The SELECT command. Used in 'connect'.
select
:: RedisCtx m f
=> Integer -- ^ index
-> m (f Status)
select ix = sendRequest ["SELECT", encode ix] | fpco/hedis | src/Database/Redis/Core.hs | bsd-3-clause | 6,428 | 0 | 16 | 1,454 | 1,029 | 583 | 446 | 87 | 2 |
module LJI.Parser (
module Text.Parsec
, module Text.Parsec.String
, Chart(..)
, parseChart
, wrapParser
, chartParser
, rangeParser
, durParser
, integerParser
, listParser
) where
import Prelude hiding (mapM, mapM_, foldl, sum)
import Control.Applicative hiding ((<|>), many)
import Control.Monad hiding (mapM, mapM_)
import Control.Newtype
import Data.Char (isSpace)
import Data.Foldable
import Data.Monoid
import Data.Pointed
import qualified Data.Pointed as P (Pointed(..))
import Data.Traversable
import LJI.Music (Relative, Pitch, Class, Dur, Note(..), (%),
Chord(..))
import LJI.Music.Notation (Key(..), Tonality(..), Name(..), Staff(..),
Section(..), Chart(..))
import qualified LJI.Music.Notation as N (Class(..))
import Text.Parsec
import Text.Parsec.String
import Text.Printf
import Debug.Trace
wrapParser :: Monad m => Parser a -> String -> m a
wrapParser p = either (fail . show) return . parse p ""
-- General parsers ----
integerParser = signedParser naturalParser
signedParser :: Num a => Parser a -> Parser a
signedParser num = (*) <$> (option 1 neg) <*> num
where
neg = -1 <$ char '-'
naturalParser :: Parser Int
naturalParser =
do ds <- many digit
let ds' = map ((+(-48)) . fromEnum) ds
d = foldl (\a b -> a*10 + b) 0 ds'
return d
-- Chart parsers ----
parseChart :: Monad m => String -> m Chart
parseChart = wrapParser (chartParser <* eof) . filter (not . isSpace)
chartParser :: Parser Chart
chartParser =
do t <- keyParser
cs <- chords
m <- melody <|> return mempty
return $ Chart t cs m
chords :: Parser (Staff Chord)
chords = (pack . fromList) <$> bars <* string "|||"
where
bars :: Parser [Section Chord]
bars = sectionParser chordsParser 4
`sepBy` try (string "||" >> notFollowedBy (char '|'))
melody :: Parser (Staff (Class, Dur))
melody = (pack . fromList) <$> bars <* string "|||"
where
bars :: Parser [Section (Class, Dur)]
bars = sectionParser (const melodyParser) 4
`sepBy` try (string "||" >> notFollowedBy (char '|'))
-- Key parser ----
keyParser :: Parser Key
keyParser = do c <- classParser
t <- char 'm' *> return Minor
<|> return Major
return $ Key c t
classParser :: Parser N.Class
classParser = do n <- keyNameParser
(flatParser n
<|> sharpParser n
<|> return (N.Natural n))
where
flatParser :: Name -> Parser N.Class
flatParser n = do char 'b'
char 'b' *> return (N.FlatFlat n)
<|> return (N.Flat n)
sharpParser :: Name -> Parser N.Class
sharpParser n = do char '#'
(char '#' *> return (N.SharpSharp n)
<|> return (N.Sharp n))
keyNameParser :: Parser Name
keyNameParser = do n <- oneOf "ABCDEFGabcdefg"
return $ case n of
'A' -> A ; 'a' -> A ; 'B' -> B ; 'b' -> B
'C' -> C ; 'c' -> C ; 'D' -> D ; 'd' -> D
'E' -> E ; 'e' -> E ; 'F' -> F ; 'f' -> F
'G' -> G ; 'g' -> G
-- Section parsers (Anything between bars and ended by double bar lines) ----
sectionParser :: (Int -> Parser (Section a)) -> Int -> Parser (Section a)
sectionParser p n =
mconcat <$> p n `sepBy` try (char '|' >> notFollowedBy (char '|'))
-- chordsParser - a parser parameterised on the number of chrochets in a bar
-- that parses a succession of chords annotated for rhythm with slashes
chordsParser :: Int -> Parser (Section Chord)
chordsParser n = do
cs <- many1 chordParser
when (dur cs > toInteger n % 4)
(fail . printf "Bar exceeds %d beats" $ n)
when (dur cs < toInteger n % 4)
(fail . printf "Bar has fewer than %d beats" $ n)
return (fromList cs)
where
dur = sum . map chdDur
-- Chord parser ----
chordParser :: Parser Chord
chordParser = do
nm <- noteNameParser
a <- option 0 accidentalParser
let r = fromEnum nm + a
tns <- fmap (toEnum . (+ r))
<$> option [4, 7, 12] chordTypeParser
d <- length <$> many (char '/')
return $ Chord (toEnum r) (tns !! 0) (tns !! 1) (tns !! 2) (countBeats d)
where
countBeats = (%4) . (+1) . toInteger
chordTypeParser :: Parser [Relative]
chordTypeParser = [4, 7, 11] <$ char '^'
<|> [4, 7, 10] <$ char '7'
<|> [4, 7, 9] <$ char '6'
<|> [3, 7, 10] <$ (try . string $ "m7")
<|> [3, 7, 11] <$ (try . string $ "m^7")
<|> [3, 7, 9] <$ (try . string $ "m6")
<|> [3, 7, 12] <$ char 'm'
<|> [3, 6, 10] <$ char '0'
<|> [3, 6, 9] <$ (try . string $ "o7")
<|> [3, 6, 12] <$ char 'o'
<|> [3, 8, 10] <$ (try . string $ "+7")
<|> [3, 8, 12] <$ char '+'
-- Range parser ----
rangeParser :: Parser (Pitch, Pitch)
rangeParser = do liftM2 (,) (pitchParser <* char '~') pitchParser
-- Dur parser ----
durParser :: Parser Dur
durParser = do n <- toInteger `liftM` naturalParser
s <- option (1%1) (do char '.'
option (3%2) (do char '.'
return (9%4)
)
)
return $ (1%n) * s
-- Pitch parser ----
pitchParser :: Parser Pitch
pitchParser = do n <- noteNameParser
a <- option 0 accidentalParser
o <- octaveParser
return $ fromEnum n + a + ((o+1) * 12)
noteNameParser :: Parser Class
noteNameParser = do n <- oneOf "CDEFGABcdefgab"
return . toEnum $ case n of
'C' -> 0 ; 'c' -> 0 ; 'D' -> 2 ; 'd' -> 2
'E' -> 4 ; 'e' -> 4 ; 'F' -> 5 ; 'f' -> 5
'G' -> 7 ; 'g' -> 7 ; 'A' -> 9 ; 'a' -> 9
'B' -> 11 ; 'b' -> 11
accidentalParser :: Parser Int
accidentalParser = (negate . length) <$> many1 (char 'b')
<|> length <$> many1 (char '#')
octaveParser :: Parser Int
octaveParser = do o <- integerParser
if (-2) < o && o < 10
then return o
else fail "Octave not in range -1 to 9"
-- List parsers ----
listParser :: Parser a -> Parser [a]
listParser elem = between (char '[') (char ']') elems
where elems = (spaces *> elem <* spaces) `sepBy` char ','
-- Melody parser ----
melodyParser :: Parser (Section (Class, Dur))
melodyParser = fromList <$> many melNoteParser
melNoteParser :: Parser (Class, Dur)
melNoteParser = (,) <$> (augment <$> noteNameParser
<*> (accidentalParser <|> return 0))
<*> durParser
where
augment c a = toEnum . (+a) . fromEnum $ c
| mrehayden1/lji | src/LJI/Parser.hs | bsd-3-clause | 6,953 | 0 | 28 | 2,339 | 2,514 | 1,325 | 1,189 | 158 | 14 |
{- |
Module : Control.Monad.Cont
Copyright : (c) The University of Glasgow 2001,
(c) Jeff Newbern 2003-2007,
(c) Andriy Palamarchuk 2007
License : BSD-style (see the file LICENSE)
Maintainer : libraries@haskell.org
Stability : experimental
Portability : portable
[Computation type:] Computations which can be interrupted and resumed.
[Binding strategy:] Binding a function to a monadic value creates
a new continuation which uses the function as the continuation of the monadic
computation.
[Useful for:] Complex control structures, error handling,
and creating co-routines.
[Zero and plus:] None.
[Example type:] @'Cont' r a@
The Continuation monad represents computations in continuation-passing style
(CPS).
In continuation-passing style function result is not returned,
but instead is passed to another function,
received as a parameter (continuation).
Computations are built up from sequences
of nested continuations, terminated by a final continuation (often @id@)
which produces the final result.
Since continuations are functions which represent the future of a computation,
manipulation of the continuation functions can achieve complex manipulations
of the future of the computation,
such as interrupting a computation in the middle, aborting a portion
of a computation, restarting a computation, and interleaving execution of
computations.
The Continuation monad adapts CPS to the structure of a monad.
Before using the Continuation monad, be sure that you have
a firm understanding of continuation-passing style
and that continuations represent the best solution to your particular
design problem.
Many algorithms which require continuations in other languages do not require
them in Haskell, due to Haskell's lazy semantics.
Abuse of the Continuation monad can produce code that is impossible
to understand and maintain.
-}
module Control.Monad.Cont (
-- * MonadCont class
MonadCont(..),
-- * The Cont monad
Cont,
cont,
runCont,
mapCont,
withCont,
-- * The ContT monad transformer
ContT(..),
mapContT,
withContT,
module Control.Monad,
module Control.Monad.Trans,
-- * Example 1: Simple Continuation Usage
-- $simpleContExample
-- * Example 2: Using @callCC@
-- $callCCExample
-- * Example 3: Using @ContT@ Monad Transformer
-- $ContTExample
) where
import Control.Monad.Cont.Class
import Control.Monad.Trans
import Control.Monad.Trans.Cont
import Control.Monad
{- $simpleContExample
Calculating length of a list continuation-style:
>calculateLength :: [a] -> Cont r Int
>calculateLength l = return (length l)
Here we use @calculateLength@ by making it to pass its result to @print@:
>main = do
> runCont (calculateLength "123") print
> -- result: 3
It is possible to chain 'Cont' blocks with @>>=@.
>double :: Int -> Cont r Int
>double n = return (n * 2)
>
>main = do
> runCont (calculateLength "123" >>= double) print
> -- result: 6
-}
{- $callCCExample
This example gives a taste of how escape continuations work, shows a typical
pattern for their usage.
>-- Returns a string depending on the length of the name parameter.
>-- If the provided string is empty, returns an error.
>-- Otherwise, returns a welcome message.
>whatsYourName :: String -> String
>whatsYourName name =
> (`runCont` id) $ do -- 1
> response <- callCC $ \exit -> do -- 2
> validateName name exit -- 3
> return $ "Welcome, " ++ name ++ "!" -- 4
> return response -- 5
>
>validateName name exit = do
> when (null name) (exit "You forgot to tell me your name!")
Here is what this example does:
(1) Runs an anonymous 'Cont' block and extracts value from it with
@(\`runCont\` id)@. Here @id@ is the continuation, passed to the @Cont@ block.
(1) Binds @response@ to the result of the following 'Control.Monad.Cont.Class.callCC' block,
binds @exit@ to the continuation.
(1) Validates @name@.
This approach illustrates advantage of using 'Control.Monad.Cont.Class.callCC' over @return@.
We pass the continuation to @validateName@,
and interrupt execution of the @Cont@ block from /inside/ of @validateName@.
(1) Returns the welcome message from the 'Control.Monad.Cont.Class.callCC' block.
This line is not executed if @validateName@ fails.
(1) Returns from the @Cont@ block.
-}
{-$ContTExample
'ContT' can be used to add continuation handling to other monads.
Here is an example how to combine it with @IO@ monad:
>import Control.Monad.Cont
>import System.IO
>
>main = do
> hSetBuffering stdout NoBuffering
> runContT (callCC askString) reportResult
>
>askString :: (String -> ContT () IO String) -> ContT () IO String
>askString next = do
> liftIO $ putStrLn "Please enter a string"
> s <- liftIO $ getLine
> next s
>
>reportResult :: String -> IO ()
>reportResult s = do
> putStrLn ("You entered: " ++ s)
Action @askString@ requests user to enter a string,
and passes it to the continuation.
@askString@ takes as a parameter a continuation taking a string parameter,
and returning @IO ()@.
Compare its signature to 'runContT' definition.
-}
| davnils/minijava-compiler | lib/mtl-2.1.3.1/Control/Monad/Cont.hs | bsd-3-clause | 5,185 | 0 | 5 | 1,014 | 96 | 70 | 26 | 16 | 0 |
{-# LANGUAGE TypeFamilies, DeriveDataTypeable, TemplateHaskell #-}
-- | This module is an IRC plugin that manages quotes for posterity and legend
module Hsbot.Plugin.Quote
( QuoteArgs (..)
, quote
, theQuote
) where
import Control.Monad.Reader
import Control.Monad.State
import Data.Acid
import qualified Data.Map as M
import Data.Maybe
import Data.SafeCopy
import Data.Time
import Data.Time.Clock.POSIX
import Data.Typeable
import qualified Network.IRC as IRC
import System.Environment.XDG.BaseDir
import System.Random
import Hsbot.Message
import Hsbot.Types
-- | A quote element
data QuoteElt = QuoteElt
{ eltQuotee :: IRC.UserName
, eltQuote :: String
} deriving (Show, Typeable)
type QuoteID = Int
-- | A quote object
data Quote = Quote
{ quoter :: IRC.UserName
, quoteFrom :: IRC.Channel
, quotE :: [QuoteElt]
, quoteTime :: UTCTime
, votes :: Int
, voters :: M.Map IRC.UserName QuoteID
} deriving (Show, Typeable)
emptyQuote :: Quote
emptyQuote = Quote { quoter = ""
, quoteFrom = ""
, quotE = []
, quoteTime = posixSecondsToUTCTime 0
, votes = 0
, voters = M.empty }
-- The Quote database
data QuoteDB = QuoteDB
{ nextQuoteId :: QuoteID
, quoteBotDB :: M.Map QuoteID Quote
, lockedQuotes :: M.Map QuoteID (IRC.UserName, UTCTime)
, lastActive :: M.Map IRC.Channel QuoteID
} deriving (Show, Typeable)
emptyQuoteDB :: QuoteDB
emptyQuoteDB = QuoteDB { nextQuoteId = 0
, quoteBotDB = M.empty
, lockedQuotes = M.empty
, lastActive = M.empty }
$(deriveSafeCopy 0 'base ''QuoteElt)
$(deriveSafeCopy 0 'base ''Quote)
$(deriveSafeCopy 0 'base ''QuoteDB)
-- | Quote database transactions
getQuote :: QuoteID -> Query QuoteDB (Maybe Quote)
getQuote quoteId = fmap (M.lookup quoteId) (asks quoteBotDB)
getQuoteDB :: Query QuoteDB (M.Map QuoteID Quote)
getQuoteDB = asks quoteBotDB
-- TODO : a function for cleaning locks
isQuoteLockedFor :: QuoteID -> IRC.UserName -> UTCTime -> Query QuoteDB (Maybe Bool)
isQuoteLockedFor quoteId requestor now = do
theQuote <- fmap (M.lookup quoteId) (asks quoteBotDB)
case theQuote of
Just _ -> do
currentLock <- fmap (M.lookup quoteId) (asks lockedQuotes)
case currentLock of
Just (owner, lockStamp) ->
if owner == requestor
then return $ Just True
else return . Just $ (addUTCTime 300 lockStamp < now) -- Is the entry older than 5 min?
Nothing -> return $ Just True
Nothing -> return Nothing
lockQuoteIdFor :: QuoteID -> IRC.UserName -> IRC.Channel -> UTCTime -> Update QuoteDB ()
lockQuoteIdFor quoteId requestor channel now = get >>= \db -> put db { lockedQuotes = M.insert quoteId (requestor, now) (lockedQuotes db)
, lastActive = M.insert channel quoteId (lastActive db) }
deleteQuote :: QuoteID -> IRC.Channel -> Update QuoteDB ()
deleteQuote quoteId channel = get >>= \db -> put db { quoteBotDB = M.delete quoteId (quoteBotDB db)
, lockedQuotes = M.delete quoteId (lockedQuotes db)
, lastActive = M.delete channel (lastActive db) }
setQuote :: QuoteID -> Quote -> Update QuoteDB ()
setQuote quoteId theQuote = get >>= \db -> put db { quoteBotDB = M.insert quoteId theQuote (quoteBotDB db) }
getLastActiveQuote :: IRC.Channel -> Query QuoteDB (Maybe QuoteID)
getLastActiveQuote channel = fmap (M.lookup channel) (asks lastActive)
setLastActiveQuote :: IRC.Channel -> QuoteID -> Update QuoteDB ()
setLastActiveQuote channel quoteID = get >>= \db -> put db { lastActive = M.insert channel quoteID (lastActive db) }
takeNextQuoteID :: IRC.UserName -> IRC.Channel -> UTCTime -> Update QuoteDB QuoteID
takeNextQuoteID requestor channel now = do
db <- get
let quoteId = nextQuoteId db
put db { nextQuoteId = nextQuoteId db + 1
, lockedQuotes = M.insert quoteId (requestor, now) (lockedQuotes db)
, lastActive = M.insert channel quoteId (lastActive db) }
return quoteId
$(makeAcidic ''QuoteDB [ 'getQuote, 'getQuoteDB, 'isQuoteLockedFor, 'lockQuoteIdFor, 'deleteQuote, 'setQuote
, 'getLastActiveQuote, 'setLastActiveQuote, 'takeNextQuoteID ])
-- | gets a random quote from the database
getRandomQuote :: AcidState QuoteDB -> IO (Maybe (Quote, QuoteID))
getRandomQuote quoteDB = do
db <- liftIO $ query quoteDB GetQuoteDB
if M.size db > 0
then getStdRandom (randomR (0, M.size db - 1)) >>= \rInt -> return $ Just (snd (M.elemAt rInt db), rInt)
else return Nothing
-- | The quote plugin identity
quote :: PluginId
quote = PluginId
{ pluginName = "quote"
, pluginEp = theQuote QuoteArgs { quoteDbName = "quoteDB" } }
data QuoteArgs = QuoteArgs
{ quoteDbName :: String }
-- | An IRC plugin that handle quotes
theQuote :: QuoteArgs -> Plugin (Env IO) () -- TODO : an argument for the history size
theQuote (QuoteArgs dbName) = do
baseDir <- liftIO $ System.Environment.XDG.BaseDir.getUserDataDir "hsbot"
quoteDB <- liftIO $ openLocalStateFrom (baseDir ++ "/" ++ dbName ++ "/") emptyQuoteDB
forever $ readMsg >>= eval quoteDB
where
eval :: AcidState QuoteDB -> Message -> Plugin (Env IO) ()
eval quoteDB (IncomingMsg msg)
| IRC.msg_command msg == "PRIVMSG" = do
cmdArgs <- lift $ getCommand msg
case cmdArgs of
"quote":"append":quoteID:quotee:quoteTxt ->
case reads quoteID :: [(Int, String)] of
(qid,_):_ -> quoteAppend quoteDB msg qid quotee $ unwords quoteTxt
_ -> do
let quotee' = quoteID
quoteTxt' = quotee : quoteTxt
lastQid <- liftIO . query quoteDB $ GetLastActiveQuote (getChannel msg)
case lastQid of
Just qid -> quoteAppend quoteDB msg qid quotee' $ unwords quoteTxt'
Nothing -> answerMsg msg $ getSender msg ++ " : Invalid quoteID."
"quote":"delete":quoteID:eltID ->
case reads quoteID :: [(Int, String)] of
(qid,_):_ -> case eltID of
[] -> quoteDelete quoteDB msg qid
eltID':[] -> case reads eltID' :: [(Int, String)] of
(eltid,_):_ -> quoteDeleteElt quoteDB msg qid eltid
_ -> answerMsg msg $ getSender msg ++ ": Invalid elementID."
_ -> answerMsg msg $ getSender msg ++ ": Invalid elementID."
_ -> answerMsg msg $ getSender msg ++ " : Invalid quoteID."
"quote":"help":"append":_ -> answerMsg msg $ "quote append [QUOTEID] QUOTEE QUOTE"
++ "If no QUOTEID is provided, tries to append to the last active quote."
"quote":"help":"delete":_ -> do
answerMsg msg "quote delete QUOTEID [ELTID] :"
answerMsg msg $ " If an ELTID is provided, deletes the ELTID's line in the quote QUOTEID. "
++ "If not the whole quote is deleted."
"quote":"help":"start":_ -> do
answerMsg msg "quote [start] QUOTEE [QUOTE] :"
answerMsg msg $ " Begins a quote for QUOTEE. You must provide the keywork start if the "
++ "QUOTEE's nickname is a reserved word for this quote module. If no QUOTE is "
++ "provided this module lookup it's conversation history and records the "
++ "last sentence of QUOTEE."
"quote":"help":"show":_ -> answerMsg msg "quote show { QUOTEID | [random] }"
"quote":"help":"stat":_ -> do
answerMsg msg "quote stat"
answerMsg msg " Compute statistics about the quote database : Most quoters, most quoted "
"quote":"help":[] ->
answerMsg msg $ "Usage: quote { [start] QUOTEE [QUOTE] | append [QUOTEID] QUOTEE QUOTE | "
++ "delete QUOTEID [ELTID] | show { QUOTEID | random [MIN_SCORE] } | stat }"
"quote":"help":_ -> answerMsg msg "Invalid help topic."
"quote":"show":"random":[] -> showRandomQuote
"quote":"show":quoteID:[] ->
case reads quoteID :: [(Int, String)] of
(qid,_):_ -> do
thisQuote <- liftIO . query quoteDB $ GetQuote qid
case thisQuote of
Just this -> quoteShow quoteDB msg qid this
Nothing -> answerMsg msg $ getSender msg ++ ": Invalid quoteID or empty database."
_ -> answerMsg msg $ getSender msg ++ " : Invalid quoteID."
"quote":"show":[] -> showRandomQuote
"quote":"start":quotee:phrase -> quoteStart quoteDB msg quotee $ unwords phrase
"quote":quotee:phrase -> quoteStart quoteDB msg quotee $ unwords phrase
"quote":_ -> answerMsg msg "Invalid quote command."
"vote":"help":"quick":_ -> do
answerMsg msg "vote [quick] [QUOTEID] { +1 | -1 | ++ | -- }"
answerMsg msg $ " Vote for a quote. You can also vote for the last active quote on this chan "
++ "by typing something that begins by +1, -1 or ++ or --."
"vote":"help":[] -> answerMsg msg "Usage: vote { [quick] [QUOTEID] { +1 | -1 } | show [QUOTEID] | stat }"
"vote":"help":_ -> answerMsg msg "Invalid help topic."
"vote":_ -> answerMsg msg "Invalid vote command."
_ -> return ()
| otherwise = return ()
where
showRandomQuote :: Plugin (Env IO) ()
showRandomQuote = do
rquote <- liftIO (getRandomQuote quoteDB)
case rquote of
Just (that, qid) -> quoteShow quoteDB msg qid that
Nothing -> answerMsg msg $ getSender msg ++ ": the quote database is empty."
eval _ _ = return ()
quoteAppend :: AcidState QuoteDB -> IRC.Message -> QuoteID -> IRC.UserName -> String -> Plugin (Env IO) ()
quoteAppend quoteDB msg quoteID quotee text = do
now <- liftIO getCurrentTime
activeLock <- liftIO . query quoteDB $ IsQuoteLockedFor quoteID sender now
case activeLock of
Just True -> do
_ <- liftIO . update quoteDB $ LockQuoteIdFor quoteID sender channel now
mQuote <- liftIO . query quoteDB $ GetQuote quoteID
let newQuote = fromMaybe emptyQuote mQuote
newQuote' = newQuote { quotE = quotE newQuote ++ [ QuoteElt { eltQuotee = quotee, eltQuote = text } ] }
_ <- liftIO . update quoteDB $ SetQuote quoteID newQuote'
answerMsg msg $ sender ++ ": Appended to quote " ++ show quoteID ++ "."
Just False -> answerMsg msg $ sender ++ ": Someone else is editing this quote right now."
Nothing -> answerMsg msg $ sender ++ ":quoteId not found."
where
sender = getSender msg
channel = getChannel msg
quoteDelete :: AcidState QuoteDB -> IRC.Message -> QuoteID -> Plugin (Env IO) ()
quoteDelete quoteDB msg quoteID = do
now <- liftIO getCurrentTime
activeLock <- liftIO . query quoteDB $ IsQuoteLockedFor quoteID sender now
case activeLock of
Just True -> do
_ <- liftIO . update quoteDB $ DeleteQuote quoteID channel
answerMsg msg $ sender ++ ": deleted quote " ++ show quoteID ++ "."
Just False -> answerMsg msg $ sender ++ ": Someone else is editing this quote right now."
Nothing -> answerMsg msg $ sender ++ ":quoteId not found."
where
sender = getSender msg
channel = getChannel msg
quoteDeleteElt :: AcidState QuoteDB -> IRC.Message -> QuoteID -> Int -> Plugin (Env IO) ()
quoteDeleteElt quoteDB msg quoteID eltID = do
now <- liftIO getCurrentTime
activeLock <- liftIO . query quoteDB $ IsQuoteLockedFor quoteID sender now
case activeLock of
Just True -> do
_ <- liftIO . update quoteDB $ LockQuoteIdFor quoteID sender channel now
mQuote <- liftIO . query quoteDB $ GetQuote quoteID
let newQuote = fromMaybe emptyQuote mQuote
newQuote' = newQuote { quotE = getRidOfEltFrom (quotE newQuote) }
_ <- liftIO . update quoteDB $ SetQuote quoteID newQuote'
answerMsg msg $ sender ++ ": deleted element number " ++ show eltID ++ " from quote " ++ show quoteID ++ "."
Just False -> answerMsg msg $ sender ++ ": Someone else is editing this quote right now."
Nothing -> answerMsg msg $ sender ++ ": quoteId not found."
where
sender = getSender msg
channel = getChannel msg
getRidOfEltFrom :: [QuoteElt] -> [QuoteElt]
getRidOfEltFrom elts
| eltID <= 0 = elts
| eltID > length elts = elts
| otherwise = let (l, r) = splitAt (eltID -1) elts
in l ++ tail r
quoteShow :: AcidState QuoteDB -> IRC.Message -> QuoteID -> Quote -> Plugin (Env IO) ()
quoteShow quoteDB msg quoteID thatQuote = do
mapM_ (answerMsg msg) formatQuote
liftIO . update quoteDB $ SetLastActiveQuote channel quoteID
where
channel = getChannel msg
formatQuote :: [String]
formatQuote = ("+-- [" ++ show quoteID ++ "] --- Reported by " ++ quoter thatQuote ++ " on " ++ quoteFrom thatQuote)
: map formatElt (quotE thatQuote)
++ [ "+-- Added on " ++ show (quoteTime thatQuote) ++ " --- Score : " ++ show (votes thatQuote) ]
formatElt :: QuoteElt -> String
formatElt this = "| " ++ eltQuotee this ++ ": " ++ eltQuote this
quoteStart :: AcidState QuoteDB -> IRC.Message -> IRC.UserName -> String -> Plugin (Env IO) ()
quoteStart quoteDB msg quotee phrase =
case phrase of
[] -> answerMsg msg "TODO: implement history lookup"
that -> quoteThat that
where
sender = getSender msg
channel = getChannel msg
quoteThat :: String -> Plugin (Env IO) ()
quoteThat thatQuote = do
now <- liftIO getCurrentTime
quoteID <- liftIO . update quoteDB $ TakeNextQuoteID sender channel now
let newQuote = emptyQuote { quoter = sender
, quoteFrom = channel
, quotE = [ QuoteElt { eltQuotee = quotee, eltQuote = thatQuote } ]
, quoteTime = now }
_ <- liftIO . update quoteDB $ SetQuote quoteID newQuote
answerMsg msg $ sender ++ ": new quote added with ID " ++ show quoteID
| adyxax/hsbot | Hsbot/Plugin/Quote.hs | bsd-3-clause | 15,130 | 0 | 24 | 4,846 | 4,122 | 2,058 | 2,064 | 261 | 30 |
module MsgDiagram.Lexer where
import Control.Monad (void)
import Text.Parsec
import Text.Parsec.String (GenParser)
import qualified Text.Parsec.Token as Tok
import Text.Parsec.Language (javaStyle)
type Parser a = GenParser Char Int a
-- ----------------------------------------------------- [ Define Token Parser ]
lexer = Tok.makeTokenParser style
where
style = javaStyle {Tok.reservedOpNames = ["->"],
Tok.reservedNames = [],
Tok.commentLine = "//"}
-- ------------------------------------------------------ [ Define Lexer Rules ]
-- | Do the lexing
runLex :: Parser a -> Parser a
runLex p = do Tok.whiteSpace lexer
res <- p
eof
return res
-- | Core Lexer Operation
lexeme :: Parser a -> Parser a
lexeme = Tok.lexeme lexer
-- | Lex these bad boys -> ','
comma :: Parser ()
comma = void (Tok.comma lexer)
-- | Lex these bad boys -> ':'
colon :: Parser ()
colon = void (Tok.colon lexer)
-- | Lex these bad boys -> ';'
semi :: Parser ()
semi = void (Tok.semi lexer)
-- | Lex these bad boys -> '[]'
brackets :: Parser a -> Parser a
brackets = Tok.brackets lexer
-- | Lex these base boys -> '()'
parens :: Parser a -> Parser a
parens = Tok.parens lexer
-- | Lex these bad boys -> '{}'
braces :: Parser a -> Parser a
braces = Tok.braces lexer
-- | Lex these bad boys -> '||'
pipes :: Parser a -> Parser a
pipes = between (symbol "|") (symbol "|")
-- | Lex Symbols
symbol :: String -> Parser String
symbol = Tok.symbol lexer
-- | Lex Lists sep by comma
commaSep1 :: Parser a -> Parser [a]
commaSep1 = Tok.commaSep1 lexer
-- | Lex Lists sep by comma
commaSep :: Parser a -> Parser [a]
commaSep = Tok.commaSep lexer
-- | Lex keywords
reserved :: String -> Parser ()
reserved = Tok.reserved lexer
-- | Lex operators
reservedOp :: String -> Parser ()
reservedOp = Tok.reservedOp lexer
-- | Lex identifiers
identifier :: Parser String
identifier = Tok.identifier lexer
-- | Lex strings
stringLiteral :: Parser String
stringLiteral = Tok.stringLiteral lexer
-- --------------------------------------------------------------------- [ EOF ]
| jfdm/hUML | src/MsgDiagram/Lexer.hs | bsd-3-clause | 2,153 | 0 | 9 | 460 | 557 | 295 | 262 | 46 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE QuasiQuotes #-}
import Database.Persist.Quasi
import Prelude hiding (filter)
import Database.Persist
import Database.Persist.State
import Database.Persist.Sqlite3
import Control.Monad.IO.Class
import qualified Data.Map as Map
import Database.HDBC.Sqlite3 (connectSqlite3)
persistSqlite3 [$persist|
Person
name String update Eq Ne Desc
age Int update Lt Asc
color String null Eq Ne
PersonNameKey name
|]
deriving instance Show Person
main = do
--evalPersistState go (Map.empty :: Map.Map Int Person)
conn <- connectSqlite3 "test.db3"
runSqlite3 go conn
go = do
initialize (undefined :: Person)
pid <- insert $ Person "Michael" 25 Nothing
liftIO $ print pid
p1 <- get pid
liftIO $ print p1
replace pid $ Person "Michael" 26 Nothing
p2 <- get pid
liftIO $ print p2
p3 <- select [PersonNameEq "Michael"] []
liftIO $ print p3
insert_ $ Person "Michael2" 27 Nothing
deleteWhere [PersonNameEq "Michael2"]
p4 <- select [PersonAgeLt 28] []
liftIO $ print p4
update pid [PersonAge 28]
p5 <- get pid
liftIO $ print p5
updateWhere [PersonNameEq "Michael"] [PersonAge 29]
p6 <- get pid
liftIO $ print p6
insert $ Person "Eliezer" 2 $ Just "blue"
p7 <- select [] [PersonAgeAsc]
liftIO $ print p7
insert $ Person "Abe" 30 $ Just "black"
p8 <- select [PersonAgeLt 30] [PersonNameDesc]
liftIO $ print p8
insertR $ Person "Abe" 31 $ Just "brown"
p9 <- select [PersonNameEq "Abe"] []
liftIO $ print p9
p10 <- getBy $ PersonNameKey "Michael"
liftIO $ print p10
p11 <- select [PersonColorEq $ Just "blue"] []
liftIO $ print p11
p12 <- select [PersonColorEq Nothing] []
liftIO $ print p12
p13 <- select [PersonColorNe Nothing] []
liftIO $ print p13
delete pid
plast <- get pid
liftIO $ print plast
| yesodweb/persistent | persistent-sqlite/test3.hs | mit | 2,079 | 2 | 14 | 496 | 702 | 322 | 380 | -1 | -1 |
-- Ferlicot Delbecque Cyril
-- PF TP3
module Main where
import Graphics.Gloss
main::IO()
main = animate (InWindow "L-systeme" (1000, 1000) (0, 0)) white brindilleAnime
dessin :: Picture
dessin = interpreteMot (((-150,0),0),100,1,pi/3,"F+-") "F+F--F+F"
type Symbole = Char
type Mot = [Symbole]
type Axiome = Mot
type Regles = Symbole -> Mot
type LSysteme = [Mot]
-- Question 1
motSuivant :: Regles -> Mot -> Mot
motSuivant _ "" = []
motSuivant regle (x:xs) = regle x ++ motSuivant regle xs
motSuivant' :: Regles -> Mot -> Mot
motSuivant' regle xs = concat [regle x| x<-xs]
motSuivant'' :: Regles -> Mot -> Mot
motSuivant'' regle xs = concatMap regle xs
-- Question 2
vanKoch:: Symbole -> Mot
vanKoch '+' = "+"
vanKoch '-' = "-"
vanKoch 'F' = "F-F++F-F"
vanKoch _ = ""
-- Question 3
lsysteme :: Axiome -> Regles -> LSysteme
lsysteme x regle = iterate (motSuivant regle) x
-- Question 4
type EtatTortue = (Point, Float)
type Config = (EtatTortue -- État initial de la tortue
,Float -- Longueur initiale d’un pas
,Float -- Facteur d’échelle
,Float -- Angle pour les rotations de la tortue
,[Symbole]) -- Liste des symboles compris par la tortue
etatInitial :: Config -> EtatTortue
etatInitial (etat,_,_,_,_) = etat
longueurPas :: Config -> Float
longueurPas (_,l,_,_,_) = l
facteurEchelle :: Config -> Float
facteurEchelle (_,_,f,_,_) = f
angle :: Config -> Float
angle (_,_,_,a,_) = a
symbolesTortue :: Config -> [Symbole]
symbolesTortue (_,_,_,_,t) = t
-- Question 5
avance :: Config -> EtatTortue -> EtatTortue
avance config ((x,y),a) = ( ( x + longueur*cos a,y + longueur*sin a) , a)
where longueur = longueurPas config
-- Question 6
tourneAGauche :: Config -> EtatTortue -> EtatTortue
tourneAGauche config (p, a)= (p, a + angle config )
tourneADroite :: Config -> EtatTortue -> EtatTortue
tourneADroite config (p, a) = (p, a - angle config)
-- Question 7
filtreSymbolesTortue :: Config -> Mot -> Mot
filtreSymbolesTortue config mot = [x | x<-mot, x `elem` symbolesTortue config ]
-- Question 8
type EtatDessin = (EtatTortue, Path)
--On part du principe que les symboles seront filtrés donc si ce n'est pas un '+' ou un '-' on fait comme si c'était un 'F'.
interpreteSymbole :: Config -> EtatDessin -> Symbole -> EtatDessin
interpreteSymbole config (etat, path) symb | symb == '+' = (tourneAGauche config etat , path)
| symb == '-' = (tourneADroite config etat , path)
| otherwise = (avance config etat , path ++ [fst (avance config etat)])
-- Question 9
interpreteMot :: Config -> Mot -> Picture
interpreteMot config mot = interpreteMot' config (filtreSymbolesTortue config mot)
interpreteMot':: Config -> Mot -> Picture
interpreteMot' config mot = line (snd (foldl (interpreteSymbole config) (initi,[fst initi]) mot))
where initi = etatInitial config
-- Question 10
lsystemeAnime :: LSysteme -> Config -> Float -> Picture
lsystemeAnime sys config t = interpreteMot newConf (sys !! iteration)
where iteration = round t `mod` 8
newConf = (etatInitial config, longueurPas config * (facteurEchelle config) ^ iteration, facteurEchelle config, angle config, symbolesTortue config)
vonKoch1 :: LSysteme
vonKoch1 = lsysteme "F" regles
where regles 'F' = "F-F++F-F"
regles s = [s]
vonKoch2 :: LSysteme
vonKoch2 = lsysteme "F++F++F++" regles
where regles 'F' = "F-F++F-F"
regles s = [s]
hilbert :: LSysteme
hilbert = lsysteme "X" regles
where regles 'X' = "+YF-XFX-FY+"
regles 'Y' = "-XF+YFY+FX-"
regles s = [s]
dragon :: LSysteme
dragon = lsysteme "FX" regles
where regles 'X' = "X+YF+"
regles 'Y' = "-FX-Y"
regles s = [s]
vonKoch1Anime :: Float -> Picture
vonKoch1Anime = lsystemeAnime' vonKoch1 (((-400, 0), 0), 800, 1/3, pi/3, "F+-")
vonKoch2Anime :: Float -> Picture
vonKoch2Anime = lsystemeAnime' vonKoch2 (((-400, -250), 0), 800, 1/3, pi/3, "F+-")
hilbertAnime :: Float -> Picture
hilbertAnime = lsystemeAnime' hilbert (((-400, -400), 0), 800, 1/2, pi/2, "F+-")
dragonAnime :: Float -> Picture
dragonAnime = lsystemeAnime' dragon (((0, 0), 0), 50, 1, pi/2, "F+-")
-- Question 11
type EtatDessin' = ([EtatTortue], [Path])
-- Question 12
-- Adaptons tout d'abord l'interpretation des symboles.
interpreteSymbole' :: Config -> EtatDessin' -> Symbole -> EtatDessin'
interpreteSymbole' config (etat:xs, path:ys) symb | symb == '+' = (tourneAGauche config etat:xs , path:ys)
| symb == '-' = (tourneADroite config etat:xs , path:ys)
| symb == '[' = (etat:etat:xs, [fst etat]:path:ys)
| symb == ']' = (xs, [fst (head xs)]:path:ys)
| otherwise = (avance config etat:xs , (path ++ [fst (avance config etat)]):ys)
interpreteSymbole' _ _ _ = error "Not matching"
-- Maintenant on adapte l'interpretation des mots.
interpreteMots :: Config -> Mot -> Picture
interpreteMots config mot = interpreteMot' config (filtreSymbolesTortue config mot)
interpreteMots':: Config -> Mot -> Picture
interpreteMots' config mot = pictures (map line (snd (foldl (interpreteSymbole' config) (initi, [[fst (head initi)]]) mot)) )
where initi = [etatInitial config]
lsystemeAnime' :: LSysteme -> Config -> Float -> Picture
lsystemeAnime' sys config t = interpreteMots newConf (sys !! iteration)
where iteration = round t `mod` 6
newConf = (etatInitial config, longueurPas config * (facteurEchelle config) ^ iteration, facteurEchelle config, angle config, symbolesTortue config)
brindille :: LSysteme
brindille = lsysteme "F" regles
where regles 'F' = "F[-F]F[+F]F"
regles s = [s]
broussaille :: LSysteme
broussaille = lsysteme "F" regles
where regles 'F' = "FF-[-F+F+F]+[+F-F-F]"
regles s = [s]
brindilleAnime :: Float -> Picture
brindilleAnime = lsystemeAnime' brindille (((0, -400), pi/2), 800, 1/3, 25*pi/180, "F+-[]")
broussailleAnime :: Float -> Picture
broussailleAnime = lsystemeAnime' broussaille (((0, -400), pi/2), 500, 2/5, 25*pi/180, "F+-[]")
| jecisc/TP_PF_L3 | PF-TP3/src/TP3_PF_FERLICOT/Main.hs | mit | 6,415 | 0 | 17 | 1,573 | 2,191 | 1,203 | 988 | 119 | 3 |
module Lib.Fifo
( Fifo
, empty, null
, enqueue, dequeue
, extract
) where
import Prelude.Compat hiding (null)
import Data.List (partition)
data Fifo a = Fifo
{ _new :: [a] -- reverse order (fast prepend)
, _old :: [a] -- forward order (fast pop-head)
}
null :: Fifo a -> Bool
null (Fifo [] []) = True
null _ = False
empty :: Fifo a
empty = Fifo [] []
extract :: (a -> Bool) -> Fifo a -> (Fifo a, [a])
extract p (Fifo new old) = (Fifo newF oldF, newT ++ oldT)
where
(newT, newF) = partition p new
(oldT, oldF) = partition p old
enqueue :: a -> Fifo a -> Fifo a
enqueue x (Fifo new old) = Fifo (x:new) old
dequeue :: Fifo a -> Maybe (Fifo a, a)
dequeue (Fifo new (o:os)) = Just (Fifo new os, o)
dequeue (Fifo new []) =
case reverse new of
[] -> Nothing
(o:os) -> Just (Fifo [] os, o)
| buildsome/buildsome | src/Lib/Fifo.hs | gpl-2.0 | 822 | 0 | 11 | 203 | 415 | 222 | 193 | 27 | 2 |
instance SomeClass [a]
| roberth/uu-helium | test/typeClassesStatic/UndefinedClass.hs | gpl-3.0 | 23 | 0 | 6 | 3 | 11 | 5 | 6 | 1 | 0 |
{-# LANGUAGE FlexibleContexts #-}
module Propellor.Property.Apt where
import Data.Maybe
import Control.Applicative
import Data.List
import System.IO
import Control.Monad
import Propellor
import qualified Propellor.Property.File as File
import qualified Propellor.Property.Service as Service
import Propellor.Property.File (Line)
sourcesList :: FilePath
sourcesList = "/etc/apt/sources.list"
type Url = String
type Section = String
type SourcesGenerator = DebianSuite -> [Line]
showSuite :: DebianSuite -> String
showSuite (Stable s) = s
showSuite Testing = "testing"
showSuite Unstable = "unstable"
showSuite Experimental = "experimental"
backportSuite :: DebianSuite -> Maybe String
backportSuite (Stable s) = Just (s ++ "-backports")
backportSuite _ = Nothing
stableUpdatesSuite :: DebianSuite -> Maybe String
stableUpdatesSuite (Stable s) = Just (s ++ "-updates")
stableUpdatesSuite _ = Nothing
debLine :: String -> Url -> [Section] -> Line
debLine suite mirror sections = unwords $
["deb", mirror, suite] ++ sections
srcLine :: Line -> Line
srcLine l = case words l of
("deb":rest) -> unwords $ "deb-src" : rest
_ -> ""
stdSections :: [Section]
stdSections = ["main", "contrib", "non-free"]
binandsrc :: String -> SourcesGenerator
binandsrc url suite = catMaybes
[ Just l
, Just $ srcLine l
, bl
, srcLine <$> bl
]
where
l = debLine (showSuite suite) url stdSections
bl = do
bs <- backportSuite suite
return $ debLine bs url stdSections
debCdn :: SourcesGenerator
debCdn = binandsrc "http://httpredir.debian.org/debian"
kernelOrg :: SourcesGenerator
kernelOrg = binandsrc "http://mirrors.kernel.org/debian"
-- | Only available for Stable and Testing
securityUpdates :: SourcesGenerator
securityUpdates suite
| isStable suite || suite == Testing =
let l = "deb http://security.debian.org/ " ++ showSuite suite ++ "/updates " ++ unwords stdSections
in [l, srcLine l]
| otherwise = []
-- | Makes sources.list have a standard content using the mirror CDN,
-- with the Debian suite configured by the os.
--
-- Since the CDN is sometimes unreliable, also adds backup lines using
-- kernel.org.
stdSourcesList :: Property NoInfo
stdSourcesList = withOS ("standard sources.list") $ \o ->
case o of
(Just (System (Debian suite) _)) ->
ensureProperty $ stdSourcesListFor suite
_ -> error "os is not declared to be Debian"
stdSourcesListFor :: DebianSuite -> Property NoInfo
stdSourcesListFor suite = stdSourcesList' suite []
-- | Adds additional sources.list generators.
--
-- Note that if a Property needs to enable an apt source, it's better
-- to do so via a separate file in </etc/apt/sources.list.d/>
stdSourcesList' :: DebianSuite -> [SourcesGenerator] -> Property NoInfo
stdSourcesList' suite more = setSourcesList
(concatMap (\gen -> gen suite) generators)
`describe` ("standard sources.list for " ++ show suite)
where
generators = [debCdn, kernelOrg, securityUpdates] ++ more
setSourcesList :: [Line] -> Property NoInfo
setSourcesList ls = sourcesList `File.hasContent` ls `onChange` update
setSourcesListD :: [Line] -> FilePath -> Property NoInfo
setSourcesListD ls basename = f `File.hasContent` ls `onChange` update
where
f = "/etc/apt/sources.list.d/" ++ basename ++ ".list"
runApt :: [String] -> Property NoInfo
runApt ps = cmdPropertyEnv "apt-get" ps noninteractiveEnv
noninteractiveEnv :: [(String, String)]
noninteractiveEnv =
[ ("DEBIAN_FRONTEND", "noninteractive")
, ("APT_LISTCHANGES_FRONTEND", "none")
]
update :: Property NoInfo
update = runApt ["update"]
`describe` "apt update"
upgrade :: Property NoInfo
upgrade = runApt ["-y", "dist-upgrade"]
`describe` "apt dist-upgrade"
type Package = String
installed :: [Package] -> Property NoInfo
installed = installed' ["-y"]
installed' :: [String] -> [Package] -> Property NoInfo
installed' params ps = robustly $ check (isInstallable ps) go
`describe` (unwords $ "apt installed":ps)
where
go = runApt $ params ++ ["install"] ++ ps
installedBackport :: [Package] -> Property NoInfo
installedBackport ps = trivial $ withOS desc $ \o -> case o of
Nothing -> error "cannot install backports; os not declared"
(Just (System (Debian suite) _)) -> case backportSuite suite of
Nothing -> notsupported o
Just bs -> ensureProperty $ runApt $
["install", "-t", bs, "-y"] ++ ps
_ -> notsupported o
where
desc = (unwords $ "apt installed backport":ps)
notsupported o = error $ "backports not supported on " ++ show o
-- | Minimal install of package, without recommends.
installedMin :: [Package] -> Property NoInfo
installedMin = installed' ["--no-install-recommends", "-y"]
removed :: [Package] -> Property NoInfo
removed ps = check (or <$> isInstalled' ps) go
`describe` (unwords $ "apt removed":ps)
where
go = runApt $ ["-y", "remove"] ++ ps
buildDep :: [Package] -> Property NoInfo
buildDep ps = robustly go
`describe` (unwords $ "apt build-dep":ps)
where
go = runApt $ ["-y", "build-dep"] ++ ps
-- | Installs the build deps for the source package unpacked
-- in the specifed directory, with a dummy package also
-- installed so that autoRemove won't remove them.
buildDepIn :: FilePath -> Property NoInfo
buildDepIn dir = go `requires` installedMin ["devscripts", "equivs"]
where
go = cmdPropertyEnv "sh" ["-c", "cd '" ++ dir ++ "' && mk-build-deps debian/control --install --tool 'apt-get -y --no-install-recommends' --remove"]
noninteractiveEnv
-- | Package installation may fail becuse the archive has changed.
-- Run an update in that case and retry.
robustly :: (Combines (Property i) (Property NoInfo)) => Property i -> Property i
robustly p = adjustPropertySatisfy p $ \satisfy -> do
r <- satisfy
if r == FailedChange
-- Safe to use ignoreInfo because we're re-running
-- the same property.
then ensureProperty $ ignoreInfo $ p `requires` update
else return r
isInstallable :: [Package] -> IO Bool
isInstallable ps = do
l <- isInstalled' ps
return $ any (== False) l && not (null l)
isInstalled :: Package -> IO Bool
isInstalled p = (== [True]) <$> isInstalled' [p]
-- | Note that the order of the returned list will not always
-- correspond to the order of the input list. The number of items may
-- even vary. If apt does not know about a package at all, it will not
-- be included in the result list.
isInstalled' :: [Package] -> IO [Bool]
isInstalled' ps = catMaybes . map parse . lines <$> policy
where
parse l
| "Installed: (none)" `isInfixOf` l = Just False
| "Installed: " `isInfixOf` l = Just True
| otherwise = Nothing
policy = do
environ <- addEntry "LANG" "C" <$> getEnvironment
readProcessEnv "apt-cache" ("policy":ps) (Just environ)
autoRemove :: Property NoInfo
autoRemove = runApt ["-y", "autoremove"]
`describe` "apt autoremove"
-- | Enables unattended upgrades. Revert to disable.
unattendedUpgrades :: RevertableProperty
unattendedUpgrades = enable <!> disable
where
enable = setup True
`before` Service.running "cron"
`before` configure
disable = setup False
setup enabled = (if enabled then installed else removed) ["unattended-upgrades"]
`onChange` reConfigure "unattended-upgrades"
[("unattended-upgrades/enable_auto_updates" , "boolean", v)]
`describe` ("unattended upgrades " ++ v)
where
v
| enabled = "true"
| otherwise = "false"
configure = withOS "unattended upgrades configured" $ \o ->
case o of
-- the package defaults to only upgrading stable
(Just (System (Debian suite) _))
| not (isStable suite) -> ensureProperty $
"/etc/apt/apt.conf.d/50unattended-upgrades"
`File.containsLine`
("Unattended-Upgrade::Origins-Pattern { \"o=Debian,a="++showSuite suite++"\"; };")
_ -> noChange
-- | Preseeds debconf values and reconfigures the package so it takes
-- effect.
reConfigure :: Package -> [(String, String, String)] -> Property NoInfo
reConfigure package vals = reconfigure `requires` setselections
`describe` ("reconfigure " ++ package)
where
setselections = property "preseed" $ makeChange $
withHandle StdinHandle createProcessSuccess
(proc "debconf-set-selections" []) $ \h -> do
forM_ vals $ \(tmpl, tmpltype, value) ->
hPutStrLn h $ unwords [package, tmpl, tmpltype, value]
hClose h
reconfigure = cmdPropertyEnv "dpkg-reconfigure" ["-fnone", package] noninteractiveEnv
-- | Ensures that a service is installed and running.
--
-- Assumes that there is a 1:1 mapping between service names and apt
-- package names.
serviceInstalledRunning :: Package -> Property NoInfo
serviceInstalledRunning svc = Service.running svc `requires` installed [svc]
data AptKey = AptKey
{ keyname :: String
, pubkey :: String
}
trustsKey :: AptKey -> RevertableProperty
trustsKey k = trustsKey' k <!> untrustKey k
trustsKey' :: AptKey -> Property NoInfo
trustsKey' k = check (not <$> doesFileExist f) $ property desc $ makeChange $ do
withHandle StdinHandle createProcessSuccess
(proc "gpg" ["--no-default-keyring", "--keyring", f, "--import", "-"]) $ \h -> do
hPutStr h (pubkey k)
hClose h
nukeFile $ f ++ "~" -- gpg dropping
where
desc = "apt trusts key " ++ keyname k
f = aptKeyFile k
untrustKey :: AptKey -> Property NoInfo
untrustKey = File.notPresent . aptKeyFile
aptKeyFile :: AptKey -> FilePath
aptKeyFile k = "/etc/apt/trusted.gpg.d" </> keyname k ++ ".gpg"
-- | Cleans apt's cache of downloaded packages to avoid using up disk
-- space.
cacheCleaned :: Property NoInfo
cacheCleaned = trivial $ cmdProperty "apt-get" ["clean"]
`describe` "apt cache cleaned"
| sjfloat/propellor | src/Propellor/Property/Apt.hs | bsd-2-clause | 9,497 | 74 | 17 | 1,616 | 2,660 | 1,418 | 1,242 | 195 | 4 |
-- The main module of the application. Performs GLFW-specific initialization and others.
module Main ( main ) where
import Control.Concurrent
import Control.Monad
import qualified Graphics.UI.GLFW as GLFW
import System.Environment
import System.IO
import qualified Renderer as R
-- | The error handler to be called when a GLFW error occurs.
errorHandler :: GLFW.ErrorCallback
errorHandler error description = do
hPutStrLn stderr $ (show error) ++ ": " ++ description
-- | The rendering loop.
renderingLoop
:: GLFW.Window -- ^ the window handle
-> IO () -- ^ rendering action
-> IO ()
renderingLoop window render = do
loop
where
loop = (GLFW.windowShouldClose window) >>= (flip unless) go
go = do
render
GLFW.swapBuffers window
GLFW.pollEvents
threadDelay 100000 -- Suspends to reduce the CPU usage.
loop
-- | The process after the createWindow.
afterCreateWindow
:: GLFW.Window -- ^ the window handle
-> IO ()
afterCreateWindow window = do
GLFW.makeContextCurrent $ Just window
GLFW.swapInterval 1
desc <- R.initialize
renderingLoop window (R.render desc)
R.terminate desc
GLFW.destroyWindow window
-- | The entry point of the application.
main :: IO ()
main = do
progName <- getProgName
GLFW.setErrorCallback $ Just errorHandler
GLFW.init
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMajor 3
GLFW.windowHint $ GLFW.WindowHint'ContextVersionMinor 3
GLFW.windowHint $ GLFW.WindowHint'OpenGLProfile GLFW.OpenGLProfile'Core
GLFW.createWindow 500 500 progName Nothing Nothing >>= maybe (return ()) afterCreateWindow
GLFW.terminate
| fujiyan/toriaezuzakki | haskell/opengl/texture/Rectangle.hs | bsd-2-clause | 1,686 | 0 | 11 | 364 | 396 | 194 | 202 | 43 | 1 |
-- |
-- Module : Data.Memory.Internal.DeepSeq
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : unknown
--
-- Simple abstraction module to allow compilation without deepseq
-- by defining our own NFData class if not compiling with deepseq
-- support.
--
{-# LANGUAGE CPP #-}
module Data.Memory.Internal.DeepSeq
( NFData(..)
) where
#ifdef WITH_DEEPSEQ_SUPPORT
import Control.DeepSeq
#else
import Data.Word
class NFData a where rnf :: a -> ()
instance NFData Word8 where rnf w = w `seq` ()
instance NFData Word16 where rnf w = w `seq` ()
instance NFData Word32 where rnf w = w `seq` ()
instance NFData Word64 where rnf w = w `seq` ()
#endif
| NicolasDP/hs-memory | Data/Memory/Internal/DeepSeq.hs | bsd-3-clause | 733 | 0 | 5 | 139 | 37 | 30 | 7 | 9 | 0 |
--
-- Data vault for metrics
--
-- Copyright © 2013-2014 Anchor Systems, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the 3-clause BSD licence.
--
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS -fno-warn-type-defaults #-}
module Main where
import Control.Concurrent
import Control.Concurrent.Async
import Data.HashMap.Strict (fromList)
import Data.Maybe
import Data.Text
import Network.URI
import Pipes
import qualified Pipes.Prelude as P
import System.Directory
import System.IO
import Test.Hspec hiding (pending)
import CommandRunners
import DaemonRunners
import Marquise.Client
import Marquise.Server
import TestHelpers (cleanup, daemonArgsTest)
import Vaultaire.Daemon hiding (broker, shutdown)
pool :: String
pool = "test"
user :: String
user = "vaultaire"
destroyExistingVault :: IO ()
destroyExistingVault = do
args <- daemonArgsTest (fromJust $ parseURI "inproc://1")
(Just user) pool
runDaemon args cleanup
startServerDaemons :: FilePath -> MVar () -> IO ()
startServerDaemons tmp shutdown =
let
broker = "localhost"
bucket_size = 4194304
num_buckets = 128
step_size = 1440 * 1000000000
origin = Origin "ZZZZZZ"
namespace = "integration"
in do
a1 <- runBrokerDaemon shutdown
a2 <- runWriterDaemon pool user broker bucket_size shutdown "" Nothing
a3 <- runReaderDaemon pool user broker shutdown "" Nothing
a4 <- runContentsDaemon pool user broker shutdown "" Nothing
a5 <- runMarquiseDaemon broker origin namespace shutdown tmp 60
-- link the following threads to this main thread
mapM_ link [ daemonWorker a1
, daemonWorker a2
, daemonWorker a3
, daemonWorker a4
, a5 ]
runRegisterOrigin pool user origin num_buckets step_size 0 0
setupClientSide :: IO SpoolFiles
setupClientSide = createSpoolFiles "integration"
--
-- Sadly, the smazing standard library lacks a standardized way to create a
-- temporary file. You'll need to remove this file when it's done.
--
createTempFile :: IO FilePath
createTempFile = do
(name,h) <- openTempFile "." "cache_file-.tmp"
hClose h
return name
main :: IO ()
main = do
quit <- newEmptyMVar
destroyExistingVault
tmp <- createTempFile
startServerDaemons tmp quit
spool <- setupClientSide
hspec (suite spool)
putMVar quit ()
removeFile tmp
suite :: SpoolFiles -> Spec
suite spool =
let
origin = Origin "ZZZZZZ"
address = hashIdentifier "Row row row yer boat"
begin = 1406078299651575183
end = 1406078299651575183
timestamp = 1406078299651575183
payload = 42
in do
describe "Generate data" $
it "sends point via marquise" $ do
queueSimple spool address timestamp payload
flush spool
pass
describe "Retreive data" $
it "reads point via marquise" $
let
go n = do
result <- withReaderConnection "localhost" $ \c ->
P.head (readSimple address begin end origin c >-> decodeSimple)
case result of
Nothing -> if n > 100
then expectationFailure "Expected a value back, didn't get one"
else do
threadDelay 10000 -- 10 ms
go (n+1)
Just v -> simplePayload v `shouldBe` payload
in
go 1
-- | Mark that we are expecting this code to have succeeded, unless it threw an exception
pass :: Expectation
pass = return ()
listToDict :: [(Text, Text)] -> SourceDict
listToDict elts = either error id . makeSourceDict $ fromList elts
| afcowie/vaultaire | tests/IntegrationTest.hs | bsd-3-clause | 3,958 | 0 | 24 | 1,122 | 857 | 436 | 421 | 101 | 3 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE BangPatterns #-}
module Bench.State where
import Pure.Bench
import Pure.Test
import Ef
import Ef.Interpreter as I
import qualified Control.Monad.Trans.State as T
import Data.Functor.Identity
import Control.Concurrent
suite :: Test Sync ()
suite = scope "state" $ tests
[ Bench.State.state
]
state :: Test Sync ()
state = tests
[ addReturn
, fmapChain
]
{-# INLINE addReturn #-}
addReturn :: Test Sync ()
addReturn = scope "add/return" $ do
let (_,a) = runIdentity (interp ef_add_return 1)
b = runIdentity (T.evalStateT mtl_add_return 1)
expect (a == b)
scope "transformers" $ whnf (runIdentity . T.evalStateT mtl_add_return) 1 >>= summary
scope "ef" $ whnf (runIdentity . interp ef_add_return) 1 >>= summary
{-# INLINE fmapChain #-}
fmapChain :: Test Sync ()
fmapChain = scope "fmap/fmap/fmap" $ do
scope "transformers" $ whnf (runIdentity . T.evalStateT mtl_fmap) (1 :: Int) >>= summary
scope "ef" $ whnf (runIdentity . interp ef_fmap) (1 :: Int) >>= summary
{-# INLINE mtl_fmap #-}
mtl_fmap :: Monad m => T.StateT Int m Int
mtl_fmap = fmap (+1) . fmap (+1) . fmap (+1) $ T.get
{-# INLINE ef_fmap #-}
ef_fmap :: Monad m => StateT Int m Int
ef_fmap = fmap (+1) . fmap (+1) . fmap (+1) $ get
{-# INLINE ef_add_return #-}
ef_add_return :: Monad m => StateT Int m Int
ef_add_return = do
w :: Int <- get
x :: Int <- get
y :: Int <- get
z :: Int <- get
put $! w + x + y + z
get
{-# INLINE mtl_add_return #-}
mtl_add_return :: Monad m => T.StateT Int m Int
mtl_add_return = do
w :: Int <- T.get
x :: Int <- T.get
y :: Int <- T.get
z :: Int <- T.get
T.put $! w + x + y + z
T.get
type StateT s c a = Interp s (State s) c a
newtype State s k = State { runState :: s -> (s,k) }
deriving Functor
{-# INLINE eval #-}
eval :: Monad c => Narrative (State s) c a -> s -> c (s,a)
eval n = \s ->
Ef.thread (\(State ssk) s -> let (s',k) = ssk s in k s') n s
{-# INLINE interp #-}
interp :: Monad c => StateT s c a -> s -> c (s,a)
interp = I.thread eval
{-# INLINE get #-}
get :: StateT s c s
get = I.send (State (\s -> (s,s)))
{-# INLINE put #-}
put :: s -> StateT s c ()
put s = I.send (State (\_ -> (s,())))
{-# INLINE modify' #-}
modify' :: (s -> s) -> StateT s c ()
modify' f = I.send (State (\s -> let !s' = f s in (s',())))
{-# INLINE modify #-}
modify :: (s -> s) -> StateT s c ()
modify f = I.send (State (\s -> (f s,())))
| grumply/mop | bench/Bench/State.hs | bsd-3-clause | 2,472 | 0 | 14 | 552 | 1,107 | 575 | 532 | 77 | 1 |
import Control.Monad
import Paths
import System.FilePath
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core
{-----------------------------------------------------------------------------
Main
------------------------------------------------------------------------------}
main :: IO ()
main = startGUI defaultConfig setup
setup :: Window -> UI ()
setup window = do
return window # set title "Drawing"
canvas <- UI.canvas
# set UI.height 400
# set UI.width 400
# set style [("border", "solid black 1px")]
clear <- UI.button #+ [string "Clear the canvas."]
getBody window #+ [column
[element canvas, string "Click to places images."]
,element clear
]
dir <- liftIO $ getStaticDir
url <- loadFile "image/png" (dir </> "game" </> "wizard-blue" <.> "png")
img <- UI.img # set UI.src url
let positions = [(x,y) | x <- [0,20..300], y <- [0,20..300]] :: [(Int,Int)]
on UI.click canvas $ const $ forM_ positions $
\xy -> UI.drawImage img xy canvas
on UI.click clear $ const $ do
UI.clearCanvas canvas
| yuvallanger/threepenny-gui | samples/Drawing.hs | bsd-3-clause | 1,161 | 0 | 13 | 280 | 375 | 189 | 186 | 26 | 1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE ScopedTypeVariables #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bifoldable
-- Copyright : (C) 2011-2016 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- @since 4.10.0.0
----------------------------------------------------------------------------
module Data.Bifoldable
( Bifoldable(..)
, bifoldr'
, bifoldr1
, bifoldrM
, bifoldl'
, bifoldl1
, bifoldlM
, bitraverse_
, bifor_
, bimapM_
, biforM_
, bimsum
, bisequenceA_
, bisequence_
, biasum
, biList
, binull
, bilength
, bielem
, bimaximum
, biminimum
, bisum
, biproduct
, biconcat
, biconcatMap
, biand
, bior
, biany
, biall
, bimaximumBy
, biminimumBy
, binotElem
, bifind
) where
import Control.Applicative
import Data.Functor.Utils (Max(..), Min(..), (#.))
import Data.Maybe (fromMaybe)
import Data.Monoid
import GHC.Generics (K1(..))
-- | 'Bifoldable' identifies foldable structures with two different varieties
-- of elements (as opposed to 'Foldable', which has one variety of element).
-- Common examples are 'Either' and '(,)':
--
-- > instance Bifoldable Either where
-- > bifoldMap f _ (Left a) = f a
-- > bifoldMap _ g (Right b) = g b
-- >
-- > instance Bifoldable (,) where
-- > bifoldr f g z (a, b) = f a (g b z)
--
-- A minimal 'Bifoldable' definition consists of either 'bifoldMap' or
-- 'bifoldr'. When defining more than this minimal set, one should ensure
-- that the following identities hold:
--
-- @
-- 'bifold' ≡ 'bifoldMap' 'id' 'id'
-- 'bifoldMap' f g ≡ 'bifoldr' ('mappend' . f) ('mappend' . g) 'mempty'
-- 'bifoldr' f g z t ≡ 'appEndo' ('bifoldMap' (Endo . f) (Endo . g) t) z
-- @
--
-- If the type is also a 'Data.Bifunctor.Bifunctor' instance, it should satisfy:
--
-- @
-- 'bifoldMap' f g ≡ 'bifold' . 'Data.Bifunctor.bimap' f g
-- @
--
-- which implies that
--
-- @
-- 'bifoldMap' f g . 'Data.Bifunctor.bimap' h i ≡ 'bifoldMap' (f . h) (g . i)
-- @
--
-- @since 4.10.0.0
class Bifoldable p where
{-# MINIMAL bifoldr | bifoldMap #-}
-- | Combines the elements of a structure using a monoid.
--
-- @'bifold' ≡ 'bifoldMap' 'id' 'id'@
--
-- @since 4.10.0.0
bifold :: Monoid m => p m m -> m
bifold = bifoldMap id id
-- | Combines the elements of a structure, given ways of mapping them to a
-- common monoid.
--
-- @'bifoldMap' f g
-- ≡ 'bifoldr' ('mappend' . f) ('mappend' . g) 'mempty'@
--
-- @since 4.10.0.0
bifoldMap :: Monoid m => (a -> m) -> (b -> m) -> p a b -> m
bifoldMap f g = bifoldr (mappend . f) (mappend . g) mempty
-- | Combines the elements of a structure in a right associative manner.
-- Given a hypothetical function @toEitherList :: p a b -> [Either a b]@
-- yielding a list of all elements of a structure in order, the following
-- would hold:
--
-- @'bifoldr' f g z ≡ 'foldr' ('either' f g) z . toEitherList@
--
-- @since 4.10.0.0
bifoldr :: (a -> c -> c) -> (b -> c -> c) -> c -> p a b -> c
bifoldr f g z t = appEndo (bifoldMap (Endo #. f) (Endo #. g) t) z
-- | Combines the elements of a structure in a left associative manner. Given
-- a hypothetical function @toEitherList :: p a b -> [Either a b]@ yielding a
-- list of all elements of a structure in order, the following would hold:
--
-- @'bifoldl' f g z
-- ≡ 'foldl' (\acc -> 'either' (f acc) (g acc)) z . toEitherList@
--
-- Note that if you want an efficient left-fold, you probably want to use
-- 'bifoldl'' instead of 'bifoldl'. The reason is that the latter does not
-- force the "inner" results, resulting in a thunk chain which then must be
-- evaluated from the outside-in.
--
-- @since 4.10.0.0
bifoldl :: (c -> a -> c) -> (c -> b -> c) -> c -> p a b -> c
bifoldl f g z t = appEndo (getDual (bifoldMap (Dual . Endo . flip f)
(Dual . Endo . flip g) t)) z
-- | @since 4.10.0.0
instance Bifoldable (,) where
bifoldMap f g ~(a, b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable Const where
bifoldMap f _ (Const a) = f a
-- | @since 4.10.0.0
instance Bifoldable (K1 i) where
bifoldMap f _ (K1 c) = f c
-- | @since 4.10.0.0
instance Bifoldable ((,,) x) where
bifoldMap f g ~(_,a,b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable ((,,,) x y) where
bifoldMap f g ~(_,_,a,b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable ((,,,,) x y z) where
bifoldMap f g ~(_,_,_,a,b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable ((,,,,,) x y z w) where
bifoldMap f g ~(_,_,_,_,a,b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable ((,,,,,,) x y z w v) where
bifoldMap f g ~(_,_,_,_,_,a,b) = f a `mappend` g b
-- | @since 4.10.0.0
instance Bifoldable Either where
bifoldMap f _ (Left a) = f a
bifoldMap _ g (Right b) = g b
-- | As 'bifoldr', but strict in the result of the reduction functions at each
-- step.
--
-- @since 4.10.0.0
bifoldr' :: Bifoldable t => (a -> c -> c) -> (b -> c -> c) -> c -> t a b -> c
bifoldr' f g z0 xs = bifoldl f' g' id xs z0 where
f' k x z = k $! f x z
g' k x z = k $! g x z
-- | A variant of 'bifoldr' that has no base case,
-- and thus may only be applied to non-empty structures.
--
-- @since 4.10.0.0
bifoldr1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
bifoldr1 f xs = fromMaybe (error "bifoldr1: empty structure")
(bifoldr mbf mbf Nothing xs)
where
mbf x m = Just (case m of
Nothing -> x
Just y -> f x y)
-- | Right associative monadic bifold over a structure.
--
-- @since 4.10.0.0
bifoldrM :: (Bifoldable t, Monad m)
=> (a -> c -> m c) -> (b -> c -> m c) -> c -> t a b -> m c
bifoldrM f g z0 xs = bifoldl f' g' return xs z0 where
f' k x z = f x z >>= k
g' k x z = g x z >>= k
-- | As 'bifoldl', but strict in the result of the reduction functions at each
-- step.
--
-- This ensures that each step of the bifold is forced to weak head normal form
-- before being applied, avoiding the collection of thunks that would otherwise
-- occur. This is often what you want to strictly reduce a finite structure to
-- a single, monolithic result (e.g., 'bilength').
--
-- @since 4.10.0.0
bifoldl':: Bifoldable t => (a -> b -> a) -> (a -> c -> a) -> a -> t b c -> a
bifoldl' f g z0 xs = bifoldr f' g' id xs z0 where
f' x k z = k $! f z x
g' x k z = k $! g z x
-- | A variant of 'bifoldl' that has no base case,
-- and thus may only be applied to non-empty structures.
--
-- @since 4.10.0.0
bifoldl1 :: Bifoldable t => (a -> a -> a) -> t a a -> a
bifoldl1 f xs = fromMaybe (error "bifoldl1: empty structure")
(bifoldl mbf mbf Nothing xs)
where
mbf m y = Just (case m of
Nothing -> y
Just x -> f x y)
-- | Left associative monadic bifold over a structure.
--
-- @since 4.10.0.0
bifoldlM :: (Bifoldable t, Monad m)
=> (a -> b -> m a) -> (a -> c -> m a) -> a -> t b c -> m a
bifoldlM f g z0 xs = bifoldr f' g' return xs z0 where
f' x k z = f z x >>= k
g' x k z = g z x >>= k
-- | Map each element of a structure using one of two actions, evaluate these
-- actions from left to right, and ignore the results. For a version that
-- doesn't ignore the results, see 'Data.Bitraversable.bitraverse'.
--
-- @since 4.10.0.0
bitraverse_ :: (Bifoldable t, Applicative f)
=> (a -> f c) -> (b -> f d) -> t a b -> f ()
bitraverse_ f g = bifoldr ((*>) . f) ((*>) . g) (pure ())
-- | As 'bitraverse_', but with the structure as the primary argument. For a
-- version that doesn't ignore the results, see 'Data.Bitraversable.bifor'.
--
-- >>> > bifor_ ('a', "bc") print (print . reverse)
-- 'a'
-- "cb"
--
-- @since 4.10.0.0
bifor_ :: (Bifoldable t, Applicative f)
=> t a b -> (a -> f c) -> (b -> f d) -> f ()
bifor_ t f g = bitraverse_ f g t
-- | Alias for 'bitraverse_'.
--
-- @since 4.10.0.0
bimapM_ :: (Bifoldable t, Applicative f)
=> (a -> f c) -> (b -> f d) -> t a b -> f ()
bimapM_ = bitraverse_
-- | Alias for 'bifor_'.
--
-- @since 4.10.0.0
biforM_ :: (Bifoldable t, Applicative f)
=> t a b -> (a -> f c) -> (b -> f d) -> f ()
biforM_ = bifor_
-- | Alias for 'bisequence_'.
--
-- @since 4.10.0.0
bisequenceA_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()
bisequenceA_ = bisequence_
-- | Evaluate each action in the structure from left to right, and ignore the
-- results. For a version that doesn't ignore the results, see
-- 'Data.Bitraversable.bisequence'.
--
-- @since 4.10.0.0
bisequence_ :: (Bifoldable t, Applicative f) => t (f a) (f b) -> f ()
bisequence_ = bifoldr (*>) (*>) (pure ())
-- | The sum of a collection of actions, generalizing 'biconcat'.
--
-- @since 4.10.0.0
biasum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a
biasum = bifoldr (<|>) (<|>) empty
-- | Alias for 'biasum'.
--
-- @since 4.10.0.0
bimsum :: (Bifoldable t, Alternative f) => t (f a) (f a) -> f a
bimsum = biasum
-- | Collects the list of elements of a structure, from left to right.
--
-- @since 4.10.0.0
biList :: Bifoldable t => t a a -> [a]
biList = bifoldr (:) (:) []
-- | Test whether the structure is empty.
--
-- @since 4.10.0.0
binull :: Bifoldable t => t a b -> Bool
binull = bifoldr (\_ _ -> False) (\_ _ -> False) True
-- | Returns the size/length of a finite structure as an 'Int'.
--
-- @since 4.10.0.0
bilength :: Bifoldable t => t a b -> Int
bilength = bifoldl' (\c _ -> c+1) (\c _ -> c+1) 0
-- | Does the element occur in the structure?
--
-- @since 4.10.0.0
bielem :: (Bifoldable t, Eq a) => a -> t a a -> Bool
bielem x = biany (== x) (== x)
-- | Reduces a structure of lists to the concatenation of those lists.
--
-- @since 4.10.0.0
biconcat :: Bifoldable t => t [a] [a] -> [a]
biconcat = bifold
-- | The largest element of a non-empty structure.
--
-- @since 4.10.0.0
bimaximum :: forall t a. (Bifoldable t, Ord a) => t a a -> a
bimaximum = fromMaybe (error "bimaximum: empty structure") .
getMax . bifoldMap mj mj
where mj = Max #. (Just :: a -> Maybe a)
-- | The least element of a non-empty structure.
--
-- @since 4.10.0.0
biminimum :: forall t a. (Bifoldable t, Ord a) => t a a -> a
biminimum = fromMaybe (error "biminimum: empty structure") .
getMin . bifoldMap mj mj
where mj = Min #. (Just :: a -> Maybe a)
-- | The 'bisum' function computes the sum of the numbers of a structure.
--
-- @since 4.10.0.0
bisum :: (Bifoldable t, Num a) => t a a -> a
bisum = getSum #. bifoldMap Sum Sum
-- | The 'biproduct' function computes the product of the numbers of a
-- structure.
--
-- @since 4.10.0.0
biproduct :: (Bifoldable t, Num a) => t a a -> a
biproduct = getProduct #. bifoldMap Product Product
-- | Given a means of mapping the elements of a structure to lists, computes the
-- concatenation of all such lists in order.
--
-- @since 4.10.0.0
biconcatMap :: Bifoldable t => (a -> [c]) -> (b -> [c]) -> t a b -> [c]
biconcatMap = bifoldMap
-- | 'biand' returns the conjunction of a container of Bools. For the
-- result to be 'True', the container must be finite; 'False', however,
-- results from a 'False' value finitely far from the left end.
--
-- @since 4.10.0.0
biand :: Bifoldable t => t Bool Bool -> Bool
biand = getAll #. bifoldMap All All
-- | 'bior' returns the disjunction of a container of Bools. For the
-- result to be 'False', the container must be finite; 'True', however,
-- results from a 'True' value finitely far from the left end.
--
-- @since 4.10.0.0
bior :: Bifoldable t => t Bool Bool -> Bool
bior = getAny #. bifoldMap Any Any
-- | Determines whether any element of the structure satisfies its appropriate
-- predicate argument.
--
-- @since 4.10.0.0
biany :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
biany p q = getAny #. bifoldMap (Any . p) (Any . q)
-- | Determines whether all elements of the structure satisfy their appropriate
-- predicate argument.
--
-- @since 4.10.0.0
biall :: Bifoldable t => (a -> Bool) -> (b -> Bool) -> t a b -> Bool
biall p q = getAll #. bifoldMap (All . p) (All . q)
-- | The largest element of a non-empty structure with respect to the
-- given comparison function.
--
-- @since 4.10.0.0
bimaximumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
bimaximumBy cmp = bifoldr1 max'
where max' x y = case cmp x y of
GT -> x
_ -> y
-- | The least element of a non-empty structure with respect to the
-- given comparison function.
--
-- @since 4.10.0.0
biminimumBy :: Bifoldable t => (a -> a -> Ordering) -> t a a -> a
biminimumBy cmp = bifoldr1 min'
where min' x y = case cmp x y of
GT -> y
_ -> x
-- | 'binotElem' is the negation of 'bielem'.
--
-- @since 4.10.0.0
binotElem :: (Bifoldable t, Eq a) => a -> t a a-> Bool
binotElem x = not . bielem x
-- | The 'bifind' function takes a predicate and a structure and returns
-- the leftmost element of the structure matching the predicate, or
-- 'Nothing' if there is no such element.
--
-- @since 4.10.0.0
bifind :: Bifoldable t => (a -> Bool) -> t a a -> Maybe a
bifind p = getFirst . bifoldMap finder finder
where finder x = First (if p x then Just x else Nothing)
| sdiehl/ghc | libraries/base/Data/Bifoldable.hs | bsd-3-clause | 13,417 | 0 | 14 | 3,222 | 3,555 | 1,949 | 1,606 | 168 | 2 |
{-# LANGUAGE TypeFamilies #-}
module T17067 where
import Data.Kind
data family D1 a
data family D2 :: Type -> Type
type family F a
type instance F (D1 a) = a
type instance F (D2 a) = a
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T17067.hs | bsd-3-clause | 188 | 0 | 6 | 41 | 64 | 40 | 24 | -1 | -1 |
#!/usr/bin/env stack
-- stack --install-ghc runghc --package=shake --package=extra --package=zip-archive --package=mime-types --package=http-types --package=http-conduit --package=text --package=conduit-combinators --package=conduit --package=case-insensitive --package=aeson --package=zlib --package executable-path
{-# OPTIONS_GHC -Wall -Werror #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Applicative
import Control.Exception
import Control.Monad
import qualified Data.ByteString.Char8 as S8
import qualified Data.ByteString.Lazy.Char8 as L8
import Data.List
import Data.Maybe
import Distribution.PackageDescription.Parse
import Distribution.Text
import Distribution.System
import Distribution.Package
import Distribution.PackageDescription hiding (options)
import Distribution.Verbosity
import System.Console.GetOpt
import System.Environment
import System.Directory
import System.IO.Error
import System.Process
import qualified Codec.Archive.Zip as Zip
import qualified Codec.Compression.GZip as GZip
import Data.Aeson
import qualified Data.CaseInsensitive as CI
import Data.Conduit
import qualified Data.Conduit.Combinators as CC
import Data.List.Extra
import qualified Data.Text as T
import Development.Shake
import Development.Shake.FilePath
import Network.HTTP.Conduit
import Network.HTTP.Types
import Network.Mime
import System.Environment.Executable
-- | Entrypoint.
main :: IO ()
main =
shakeArgsWith
shakeOptions { shakeFiles = releaseDir
, shakeVerbosity = Chatty
, shakeChange = ChangeModtimeAndDigestInput }
options $
\flags args -> do
gStackPackageDescription <-
packageDescription <$> readPackageDescription silent "stack.cabal"
gGithubAuthToken <- lookupEnv githubAuthTokenEnvVar
gGitRevCount <- length . lines <$> readProcess "git" ["rev-list", "HEAD"] ""
gGitSha <- trim <$> readProcess "git" ["rev-parse", "HEAD"] ""
gHomeDir <- getHomeDirectory
RunGHC gScriptPath <- getScriptPath
let gGpgKey = "9BEFB442"
gAllowDirty = False
gGithubReleaseTag = Nothing
Platform arch _ = buildPlatform
gArch = arch
gBinarySuffix = ""
gLocalInstallRoot = "" -- Set to real value below.
gProjectRoot = "" -- Set to real value velow.
global0 = foldl (flip id) Global{..} flags
-- Need to get paths after options since the '--arch' argument can effect them.
localInstallRoot' <- getStackPath global0 "local-install-root"
projectRoot' <- getStackPath global0 "project-root"
let global = global0
{ gLocalInstallRoot = localInstallRoot'
, gProjectRoot = projectRoot' }
return $ Just $ rules global args
where
getStackPath global path = do
out <- readProcess stackProgName (stackArgs global ++ ["path", "--" ++ path]) ""
return $ trim $ fromMaybe out $ stripPrefix (path ++ ":") out
-- | Additional command-line options.
options :: [OptDescr (Either String (Global -> Global))]
options =
[ Option "" [gpgKeyOptName]
(ReqArg (\v -> Right $ \g -> g{gGpgKey = v}) "USER-ID")
"GPG user ID to sign distribution package with."
, Option "" [allowDirtyOptName] (NoArg $ Right $ \g -> g{gAllowDirty = True})
"Allow a dirty working tree for release."
, Option "" [githubAuthTokenOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubAuthToken = Just v}) "TOKEN")
("Github personal access token (defaults to " ++
githubAuthTokenEnvVar ++
" environment variable).")
, Option "" [githubReleaseTagOptName]
(ReqArg (\v -> Right $ \g -> g{gGithubReleaseTag = Just v}) "TAG")
"Github release tag to upload to."
, Option "" [archOptName]
(ReqArg
(\v -> case simpleParse v of
Nothing -> Left $ "Unknown architecture in --arch option: " ++ v
Just arch -> Right $ \g -> g{gArch = arch})
"ARCHITECTURE")
"Architecture to build (e.g. 'i386' or 'x86_64')."
, Option "" [binarySuffixOptName]
(ReqArg (\v -> Right $ \g -> g{gBinarySuffix = v}) "SUFFIX")
"Extra suffix to add to binary executable archive filename." ]
-- | Shake rules.
rules :: Global -> [String] -> Rules ()
rules global@Global{..} args = do
case args of
[] -> error "No wanted target(s) specified."
_ -> want args
phony releasePhony $ do
need [checkPhony]
need [uploadPhony]
phony cleanPhony $
removeFilesAfter releaseDir ["//*"]
phony checkPhony $
need [releaseCheckDir </> binaryExeFileName]
phony uploadPhony $
mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryFileNames
phony buildPhony $
mapM_ (\f -> need [releaseDir </> f]) binaryFileNames
forM_ distros $ \distro -> do
phony (distroUploadPhony distro) $
mapM_
(\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro <.> uploadExt])
(distroVersions distro)
phony (distroPackagesPhony distro) $
mapM_
(\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro])
(distroVersions distro)
releaseDir </> "*" <.> uploadExt %> \out -> do
need [dropExtension out]
uploadToGithubRelease global (dropExtension out)
copyFile' (dropExtension out) out
releaseCheckDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackOrigExeFileName]
Stdout dirty <- cmd "git status --porcelain"
when (not gAllowDirty && not (null (trim dirty))) $
error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.")
let instExeFile = installBinDir </> stackOrigExeFileName
tmpExeFile = installBinDir </> stackOrigExeFileName <.> "tmp"
--EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file.
liftIO $ renameFile instExeFile tmpExeFile
actionFinally
(do opt <- addPath [installBinDir] []
() <- cmd opt stackProgName (stackArgs global) "build"
() <- cmd opt stackProgName (stackArgs global) "clean"
() <- cmd opt stackProgName (stackArgs global) "build --pedantic"
() <- cmd opt stackProgName (stackArgs global) "test --flag stack:integration-tests"
return ())
(renameFile tmpExeFile instExeFile)
copyFileChanged (installBinDir </> stackOrigExeFileName) out
releaseDir </> binaryExeZipFileName %> \out -> do
need [releaseDir </> binaryExeFileName]
putNormal $ "zip " ++ (releaseDir </> binaryExeFileName)
liftIO $ do
entry <- Zip.readEntry [] (releaseDir </> binaryExeFileName)
let entry' = entry{Zip.eRelativePath = binaryExeFileName}
archive = Zip.addEntryToArchive entry' Zip.emptyArchive
L8.writeFile out (Zip.fromArchive archive)
releaseDir </> binaryExeGzFileName %> \out -> do
need [releaseDir </> binaryExeFileName]
putNormal $ "gzip " ++ (releaseDir </> binaryExeFileName)
liftIO $ do
fc <- L8.readFile (releaseDir </> binaryExeFileName)
L8.writeFile out $ GZip.compress fc
releaseDir </> binaryExeFileName %> \out -> do
need [installBinDir </> stackOrigExeFileName]
case platformOS of
Windows ->
-- Windows doesn't have or need a 'strip' command, so skip it.
liftIO $ copyFile (installBinDir </> stackOrigExeFileName) out
Linux ->
cmd "strip -p --strip-unneeded --remove-section=.comment -o"
[out, installBinDir </> stackOrigExeFileName]
_ ->
cmd "strip -o"
[out, installBinDir </> stackOrigExeFileName]
releaseDir </> binaryExeCompressedAscFileName %> \out -> do
need [out -<.> ""]
_ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out)
cmd "gpg --detach-sig --armor"
[ "-u", gGpgKey
, dropExtension out ]
installBinDir </> stackOrigExeFileName %> \_ -> do
alwaysRerun
cmd stackProgName (stackArgs global) "build"
forM_ distros $ \distro0 -> do
distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 <.> uploadExt %> \out -> do
let dv@DistroVersion{..} = distroVersionFromPath out
need [dropExtension out]
uploadPackage (distroPackageExt dvDistro) dv (dropExtension out)
copyFileChanged (dropExtension out) out
distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 %> \out -> do
alwaysRerun
let dv@DistroVersion{..} = distroVersionFromPath out
need [distroVersionDir dv </> imageIDFileName]
liftIO $ createDirectoryIfMissing True (takeDirectory out)
cmd "docker run --rm"
[ "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-root" ++
":/mnt/stack-root"
, "--env=STACK_ROOT=/mnt/stack-root"
, "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-work" ++
":/mnt/src/.stack-work"
, "--volume=" ++ gProjectRoot ++ ":/mnt/src"
, "--workdir=/mnt/src"
, "--volume=" ++ gProjectRoot </> distroVersionDir dv ++ ":/mnt/out"
, "--env=OUTPUT_PKG=/mnt/out/" ++ distroPackageFileName dvDistro
, "--env=PKG_VERSION=" ++ distroPackageVersionStr dvDistro
, "--env=PKG_MAINTAINER=" ++ maintainer gStackPackageDescription
, "--env=PKG_DESCRIPTION=" ++ synopsis gStackPackageDescription
, "--env=PKG_LICENSE=" ++ display (license gStackPackageDescription)
, "--env=PKG_URL=" ++ homepage gStackPackageDescription
, distroVersionDockerImageTag dv ]
distroVersionDir anyDistroVersion </> imageIDFileName %> \out -> do
alwaysRerun
let dv@DistroVersion{..} = distroVersionFromPath out
imageTag = distroVersionDockerImageTag dv
need
[ distroVersionDockerDir dv </> "Dockerfile"
, distroVersionDockerDir dv </> "run.sh" ]
_ <- buildDockerImage (distroVersionDockerDir dv) imageTag out
return ()
distroVersionDockerDir anyDistroVersion </> "Dockerfile" %> \out -> do
let DistroVersion{..} = distroVersionFromPath out
template <- readTemplate (distroPackageExt dvDistro </> "docker/Dockerfile")
writeFileChanged out $
replace "<<DISTRO-VERSION>>" dvVersion $
replace "<<DISTRO>>" dvDistro template
distroVersionDockerDir anyDistroVersion </> "run.sh" %> \out -> do
let DistroVersion{..} = distroVersionFromPath out
writeFileChanged out =<< readTemplate (distroPackageExt dvDistro </> "docker/run.sh")
where
distroVersionFromPath path =
case stripPrefix (releaseDir ++ "/") path of
Nothing -> error ("Cannot determine Ubuntu version from path: " ++ path)
Just path' -> DistroVersion (takeDirectory1 path') (takeDirectory1 (dropDirectory1 path'))
readTemplate path =
readFile' (takeDirectory gScriptPath </> "templates" </> path)
releasePhony = "release"
checkPhony = "check"
uploadPhony = "upload"
cleanPhony = "clean"
buildPhony = "build"
distroPackagesPhony distro = distro ++ "-packages"
distroUploadPhony distro = distro ++ "-upload"
releaseCheckDir = releaseDir </> "check"
installBinDir = gLocalInstallRoot </> "bin"
distroVersionDockerDir dv = distroVersionDir dv </> "docker"
distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion
stackOrigExeFileName = stackProgName <.> exe
binaryFileNames = [binaryExeCompressedFileName, binaryExeCompressedAscFileName]
binaryExeCompressedAscFileName = binaryExeCompressedFileName <.> ascExt
binaryExeCompressedFileName =
case platformOS of
Windows -> binaryExeZipFileName
_ -> binaryExeGzFileName
binaryExeZipFileName = binaryExeFileNameNoExt <.> zipExt
binaryExeGzFileName = binaryExeFileName <.> gzExt
binaryExeFileName = binaryExeFileNameNoExt <.> exe
binaryExeFileNameNoExt = binaryName global
distroPackageFileName distro
| distroPackageExt distro == debExt =
concat [stackProgName, "_", distroPackageVersionStr distro, "_amd64"] <.> debExt
| distroPackageExt distro == rpmExt =
concat [stackProgName, "-", distroPackageVersionStr distro] <.> "x86_64" <.> rpmExt
| otherwise = error ("distroPackageFileName: unknown extension: " ++ distroPackageExt distro)
imageIDFileName = "image-id"
zipExt = "zip"
gzExt = "gz"
ascExt = "asc"
uploadExt = "upload"
debExt = "deb"
rpmExt = "rpm"
distroVersionDockerImageTag DistroVersion{..} =
"stack_release_tool/" ++ dvDistro ++ ":" ++ dvVersion
distroPackageVersionStr distro
| distroPackageExt distro == debExt =
concat [stackVersionStr global, "-", show gGitRevCount, "-", gGitSha]
| distroPackageExt distro == rpmExt =
concat [stackVersionStr global, "_", show gGitRevCount, "_", gGitSha]
| otherwise = error ("distroPackageVersionStr: unknown extension: " ++ distroPackageExt distro)
distroPackageExt distro
| distro `elem` [ubuntuDistro, debianDistro] = debExt
| distro `elem` [centosDistro, fedoraDistro] = rpmExt
| otherwise = error ("distroPackageExt: unknown distro: " ++ distro)
distroVersions distro
| distro == ubuntuDistro =
[ ("12.04", "precise")
, ("14.04", "trusty")
, ("14.10", "utopic")
, ("15.04", "vivid") ]
| distro == debianDistro =
[ ("7", "wheezy")
, ("8", "jessie") ]
| distro == centosDistro =
[ ("7", "7")
, ("6", "6") ]
| distro == fedoraDistro =
[ ("20", "20")
, ("21", "21")
, ("22", "22") ]
| otherwise = error ("distroVersions: unknown distro: " ++ distro)
distroVersionCodeName DistroVersion{..} =
fromMaybe
("distroVersionCodeName: unknown " ++ dvDistro ++ " version: " ++ dvVersion)
(lookup dvVersion (distroVersions dvDistro))
distros =
[ ubuntuDistro
, debianDistro
, centosDistro
, fedoraDistro ]
ubuntuDistro = "ubuntu"
debianDistro = "debian"
centosDistro = "centos"
fedoraDistro = "fedora"
anyDistroVersion = DistroVersion "*" "*"
anyDistroVersion' distro = DistroVersion distro "*"
uploadPackage :: String -> DistroVersion -> FilePath -> Action ()
uploadPackage ext dv@DistroVersion{..} pkgFile
| ext == debExt =
cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions"
[ "--sign=" ++ gGpgKey
, "--prefix=" ++ dvDistro ++ "/" ++ distroVersionCodeName dv
, pkgFile ]
| ext == rpmExt = do
let rpmmacrosFile = gHomeDir </> ".rpmmacros"
rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile
when rpmmacrosExists $
error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.")
actionFinally
(do writeFileLines rpmmacrosFile
[ "%_signature gpg"
, "%_gpg_name " ++ gGpgKey ]
cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com"
[ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion
, pkgFile ])
(liftIO $ removeFile rpmmacrosFile)
| otherwise = error ("uploadPackage: unknown extension: " ++ ext)
-- | Upload file to Github release.
uploadToGithubRelease :: Global -> FilePath -> Action ()
uploadToGithubRelease global@Global{..} file = do
putNormal $ "Uploading to Github: " ++ file
GithubRelease{..} <- getGithubRelease
resp <- liftIO $ callGithubApi global
[(CI.mk $ S8.pack "Content-Type", defaultMimeLookup (T.pack file))]
(Just file)
(replace
"{?name}"
("?name=" ++ S8.unpack (urlEncode True (S8.pack (takeFileName file))))
relUploadUrl)
case eitherDecode resp of
Left e -> error ("Could not parse Github asset upload response (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right (GithubReleaseAsset{..}) ->
when (assetState /= "uploaded") $
error ("Invalid asset state after Github asset upload: " ++ assetState)
where
getGithubRelease = do
releases <- getGithubReleases
let tag = fromMaybe ("v" ++ stackVersionStr global) gGithubReleaseTag
return $ fromMaybe
(error ("Could not find Github release with tag '" ++ tag ++ "'.\n" ++
"Use --" ++ githubReleaseTagOptName ++ " option to specify a different tag."))
(find (\r -> relTagName r == tag) releases)
getGithubReleases = do
resp <- liftIO $ callGithubApi global
[] Nothing "https://api.github.com/repos/commercialhaskell/stack/releases"
case eitherDecode resp of
Left e -> error ("Could not parse Github releases (" ++ e ++ "):\n" ++ L8.unpack resp ++ "\n")
Right r -> return r
-- | Make a request to the Github API and return the response.
callGithubApi :: Global -> RequestHeaders -> Maybe FilePath -> String -> IO L8.ByteString
callGithubApi Global{..} headers mpostFile url = do
req0 <- parseUrl url
let authToken =
fromMaybe
(error $
"Github auth token required.\n" ++
"Use " ++ githubAuthTokenEnvVar ++ " environment variable\n" ++
"or --" ++ githubAuthTokenOptName ++ " option to specify.")
gGithubAuthToken
req1 =
req0
{ checkStatus = \_ _ _ -> Nothing
, requestHeaders =
[ (CI.mk $ S8.pack "Authorization", S8.pack $ "token " ++ authToken)
, (CI.mk $ S8.pack "User-Agent", S8.pack "commercialhaskell/stack") ] ++
headers }
req <- case mpostFile of
Nothing -> return req1
Just postFile -> do
lbs <- L8.readFile postFile
return $ req1
{ method = S8.pack "POST"
, requestBody = RequestBodyLBS lbs }
withManager $ \manager -> do
res <- http req manager
responseBody res $$+- CC.sinkLazy
-- | Build a Docker image and write its ID to a file if changed.
buildDockerImage :: FilePath -> String -> FilePath -> Action String
buildDockerImage buildDir imageTag out = do
alwaysRerun
() <- cmd "docker build" ["--tag=" ++ imageTag, buildDir]
(Stdout imageIdOut) <- cmd "docker inspect --format={{.Id}}" [imageTag]
writeFileChanged out imageIdOut
return (trim imageIdOut)
-- | Name of the release binary (e.g. @stack-x.y.x-arch-os@)
binaryName :: Global -> String
binaryName global@Global{..} =
concat
[ stackProgName
, "-"
, stackVersionStr global
, "-"
, platformName global
, if null gBinarySuffix then "" else "-" ++ gBinarySuffix ]
-- | String representation of stack package version.
stackVersionStr :: Global -> String
stackVersionStr =
display . pkgVersion . package . gStackPackageDescription
-- | Name of current platform.
platformName :: Global -> String
platformName Global{..} =
display (Platform gArch platformOS)
-- | Current operating system.
platformOS :: OS
platformOS =
let Platform _ os = buildPlatform
in os
-- | Directory in which to store build and intermediate files.
releaseDir :: FilePath
releaseDir = "_release"
-- | @GITHUB_AUTH_TOKEN@ environment variale name.
githubAuthTokenEnvVar :: String
githubAuthTokenEnvVar = "GITHUB_AUTH_TOKEN"
-- | @--github-auth-token@ command-line option name.
githubAuthTokenOptName :: String
githubAuthTokenOptName = "github-auth-token"
-- | @--github-release-tag@ command-line option name.
githubReleaseTagOptName :: String
githubReleaseTagOptName = "github-release-tag"
-- | @--gpg-key@ command-line option name.
gpgKeyOptName :: String
gpgKeyOptName = "gpg-key"
-- | @--allow-dirty@ command-line option name.
allowDirtyOptName :: String
allowDirtyOptName = "allow-dirty"
-- | @--arch@ command-line option name.
archOptName :: String
archOptName = "arch"
-- | @--binary-suffix@ command-line option name.
binarySuffixOptName :: String
binarySuffixOptName = "binary-suffix"
-- | Arguments to pass to all 'stack' invocations.
stackArgs :: Global -> [String]
stackArgs Global{..} = ["--arch=" ++ display gArch]
-- | Name of the 'stack' program.
stackProgName :: FilePath
stackProgName = "stack"
-- | Linux distribution/version combination.
data DistroVersion = DistroVersion
{ dvDistro :: !String
, dvVersion :: !String }
-- | A Github release, as returned by the Github API.
data GithubRelease = GithubRelease
{ relUploadUrl :: !String
, relTagName :: !String }
deriving (Show)
instance FromJSON GithubRelease where
parseJSON = withObject "GithubRelease" $ \o ->
GithubRelease
<$> o .: T.pack "upload_url"
<*> o .: T.pack "tag_name"
-- | A Github release asset, as returned by the Github API.
data GithubReleaseAsset = GithubReleaseAsset
{ assetState :: !String }
deriving (Show)
instance FromJSON GithubReleaseAsset where
parseJSON = withObject "GithubReleaseAsset" $ \o ->
GithubReleaseAsset
<$> o .: T.pack "state"
-- | Global values and options.
data Global = Global
{ gStackPackageDescription :: !PackageDescription
, gLocalInstallRoot :: !FilePath
, gGpgKey :: !String
, gAllowDirty :: !Bool
, gGithubAuthToken :: !(Maybe String)
, gGithubReleaseTag :: !(Maybe String)
, gGitRevCount :: !Int
, gGitSha :: !String
, gProjectRoot :: !FilePath
, gHomeDir :: !FilePath
, gScriptPath :: !FilePath
, gArch :: !Arch
, gBinarySuffix :: !String }
deriving (Show)
| chreekat/stack | scripts/release/release.hs | bsd-3-clause | 22,652 | 104 | 24 | 6,078 | 5,088 | 2,637 | 2,451 | 495 | 6 |
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2010
--
-- The Session type and related functionality
--
-- -----------------------------------------------------------------------------
module GhcMonad (
-- * 'Ghc' monad stuff
GhcMonad(..),
Ghc(..),
GhcT(..), liftGhcT,
reflectGhc, reifyGhc,
getSessionDynFlags,
liftIO,
Session(..), withSession, modifySession, withTempSession,
-- ** Warnings
logWarnings, printException,
WarnErrLogger, defaultWarnErrLogger
) where
import MonadUtils
import HscTypes
import DynFlags
import Exception
import ErrUtils
import Data.IORef
-- -----------------------------------------------------------------------------
-- | A monad that has all the features needed by GHC API calls.
--
-- In short, a GHC monad
--
-- - allows embedding of IO actions,
--
-- - can log warnings,
--
-- - allows handling of (extensible) exceptions, and
--
-- - maintains a current session.
--
-- If you do not use 'Ghc' or 'GhcT', make sure to call 'GHC.initGhcMonad'
-- before any call to the GHC API functions can occur.
--
class (Functor m, MonadIO m, ExceptionMonad m, HasDynFlags m) => GhcMonad m where
getSession :: m HscEnv
setSession :: HscEnv -> m ()
-- | Call the argument with the current session.
withSession :: GhcMonad m => (HscEnv -> m a) -> m a
withSession f = getSession >>= f
-- | Grabs the DynFlags from the Session
getSessionDynFlags :: GhcMonad m => m DynFlags
getSessionDynFlags = withSession (return . hsc_dflags)
-- | Set the current session to the result of applying the current session to
-- the argument.
modifySession :: GhcMonad m => (HscEnv -> HscEnv) -> m ()
modifySession f = do h <- getSession
setSession $! f h
withSavedSession :: GhcMonad m => m a -> m a
withSavedSession m = do
saved_session <- getSession
m `gfinally` setSession saved_session
-- | Call an action with a temporarily modified Session.
withTempSession :: GhcMonad m => (HscEnv -> HscEnv) -> m a -> m a
withTempSession f m =
withSavedSession $ modifySession f >> m
-- -----------------------------------------------------------------------------
-- | A monad that allows logging of warnings.
logWarnings :: GhcMonad m => WarningMessages -> m ()
logWarnings warns = do
dflags <- getSessionDynFlags
liftIO $ printOrThrowWarnings dflags warns
-- -----------------------------------------------------------------------------
-- | A minimal implementation of a 'GhcMonad'. If you need a custom monad,
-- e.g., to maintain additional state consider wrapping this monad or using
-- 'GhcT'.
newtype Ghc a = Ghc { unGhc :: Session -> IO a }
-- | The Session is a handle to the complete state of a compilation
-- session. A compilation session consists of a set of modules
-- constituting the current program or library, the context for
-- interactive evaluation, and various caches.
data Session = Session !(IORef HscEnv)
instance Functor Ghc where
fmap f m = Ghc $ \s -> f `fmap` unGhc m s
instance Applicative Ghc where
pure = return
g <*> m = do f <- g; a <- m; return (f a)
instance Monad Ghc where
return a = Ghc $ \_ -> return a
m >>= g = Ghc $ \s -> do a <- unGhc m s; unGhc (g a) s
instance MonadIO Ghc where
liftIO ioA = Ghc $ \_ -> ioA
instance MonadFix Ghc where
mfix f = Ghc $ \s -> mfix (\x -> unGhc (f x) s)
instance ExceptionMonad Ghc where
gcatch act handle =
Ghc $ \s -> unGhc act s `gcatch` \e -> unGhc (handle e) s
gmask f =
Ghc $ \s -> gmask $ \io_restore ->
let
g_restore (Ghc m) = Ghc $ \s -> io_restore (m s)
in
unGhc (f g_restore) s
instance HasDynFlags Ghc where
getDynFlags = getSessionDynFlags
instance GhcMonad Ghc where
getSession = Ghc $ \(Session r) -> readIORef r
setSession s' = Ghc $ \(Session r) -> writeIORef r s'
-- | Reflect a computation in the 'Ghc' monad into the 'IO' monad.
--
-- You can use this to call functions returning an action in the 'Ghc' monad
-- inside an 'IO' action. This is needed for some (too restrictive) callback
-- arguments of some library functions:
--
-- > libFunc :: String -> (Int -> IO a) -> IO a
-- > ghcFunc :: Int -> Ghc a
-- >
-- > ghcFuncUsingLibFunc :: String -> Ghc a -> Ghc a
-- > ghcFuncUsingLibFunc str =
-- > reifyGhc $ \s ->
-- > libFunc $ \i -> do
-- > reflectGhc (ghcFunc i) s
--
reflectGhc :: Ghc a -> Session -> IO a
reflectGhc m = unGhc m
-- > Dual to 'reflectGhc'. See its documentation.
reifyGhc :: (Session -> IO a) -> Ghc a
reifyGhc act = Ghc $ act
-- -----------------------------------------------------------------------------
-- | A monad transformer to add GHC specific features to another monad.
--
-- Note that the wrapped monad must support IO and handling of exceptions.
newtype GhcT m a = GhcT { unGhcT :: Session -> m a }
liftGhcT :: Monad m => m a -> GhcT m a
liftGhcT m = GhcT $ \_ -> m
instance Functor m => Functor (GhcT m) where
fmap f m = GhcT $ \s -> f `fmap` unGhcT m s
instance Applicative m => Applicative (GhcT m) where
pure x = GhcT $ \_ -> pure x
g <*> m = GhcT $ \s -> unGhcT g s <*> unGhcT m s
instance Monad m => Monad (GhcT m) where
return x = GhcT $ \_ -> return x
m >>= k = GhcT $ \s -> do a <- unGhcT m s; unGhcT (k a) s
instance MonadIO m => MonadIO (GhcT m) where
liftIO ioA = GhcT $ \_ -> liftIO ioA
instance ExceptionMonad m => ExceptionMonad (GhcT m) where
gcatch act handle =
GhcT $ \s -> unGhcT act s `gcatch` \e -> unGhcT (handle e) s
gmask f =
GhcT $ \s -> gmask $ \io_restore ->
let
g_restore (GhcT m) = GhcT $ \s -> io_restore (m s)
in
unGhcT (f g_restore) s
instance (Functor m, ExceptionMonad m, MonadIO m) => HasDynFlags (GhcT m) where
getDynFlags = getSessionDynFlags
instance (Functor m, ExceptionMonad m, MonadIO m) => GhcMonad (GhcT m) where
getSession = GhcT $ \(Session r) -> liftIO $ readIORef r
setSession s' = GhcT $ \(Session r) -> liftIO $ writeIORef r s'
-- | Print the error message and all warnings. Useful inside exception
-- handlers. Clears warnings after printing.
printException :: GhcMonad m => SourceError -> m ()
printException err = do
dflags <- getSessionDynFlags
liftIO $ printBagOfErrors dflags (srcErrorMessages err)
-- | A function called to log warnings and errors.
type WarnErrLogger = forall m. GhcMonad m => Maybe SourceError -> m ()
defaultWarnErrLogger :: WarnErrLogger
defaultWarnErrLogger Nothing = return ()
defaultWarnErrLogger (Just e) = printException e
| spacekitteh/smcghc | compiler/main/GhcMonad.hs | bsd-3-clause | 6,878 | 0 | 18 | 1,622 | 1,740 | 913 | 827 | 106 | 1 |
-- Dummny LeftistHeap module
module LeftistHeap where
import Sequence
data Heap a
maxElem :: Ord a => Heap a -> a
maxElem = undefined
null :: Ord a => Heap a -> Bool
null = undefined
delete :: Ord a => a -> Heap a -> Heap a
delete = undefined
insert :: Ord a => a -> Heap a -> Heap a
insert = undefined
empty :: Ord a => Heap a
empty = undefined
deleteMax :: Ord a => Heap a -> Heap a
deleteMax = undefined
toSeq :: (Ord a, Sequence seq) => Heap a -> seq a
toSeq = undefined
filter :: Ord a => (a -> Bool) -> Heap a -> Heap a
filter = undefined
| forste/haReFork | tools/base/tests/GhcLibraries/LeftistHeap.hs | bsd-3-clause | 554 | 0 | 8 | 130 | 242 | 123 | 119 | -1 | -1 |
module LiftToToplevel.NoWhere where
liftToTopLevel' modName pn = do
renamed <- getRefactRenamed
return []
where
{-step1: divide the module's top level declaration list into three parts:
'parent' is the top level declaration containing the lifted declaration,
'before' and `after` are those declarations before and after 'parent'.
step2: get the declarations to be lifted from parent, bind it to liftedDecls
step3: remove the lifted declarations from parent and extra arguments may be introduce.
step4. test whether there are any names need to be renamed.
-}
liftToMod = ['a'] -- do
getRefactRenamed :: IO String
getRefactRenamed = undefined
| RefactoringTools/HaRe | test/testdata/LiftToToplevel/NoWhere.hs | bsd-3-clause | 718 | 0 | 8 | 172 | 56 | 30 | 26 | 7 | 1 |
{-# OPTIONS_GHC -fdefer-type-errors #-} -- Very important to this bug!
{-# Language PartialTypeSignatures #-}
{-# Language TypeFamilyDependencies, KindSignatures #-}
{-# Language PolyKinds #-}
{-# Language DataKinds #-}
{-# Language TypeFamilies #-}
{-# Language RankNTypes #-}
{-# Language NoImplicitPrelude #-}
{-# Language FlexibleContexts #-}
{-# Language MultiParamTypeClasses #-}
{-# Language GADTs #-}
{-# Language ConstraintKinds #-}
{-# Language FlexibleInstances #-}
{-# Language TypeOperators #-}
{-# Language ScopedTypeVariables #-}
{-# Language DefaultSignatures #-}
{-# Language FunctionalDependencies #-}
{-# Language UndecidableSuperClasses #-}
{-# Language UndecidableInstances #-}
{-# Language AllowAmbiguousTypes #-}
{-# Language InstanceSigs, TypeApplications #-}
module T14584 where
import Data.Monoid
import Data.Kind
data family Sing (a::k)
class SingKind k where
type Demote k = (res :: Type) | res -> k
fromSing :: Sing (a::k) -> Demote k
class SingI (a::k) where
sing :: Sing a
data ACT :: Type -> Type -> Type
data MHOM :: Type -> Type -> Type
type m %%- a = ACT m a -> Type
type m %%-> m' = MHOM m m' -> Type
class Monoid m => Action (act :: m %%- a) where
act :: m -> (a -> a)
class (Monoid m, Monoid m') => MonHom (mhom :: m %%-> m') where
monHom :: m -> m'
data MonHom_Distributive m :: (m %%- a) -> (a %%-> a)
type Good k = (Demote k ~ k, SingKind k)
instance (Action act, Monoid a, Good m) => MonHom (MonHom_Distributive m act :: a %%-> a) where
monHom :: a -> a
monHom = act @_ @_ @act (fromSing @m (sing @m @a :: Sing _))
| sdiehl/ghc | testsuite/tests/partial-sigs/should_fail/T14584.hs | bsd-3-clause | 1,593 | 31 | 10 | 298 | 419 | 238 | 181 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables, PatternSynonyms, DataKinds, PolyKinds,
GADTs, TypeOperators, TypeFamilies #-}
module T13441 where
import Data.Functor.Identity
data FList f xs where
FNil :: FList f '[]
(:@) :: f x -> FList f xs -> FList f (x ': xs)
data Nat = Zero | Succ Nat
type family Length (xs :: [k]) :: Nat where
Length '[] = Zero
Length (_ ': xs) = Succ (Length xs)
type family Replicate (n :: Nat) (x :: a) = (r :: [a]) where
Replicate Zero _ = '[]
Replicate (Succ n) x = x ': Replicate n x
type Vec n a = FList Identity (Replicate n a)
-- Using explicitly-bidirectional pattern
pattern (:>) :: forall n a. n ~ Length (Replicate n a)
=> forall m. n ~ Succ m
=> a -> Vec m a -> Vec n a
pattern x :> xs <- Identity x :@ xs
where
x :> xs = Identity x :@ xs
-- Using implicitly-bidirectional pattern
pattern (:>>) :: forall n a. n ~ Length (Replicate n a)
=> forall m. n ~ Succ m
=> a -> Vec m a -> Vec n a
pattern x :>> xs = Identity x :@ xs
| shlevy/ghc | testsuite/tests/patsyn/should_compile/T13441.hs | bsd-3-clause | 1,051 | 0 | 12 | 301 | 428 | 231 | 197 | -1 | -1 |
-- Trac #2931
module Foo where
a = 1
-- NB: no newline after the 'a'!
b = 'a
| urbanslug/ghc | testsuite/tests/quotes/T2931.hs | bsd-3-clause | 79 | 0 | 4 | 21 | 17 | 12 | 5 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
{-# LANGUAGE FlexibleContexts #-}
module T4398 where
{-# RULES "suspicious" forall (x :: a) y. f (x :: Ord a => a) y = g x y #-}
{-# NOINLINE f #-}
f :: a -> a -> Bool
f x y = True
g :: Ord a => a -> a -> Bool
g = (<)
| urbanslug/ghc | testsuite/tests/simplCore/should_compile/T4398.hs | bsd-3-clause | 276 | 0 | 7 | 67 | 58 | 34 | 24 | 9 | 1 |
{-# OPTIONS -XRecursiveDo #-}
-- OLD: mdo requires MonadFix instance, even
-- if no recursion is present
-- Dec 2010: Small change of behaviour
-- MonadFix is only required if recursion is present
module Main (main) where
import Control.Monad.Fix
import Control.Applicative (Applicative(..))
import Control.Monad (liftM, ap)
data X a = X a deriving Show
instance Functor X where
fmap = liftM
instance Applicative X where
pure = return
(<*>) = ap
instance Monad X where
return = X
(X a) >>= f = f a
z :: X [Int]
z = mdo { a <- return 1; return [a] }
main = print z
| urbanslug/ghc | testsuite/tests/mdo/should_fail/mdofail004.hs | bsd-3-clause | 605 | 0 | 8 | 145 | 172 | 99 | 73 | -1 | -1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
module GHCJS.DOMDelegator.Internal where
import Language.Haskell.TH.Quote
import GHCJS.Foreign.QQ
import GHCJS.Types
foreign import javascript unsafe "h$domDelegator.addEvent($1,$2,$3)"
js_add_event :: JSRef a -> JSString -> JSFun (JSRef b -> IO c) -> IO ()
foreign import javascript unsafe "h$domDelegator.DOMDelegator()"
js_dom_delegator :: IO (JSRef a)
foreign import javascript unsafe "h$domDelegator.Delegator($1)"
js_delegator :: JSRef a -> IO (JSRef b)
foreign import javascript unsafe "h$domDelegator.ProxyEvent($1)"
js_proxy_event :: JSRef a -> IO (JSRef b)
foreign import javascript unsafe "h$domDelegator.removeEvent($1,$2,$3)"
js_remove_event :: JSRef a -> JSString -> JSFun (JSRef b -> IO c) -> IO ()
| wavewave/ghcjs-dom-delegator | src/GHCJS/DOMDelegator/Internal.hs | mit | 810 | 15 | 8 | 118 | 209 | 109 | 100 | 16 | 0 |
-- Type.hs ---
--
-- Filename: Type.hs
-- Description:
-- Author: Manuel Schneckenreither
-- Maintainer:
-- Created: Thu Sep 4 12:19:36 2014 (+0200)
-- Version:
-- Package-Requires: ()
-- Last-Updated: Mon Apr 8 09:49:45 2019 (+0200)
-- By: Manuel Schneckenreither
-- Update #: 95
-- URL:
-- Doc URL:
-- Keywords:
-- Compatibility:
--
--
-- Commentary:
--
--
--
--
-- Change Log:
--
--
--
--
--
-- Code:
module Data.Rewriting.ARA.ByInferenceRules.CmdLineArguments.Type
( ArgumentOptions (..)
, SMTSolver (..)
) where
import qualified Data.Text as T
data SMTSolver = Z3 | MiniSMT
deriving (Show, Eq)
data ArgumentOptions = ArgumentOptions
{ filePath :: FilePath
, maxVectorLength :: Int
, minVectorLength :: Int
, uniqueConstrFuns :: Bool
, separateBaseCtr :: Bool
, noHeur :: Bool
, helpText :: Bool
, tempFilePath :: FilePath
, keepFiles :: Bool
, printInfTree :: Bool
, verbose :: Bool
, shift :: Bool
, allowLowerSCC :: Bool
, allowCf :: Bool
, lowerbound :: Bool
, lowerboundArg :: Maybe Int
, constructorArgSelection :: [(T.Text,Int)]
, lowerboundNoComplDef :: Bool
, timeout :: Maybe Int
, smtSolver :: SMTSolver
, findStrictRules :: Maybe Int
, directArgumentFilter :: Bool
, nrOfRules :: Maybe Int -- value not to set, only to pass through system
} deriving (Show, Eq)
--
-- Type.hs ends here
| ComputationWithBoundedResources/ara-inference | src/Data/Rewriting/ARA/ByInferenceRules/CmdLineArguments/Type.hs | mit | 1,696 | 0 | 11 | 609 | 269 | 184 | 85 | 31 | 0 |
module Main where
import Analys
import System.Environment
parse :: String -> ([Int], [([Int], [Int])])
parse = subParse . lines where
subParse :: [String] -> ([Int], [([Int], [Int])])
subParse (strMark : strTranses) = let
mark = read strMark
transfers = read $ concat strTranses
in (mark, transfers)
subParse xs = error "Error while parse \"" ++ xs ++ "\""
-- Input string example
-- [3, 1, 2]
-- [([0, 0], [1 ]), ([1 ], [1, 2]),([0 ], [0, 2]),([0, 2], [ ])]
-- Args example:
-- ./main --from-args "[3, 1, 2]" \
-- "[([0, 0], [1 ]), ([1 ], [1, 2]),([0 ], [0, 2]),([0, 2], [ ])]"
main :: IO ()
main = do
text <- do
args <- getArgs
case args of
"--from-args" : content -> return $ unlines content
_ -> getContents
let (mark, transfers) = parse text
putStrLn $ growAndGetInfo transfers mark
-- let mark = [1, 2]
-- let transfers = [([1, 0], [1, 1]),
-- ([1,1], [1,1])]
-- print $ findTree transfers mark
| NickolayStorm/PetriNet | main.hs | mit | 1,081 | 0 | 14 | 347 | 258 | 143 | 115 | 20 | 2 |
module TLexer (
testModule -- tests the module Lexer
)
where
-- imports --
import Test.HUnit
import InterfaceDT as IDT
import qualified Preprocessor as PreProc
import qualified Lexer
-- functions --
testLexer01 = "Proper turning: " ~: res [Constant "1"] @=? run [" \\", " \\ /-t-#", " ---/--f-#"]
testLexer02 = "Reflection: " ~: res [Constant "1"] @=? run [" \\", " \\ # # #", " \\ f f f", " \\ \\|/", " #t-------@-f#", " /|\\", " f f f", " # # #"]
testLexer03 = "Rail crash: " ~: crash @=? run [" /", "#"]
testLexer04 = "One liner: " ~: crash @=? run []
testLexer05 = "Endless loop: " ~: IDT.ILS [("main",[(1,Start,2),(2,Constant "1",3),(3,NOP,3)])] @=? run [" \\", " 1 ", " \\", " @--@"]
testLexer06 = "Junction test: " ~: IDT.ILS [("main", [(1, Start, 2), (2, Junction 3, 5), (3, Constant "1", 4), (4, Finish, 0), (5, Constant "0", 6), (6, Finish, 0)])] @=? run [" \\", " \\ /-1#", " -<", " \\-0#"]
testLexer07 = "Simple Junction test: " ~: crash @=? run [" *-1#"]
testLexer08 = "Two Junctions: " ~: IDT.ILS [("main", [(1, Start, 2), (2, Junction 3, 5), (3, Junction 4, 5), (4, Finish, 0), (5, Constant "0", 6), (6, Finish, 0)])] @=? run [" \\ --\\ -#", " \\ / \\ /", " -< --<", " \\ \\", " ---------0#"]
testLexer09 = "Merging Junctions: " ~: IDT.ILS [("main", [(1, Start, 2), (2, Junction 3, 3), (3, Finish, 0)])] @=? run [" \\ -\\", " \\ / \\", " -< -#", " \\ /", " -/"]
testLexer10 = "Push and Pop: " ~: res [Constant "1", Pop "x", Push "x"] @=? run [" \\", " --1(!x!)(x)#"]
testLexer11 = "Illegal cross Junctions: " ~: crash @=? run [" \\", " +-#"]
testLexer12 = "While: " ~: IDT.ILS [("main", [(1, Start, 2), (2, EOF, 3), (3, Junction 2, 4), (4, Finish, 0)])] @=? run [" \\ /----\\", " \\ | |", " \\ \\ /", " ---e-<", " \\-#"]
testLexer13 = "Empty Junction ends: " ~: IDT.ILS [("main",[(1, Start, 2), (2, Junction 0, 3), (3, Junction 4, 0), (4, Junction 5, 6), (5, Finish, 0), (6, Finish, 0)])] @=? run [" \\", " \\ / /--\\ /-#", " \\--< --< --<", " \\--/ \\ \\-#"]
testLexer14 = "Turning on Lexeme: " ~: crash @=? run [" \\", " \\#"]
testLexer15 = "Lambda: " ~: IDT.ILS [("main",[(1, Start, 2), (2, Lambda 3, 5), (3, Underflow, 4), (4, Finish, 0), (5, Finish, 0)])] @=? run [" \\", "#--&u#"]
testLexer16 = "Empty Lambda: " ~: IDT.ILS [("main",[(1, Start, 2), (2, Lambda 0, 3), (3, Finish, 0)])] @=? run [" \\", "#--&"]
testLexer17 = "\\\\ Escaping: " ~: res [Constant "\\"] @=? run [" \\-[\\\\]#"]
testLexer18 = "Dot Command: " ~: crash @=? run [" .", " #"]
-- helper functions
run :: [String] -> IDT.Lexer2SynAna
run grid = Lexer.process (PreProc.process (IIP (unlines ("$ 'main'":grid))))
res :: [Lexeme] -> IDT.Lexer2SynAna
res lexeme = IDT.ILS [("main", (1, Start, 2):nodes 2 lexeme)]
where
nodes i [] = [(i, Finish, 0)]
nodes i (x:xs) = (i, x, i+1):nodes (i+1) xs
crash :: IDT.Lexer2SynAna
crash = IDT.ILS [("main", [(1, Start, 0)])]
testModule = [testLexer01, testLexer02, testLexer03, testLexer04, testLexer05, testLexer06, testLexer07, testLexer08, testLexer09, testLexer10, testLexer11, testLexer12, testLexer13, testLexer14, testLexer15, testLexer16, testLexer17, testLexer18]
| SWP-Ubau-SoSe2014-Haskell/SWPSoSe14 | tests/TLexer.hs | mit | 3,372 | 0 | 13 | 823 | 1,396 | 826 | 570 | 33 | 2 |
head1 :: [a] -> a
head1 [] = error "Can't call head on an empty list, dummy!"
head1 (x:_) = x
| v0lkan/learning-haskell | session-003/006-head-1.hs | mit | 94 | 0 | 7 | 21 | 41 | 21 | 20 | 3 | 1 |
module Foster.Generator (generate) where
import Foster.Data
import Foster.Utils
import Foster.IO (writeUnsolvedPuzzle)
import Control.Monad
import System.Random
import Data.Array.IO hiding (newArray)
calcNorthId :: Size -> Int -> PieceId
calcNorthId (w, _) i =
let x = i - w
in if x >= 0
then show x
else noneId
calcEastId :: Size -> Int -> PieceId
calcEastId (w, _) i =
let x = i + 1
in if (x `mod` w) /= 0
then show x
else noneId
calcSouthId :: Size -> Int -> PieceId
calcSouthId (w, h) i =
let x = i + w
in if (x `div` w) < h
then show x
else noneId
calcWestId :: Size -> Int -> PieceId
calcWestId (w, _) i =
let x = i - 1
in if (i `mod` w) /= 0
then show x
else noneId
generatePiece :: Size -> String -> Int -> Piece
generatePiece sz s i =
let c = s !! (i `mod` length s)
in Piece
c
(show i)
(calcNorthId sz i)
(calcEastId sz i)
(calcSouthId sz i)
(calcWestId sz i)
generatePieces :: Size -> Bool -> String -> IO [Piece]
generatePieces siz@(w, h) sil str = do
let tot = w * h
ps <- mapM
(\i -> do
unless sil $ putPercOver (i + 1, tot) "Generating"
return $ generatePiece siz str i)
[0..(tot - 1)]
unless sil $ putStrLn "" >> flush
return ps
-- @todo:
-- we can probably get rid of this
-- with a total injective mapping function
-- to generate pieces already "shuffled"
shuffle :: Bool -> [a] -> IO [a]
shuffle sil xs = do
ar <- newArray n xs
es <- forM [1..n] $ \i -> do
unless sil $ putPercOver (i, n) "Shuffling"
j <- randomRIO (i,n)
vi <- readArray ar i
vj <- readArray ar j
writeArray ar j vi
return vj
unless sil $ putStrLn "" >> flush
return es
where
n = length xs
newArray :: Int -> [a] -> IO (IOArray Int a)
newArray ni = newListArray (1, ni)
generatePuzzle :: Size -> String -> Bool -> IO UnsolvedPuzzle
generatePuzzle (w, h) str sil = do
ps <- generatePieces (w, h) sil str
shuffle sil ps
generate :: Size -> String -> FilePath -> Bool -> IO ()
generate (h, w) str out sil = do
puz <- generatePuzzle (w, h) str sil
unless sil $ putPercOver (0, 1) "Saving" >> flush
writeUnsolvedPuzzle out puz
unless sil $ do
putPercOver (1, 1) "Saving" >> putStr "\n"
putStrLn $ "Generated → " ++ out
| Jefffrey/Foster | src/Foster/Generator.hs | mit | 2,455 | 30 | 16 | 776 | 1,037 | 528 | 509 | 78 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -Wno-partial-type-signatures #-}
module Oczor.Converter.Converter where
import Oczor.Utl
import Control.Monad.State
import Control.Monad.Reader
import ClassyPrelude hiding (first)
import Oczor.Infer.Substitutable
import Oczor.Syntax.Syntax as S
import qualified Oczor.Converter.CodeGenAst as A
import Oczor.Infer.InferContext as T
import Oczor.Infer.Infer
import qualified Data.List as L
-- typeFuncArity x | traceArgs ["typeFuncArity", show x] = undefined
typeFuncArity = \case
TypeFunc x _ -> typeArity x
TypeConstraints _ y -> typeFuncArity y
TypePoly _ (TypeFunc x _) -> typeArity x
_ -> 0
rootModule = A.Ident "oc"
type Converter = Reader InferContext
identWithNamespace isModule = \case
[h] | not isModule -> A.Ident h
x -> foldl' A.Field rootModule x
initObjectIfNull :: A.Ast -> A.Ast
initObjectIfNull x = A.If (A.Equal x (A.Lit A.LitNull)) [A.Set x A.emptyObject] []
initModuleIfNull moduleName = initObjectIfNull . identWithNamespace True <$> (L.tail . L.inits . L.init $ moduleName)
typeNormalizeEq = (==) `on` normalizeType
curryApply :: [A.Ast] -> Int -> A.Ast -> A.Ast
curryApply args arity func =
if hasParams then A.Function params [A.Return (A.Call func (args ++ (params <&> A.Ident)))]
else A.Call func args
where
hasParams = arity > 0
params = if hasParams then map (show >>> ("p" ++)) [1..arity] else []
instancesObject = A.Field $ A.Field rootModule "instances"
-- applyParam context x | traceArgs ["applyParam", show x] = undefined
applyParam context (TypeApply (TypeIdent ident) y) = makeType t y
where
t = context & T.lookupType ident & map fst & fromMaybe (error "applyParam")
-- findInstancesList :: String -> [TypeExpr] -> [TypeExpr] -> Maybe TypeExpr
-- findInstances context l1 l2 | traceArgs ["findInstaces", show l1, show l2] = undefined
findInstances context l1 l2 = go mempty l1 l2 & ordNub & map (\(_, x, y) -> (x, y))
where
goList vars l1 l2 = zip l1 l2 >>= uncurry (go vars)
go :: Map String [String] -> TypeExpr -> TypeExpr -> [(String, String, TypeExpr)]
-- go var x y | traceArgs ["findInstances go", show var, show x, show y] = undefined
go var x (TypeConstraints _ y) = go var x y
go var (TypeVar x) tp = (var &lookup x) & maybe [] (map (\cls -> (x, cls, tp)))
go var (TypeRecord l1) (TypeRecord l2) = goList var l1 l2
go var (TypeRecord [x]) y = go var x y
go var (TypeRow x l1) (TypeRow y l2) = goList var (l1 ++ [x]) (l2 ++ [y])
go var (TypeConstraints list x) y = go (unionWith (++) var (constraintSetToMap list)) x y
go var (TypeFunc x y) (TypeFunc x2 y2) = goList var [x,y] [x2,y2]
go var (TypeApply x y) (TypeApply x2 y2) = goList var (x:y) (x2:y2)
go var (TypeLabel x t1) (TypeLabel y t2) | x == y = go var t1 t2
go var (TypeIdent x) (TypeIdent y) | x == y = []
go var z x@(TypeApply t _) | not $ T.isFfiType t context = go var z (applyParam context x)
go var x y = error $ unwords ["findInstances", show var, show x, show y]
-- instanceIdent cls tp exprTp | traceArgs ["instanceIdent", show cls, show tp, show exprTp] = undefined
instanceIdent :: _ -> _ -> _ -> Converter A.Ast
instanceIdent cls tp exprTp = do
context <- ask
let (_, classType) = context & lookupClass cls & unsafeHead
let instanceTypeIdent = instanceTypeName tp
let instanceType = context & T.lookupInstanceType instanceTypeIdent cls & fromMaybe (error "instanceIdent") -- & trac "instaceType"
let typeConstraints = getTypeConstraints instanceType -- & trac "typeconstraints"
let expr = A.Field (instancesObject cls) instanceTypeIdent
if onull typeConstraints then return expr
else addInstancesArgs (typeFuncArity classType) expr instanceType exprTp
-- addInstancesArgs arity expr contextTp exprTp | traceArgs ["addInstacesArgs", show arity, show expr, show contextTp, show exprTp] = undefined
addInstancesArgs arity expr contextTp exprTp =
if contextTp == exprTp then return expr
else do
args <- instancesToArgs contextTp exprTp -- <&> trac "instances"
return $ if null args then expr else curryApply args arity expr
addInstancesParams :: InferExpr -> A.Ast -> Converter A.Ast
-- addInstancesParams context expr | traceArgs ["addInstacesParams", show expr] = undefined
addInstancesParams expr targetExpr = do
let clist = collectAllConstraints expr -- & trac "constraints"
let clistParam = clist & map (\(TypeVar p, cl) -> paramInstancesName p cl)
return $ if onull clistParam then targetExpr else
case targetExpr of
A.Function x y -> A.Function (clistParam ++ x) y
_ -> A.Function clistParam [A.Return targetExpr]
-- instancesToArgs context contextTp exprTp | traceArgs ["instancesToArgs", show contextTp, show exprTp] = undefined
instancesToArgs contextTp exprTp =
-- if contextTp == exprTp then return []
-- else
let classes = getTypeConstraints contextTp in
case classes of
[] -> return []
_ -> do
context <- ask
traverse go $ findInstances context contextTp exprTp
where
go (cls, TypeVar x) = return $ A.Ident $ paramInstancesName x cls
go (cls, tp) = instanceIdent cls tp tp
isLazy = getTypeIdent >>> maybe False (== "Lazy")
-- convertExprWithTypeChange tp expr | traceArgs ["convertExprWithTypeChange", show tp, show expr] = undefined
-- convertExprWithTypeChange ctx tp exprTp expr =
-- if T.isFfiType exprTp ctx then (A.Field expr "value")
-- else A.Call (A.Ident "convertExprWithTypeChange") [expr, litString $ typeString exprTp]
cloneObjectCall x = A.Call (A.Field rootModule "cloneObject") [x]
convertExprWithTypeChange tp exprTp expr
| isLazy tp = A.Call expr []
| isLazy exprTp = A.Function [] [A.Return expr]
| otherwise = expr
convertExprWithNewTypeMaybe tp exprTp expr = maybe expr (\x -> convertExprWithTypeChange tp x expr) exprTp
-- isUnionSubtype context identTp t | traceArgs ["isUnionSubtype", show identTp, show t] = undefined
isUnionSubtype context identTp t | (getTypeIdent t & isJust) && not (T.isFfiType t context) =
case context & T.lookupType (getTypeIdent t & unsafeHead) & unsafeHead & fst of
TypeUnion list -> list & any (typeNormalizeEq identTp)
TypePoly _ (TypeUnion list) -> list & any (typeNormalizeEq identTp)
_ -> False
isUnionSubtype _ _ _ = False
-- isTypeUnionOrMaker x | traceArgs ["isTypeUnionOrMaker", show x] = undefined
isTypeUnionOrMaker (TypeUnion list) = True
isTypeUnionOrMaker (TypePoly _ (TypeUnion list)) = True
isTypeUnionOrMaker _ = False
checkExprTypeChange :: _ -> _ -> _ -> Converter _
checkExprTypeChange tp exprTp expr = do
context <- ask
let typeIdentIsUnion x = getTypeIdent x & maybe False (\x -> context & T.lookupType x & unsafeHead & fst & isTypeUnionOrMaker)
return $
if exprTp == NoType || typeNormalizeEq tp exprTp || typeIdentIsUnion exprTp || hasTypeVar tp then expr
else convertExprWithTypeChange tp exprTp expr
paramInstancesName ident cls = sysPrefix ++ ident ++ cls
-- getIdentInstancesArgs ident exprTp |traceArgs ["getIdentInstancesArgs", show ident, show exprTp] = undefined
getIdentInstancesArgs ident exprTp = do
identTp <- identType ident -- <&> trac (unwords ["ident tp", ident, show exprTp] )
-- if identTp == exprTp then return []
-- else instancesToArgs identTp exprTp
foo <- view T.params
if foo & member ident then return []
else instancesToArgs identTp exprTp
-- instancesToArgs identTp exprTp
-- getTypeInstancesArgs contextTp exprTp = do
-- let classes = getTypeConstraints contextTp
-- if onull classes then return []
-- else instancesToArgs contextTp exprTp
identAddInstancesArgs ident exprTp = do
ctx <- ask
-- instancesArgs <- getIdentInstancesArgs ident exprTp
identTp <- identType ident -- <&> trac (unwords ["ident tp", ident, show exprTp] )
expr2 <- newIdent ident >>= checkExprTypeChange identTp exprTp
-- if exprTp == identTp then return expr2
-- else addInstancesArgs (typeFuncArity identTp) expr2 identTp exprTp
addInstancesArgs (typeFuncArity identTp) expr2 identTp exprTp
identType :: String -> Converter TypeExpr
identType x = do
context <- ask
return $ T.getIdentType context x & map (\(Forall _ x) -> x) & fromMaybe NoType
getTypeConstraints :: TypeExpr -> ConstraintSet
getTypeConstraints = para $ \case
TypeConstraintsF list (TypeLabel x y, _) -> []
TypeConstraintsF list x -> list <&> first fst
x -> ffold $ getResults x
getResults :: TypeExprF (a, b) -> TypeExprF b
getResults = map snd
removeResults :: TypeExprF (a, b) -> TypeExprF a
removeResults = map fst
newIdent :: String -> Converter A.Ast
newIdent ident = identWithNamespace False . (<> [ident]) . fromMaybe [] . lookup ident <$> view (openModules . identsNs)
collectAllConstraints :: InferExpr -> [(TypeExpr, String)]
-- collectAllConstraints x | traceArgs ["collectAllConstraints", pshow x] = undefined
collectAllConstraints (UnAnn RecordF {}) = []
collectAllConstraints (UnAnn RecordLabelF {}) = []
-- collectAllConstraints (UnAnn IdentF {}) = []
collectAllConstraints (UnAnn (CallF (UnAnn LabelAccessF {}) _)) = [] -- TODO why?
-- collectAllConstraints (UnAnn (LabelAccessCallF {})) = []
collectAllConstraints x = y x & ordNub
where
y = cata $ \case
-- x | traceArgs ["collect alg", show x] -> undefined
(AnnF y (x,ctx)) -> collectConstrainFromTypeExpr x ++ ffold y
convertModule ctx expr moduleName ffiCode =
A.StmtList $ initModuleIfNull moduleName ++
[A.Set (identWithNamespace True moduleName) newModuleAst]
where
moduleAst = case convert2 ctx expr of {A.None -> A.emptyObject; x -> x}
newModuleAst = case ffiCode of
Nothing -> moduleAst
Just code ->
case moduleAst of
A.Scope x y -> A.Scope (A.Code code : x) y
x -> A.Scope [A.Code code] x
-- convert2 ctx expr | traceArgs ["convert context", pshow $ ctx ^. openModules] = undefined
convert2 ctx expr = runReader (convert expr) ctx
convertPhi :: ExprF A.Ast -> Converter A.Ast
convertPhi = \case
UniqObjectF x -> return $ A.UniqObject x
ArrayF x -> return $ A.Array x
SetStmtF l r -> return $ A.Set l r
ExprTypeF {} -> return A.None
TypeDeclF {} -> return A.None
FfiTypeF {} -> return A.None
StmtF {} -> return A.None
IfF b t f -> return $ A.ConditionOperator b t f
x -> error $ unwords ["convert", show x]
convert :: InferExpr -> Converter A.Ast
convert annAst@(Ann ast (tp, ctx)) = localPut ctx $ go ast where
-- go x | traceArgs $ ["convert", show x] = undefined
go :: ExprF InferExpr -> Converter A.Ast
go = \case
IdentF ident -> identAddInstancesArgs ident tp
UpdateF expr labels -> do
temp <- convert expr
temp2 <- traverse go labels
convertUpdate ast temp temp2
where go (UnAnn (RecordLabelF label value)) = A.setField (A.Ident "_clone") label <$> convert value
FunctionF params guard body -> do
y <- convert body
convertFunction ast (Just outtp) y where TypeFunc _ outtp = tp
CasesF expr -> cases expr Nothing -- TODO add out type
LitF value -> checkExprTypeChange (inferLit value) tp (convertLit value)
RecordLabelF name expr -> (A.Object . (:[])) <$> convertRecordLabel ast
CallF {} -> convertCall annAst
RecordF list -> newScope <$> convertAstList list
ClassFnF name _ -> return $ convertClass ast
LetF e1 e2 -> do
e1Ast <- evalStateT (convertRecordToVars e1) 1
e2Ast <- convert e2
return $ newScope (partsToAsts e1Ast, e2Ast)
InstanceFnF tpName name body ->
A.setField (instancesObject name) (instanceTypeName tpName) <$> (addInstancesParams body =<< convert body)
FfiF {} -> return $ A.Object [convertFfiLabel ast]
_ -> convertPhi =<< traverse convert ast
convertUpdate :: ExprF InferExpr -> A.Ast -> [A.Ast] -> Converter A.Ast
convertUpdate (UpdateF expr labels) temp temp2 = do
let obj = A.Ident "_obj"
let objAndClone = [A.Var "_obj" temp, A.Var "_clone" (cloneObjectCall obj)]
return $ newScope (objAndClone ++ temp2, A.Ident "_clone")
-- convertRecordLabel context x | traceArgs ["convertRecordLabel", show x] = undefined
convertRecordLabel ast@(RecordLabelF name expr) = do
target <- convert expr
context <- ask
-- UNUSED let exprType = (\(S.Forall _ x) -> x) <$> T.getIdentType context name
(name, ) <$> addInstancesParams expr target
convertFfiLabel (FfiF name expr) = (name, A.Ident name)
convertFunction (FunctionF params guard body) newOutType y =
A.Function (convertFuncParams params) <$> functionBody body newOutType y
-- convertCallLabel CallF (UnAnn (LabelAccessF label)) expr -> convert expr <&> flip A.Field label
-- convertCall (Ann (CallF (UnAnn (LabelAccessF label)) (UnAnn (IdentF ident))) (exprTp,ctx)) | traceArgs ["convertCall", label, show exprTp] = undefined
convertCall (Ann (CallF (UnAnn (LabelAccessF label)) (UnAnn (IdentF ident))) (exprTp,ctx)) = do
expr <- liftA2 A.Field (newIdent ident) (pure label)
let arity = typeFuncArity exprTp
contextTp <- identType ident <&> getLabelType label
maybe (return expr ) (\contextTp -> addInstancesArgs arity expr contextTp exprTp) contextTp
convertCall (UnAnn (CallF expr args)) = do
callArgs <- convertFuncArgs args
case expr of
(Ann (IdentF ident) (tp, ctx)) -> do
instanceArgs <- localPut ctx $ getIdentInstancesArgs ident tp
exprCode <- newIdent ident
let isClass = ctx & lookupClass ident & isJust
return $ if isClass && length instanceArgs == 1 then A.Call (unsafeHead instanceArgs) callArgs else A.Call exprCode (instanceArgs ++ callArgs)
_ -> do
exprCode <- convert expr
return $ A.Call exprCode callArgs
convertClass (ClassFnF name body) =
A.StmtList [A.Set (instancesObject name) $ A.Object [],
A.Label name codeBody]
where
clsArity = typeFuncArity body
hasParams = clsArity > 0
params = if hasParams then [1..clsArity] & map (show >>> ("p" ++)) else []
codeBody =
if hasParams then A.Function ("x" : params) [A.Return (A.Call (A.Ident "x") (params <&> A.Ident))]
else A.Function ["x"] [A.Return (A.Ident "x")]
-- newScope (x,y) = if onull x then y else (A.Call (A.Parens (A.Function [] $ x ++ [A.Return y])) [])
newScope ([], y) = y
newScope (x, y) = A.Scope x y
functionBody expr@(Ann (RecordF l) (tp,ctx)) newOutType _ = localPut ctx $ do
(body, ret) <- convertAstList l
-- UNUSED let r = convertExprWithNewTypeMaybe tp newOutType ret
return $ body ++ [A.Return ret]
functionBody expr@(Ann _ (tp,ctx)) newOutType y = localPut ctx $
case y of
(A.Scope body ret) -> return $ body ++ [A.Return $ convertExprWithNewTypeMaybe tp newOutType ret]
_ -> return [A.Return $ convertExprWithNewTypeMaybe tp newOutType y]
convertFuncParams :: InferExpr -> [String]
convertFuncParams = cataM $ \case
AnnF (RecordF list) _ -> list
AnnF (ParamIdentF x) _ -> [x]
convertFuncArgs = \case
UnAnn (RecordF list) -> list &traverse convert
x -> (:[]) <$> convert x
convertAstList list = do
parts <- evalStateT (convertRecordToVarsList list) 1 -- & trac "parts"
let hasStmts = parts & any (fst >>> isNothing)
let labels = parts & map fst & catMaybes & filter (snd >>> not) & map fst
let asts = parts & partsToAsts
let funcLabels = parts & filter (snd >>> A.isFunction) & map fst & catMaybes & map fst
let labelsWithIdents = asts >>= A.containsIdents labels
let labelsInScope = if notNull labelsWithIdents || hasStmts then labelsWithIdents ++ funcLabels else []
let returnObject = parts & filter (fst >>> isJust) & map (\(Just (x, _), y) -> if x `elem` labelsInScope then (x, A.Ident x) else (x, y)) & A.Object
return (parts & filter (fst >>> maybe True (fst >>> (`elem` labelsInScope))) & map partToAst, returnObject)
type RecordParts = (Maybe (String, T.IsFfi), A.Ast)
partToAst (x,y) = maybe y (\(x,isFfi) -> if isFfi then A.None else A.Var x y) x
partsToAsts = map partToAst
astToPart = \case
A.Label x y -> (Just (x,False), y)
x -> (Nothing, x)
convertRecordToVarsList :: [InferExpr] -> StateT Int Converter [RecordParts]
convertRecordToVarsList list =
list & traverse convertRecordToVars & map (concat >>> filter (snd >>> (/= A.None)))
convertRecordToVars :: InferExpr -> StateT Int Converter [RecordParts]
convertRecordToVars ast@(Ann ex (tp, ctx)) = case ex of
RecordF list -> list & traverse convertRecordToVars & map concat
RecordLabelF {} -> do
(x,y) <- lift $ convertRecordLabel ex
return [(Just (x,False), y)]
FfiF {} -> do
let (x,y) = convertFfiLabel ex
return [(Just (x,True), y)]
_ | isExpr ex -> tupleLabel ast
_ -> do
temp <- lift $ convert ast
return $ temp & A.astToList & map astToPart
where
tupleLabel ast = do
index <- get
put (index + 1)
x <- lift $ convert ast
return [(Just ("item" ++ show index, False), x)]
isExpr = \case
IdentF {} -> True
LitF {} -> True
CasesF {} -> True
LetF {} -> True
CallF {} -> True
UpdateF {} -> True
FunctionF {} -> True
ArrayF {} -> True
IfF {} -> True
_ -> False
newBoolAnds list = if olength list > 1 then A.BoolAnds list else list & unsafeHead
funcParamCond = \case
Ann (ParamIdentF x) (tp, cxt) | notNull typeLabels ->
map (A.HasField (A.Ident x)) typeLabels
where typeLabels = getTypeLabels tp
UnAnn (RecordF list) -> list >>= funcParamCond
_ -> []
casesFuncs newOutType (UnAnn f@(FunctionF params guard body)) = do
temp1 <- maybe (return []) (fmap (:[]) . convert) guard
y <- convert body
let conds = funcParamCond params ++ temp1
func@(A.Function aparams body) <- convertFunction f newOutType y
return $ case conds of
[] -> (func, Nothing)
_ -> (A.Function aparams body, Just $ A.Function aparams [A.Return $ newBoolAnds conds])
-- casesDiffParamTypes :: Functor f => f (Fix (AnnF ExprF b)) -> f b
-- casesDiffParamTypes :: [InferExpr] -> [TypeExpr]
-- casesDiffParamTypes list = list & map (\(UnAnn (FunctionF (Ann _ tp) _ _)) -> tp)
cases list newOutType = do
funcsWithCond <- list & traverse (casesFuncs newOutType)
let hasNoCondFunc = funcsWithCond & any (snd >>> isNothing)
let arity = list & map stripAnns & casesArity
let count = if olength arity == 1 then arity & unsafeHead else error "cases arity length <> 1"
let params = [1..count] & map (\i -> sysPrefix ++ "a" ++ show i)
let paramIdents = params & map A.Ident
let init = if hasNoCondFunc then [] else [A.Throw "cases error"]
let funcCondCode (x, cond) acc =
let r = A.Call x paramIdents in
maybe [A.Return r] (\cond -> [A.If (A.Call cond paramIdents) [A.Return r] acc]) cond
let funcIfs = foldr funcCondCode init funcsWithCond
let body = funcIfs
return $ A.Function params body
convertLit = A.Lit . \case
LitInt value -> A.LitInt value
LitDouble value -> A.LitDouble value
LitChar value -> A.LitChar value
LitString value -> A.LitString value
LitBool value -> A.LitBool value
| ptol/oczor | src/Oczor/Converter/Converter.hs | mit | 18,878 | 0 | 19 | 3,744 | 6,464 | 3,217 | 3,247 | -1 | -1 |
module Network.BitTorrent.Tracker.AnnounceServer
( AnnounceConfig(..)
, AnnounceEnv(..)
, AnnounceState(..)
, AnnounceT(..)
, IpVersion(..)
, defaultConfig
, emptyAnnounceState
, handleAnnounce
, handleScrape
, pruneQueue
) where
import Control.Concurrent.MVar
import Control.Monad hiding (forM, mapM)
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import qualified Data.ByteString as B
import Data.Int
import Data.List (foldl')
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Set as S
import Data.Time.Clock
import Data.Traversable
import Data.Word
import Network.BitTorrent.Tracker.Announce
import Network.BitTorrent.Tracker.PeerFinder
import Network.Socket
-- | A Map to keep track of when a peer was last seen.
type ActivityRecord = M.Map PeerId UTCTime
-- | A Queue used to keep track of when a peer was last seen in order of the
-- sightings. Used together with the ActivityRecord to make sure that only
-- active hashes are kept around.
type ActivityQueue = S.Set (UTCTime, Maybe PeerId)
-- | All the state necessary to respond to Announce or Scrape Requests
data AnnounceState = AnnounceState
-- | The current set of active hashes
{ activeHashes :: MVar (M.Map InfoHash HashRecord)
-- | A map from hashes to the ActivityRecord for that hash. Used to allow
-- removal of entries from the activity queue.
, peersLastSeen :: MVar (M.Map InfoHash (MVar ActivityRecord))
-- | A map from hashes to the ActivityQueue for that hash
, peerActivityQueue :: MVar (M.Map InfoHash (MVar ActivityQueue))
}
-- | Create an empty announce state serving no hashes and having no peers.
emptyAnnounceState :: IO AnnounceState
emptyAnnounceState = do
ah <- newMVar M.empty
pls <- newMVar M.empty
paq <- newMVar M.empty
return
AnnounceState
{activeHashes = ah, peersLastSeen = pls, peerActivityQueue = paq}
type Seconds = Int32
-- | Configuration parameters for how an Announce Server behaves.
data AnnounceConfig = AnnounceConfig
{ ancInterval :: !Seconds
, ancMaxPeers :: !Word32
, ancDefaultPeers :: !Word32
, ancIdlePeerTimeout :: !Seconds
, ancAddrs :: [(String, String)]
}
-- | The default config
defaultConfig :: AnnounceConfig
defaultConfig =
AnnounceConfig
{ ancInterval = 120
, ancMaxPeers = 50
, ancDefaultPeers = 30
, ancIdlePeerTimeout = 360 -- Six minutes, three announce intervals
, ancAddrs = [("0.0.0.0", "6969"), ("::", "6970")]
}
-- | An announce environment is the state and the config.
data AnnounceEnv = AnnounceEnv
{ anSt :: AnnounceState
, anConf :: AnnounceConfig
}
-- | To serve anounce requests, you need access to AnnounceEnv and the ability
-- to perform IO.
type AnnounceT = ReaderT AnnounceEnv IO
-- | Helper function to get the state from AnnounceEnv
getState :: AnnounceT AnnounceState
getState = asks anSt
-- | Helper function to get the config from AnnounceEnv
getConf :: AnnounceT AnnounceConfig
getConf = asks anConf
-- | Remove inactive peers from hashes.
-- TODO: remove hashes with no active peers.
pruneQueue :: AnnounceT ()
pruneQueue = do
now <- liftIO getCurrentTime
st <- getState
hrMap <- liftIO $ takeMVar (activeHashes st)
lastSeen <- liftIO $ takeMVar (peersLastSeen st)
queue <- liftIO $ takeMVar (peerActivityQueue st)
liftIO $ putMVar (activeHashes st) hrMap
liftIO $ putMVar (peersLastSeen st) lastSeen
liftIO $ putMVar (peerActivityQueue st) queue
forM_ (M.assocs lastSeen) $ \(hash, hashActivityM) -> do
let hashQueueM = queue M.! hash
let hr = hrMap M.! hash
pruneHashQueue now hashActivityM hashQueueM hr
where
pruneHashQueue ::
UTCTime
-> MVar ActivityRecord
-> MVar ActivityQueue
-> HashRecord
-> AnnounceT ()
pruneHashQueue now hashActivityM hashQueueM hr = do
activity <- liftIO $ takeMVar hashActivityM
queue <- liftIO $ takeMVar hashQueueM
timeout <- fmap ancIdlePeerTimeout getConf
let old_now = addUTCTime (fromIntegral $ negate timeout) now
(old, queue') = S.split (old_now, Nothing) queue
activity' =
foldl' (flip (M.delete . fromJust . snd)) activity (S.elems old)
liftIO $ putMVar hashActivityM activity'
liftIO $ putMVar hashQueueM queue'
liftIO $
forM_ [hrInet4 hr, hrInet6 hr] $ \phrM -> do
phr <- takeMVar phrM
putMVar phrM $
phr
{ phrSeeders = cleanUp old (phrSeeders phr)
, phrLeechers = cleanUp old (phrLeechers phr)
}
cleanUp :: S.Set (UTCTime, Maybe PeerId) -> RandomPeerList -> RandomPeerList
cleanUp old rpl =
foldl' (flip (removePeerId . fromJust . snd)) rpl (S.elems old)
-- | Handle an announce request. Get peers if required.
handleAnnounce :: AnnounceRequest -> AnnounceT AnnounceResponse
handleAnnounce an = do
let peer = anPeer an
hash = anInfoHash an
st <- getState
hr <- liftIO $ getHashRecord st hash
liftIO $ updateActivity st hash peer
let phr = getProtocolHashRecord peer hr
peerGetter
| anEvent an == Just Completed = \count phr -> return []
| isSeeder an = getLeechers
| otherwise = getPeers
maxPeers <- fmap ancMaxPeers getConf
defPeers <- fmap ancDefaultPeers getConf
let peersWanted =
case anEvent an of
Just Completed -> 0
_ -> fromMaybe defPeers (anWant an)
peerCount = min maxPeers peersWanted
peers <- liftIO $ peerGetter (fromIntegral peerCount) phr
interval <- fmap ancInterval getConf
addOrRemovePeer an
(nSeeders, nLeechers, _) <- liftIO $ getPeerCounts phr
return
PeerList
{ plInterval = fromIntegral interval
, plSeeders = Just nSeeders
, plLeechers = Just nLeechers
, plPeers = peers
}
-- | Record a peers activity so they don't get pruned.
updateActivity :: AnnounceState -> InfoHash -> Peer -> IO ()
updateActivity st hash peer = do
lastSeenMap <- takeMVar (peersLastSeen st)
queueMap <- takeMVar (peerActivityQueue st)
case M.lookup hash lastSeenMap of
Nothing -> do
newLastSeen <- newMVar M.empty
newQueue <- newMVar S.empty
putMVar (peersLastSeen st) $ M.insert hash newLastSeen lastSeenMap
putMVar (peerActivityQueue st) $ M.insert hash newQueue queueMap
updateHashActivity peer newLastSeen newQueue
Just lastSeen -> do
putMVar (peersLastSeen st) lastSeenMap
putMVar (peerActivityQueue st) queueMap
let activityQueue = queueMap M.! hash
updateHashActivity peer lastSeen activityQueue
where
updateHashActivity peer lastSeenM queueM = do
let pid = peerId peer
now <- getCurrentTime
lastSeen <- takeMVar lastSeenM
queue <- takeMVar queueM
case M.lookup pid lastSeen of
Nothing -> do
putMVar lastSeenM $ M.insert pid now lastSeen
putMVar queueM $ S.insert (now, Just pid) queue
Just old_now -> do
putMVar lastSeenM $ M.insert pid now lastSeen
putMVar queueM $
S.insert (now, Just pid) $ S.delete (old_now, Just pid) queue
-- | Lookup or create a HashRecord for a specific hash.
getHashRecord :: AnnounceState -> InfoHash -> IO HashRecord
getHashRecord st hash = do
hrMap <- takeMVar (activeHashes st)
case M.lookup hash hrMap of
Just hr -> do
putMVar (activeHashes st) hrMap
return hr
Nothing -> do
hr <- emptyHashRecord
putMVar (activeHashes st) $ M.insert hash hr hrMap
return hr
-- | Grab the correct ProtocolHashRecord based on a peer's protocol.
getProtocolHashRecord :: Peer -> HashRecord -> MVar ProtocolHashRecord
getProtocolHashRecord peer hr =
case peerAddr peer of
SockAddrInet {} -> hrInet4 hr
SockAddrInet6 {} -> hrInet6 hr
_ -> error "Unix sockets not supported."
-- TODO: Make this a reasonable exception
-- | Predicate to determine if an announce request is from a seeder or leecher.
isSeeder :: AnnounceRequest -> Bool
isSeeder an = anLeft an == 0
-- | A peer is either added, shifted from leecher to seeder, or removed.
data PeerAction
= Add
| Shift
| Remove
-- | Add or remove a peer (or shift them from leecher to seeder) based on
-- the action in the AnnounceRequest
addOrRemovePeer :: AnnounceRequest -> AnnounceT ()
addOrRemovePeer an = do
let peer = anPeer an
hash = anInfoHash an
st <- getState
case anEvent an
-- On a non-event add them just in case
of
Nothing -> addAnnounce st an
Just Started -> addAnnounce st an
Just Completed -> shiftAnnounce st an
Just Stopped -> removeAnnounce st an
where
addAnnounce :: AnnounceState -> AnnounceRequest -> AnnounceT ()
addAnnounce = updateAnnounce Add
shiftAnnounce :: AnnounceState -> AnnounceRequest -> AnnounceT ()
shiftAnnounce = updateAnnounce Shift
removeAnnounce :: AnnounceState -> AnnounceRequest -> AnnounceT ()
removeAnnounce = updateAnnounce Remove
updateAnnounce ::
PeerAction -> AnnounceState -> AnnounceRequest -> AnnounceT ()
updateAnnounce act st an = do
let activeMapM = activeHashes st
activeMap <- liftIO $ takeMVar activeMapM
hr <-
case M.lookup (anInfoHash an) activeMap of
Nothing ->
liftIO $ do
newHr <- emptyHashRecord
putMVar activeMapM $ M.insert (anInfoHash an) newHr activeMap
return newHr
Just hr -> return hr
liftIO $ putMVar activeMapM activeMap
let phrM = getProtocolHashRecord (anPeer an) hr
phr <- liftIO $ takeMVar phrM
let (seedUpdater, leechUpdater, compInc) =
case act of
Shift ->
( addPeer (anPeer an)
, return . removePeerId (peerId (anPeer an))
, (+ 1))
Add -> makeUpdaters (addPeer (anPeer an)) an
Remove ->
makeUpdaters (return . removePeerId (peerId (anPeer an))) an
liftIO $ do
seeders' <- seedUpdater (phrSeeders phr)
leechers' <- leechUpdater (phrLeechers phr)
putMVar phrM $
phr
{ phrSeeders = seeders'
, phrLeechers = leechers'
, phrCompleteCount = compInc (phrCompleteCount phr)
}
where
makeUpdaters ::
(RandomPeerList -> IO RandomPeerList)
-> AnnounceRequest
-> ( RandomPeerList -> IO RandomPeerList
, RandomPeerList -> IO RandomPeerList
, Word32 -> Word32)
makeUpdaters mod an =
if isSeeder an
then (mod, return, id)
else (return, mod, id)
-- | IpVersion 4 or 6
data IpVersion
= Ipv4
| Ipv6
-- | Handle a scrape request. From the clients perspective the ipv6 and ipv4
-- servers are separated, so give them a count only for what they can see.
handleScrape :: IpVersion -> [ScrapeRequest] -> AnnounceT [ScrapeResponse]
handleScrape ipVersion hashes = do
hashRecords <- liftIO . readMVar =<< asks (activeHashes . anSt)
forM hashes $ \hash ->
liftIO $
case M.lookup hash hashRecords of
Nothing -> return emptyScrapeResponse
Just hr -> do
let mphr =
case ipVersion of
Ipv4 -> hrInet4 hr
Ipv6 -> hrInet6 hr
(seeders, leechers, completed) <- getPeerCounts mphr
return
ScrapeResponse
{ srSeeders = seeders
, srLeechers = leechers
, srCompletions = completed
}
| iteratee/haskell-tracker | Network/BitTorrent/Tracker/AnnounceServer.hs | mit | 11,882 | 0 | 22 | 3,324 | 2,996 | 1,498 | 1,498 | 273 | 8 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGPathSegLinetoAbs
(js_setX, setX, js_getX, getX, js_setY, setY, js_getY, getY,
SVGPathSegLinetoAbs, castToSVGPathSegLinetoAbs,
gTypeSVGPathSegLinetoAbs)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"x\"] = $2;" js_setX ::
SVGPathSegLinetoAbs -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegLinetoAbs.x Mozilla SVGPathSegLinetoAbs.x documentation>
setX :: (MonadIO m) => SVGPathSegLinetoAbs -> Float -> m ()
setX self val = liftIO (js_setX (self) val)
foreign import javascript unsafe "$1[\"x\"]" js_getX ::
SVGPathSegLinetoAbs -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegLinetoAbs.x Mozilla SVGPathSegLinetoAbs.x documentation>
getX :: (MonadIO m) => SVGPathSegLinetoAbs -> m Float
getX self = liftIO (js_getX (self))
foreign import javascript unsafe "$1[\"y\"] = $2;" js_setY ::
SVGPathSegLinetoAbs -> Float -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegLinetoAbs.y Mozilla SVGPathSegLinetoAbs.y documentation>
setY :: (MonadIO m) => SVGPathSegLinetoAbs -> Float -> m ()
setY self val = liftIO (js_setY (self) val)
foreign import javascript unsafe "$1[\"y\"]" js_getY ::
SVGPathSegLinetoAbs -> IO Float
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGPathSegLinetoAbs.y Mozilla SVGPathSegLinetoAbs.y documentation>
getY :: (MonadIO m) => SVGPathSegLinetoAbs -> m Float
getY self = liftIO (js_getY (self)) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGPathSegLinetoAbs.hs | mit | 2,345 | 28 | 8 | 309 | 594 | 353 | 241 | 35 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExplicitNamespaces #-}
-- | Extensions to 'Data.ConfigFile' and utility functions for dealing with
-- configuration in general and reading/writing files.
module Data.ConfigFile.B9Extras
( addSectionCP,
setShowCP,
setCP,
readCP,
mergeCP,
toStringCP,
sectionsCP,
emptyCP,
type CPGet,
type CPOptionSpec,
type CPSectionSpec,
type CPDocument,
CPError (),
readCPDocument,
CPReadException (..),
)
where
import Control.Exception
import Control.Monad.Except
import Data.ConfigFile
import Data.Typeable
import System.IO.B9Extras
-- * Aliases for functions and types from 'ConfigParser' in 'Data.ConfigFile'
-- | An alias for 'ConfigParser'
type CPDocument = ConfigParser
-- | An alias for 'SectionSpec'.
type CPSectionSpec = SectionSpec
-- | An alias for 'OptionSpec'
type CPOptionSpec = OptionSpec
-- | An alias for 'setshow'.
setShowCP ::
(Show a, MonadError CPError m) =>
CPDocument ->
CPSectionSpec ->
CPOptionSpec ->
a ->
m CPDocument
setShowCP = setshow
-- | An alias for 'set'.
setCP ::
(MonadError CPError m) =>
CPDocument ->
CPSectionSpec ->
CPOptionSpec ->
String ->
m CPDocument
setCP = set
-- | An alias for 'get'.
readCP ::
(CPGet a, MonadError CPError m) =>
CPDocument ->
CPSectionSpec ->
CPOptionSpec ->
m a
readCP = get
-- | An alias for 'Get_C'
type CPGet a = Get_C a
-- | An alias for 'add_section'.
addSectionCP ::
MonadError CPError m => CPDocument -> CPSectionSpec -> m CPDocument
addSectionCP = add_section
-- | An alias for 'merge'.
mergeCP :: CPDocument -> CPDocument -> CPDocument
mergeCP = merge
-- | An alias for 'to_string'
toStringCP :: CPDocument -> String
toStringCP = to_string
-- | An alias for 'sections'.
sectionsCP :: CPDocument -> [SectionSpec]
sectionsCP = sections
-- * Reading a 'CPDocument' from a 'SystemPath'
-- | Read a file and try to parse the contents as a 'CPDocument', if something
-- goes wrong throw a 'CPReadException'
readCPDocument :: MonadIO m => SystemPath -> m CPDocument
readCPDocument cfgFile' = do
cfgFilePath <- resolve cfgFile'
liftIO $ do
res <- readfile emptyCP cfgFilePath
case res of
Left e -> throwIO (CPReadException cfgFilePath e)
Right cp -> return cp
-- | An exception thrown by 'readCPDocument'.
data CPReadException = CPReadException FilePath CPError
deriving (Show, Typeable)
instance Exception CPReadException
| sheyll/b9-vm-image-builder | src/lib/Data/ConfigFile/B9Extras.hs | mit | 2,501 | 0 | 15 | 494 | 477 | 269 | 208 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module ParseWorks where
import Control.Applicative
import qualified Data.Attoparsec.Combinator as AC
import Data.Attoparsec.Text (Parser)
import qualified Data.Attoparsec.Text as A
import Data.Char
import Data.Text (Text, pack)
import qualified Data.Text as TI
import qualified Data.Text.IO as T
{-
DayOfWeek http://michaelxavier.net/posts/2012-01-20-Writing-a-Small-Parser-with-Attoparsec.html
-}
data DayOfWeek = Monday |
Tuesday
deriving (Show, Eq)
data DayDate = DayDate Integer DayOfWeek
deriving (Show, Eq)
stringChoices :: [Text] -> Parser Text
stringChoices = AC.choice . map A.asciiCI
day :: Parser DayOfWeek
day = monday <|> tuesday
where monday = stringChoices ["monday", "mon"] *> pure Monday
tuesday = stringChoices ["tuesday", "tue"] *> pure Tuesday
dayDate :: Parser DayDate
dayDate = DayDate <$> integer
<*> day
where integer = read <$> A.count 2 A.digit
dateParser :: IO ()
dateParser = do
file <- T.readFile "booklist.txt"
print $ A.parseOnly (many $ dayDate <* A.endOfLine) file
data Book = Book { bookName, authorName :: Text }
deriving (Eq, Show)
parseRecord :: Parser (Maybe Book)
parseRecord = do
trailing <- unconsumed
author <- unwords <$> upperCases
return $ Book <$> bName trailing <*> Just (pack author)
where
unconsumed = A.manyTill A.anyChar "by " <* AC.lookAhead (A.satisfy isAsciiUpper)
upperCases = many bookNames
reverseWords :: String -> Text
reverseWords = pack . unwords . reverse . words
bName :: String -> Maybe Text
bName xs = case A.parseOnly upperCases (reverseWords xs) of
Right a -> if length a <= 0 then Nothing
else Just ((pack . unwords . reverse) a )
Left _ -> Nothing
bookNames = do
y <- stringChoices [" of the ", " of ", " the ", " ", ""]
x <- A.satisfy isAsciiUpper
xs <- some A.letter
return $ x : xs ++ TI.unpack y
makeIterator :: Text -> [Either Text (Maybe Book)]
makeIterator xs = case A.parse parseRecord xs of
A.Fail x _ _ -> [Left x]
A.Partial _ -> makeIterator "by partialFailed"
A.Done rest v -> Right v : makeIterator rest
| alokpndy/haskell-learn | src/parsers/parseWorks.hs | mit | 2,409 | 0 | 16 | 704 | 728 | 380 | 348 | 55 | 3 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Jabara.Wunderlist.Client.Types (
AccessToken
, ClientId
, UserId
, ListId
, TaskId
, NoteId
, Revision
, fromWunderlistDay
, Credential(..), credentialAccessToken, credentialClientId
, Task(..), task_id, task_assignee_id, task_assigner_id, task_created_at
, task_created_by_id, task_due_date, task_list_id, task_revision
, task_starred, task_title
, List(..), list_id , list_created_at, list_title
, list_list_type, list_type, list_revision
, ListUser(..), listUser_id, listUser_name, listUser_email
, listUser_created_at
, Note(..), note_id, note_task_id, note_content
, note_created_at, note_updated_at
, note_revision
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson (FromJSON(..), ToJSON(..), Value(String))
import Data.Aeson.TH (deriveJSON, defaultOptions, fieldLabelModifier)
import Data.ByteString (ByteString)
import Data.Text (Text, pack, unpack)
import Data.Time (Day(..))
import Data.Time.Format (ParseTime(..), FormatTime(..)
, formatTime, parseTimeM, defaultTimeLocale)
import GHC.Base (mzero)
import GHC.Generics (Generic)
import Jabara.Util (omittedFirstCharLower)
type AccessToken = ByteString
type ClientId = ByteString
type UserId = Integer
type ListId = Integer
type TaskId = Integer
type NoteId = Integer
type Revision = Int
data Credential = Credential {
_credentialClientId :: ClientId
, _credentialAccessToken :: AccessToken
} deriving (Show, Read, Eq, Generic)
makeLenses ''Credential
newtype WunderlistDay = WunderlistDay {
wunderlistDayValue :: Day
} deriving (Show, Read, Eq)
instance FromJSON WunderlistDay where
parseJSON (String t) = fromWunderlistDay t
parseJSON _ = mzero
instance ToJSON WunderlistDay where
toJSON d = String $ pack $ formatTime defaultTimeLocale "%Y-%m-%d" $ wunderlistDayValue d
instance ParseTime WunderlistDay where
buildTime locale ss = let d = buildTime locale ss
in WunderlistDay d
instance FormatTime WunderlistDay where
formatCharacter c =
let mF = formatCharacter c
in
case mF of
Nothing -> Nothing
Just f -> Just (\locale mb d -> f locale mb $ wunderlistDayValue d)
fromWunderlistDay :: (Monad m) => Text -> m WunderlistDay
fromWunderlistDay t = parseTimeM False defaultTimeLocale "%Y-%m-%d" (unpack t)
-- | REST APIの結果の型群.
data ListUser = ListUser {
_listUser_id :: UserId
, _listUser_name :: Text
, _listUser_email :: Text
, _listUser_created_at :: Text
} deriving (Show, Read, Eq, Generic)
makeLenses ''ListUser
$(deriveJSON defaultOptions {
fieldLabelModifier = omittedFirstCharLower "_listUser_"
} ''ListUser)
data Task = Task {
_task_id :: TaskId
, _task_assignee_id :: Maybe UserId
, _task_assigner_id :: Maybe UserId
, _task_created_at :: Text
, _task_created_by_id :: UserId
, _task_due_date :: Maybe WunderlistDay
, _task_list_id :: ListId
, _task_revision :: Revision
, _task_starred :: Bool
, _task_title :: Text
} deriving (Show, Read, Eq, Generic)
makeLenses ''Task
$(deriveJSON defaultOptions {
fieldLabelModifier = omittedFirstCharLower "_task_"
} ''Task)
data List = List {
_list_id :: ListId
, _list_created_at :: Text
, _list_title :: Text
, _list_list_type :: Text
, _list_type :: Text
, _list_revision :: Revision
} deriving (Show, Read, Eq, Generic)
makeLenses ''List
$(deriveJSON defaultOptions {
fieldLabelModifier = omittedFirstCharLower "_list_"
} ''List)
data Note = Note {
_note_id :: NoteId
, _note_task_id :: TaskId
, _note_content :: Text
, _note_created_at :: Maybe Text
, _note_updated_at :: Maybe Text
, _note_revision :: Revision
} deriving (Show, Read, Eq, Generic)
makeLenses ''Note
$(deriveJSON defaultOptions {
fieldLabelModifier = omittedFirstCharLower "_note_"
} ''Note)
| jabaraster/jabara-wunderlist-client | src/Jabara/Wunderlist/Client/Types.hs | mit | 4,174 | 0 | 15 | 943 | 1,073 | 617 | 456 | 115 | 1 |
module Pnj where
import qualified Trie as Trie
import System.Random
import Control.Monad
data Stat =S(String,Integer)
-- Maybe implement feats one day
data Feat = F (Stat -> Bool, Stat -> Stat)
d6 :: StdGen -> (Integer, StdGen)
d6 gen = randomR (1,6) gen
sumDice :: (StdGen -> (Integer, StdGen)) -> (Integer,StdGen) -> (Integer, StdGen)
sumDice f (rolled, newgen) =
let (rolled2, newgen2) = f (newgen) in
(rolled+rolled2,newgen2)
d6x3 :: StdGen -> (Integer, StdGen)
d6x3 gen =
sumDice d6 $ sumDice d6 $ d6 gen
stats = ["Charisme","Sagesse","Intelligence","Constitution","Dexterite","Force"]
genstats :: [String] -> StdGen -> ([Stat],StdGen)
genstats [] gen = ([],gen)
genstats (name:tail) gen =
let (val, newgen) = d6x3 gen in
let (valist, finalgen) = genstats tail newgen in
(S(name,val):valist, finalgen)
readStats :: Stat -> String -> String
readStats (S(name,value)) acc = acc ++ " " ++ name ++ " " ++ (show value)
gygax :: StdGen -> (String, StdGen)
gygax gen =
let (statlist,newgen) = genstats stats gen in
(foldr readStats "" statlist, newgen)
| panzerr/RobotPanzerr | app/Pnj.hs | mit | 1,108 | 0 | 12 | 221 | 485 | 269 | 216 | 28 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.