code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
-- | Typed deep embedding of simple C expressions
--
-- This is a subset of C expressions that only have simple non-compound and
-- non-pointed types, and that don't contain any control structures.
--
-- (Of course, nothing stops one from translating 'CExp' to something other than
-- C, but its constructors and set of supported types is inspired by C.)
module Language.Embedded.CExp where
import Data.Array
import Data.Maybe
#if __GLASGOW_HASKELL__ < 710
import Data.Monoid
#endif
import Data.Typeable
import Language.Syntactic
import Language.Syntactic.Functional (Denotation)
import Language.Syntactic.TH
import Language.C.Quote.C
import Language.C.Syntax (Type, UnOp (..), BinOp (..), Exp (UnOp, BinOp))
import qualified Language.C.Syntax as C
import Language.C.Monad
import Language.Embedded.Expression
import Language.Embedded.Backend.C
import Language.Embedded.Imperative.CMD (IArr (..))
--------------------------------------------------------------------------------
-- * Expressions
--------------------------------------------------------------------------------
data Unary a
where
UnNeg :: Num a => Unary (a -> a)
UnNot :: Unary (Bool -> Bool)
evalUnary :: Unary a -> a
evalUnary UnNeg = negate
evalUnary UnNot = not
unaryOp :: Unary a -> UnOp
unaryOp UnNeg = Negate
unaryOp UnNot = Lnot
data Binary a
where
BiAdd :: Num a => Binary (a -> a -> a)
BiSub :: Num a => Binary (a -> a -> a)
BiMul :: Num a => Binary (a -> a -> a)
BiDiv :: Fractional a => Binary (a -> a -> a)
BiQuot :: Integral a => Binary (a -> a -> a)
BiRem :: Integral a => Binary (a -> a -> a)
BiAnd :: Binary (Bool -> Bool -> Bool)
BiOr :: Binary (Bool -> Bool -> Bool)
BiEq :: CType a => Binary (a -> a -> Bool)
BiNEq :: CType a => Binary (a -> a -> Bool)
BiLt :: (Ord a, CType a) => Binary (a -> a -> Bool)
BiGt :: (Ord a, CType a) => Binary (a -> a -> Bool)
BiLe :: (Ord a, CType a) => Binary (a -> a -> Bool)
BiGe :: (Ord a, CType a) => Binary (a -> a -> Bool)
evalBinary :: Binary a -> a
evalBinary BiAdd = (+)
evalBinary BiSub = (-)
evalBinary BiMul = (*)
evalBinary BiDiv = (/)
evalBinary BiQuot = quot
evalBinary BiRem = rem
evalBinary BiAnd = (&&)
evalBinary BiOr = (||)
evalBinary BiEq = (==)
evalBinary BiNEq = (/=)
evalBinary BiLt = (<)
evalBinary BiGt = (>)
evalBinary BiLe = (<=)
evalBinary BiGe = (>=)
binaryOp :: Binary a -> BinOp
binaryOp BiAdd = Add
binaryOp BiSub = Sub
binaryOp BiMul = Mul
binaryOp BiDiv = Div
binaryOp BiQuot = Div
binaryOp BiRem = Mod
binaryOp BiAnd = Land
binaryOp BiOr = Lor
binaryOp BiEq = Eq
binaryOp BiNEq = Ne
binaryOp BiLt = Lt
binaryOp BiGt = Gt
binaryOp BiLe = Le
binaryOp BiGe = Ge
-- | Syntactic symbols for C
data Sym sig
where
-- Literal
Lit :: String -> a -> Sym (Full a)
-- Predefined constant
Const :: String -> a -> Sym (Full a)
-- The difference between `Lit` and `Const` is that the latter gets turned
-- into a variable in the C code. It is like `Var`, except that it can
-- also be evaluated.
-- Function call
Fun :: Signature sig => String -> Denotation sig -> Sym sig
-- Unary operator
UOp :: Unary (a -> b) -> Sym (a :-> Full b)
-- Binary operator
Op :: Binary (a -> b -> c) -> Sym (a :-> b :-> Full c)
-- Type casting (ignored when generating code)
Cast :: (a -> b) -> Sym (a :-> Full b)
-- Conditional
Cond :: Sym (Bool :-> a :-> a :-> Full a)
-- Variable (only for compilation)
Var :: VarId -> Sym (Full a)
-- Unsafe array indexing
ArrIx :: (Integral i, Ix i) => IArr i a -> Sym (i :-> Full a)
-- Attach extra code to an expression
WithCode :: SupportCode -> Sym (a :-> Full a)
type SupportCode = forall m . MonadC m => m ()
-- Only needed because GHC 7.8 can't represent tuple constraints (like
-- `MonadC`) in Template Haskell.
data T sig
where
T :: CType (DenResult sig) => { unT :: Sym sig } -> T sig
-- | C expression
newtype CExp a = CExp {unCExp :: ASTF T a}
instance Syntactic (CExp a)
where
type Domain (CExp a) = T
type Internal (CExp a) = a
desugar = unCExp
sugar = CExp
evalSym :: Sym sig -> Denotation sig
evalSym (Lit _ a) = a
evalSym (Const _ a) = a
evalSym (Fun _ f) = f
evalSym (UOp uop) = evalUnary uop
evalSym (Op bop) = evalBinary bop
evalSym (Cast f) = f
evalSym Cond = \c t f -> if c then t else f
evalSym (ArrIx (IArrRun arr)) = \i ->
if i<l || i>h
then error $ "index "
++ show (toInteger i)
++ " out of bounds "
++ show (toInteger l, toInteger h)
else arr!i
where
(l,h) = bounds arr
evalSym (WithCode _) = id
evalSym (Var v) = error $ "evalCExp: cannot evaluate variable " ++ v
-- | Evaluate an expression
evalCExp :: CExp a -> a
evalCExp (CExp e) = go e
where
go :: AST T sig -> Denotation sig
go (Sym (T s)) = evalSym s
go (f :$ a) = go f $ go a
instance FreeExp CExp
where
type FreePred CExp = CType
constExp a = CExp $ Sym $ T $ Lit (show a) a
varExp = CExp . Sym . T . Var
instance EvalExp CExp where evalExp = evalCExp
-- | Compile an expression
compCExp :: forall m a . MonadC m => CExp a -> m Exp
compCExp = simpleMatch (\(T s) -> go s) . unCExp
where
compCExp' :: ASTF T b -> m Exp
compCExp' = compCExp . CExp
typeOfSym :: forall sig m . MonadC m =>
CType (DenResult sig) => Sym sig -> m Type
typeOfSym _ = cType (Proxy :: Proxy (DenResult sig))
go :: CType (DenResult sig) => Sym sig -> Args (AST T) sig -> m Exp
go (Var v) Nil = touchVar v >> return [cexp| $id:v |]
go (Lit _ a) Nil = cLit a
go (Const const _) Nil = do
touchVar const
return [cexp| $id:const |]
go (Fun fun _) args = do
as <- sequence $ listArgs compCExp' args
return [cexp| $id:fun($args:as) |]
go (UOp uop) (a :* Nil) = do
a' <- compCExp' a
return $ UnOp (unaryOp uop) a' mempty
go (Op bop) (a :* b :* Nil) = do
a' <- compCExp' a
b' <- compCExp' b
return $ BinOp (binaryOp bop) a' b' mempty
go s@(Cast f) (a :* Nil) = do
a' <- compCExp' a
t <- typeOfSym s
return [cexp|($ty:t) $a'|]
-- Explicit casting is usually not needed. But sometimes it is. For
-- example
--
-- printf("%f",i);
--
-- gives an error if `i` is an integer. The most robust option is
-- probably to always have explicit casts. In many cases it probably
-- also makes the generated code more readable.
go Cond (c :* t :* f :* Nil) = do
c' <- compCExp' c
t' <- compCExp' t
f' <- compCExp' f
return $ C.Cond c' t' f' mempty
go (ArrIx arr) (i :* Nil) = do
i' <- compCExp' i
touchVar arr
return [cexp| $id:arr[$i'] |]
go (WithCode code) (a :* Nil) = code >> compCExp' a
instance CompExp CExp where compExp = compCExp
-- | One-level constant folding: if all immediate sub-expressions are literals,
-- the expression is reduced to a single literal
constFold :: CExp a -> CExp a
constFold = CExp . match go . unCExp
where
go :: T sig -> Args (AST T) sig -> AST T (Full (DenResult sig))
go (T s) as = res
where
e = appArgs (Sym $ T s) as
res = if and $ listArgs (isJust . viewLit . CExp) as
then unCExp $ value $ evalCExp $ CExp e
else e
-- Deeper constant folding would require a way to witness `Show` for arbitrary
-- sub-expressions. This is certainly doable, but seems to complicate things
-- for not much gain (currently).
castAST :: forall a b . Typeable b => ASTF T a -> Maybe (ASTF T b)
castAST a = simpleMatch go a
where
go :: (DenResult sig ~ a) => T sig -> Args (AST T) sig -> Maybe (ASTF T b)
go (T _) _ = gcast a
-- | Get the value of a literal expression
viewLit :: CExp a -> Maybe a
viewLit (CExp (Sym (T (Lit _ a)))) = Just a
viewLit _ = Nothing
pattern LitP a <- CExp (Sym (T (Lit _ a)))
pattern LitP' a <- Sym (T (Lit _ a))
pattern NonLitP <- (viewLit -> Nothing)
pattern NonLitP' <- (CExp -> (viewLit -> Nothing))
pattern OpP op a b <- CExp (Sym (T (Op op)) :$ a :$ b)
pattern OpP' op a b <- Sym (T (Op op)) :$ a :$ b
pattern UOpP op a <- CExp (Sym (T (UOp op)) :$ a)
pattern UOpP' op a <- Sym (T (UOp op)) :$ a
-- | Return whether the type of the expression is a floating-point numeric type
isFloat :: forall a . CType a => CExp a -> Bool
isFloat a = t == typeOf (undefined :: Float) || t == typeOf (undefined :: Double)
where
t = typeOf (undefined :: a)
-- | Return whether the type of the expression is a non-floating-point type
isExact :: CType a => CExp a -> Bool
isExact = not . isFloat
-- | Return whether the type of the expression is a non-floating-point type
isExact' :: CType a => ASTF T a -> Bool
isExact' = isExact . CExp
--------------------------------------------------------------------------------
-- * User interface
--------------------------------------------------------------------------------
-- | Construct a literal expression
value :: CType a => a -> CExp a
value a = CExp $ Sym $ T $ Lit (show a) a
-- | Predefined constant
constant :: CType a
=> String -- ^ Name of constant
-> a -- ^ Value of constant
-> CExp a
constant const val = CExp $ Sym $ T $ Const const val
-- | Create a named variable
variable :: CType a => VarId -> CExp a
variable = CExp . Sym . T . Var
withCode :: CType a => (forall m . MonadC m => m ()) -> CExp a -> CExp a
withCode code = CExp . smartSym' (T $ WithCode code) . unCExp
true, false :: CExp Bool
true = withCode (addInclude "<stdbool.h>") $ constant "true" True
false = withCode (addInclude "<stdbool.h>") $ constant "false" False
instance (Num a, Ord a, CType a) => Num (CExp a)
where
fromInteger = value . fromInteger
LitP 0 + b | isExact b = b
a + LitP 0 | isExact a = a
a@(LitP _) + b@NonLitP | isExact a = b+a -- Move literals to the right
OpP BiAdd a (LitP' b) + LitP c | isExact' a = CExp a + value (b+c)
OpP BiSub a (LitP' b) + LitP c | isExact' a = CExp a + value (c-b)
a + LitP b | b < 0, isExact a = a - value (negate b)
a + b = constFold $ sugarSym (T $ Op BiAdd) a b
LitP 0 - b | isExact b = negate b
a - LitP 0 | isExact a = a
a@(LitP _) - b@NonLitP | isExact a = negate b - negate a -- Move literals to the right
OpP BiAdd a (LitP' b) - LitP c | isExact' a = CExp a + value (b-c)
OpP BiSub a (LitP' b) - LitP c | isExact' a = CExp a - value (b+c)
a - LitP b | b < 0, isExact a = a + value (negate b)
a - b = constFold $ sugarSym (T $ Op BiSub) a b
LitP 0 * b | isExact b = value 0
a * LitP 0 | isExact a = value 0
LitP 1 * b | isExact b = b
a * LitP 1 | isExact a = a
a@(LitP _) * b@NonLitP | isExact a = b*a -- Move literals to the right
OpP BiMul a (LitP' b) * LitP c | isExact' a = CExp a * value (b*c)
a * b = constFold $ sugarSym (T $ Op BiMul) a b
negate (UOpP UnNeg a) | isExact' a = CExp a
negate (OpP BiAdd a b) | isExact' a = negate (CExp a) - CExp b
negate (OpP BiSub a b) | isExact' a = CExp b - CExp a
negate (OpP BiMul a b) | isExact' a = CExp a * negate (CExp b)
-- Negate the right operand, because literals are moved to the right
-- in multiplications
negate a = constFold $ sugarSym (T $ UOp UnNeg) a
abs = error "abs not implemented for CExp"
signum = error "signum not implemented for CExp"
instance (Fractional a, Ord a, CType a) => Fractional (CExp a)
where
fromRational = value . fromRational
a / b = constFold $ sugarSym (T $ Op BiDiv) a b
recip = error "recip not implemented for CExp"
-- | Integer division truncated toward zero
quot_ :: (Integral a, CType a) => CExp a -> CExp a -> CExp a
quot_ (LitP 0) b = 0
quot_ a (LitP 1) = a
quot_ a b
| a == b = 1
quot_ a b = constFold $ sugarSym (T $ Op BiQuot) a b
-- | Integer remainder satisfying
--
-- > (x `quot_` y)*y + (x #% y) == x
(#%) :: (Integral a, CType a) => CExp a -> CExp a -> CExp a
LitP 0 #% _ = 0
_ #% LitP 1 = 0
a #% b | a == b = 0
a #% b = constFold $ sugarSym (T $ Op BiRem) a b
-- | Integral type casting
i2n :: (Integral a, Num b, CType b) => CExp a -> CExp b
i2n a = constFold $ sugarSym (T $ Cast (fromInteger . toInteger)) a
-- | Cast integer to 'Bool'
i2b :: Integral a => CExp a -> CExp Bool
i2b a = constFold $ sugarSym (T $ Cast (/=0)) a
-- | Cast 'Bool' to integer
b2i :: (Integral a, CType a) => CExp Bool -> CExp a
b2i a = constFold $ sugarSym (T $ Cast (\c -> if c then 1 else 0)) a
-- | Boolean negation
not_ :: CExp Bool -> CExp Bool
not_ (UOpP UnNot a) = CExp a
not_ (OpP BiEq a b) = CExp a #!= CExp b
not_ (OpP BiNEq a b) = CExp a #== CExp b
not_ (OpP BiLt a b) = CExp a #>= CExp b
not_ (OpP BiGt a b) = CExp a #<= CExp b
not_ (OpP BiLe a b) = CExp a #> CExp b
not_ (OpP BiGe a b) = CExp a #< CExp b
not_ a = constFold $ sugarSym (T $ UOp UnNot) a
-- | Logical and
(#&&) :: CExp Bool -> CExp Bool -> CExp Bool
LitP True #&& b = b
LitP False #&& b = false
a #&& LitP True = a
a #&& LitP False = false
a #&& b = constFold $ sugarSym (T $ Op BiAnd) a b
-- | Logical or
(#||) :: CExp Bool -> CExp Bool -> CExp Bool
LitP True #|| b = true
LitP False #|| b = b
a #|| LitP True = true
a #|| LitP False = a
a #|| b = constFold $ sugarSym (T $ Op BiOr) a b
-- | Equality
(#==) :: (Eq a, CType a) => CExp a -> CExp a -> CExp Bool
a #== b
| a == b, isExact a = true
| otherwise = constFold $ sugarSym (T $ Op BiEq) a b
-- | In-equality
(#!=) :: (Eq a, CType a) => CExp a -> CExp a -> CExp Bool
a #!= b
| a == b, isExact a = false
| otherwise = constFold $ sugarSym (T $ Op BiNEq) a b
(#<) :: (Ord a, CType a) => CExp a -> CExp a -> CExp Bool
a #< b
| a == b, isExact a = false
| otherwise = constFold $ sugarSym (T $ Op BiLt) a b
(#>) :: (Ord a, CType a) => CExp a -> CExp a -> CExp Bool
a #> b
| a == b, isExact a = false
| otherwise = constFold $ sugarSym (T $ Op BiGt) a b
(#<=) :: (Ord a, CType a) => CExp a -> CExp a -> CExp Bool
a #<= b
| a == b, isExact a = true
| otherwise = constFold $ sugarSym (T $ Op BiLe) a b
(#>=) :: (Ord a, CType a) => CExp a -> CExp a -> CExp Bool
a #>= b
| a == b, isExact a = true
| otherwise = constFold $ sugarSym (T $ Op BiGe) a b
infix 4 #==, #!=, #<, #>, #<=, #>=
-- | Conditional expression
cond :: CType a
=> CExp Bool -- ^ Condition
-> CExp a -- ^ True branch
-> CExp a -- ^ False branch
-> CExp a
cond (LitP c) t f = if c then t else f
cond c t f
| t == f = t
cond (UOpP UnNot a) t f = cond (CExp a) f t
cond c t f = constFold $ sugarSym (T Cond) c t f
-- | Condition operator; use as follows:
--
-- > cond1 ? a $
-- > cond2 ? b $
-- > cond3 ? c $
-- > default
(?) :: CType a
=> CExp Bool -- ^ Condition
-> CExp a -- ^ True branch
-> CExp a -- ^ False branch
-> CExp a
(?) = cond
infixl 1 ?
-- | Array indexing
(#!) :: (CType a, Integral i, Ix i) => IArr i a -> CExp i -> CExp a
arr #! i = sugarSym (T $ ArrIx arr) i
--------------------------------------------------------------------------------
-- Instances
--------------------------------------------------------------------------------
deriveSymbol ''Sym
instance Render Sym
where
renderSym (Lit a _) = a
renderSym (Const a _) = a
renderSym (Fun name _) = name
renderSym (UOp op) = show $ unaryOp op
renderSym (Op op) = show $ binaryOp op
renderSym (Cast _) = "cast"
renderSym (Var v) = v
renderSym (ArrIx (IArrComp arr)) = "ArrIx " ++ arr
renderSym (ArrIx _) = "ArrIx ..."
renderSym (WithCode _) = "WithCode ..."
renderArgs = renderArgsSmart
instance Equality Sym
where
equal = equalDefault
hash = hashDefault
instance StringTree Sym
instance Symbol T where symSig (T s) = symSig s
instance Render T
where
renderSym (T s) = renderSym s
renderArgs as (T s) = renderArgs as s
instance Equality T
where
equal (T s) (T t) = equal s t
hash (T s) = hash s
instance StringTree T
where
stringTreeSym as (T s) = stringTreeSym as s
deriving instance Eq (CExp a)
-- Must be placed here due to the sequential dependencies introduced by
-- Template Haskell
| kmate/imperative-edsl | src/Language/Embedded/CExp.hs | bsd-3-clause | 16,823 | 0 | 14 | 4,809 | 6,746 | 3,353 | 3,393 | -1 | -1 |
--------------------------------------------------------------------------------
-- | Pretty print LLVM IR Code.
--
module Llvm.PpLlvm (
-- * Top level LLVM objects.
ppLlvmModule,
ppLlvmComments,
ppLlvmComment,
ppLlvmGlobals,
ppLlvmGlobal,
ppLlvmAliases,
ppLlvmAlias,
ppLlvmMetas,
ppLlvmMeta,
ppLlvmFunctionDecls,
ppLlvmFunctionDecl,
ppLlvmFunctions,
ppLlvmFunction,
) where
#include "HsVersions.h"
import Llvm.AbsSyn
import Llvm.MetaData
import Llvm.Types
import Data.List ( intersperse )
import Outputable
import Unique
import FastString ( sLit )
--------------------------------------------------------------------------------
-- * Top Level Print functions
--------------------------------------------------------------------------------
-- | Print out a whole LLVM module.
ppLlvmModule :: LlvmModule -> SDoc
ppLlvmModule (LlvmModule comments aliases meta globals decls funcs)
= ppLlvmComments comments $+$ newLine
$+$ ppLlvmAliases aliases $+$ newLine
$+$ ppLlvmMetas meta $+$ newLine
$+$ ppLlvmGlobals globals $+$ newLine
$+$ ppLlvmFunctionDecls decls $+$ newLine
$+$ ppLlvmFunctions funcs
-- | Print out a multi-line comment, can be inside a function or on its own
ppLlvmComments :: [LMString] -> SDoc
ppLlvmComments comments = vcat $ map ppLlvmComment comments
-- | Print out a comment, can be inside a function or on its own
ppLlvmComment :: LMString -> SDoc
ppLlvmComment com = semi <+> ftext com
-- | Print out a list of global mutable variable definitions
ppLlvmGlobals :: [LMGlobal] -> SDoc
ppLlvmGlobals ls = vcat $ map ppLlvmGlobal ls
-- | Print out a global mutable variable definition
ppLlvmGlobal :: LMGlobal -> SDoc
ppLlvmGlobal (LMGlobal var@(LMGlobalVar _ _ link x a c) dat) =
let sect = case x of
Just x' -> text ", section" <+> doubleQuotes (ftext x')
Nothing -> empty
align = case a of
Just a' -> text ", align" <+> int a'
Nothing -> empty
rhs = case dat of
Just stat -> ppr stat
Nothing -> ppr (pLower $ getVarType var)
-- Position of linkage is different for aliases.
const_link = case c of
Global -> ppr link <+> text "global"
Constant -> ppr link <+> text "constant"
Alias -> text "alias" <+> ppr link
in ppAssignment var $ const_link <+> rhs <> sect <> align
$+$ newLine
ppLlvmGlobal (LMGlobal var val) = sdocWithDynFlags $ \dflags ->
error $ "Non Global var ppr as global! "
++ showSDoc dflags (ppr var) ++ " " ++ showSDoc dflags (ppr val)
-- | Print out a list of LLVM type aliases.
ppLlvmAliases :: [LlvmAlias] -> SDoc
ppLlvmAliases tys = vcat $ map ppLlvmAlias tys
-- | Print out an LLVM type alias.
ppLlvmAlias :: LlvmAlias -> SDoc
ppLlvmAlias (name, ty)
= char '%' <> ftext name <+> equals <+> text "type" <+> ppr ty
-- | Print out a list of LLVM metadata.
ppLlvmMetas :: [MetaDecl] -> SDoc
ppLlvmMetas metas = vcat $ map ppLlvmMeta metas
-- | Print out an LLVM metadata definition.
ppLlvmMeta :: MetaDecl -> SDoc
ppLlvmMeta (MetaUnamed n m)
= exclamation <> int n <> text " = " <> ppLlvmMetaExpr m
ppLlvmMeta (MetaNamed n m)
= exclamation <> ftext n <> text " = !" <> braces nodes
where
nodes = hcat $ intersperse comma $ map pprNode m
pprNode n = exclamation <> int n
-- | Print out an LLVM metadata value.
ppLlvmMetaExpr :: MetaExpr -> SDoc
ppLlvmMetaExpr (MetaStr s ) = text "metadata !" <> doubleQuotes (ftext s)
ppLlvmMetaExpr (MetaNode n ) = text "metadata !" <> int n
ppLlvmMetaExpr (MetaVar v ) = ppr v
ppLlvmMetaExpr (MetaStruct es) =
text "metadata !{" <> hsep (punctuate comma (map ppLlvmMetaExpr es)) <> char '}'
-- | Print out a list of function definitions.
ppLlvmFunctions :: LlvmFunctions -> SDoc
ppLlvmFunctions funcs = vcat $ map ppLlvmFunction funcs
-- | Print out a function definition.
ppLlvmFunction :: LlvmFunction -> SDoc
ppLlvmFunction (LlvmFunction dec args attrs sec body) =
let attrDoc = ppSpaceJoin attrs
secDoc = case sec of
Just s' -> text "section" <+> (doubleQuotes $ ftext s')
Nothing -> empty
in text "define" <+> ppLlvmFunctionHeader dec args
<+> attrDoc <+> secDoc
$+$ lbrace
$+$ ppLlvmBlocks body
$+$ rbrace
$+$ newLine
$+$ newLine
-- | Print out a function defenition header.
ppLlvmFunctionHeader :: LlvmFunctionDecl -> [LMString] -> SDoc
ppLlvmFunctionHeader (LlvmFunctionDecl n l c r varg p a) args
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align " <> ppr a'
Nothing -> empty
args' = map (\((ty,p),n) -> ppr ty <+> ppSpaceJoin p <+> char '%'
<> ftext n)
(zip p args)
in ppr l <+> ppr c <+> ppr r <+> char '@' <> ftext n <> lparen <>
(hsep $ punctuate comma args') <> ptext varg' <> rparen <> align
-- | Print out a list of function declaration.
ppLlvmFunctionDecls :: LlvmFunctionDecls -> SDoc
ppLlvmFunctionDecls decs = vcat $ map ppLlvmFunctionDecl decs
-- | Print out a function declaration.
-- Declarations define the function type but don't define the actual body of
-- the function.
ppLlvmFunctionDecl :: LlvmFunctionDecl -> SDoc
ppLlvmFunctionDecl (LlvmFunctionDecl n l c r varg p a)
= let varg' = case varg of
VarArgs | null p -> sLit "..."
| otherwise -> sLit ", ..."
_otherwise -> sLit ""
align = case a of
Just a' -> text " align" <+> ppr a'
Nothing -> empty
args = hcat $ intersperse (comma <> space) $
map (\(t,a) -> ppr t <+> ppSpaceJoin a) p
in text "declare" <+> ppr l <+> ppr c <+> ppr r <+> char '@' <>
ftext n <> lparen <> args <> ptext varg' <> rparen <> align $+$ newLine
-- | Print out a list of LLVM blocks.
ppLlvmBlocks :: LlvmBlocks -> SDoc
ppLlvmBlocks blocks = vcat $ map ppLlvmBlock blocks
-- | Print out an LLVM block.
-- It must be part of a function definition.
ppLlvmBlock :: LlvmBlock -> SDoc
ppLlvmBlock (LlvmBlock blockId stmts) =
let isLabel (MkLabel _) = True
isLabel _ = False
(block, rest) = break isLabel stmts
ppRest = case rest of
MkLabel id:xs -> ppLlvmBlock (LlvmBlock id xs)
_ -> empty
in ppLlvmBlockLabel blockId
$+$ (vcat $ map ppLlvmStatement block)
$+$ newLine
$+$ ppRest
-- | Print out an LLVM block label.
ppLlvmBlockLabel :: LlvmBlockId -> SDoc
ppLlvmBlockLabel id = pprUnique id <> colon
-- | Print out an LLVM statement.
ppLlvmStatement :: LlvmStatement -> SDoc
ppLlvmStatement stmt =
let ind = (text " " <>)
in case stmt of
Assignment dst expr -> ind $ ppAssignment dst (ppLlvmExpression expr)
Fence st ord -> ind $ ppFence st ord
Branch target -> ind $ ppBranch target
BranchIf cond ifT ifF -> ind $ ppBranchIf cond ifT ifF
Comment comments -> ind $ ppLlvmComments comments
MkLabel label -> ppLlvmBlockLabel label
Store value ptr -> ind $ ppStore value ptr
Switch scrut def tgs -> ind $ ppSwitch scrut def tgs
Return result -> ind $ ppReturn result
Expr expr -> ind $ ppLlvmExpression expr
Unreachable -> ind $ text "unreachable"
Nop -> empty
MetaStmt meta s -> ppMetaStatement meta s
-- | Print out an LLVM expression.
ppLlvmExpression :: LlvmExpression -> SDoc
ppLlvmExpression expr
= case expr of
Alloca tp amount -> ppAlloca tp amount
LlvmOp op left right -> ppMachOp op left right
Call tp fp args attrs -> ppCall tp fp (map MetaVar args) attrs
CallM tp fp args attrs -> ppCall tp fp args attrs
Cast op from to -> ppCast op from to
Compare op left right -> ppCmpOp op left right
Extract vec idx -> ppExtract vec idx
Insert vec elt idx -> ppInsert vec elt idx
GetElemPtr inb ptr indexes -> ppGetElementPtr inb ptr indexes
Load ptr -> ppLoad ptr
Malloc tp amount -> ppMalloc tp amount
Phi tp precessors -> ppPhi tp precessors
Asm asm c ty v se sk -> ppAsm asm c ty v se sk
MExpr meta expr -> ppMetaExpr meta expr
--------------------------------------------------------------------------------
-- * Individual print functions
--------------------------------------------------------------------------------
-- | Should always be a function pointer. So a global var of function type
-- (since globals are always pointers) or a local var of pointer function type.
ppCall :: LlvmCallType -> LlvmVar -> [MetaExpr] -> [LlvmFuncAttr] -> SDoc
ppCall ct fptr args attrs = case fptr of
--
-- if local var function pointer, unwrap
LMLocalVar _ (LMPointer (LMFunction d)) -> ppCall' d
-- should be function type otherwise
LMGlobalVar _ (LMFunction d) _ _ _ _ -> ppCall' d
-- not pointer or function, so error
_other -> error $ "ppCall called with non LMFunction type!\nMust be "
++ " called with either global var of function type or "
++ "local var of pointer function type."
where
ppCall' (LlvmFunctionDecl _ _ cc ret argTy params _) =
let tc = if ct == TailCall then text "tail " else empty
ppValues = ppCommaJoin args
ppArgTy = (ppCommaJoin $ map fst params) <>
(case argTy of
VarArgs -> text ", ..."
FixedArgs -> empty)
fnty = space <> lparen <> ppArgTy <> rparen <> char '*'
attrDoc = ppSpaceJoin attrs
in tc <> text "call" <+> ppr cc <+> ppr ret
<> fnty <+> ppName fptr <> lparen <+> ppValues
<+> rparen <+> attrDoc
ppMachOp :: LlvmMachOp -> LlvmVar -> LlvmVar -> SDoc
ppMachOp op left right =
(ppr op) <+> (ppr (getVarType left)) <+> ppName left
<> comma <+> ppName right
ppCmpOp :: LlvmCmpOp -> LlvmVar -> LlvmVar -> SDoc
ppCmpOp op left right =
let cmpOp
| isInt (getVarType left) && isInt (getVarType right) = text "icmp"
| isFloat (getVarType left) && isFloat (getVarType right) = text "fcmp"
| otherwise = text "icmp" -- Just continue as its much easier to debug
{-
| otherwise = error ("can't compare different types, left = "
++ (show $ getVarType left) ++ ", right = "
++ (show $ getVarType right))
-}
in cmpOp <+> ppr op <+> ppr (getVarType left)
<+> ppName left <> comma <+> ppName right
ppAssignment :: LlvmVar -> SDoc -> SDoc
ppAssignment var expr = ppName var <+> equals <+> expr
ppFence :: Bool -> LlvmSyncOrdering -> SDoc
ppFence st ord =
let singleThread = case st of True -> text "singlethread"
False -> empty
in text "fence" <+> singleThread <+> ppSyncOrdering ord
ppSyncOrdering :: LlvmSyncOrdering -> SDoc
ppSyncOrdering SyncUnord = text "unordered"
ppSyncOrdering SyncMonotonic = text "monotonic"
ppSyncOrdering SyncAcquire = text "acquire"
ppSyncOrdering SyncRelease = text "release"
ppSyncOrdering SyncAcqRel = text "acq_rel"
ppSyncOrdering SyncSeqCst = text "seq_cst"
-- XXX: On x86, vector types need to be 16-byte aligned for aligned access, but
-- we have no way of guaranteeing that this is true with GHC (we would need to
-- modify the layout of the stack and closures, change the storage manager,
-- etc.). So, we blindly tell LLVM that *any* vector store or load could be
-- unaligned. In the future we may be able to guarantee that certain vector
-- access patterns are aligned, in which case we will need a more granular way
-- of specifying alignment.
ppLoad :: LlvmVar -> SDoc
ppLoad var
| isVecPtrVar var = text "load" <+> ppr var <>
comma <+> text "align 1"
| otherwise = text "load" <+> ppr var
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppStore :: LlvmVar -> LlvmVar -> SDoc
ppStore val dst
| isVecPtrVar dst = text "store" <+> ppr val <> comma <+> ppr dst <>
comma <+> text "align 1"
| otherwise = text "store" <+> ppr val <> comma <+> ppr dst
where
isVecPtrVar :: LlvmVar -> Bool
isVecPtrVar = isVector . pLower . getVarType
ppCast :: LlvmCastOp -> LlvmVar -> LlvmType -> SDoc
ppCast op from to = ppr op <+> ppr from <+> text "to" <+> ppr to
ppMalloc :: LlvmType -> Int -> SDoc
ppMalloc tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "malloc" <+> ppr tp <> comma <+> ppr amount'
ppAlloca :: LlvmType -> Int -> SDoc
ppAlloca tp amount =
let amount' = LMLitVar $ LMIntLit (toInteger amount) i32
in text "alloca" <+> ppr tp <> comma <+> ppr amount'
ppGetElementPtr :: Bool -> LlvmVar -> [LlvmVar] -> SDoc
ppGetElementPtr inb ptr idx =
let indexes = comma <+> ppCommaJoin idx
inbound = if inb then text "inbounds" else empty
in text "getelementptr" <+> inbound <+> ppr ptr <> indexes
ppReturn :: Maybe LlvmVar -> SDoc
ppReturn (Just var) = text "ret" <+> ppr var
ppReturn Nothing = text "ret" <+> ppr LMVoid
ppBranch :: LlvmVar -> SDoc
ppBranch var = text "br" <+> ppr var
ppBranchIf :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppBranchIf cond trueT falseT
= text "br" <+> ppr cond <> comma <+> ppr trueT <> comma <+> ppr falseT
ppPhi :: LlvmType -> [(LlvmVar,LlvmVar)] -> SDoc
ppPhi tp preds =
let ppPreds (val, label) = brackets $ ppName val <> comma <+> ppName label
in text "phi" <+> ppr tp <+> hsep (punctuate comma $ map ppPreds preds)
ppSwitch :: LlvmVar -> LlvmVar -> [(LlvmVar,LlvmVar)] -> SDoc
ppSwitch scrut dflt targets =
let ppTarget (val, lab) = ppr val <> comma <+> ppr lab
ppTargets xs = brackets $ vcat (map ppTarget xs)
in text "switch" <+> ppr scrut <> comma <+> ppr dflt
<+> ppTargets targets
ppAsm :: LMString -> LMString -> LlvmType -> [LlvmVar] -> Bool -> Bool -> SDoc
ppAsm asm constraints rty vars sideeffect alignstack =
let asm' = doubleQuotes $ ftext asm
cons = doubleQuotes $ ftext constraints
rty' = ppr rty
vars' = lparen <+> ppCommaJoin vars <+> rparen
side = if sideeffect then text "sideeffect" else empty
align = if alignstack then text "alignstack" else empty
in text "call" <+> rty' <+> text "asm" <+> side <+> align <+> asm' <> comma
<+> cons <> vars'
ppExtract :: LlvmVar -> LlvmVar -> SDoc
ppExtract vec idx =
text "extractelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr idx
ppInsert :: LlvmVar -> LlvmVar -> LlvmVar -> SDoc
ppInsert vec elt idx =
text "insertelement"
<+> ppr (getVarType vec) <+> ppName vec <> comma
<+> ppr (getVarType elt) <+> ppName elt <> comma
<+> ppr idx
ppMetaStatement :: [MetaAnnot] -> LlvmStatement -> SDoc
ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
ppMetaExpr :: [MetaAnnot] -> LlvmExpression -> SDoc
ppMetaExpr meta expr = ppLlvmExpression expr <> ppMetaAnnots meta
ppMetaAnnots :: [MetaAnnot] -> SDoc
ppMetaAnnots meta = hcat $ map ppMeta meta
where
ppMeta (MetaAnnot name e)
= comma <+> exclamation <> ftext name <+>
case e of
MetaNode n -> exclamation <> int n
MetaStruct ms -> exclamation <> braces (ppCommaJoin ms)
other -> exclamation <> braces (ppr other) -- possible?
--------------------------------------------------------------------------------
-- * Misc functions
--------------------------------------------------------------------------------
-- | Blank line.
newLine :: SDoc
newLine = empty
-- | Exclamation point.
exclamation :: SDoc
exclamation = char '!'
| ekmett/ghc | compiler/llvmGen/Llvm/PpLlvm.hs | bsd-3-clause | 16,451 | 0 | 18 | 4,659 | 4,502 | 2,199 | 2,303 | 298 | 14 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
-------------------------------------------------------------------------------
--
-- (c) The University of Glasgow 2007
--
-- | Break Arrays
--
-- An array of bytes, indexed by a breakpoint number (breakpointId in Tickish)
-- There is one of these arrays per module.
--
-- Each byte is
-- 1 if the corresponding breakpoint is enabled
-- 0 otherwise
--
-------------------------------------------------------------------------------
module GHCi.BreakArray
(
BreakArray
(BA) -- constructor is exported only for ByteCodeGen
, newBreakArray
, getBreak
, setBreakOn
, setBreakOff
, showBreakArray
) where
import Prelude -- See note [Why do we import Prelude here?]
import Control.Monad
import Data.Word
import GHC.Word
import GHC.Exts
import GHC.IO ( IO(..) )
import System.IO.Unsafe ( unsafeDupablePerformIO )
data BreakArray = BA (MutableByteArray# RealWorld)
breakOff, breakOn :: Word8
breakOn = 1
breakOff = 0
showBreakArray :: BreakArray -> IO ()
showBreakArray array = do
forM_ [0 .. (size array - 1)] $ \i -> do
val <- readBreakArray array i
putStr $ ' ' : show val
putStr "\n"
setBreakOn :: BreakArray -> Int -> IO Bool
setBreakOn array index
| safeIndex array index = do
writeBreakArray array index breakOn
return True
| otherwise = return False
setBreakOff :: BreakArray -> Int -> IO Bool
setBreakOff array index
| safeIndex array index = do
writeBreakArray array index breakOff
return True
| otherwise = return False
getBreak :: BreakArray -> Int -> IO (Maybe Word8)
getBreak array index
| safeIndex array index = do
val <- readBreakArray array index
return $ Just val
| otherwise = return Nothing
safeIndex :: BreakArray -> Int -> Bool
safeIndex array index = index < size array && index >= 0
size :: BreakArray -> Int
size (BA array) = size
where
-- We want to keep this operation pure. The mutable byte array
-- is never resized so this is safe.
size = unsafeDupablePerformIO $ sizeofMutableByteArray array
sizeofMutableByteArray :: MutableByteArray# RealWorld -> IO Int
sizeofMutableByteArray arr =
IO $ \s -> case getSizeofMutableByteArray# arr s of
(# s', n# #) -> (# s', I# n# #)
allocBA :: Int -> IO BreakArray
allocBA (I# sz) = IO $ \s1 ->
case newByteArray# sz s1 of { (# s2, array #) -> (# s2, BA array #) }
-- create a new break array and initialise elements to zero
newBreakArray :: Int -> IO BreakArray
newBreakArray entries@(I# sz) = do
BA array <- allocBA entries
case breakOff of
W8# off -> do
let loop n | isTrue# (n ==# sz) = return ()
| otherwise = do writeBA# array n off; loop (n +# 1#)
loop 0#
return $ BA array
writeBA# :: MutableByteArray# RealWorld -> Int# -> Word# -> IO ()
writeBA# array i word = IO $ \s ->
case writeWord8Array# array i word s of { s -> (# s, () #) }
writeBreakArray :: BreakArray -> Int -> Word8 -> IO ()
writeBreakArray (BA array) (I# i) (W8# word) = writeBA# array i word
readBA# :: MutableByteArray# RealWorld -> Int# -> IO Word8
readBA# array i = IO $ \s ->
case readWord8Array# array i s of { (# s, c #) -> (# s, W8# c #) }
readBreakArray :: BreakArray -> Int -> IO Word8
readBreakArray (BA array) (I# i) = readBA# array i
| sdiehl/ghc | libraries/ghci/GHCi/BreakArray.hs | bsd-3-clause | 3,479 | 0 | 20 | 850 | 1,009 | 508 | 501 | 80 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE TemplateHaskell #-}
module ParseSystem where
import ClassyPrelude hiding (throwM)
import Data.Attoparsec.ByteString.Char8 hiding (take)
import qualified Data.Attoparsec.Types as A
import StreamParser
import Data.Time hiding (readTime)
import Control.Lens hiding (index)
data System
= LoadAverage
{ _timeStamp :: LocalTime
, _val :: Double
} deriving Show
makeLenses ''System
parseLoadAverage :: Int -> TimeZone -> CSVSettings -> A.Parser ByteString System
parseLoadAverage column tz csvSettings = do
row <- parseRow csvSettings
let mPair = (,) <$> index row 0 <*> index row column
case mPair of
Nothing -> fail "Could not find the load average"
Just (timeStr, valStr) -> do
let eVal = readTime tz (unpack (decodeUtf8 timeStr), unpack (decodeUtf8 valStr))
case eVal of
Left msg -> fail msg
Right (time, val) -> return $ LoadAverage time val
readTime :: TimeZone -> (String, String) -> Either String (LocalTime, Double)
readTime tz (t, v) = do
time <- parseTimeM True defaultTimeLocale "%e %b %Y %X %Z" t
case readMay v of
Nothing -> Left $ "Could not read " <> show v
Just dbl -> Right $ (utcToLocalTime tz time, dbl)
| limaner2002/EPC-tools | plots/src/ParseSystem.hs | bsd-3-clause | 1,274 | 0 | 19 | 259 | 396 | 208 | 188 | 33 | 3 |
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE DeriveAnyClass, StandaloneDeriving, DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
{-# OPTIONS_GHC -fwarn-incomplete-uni-patterns #-}
module Day11 where
import Test.Hspec
import Control.Monad (guard)
import Data.List
import Debug.Trace
import qualified Data.Set as Set
import qualified Data.Map as Map
import Data.ByteString.Char8 (ByteString, split)
import qualified Data.ByteString.Char8 as BS
import Utils
-- Parsing
parser s = let l = BS.lines s
in fmap parseLine l
parseLine l = let w = BS.words l
in parseWords w
parseWords (x:w:xs)
| "generator" `BS.isPrefixOf` w = (Generator (x)) : parseWords xs
| "microchip" `BS.isPrefixOf` w = (Chip ((head (split '-' x)))) : parseWords xs
| otherwise = parseWords (w:xs)
parseWords (_:xs) = parseWords xs
parseWords [] = []
-- Input DSL
data Item = Generator ByteString | Chip ByteString deriving (Show, Eq, Ord)
data Status = Status Int [[Item]] deriving (Show, Eq, Ord)
-- Problem DSL
possibleMoves floor = do
x <- floor
-- can be anything not already selected. The ordering relationship ensure that
-- we don't select swapped pairs
maybeY <- Nothing : fmap Just (filter (\v -> v /= x && v > x) floor)
let move = case maybeY of
Nothing -> [x]
Just y -> [x, y]
return move
possibleMoves2 (Status floorNb floors) = do
let currentFloor = floors !! floorNb
movesThisFloor = possibleMoves currentFloor
move <- movesThisFloor
let newCurrentFloor = filter (\x -> not (x `elem` move)) currentFloor
guard $ checkFloor newCurrentFloor
nextFloorNb <- [floorNb - 1, floorNb + 1]
guard $ nextFloorNb >= 0 && nextFloorNb < nbFloors
let newNextFloor = (floors !! nextFloorNb) ++ move
guard $ checkFloor newNextFloor
return . reduceProblem $ Status nextFloorNb (replace floorNb newCurrentFloor (replace nextFloorNb newNextFloor floors))
-- Uglyly written ;)
-- It transform a status to a conanical one shared amongs many others
reduceProblem (Status n l) = let allnames = getGenS (mconcat l)
allnames2 = sortOn bli allnames
bli s = (blu Map.! (Generator s), blu Map.! (Chip s), s)
blu = Map.fromList (mconcat (fmap (\(item, idx) -> fmap (,idx) item) (zip l [0..])))
sortedNames = sort allnames
replaces = Map.fromList (zip allnames2 sortedNames)
rep aList = sort (fmap rep' aList)
rep' (Generator x) = Generator (replaces Map.! x)
rep' (Chip x) = Chip (replaces Map.! x)
in Status n (fmap rep l)
-- utils
replace :: Int -> t -> [t] -> [t]
replace 0 newItem (_:xs) = newItem : xs
replace n newItem (x:xs) = x : replace (n - 1) newItem xs
start = Status 0
nbFloors = 4
checkFloor floor = not (isRadioactive floor) || allChipProtected floor
isRadioactive = any isGenerator
allChipProtected floor = let chipS = getChipS floor
genS = getGenS floor
in all (`elem` genS) chipS
getChipS = fmap (\(Chip s) -> s) . filter (not . isGenerator)
getGenS = fmap (\(Generator s) -> s). filter (isGenerator)
isGenerator (Generator _) = True
isGenerator (Chip _) = False
bfs' floors = let (_, _, d) = bfs stopCriterion (Status 0 floors) step in d
where stopCriterion todos done depth = case traceShow (depth, length todos, length done) $ find gameDone todos of
Just _ -> True
Nothing -> False
step = possibleMoves2
gameDone (Status _ [[], [], [], _]) = True
gameDone _ = False
day code = bfs' code
-- SECOND problem
day' [a, b, c, d] = bfs' [a', b, c, d]
where a' = sort (a ++ [Generator el, Chip el, Generator dil, Chip dil])
where el = "elerium"
dil = "dilithium"
-- tests and data
-- comment out and add tests
test = hspec $ do
it "isRadioactive" $ do
isRadioactive [Chip "hello", Chip "you"] `shouldBe` False
isRadioactive [Chip "hello", Generator "you"] `shouldBe` True
it "allChipProtected" $ do
allChipProtected [Chip "hello"] `shouldBe` False
allChipProtected [Chip "hello", Generator "you"] `shouldBe` False
allChipProtected [Chip "you", Generator "you", Generator "blork"] `shouldBe` True
allChipProtected [Chip "you", Generator "you"] `shouldBe` True
allChipProtected [Chip "a", Chip "you", Generator "you"] `shouldBe` False
it "checkFloor" $ do
checkFloor [Chip "hello"] `shouldBe` True
checkFloor [Chip "hello", Generator "you"] `shouldBe` False
checkFloor [Chip "you", Generator "you", Generator "blork"] `shouldBe` True
checkFloor [Chip "you", Generator "you"] `shouldBe` True
checkFloor [Chip "a", Chip "you", Generator "you"] `shouldBe` False
it "worksForAll" $ do
day <$> content `shouldReturn` 37
day' <$> content `shouldReturn` 61
fileContent = BS.readFile "content/day11"
content = parser <$> fileContent
exampleProblem = parser "\
\The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.\n\
\The second floor contains a hydrogen generator.\n\
\The third floor contains a lithium generator.\n\
\The fourth floor contains nothing relevant."
| guibou/AdventOfCode2016 | src/Day11.hs | bsd-3-clause | 5,409 | 0 | 17 | 1,352 | 1,817 | 937 | 880 | 103 | 2 |
-- Run all tests for the Haskell CnC Runtime System.
import System.Directory
import qualified Intel.Cnc
import qualified Intel.CncPure
import qualified Intel.CncUtil
import System.Cmd(system)
import System.Exit
import HSH
import Test.HUnit
import Data.String.Utils -- from MissingH package
main = do
cd <- getCurrentDirectory
putStrLn$ "Running Unit tests in directory: " ++ show cd
putStrLn$ "\n================================================================================"
putStrLn$ "Running "++ show (testCaseCount Intel.CncUtil.tests) ++" tests from Intel.CncUtil"
putStrLn$ "================================================================================\n"
code1 <- runTestTT Intel.CncUtil.tests
putStrLn$ "\n================================================================================"
putStrLn$ "Running "++ show (testCaseCount Intel.Cnc.tests) ++" tests from Intel.Cnc"
putStrLn$ "================================================================================\n"
code2 <- runTestTT Intel.Cnc.tests
putStrLn$ "\n================================================================================"
putStrLn$ "Running "++ show (testCaseCount Intel.CncPure.tests) ++" tests from Intel.CncPure"
putStrLn$ "================================================================================\n"
code3 <- runTestTT Intel.CncPure.tests
let problems = errors code1 + failures code1 +
errors code2 + failures code2 +
errors code3 + failures code3
putStrLn$ "\n================================================================================"
putStrLn$ "Finally running system tests in all configurations (example programs):"
putStrLn$ "================================================================================\n"
b1 <- doesFileExist "run_all_examples.sh"
if b1
then putStrLn "!!! run_all_examples.sh found in current directory, using that!\n\n"
else do [ver] <- run "ghc-pkg latest haskell-cnc"
dir <- run$ ("ghc-pkg field "++ver++" include-dirs ") -|- replace "include-dirs:" ""
putStrLn$ "Switching to directory: " ++ show (strip dir)
setCurrentDirectory (strip dir)
b2 <- doesFileExist "run_all_examples.sh"
if not b2
then error$ "Uh oh, the script run_all_examples.sh doesn't exist in this directory.\n"
-- " If cabal installed the package you may find it in your ~/.cabal/lib directory."
else return ()
-- I have problems with cabal sdist not preserving executable flags.
system "chmod +x ./runcnc"
system "chmod +x ./run_all_examples.sh"
system "chmod +x ./ntimes"
system "chmod +x ./ntimes_minmedmax"
code <- system "TRIALS=1 ./run_all_examples.sh"
let code = ExitSuccess
case (problems,code) of
(0, ExitSuccess) -> exitWith ExitSuccess
(n, ExitSuccess) -> do putStrLn$ "ERROR: "++ show n ++" failures in unit tests!"; exitWith (ExitFailure n)
(_, ExitFailure n) -> do putStrLn "ERROR: Example programs failed!\n"; exitWith (ExitFailure n)
| rrnewton/Haskell-CnC | runAllTests.hs | bsd-3-clause | 3,241 | 32 | 10 | 682 | 531 | 285 | 246 | 51 | 5 |
{-# LANGUAGE RecordWildCards #-}
module Main where
import qualified Beba.Options as Beba
import qualified Beba.Env as Beba
import qualified Beba.Process as Beba
import Options.Applicative
import Data.Semigroup ((<>))
import Data.Version (showVersion)
import Data.Maybe
import qualified Paths_beba_parallel as P
import System.Posix.Signals
import System.Environment
import System.Process
import System.IO
import Control.Monad (forM, when)
import Control.Concurrent (threadDelay)
import Beba.Env
main :: IO ()
main = execParser opts >>= mainRun
where
opts = info (helper <*> Beba.parseOptions)
(fullDesc <> header "beba-parallel: multi-core BEBA switch (github.com/beba-eu/beba-switch)")
mainRun :: Beba.Options -> IO ()
mainRun opt@Beba.Options{..}
| version = putStrLn $ showVersion P.version
| otherwise = do
hld <- mainRunSwitch opt
_ <- installHandler sigTERM (Catch $ routeSignal "TERM" hld) Nothing
_ <- installHandler sigINT (Catch $ routeSignal "INT" hld) Nothing
_ <- installHandler sigHUP (Catch $ routeSignal "HUP" hld) Nothing
threadDelay 5000000
anyStopped hld >>= \err ->
when err $
putStrLn "An error occurred: Exit forced!" >> terminateAll hld
mainWait hld
routeSignal :: String -> [(ProcessHandle, ProcessHandle)] -> IO ()
routeSignal n hdl = do
putStrLn $ "Signal " ++ n ++ " catched..."
mapM_ (\(a,b) -> terminateProcess a >> terminateProcess b) hdl
terminateAll :: [(ProcessHandle, ProcessHandle)] -> IO ()
terminateAll = mapM_ (\(d,p) -> terminateProcess d >> terminateProcess p)
anyStopped :: [(ProcessHandle, ProcessHandle)] -> IO Bool
anyStopped xs =
or <$> (mapM (\(p,d) -> do
pe <- isJust <$> getProcessExitCode p
pd <- isJust <$> getProcessExitCode d
return (pe || pd)) xs)
mainWait :: [(ProcessHandle, ProcessHandle)] -> IO ()
mainWait = mapM_ (\(a,b) -> waitForProcess a >> waitForProcess b)
mainRunSwitch :: Beba.Options -> IO [(ProcessHandle, ProcessHandle)]
mainRunSwitch opt@Beba.Options{..} = do
let instances' = fromIntegral $ fromMaybe 1 instances
putStrLn $ "Launching " ++ show instances' ++ " instances ofdatapath/ofprotocol..."
forM [ 0 .. instances'-1 ] $ \n -> do
env' <- (<> pfqEnvironment n opt) <$> getEnvironment
dpath <- openFile ("/var/log/ofdatapath.log." ++ show n) AppendMode
(_, _, _, d) <- launchProcess verbose $ (Beba.mkOfDataPath n opt) { std_out = UseHandle dpath
, std_err = UseHandle dpath
, env = Just env' }
(_, _, _, p) <- launchProcess verbose $ Beba.mkOfProtocol n opt
pe <- isJust <$> getProcessExitCode p
pd <- isJust <$> getProcessExitCode d
threadDelay 500000
when (pe || pd) $
putStrLn "Error launching ofdata/protocol..."
return (d,p)
launchProcess :: Bool -> CreateProcess -> IO (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
launchProcess verb cp = when verb (print cp) *> createProcess cp
mainDummy :: Beba.Options -> IO ()
mainDummy opt =
putStrLn "Options:" *>
print opt *>
putStrLn "Env:" *>
print (Beba.pfqEnvironment 0 opt)
| awgn/beba-parallel | src/Main.hs | bsd-3-clause | 3,407 | 2 | 16 | 913 | 1,083 | 554 | 529 | 73 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
-- | Main stack tool entry point.
module Main where
import Control.Exception
import qualified Control.Exception.Lifted as EL
import Control.Monad hiding (mapM, forM)
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (ask, asks, runReaderT)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Attoparsec.Args (withInterpreterArgs, parseArgs, EscapingMode (Escaping))
import qualified Data.ByteString.Lazy as L
import Data.IORef
import Data.List
import qualified Data.Map as Map
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Monoid
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Data.Traversable
import Data.Typeable (Typeable)
import Data.Version (showVersion)
import Distribution.System (buildArch)
import Distribution.Text (display)
import Development.GitRev (gitCommitCount)
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import Network.HTTP.Client
import Options.Applicative.Args
import Options.Applicative.Builder.Extra
import Options.Applicative.Simple
import Options.Applicative.Types (readerAsk)
import Path
import Path.IO
import qualified Paths_stack as Meta
import Prelude hiding (pi, mapM)
import Stack.Build
import Stack.Types.Build
import Stack.Config
import Stack.Constants
import qualified Stack.Docker as Docker
import Stack.Dot
import Stack.Exec
import Stack.Fetch
import Stack.FileWatch
import Stack.Ide
import qualified Stack.Image as Image
import Stack.Init
import Stack.New
import Stack.Options
import Stack.Package (getCabalFileName)
import qualified Stack.PackageIndex
import Stack.Ghci
import Stack.GhcPkg (getGlobalDB, mkGhcPackagePath)
import Stack.SDist (getSDistTarball)
import Stack.Setup
import Stack.Solver (solveExtraDeps)
import Stack.Types
import Stack.Types.Internal
import Stack.Types.StackT
import Stack.Upgrade
import qualified Stack.Upload as Upload
import System.Directory (canonicalizePath, doesFileExist, doesDirectoryExist, createDirectoryIfMissing)
import System.Environment (getEnvironment, getProgName)
import System.Exit
import System.FileLock (lockFile, tryLockFile, unlockFile, SharedExclusive(Exclusive), FileLock)
import System.FilePath (dropTrailingPathSeparator, searchPathSeparator)
import System.IO (hIsTerminalDevice, stderr, stdin, stdout, hSetBuffering, BufferMode(..), hPutStrLn, Handle, hGetEncoding, hSetEncoding)
import System.Process.Read
-- | Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name
| '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- | Commandline dispatcher.
main :: IO ()
main = withInterpreterArgs stackProgName $ \args isInterpreter -> do
-- Line buffer the output by default, particularly for non-terminal runs.
-- See https://github.com/commercialhaskell/stack/pull/360
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
hSetBuffering stderr LineBuffering
hSetTranslit stdout
hSetTranslit stderr
progName <- getProgName
isTerminal <- hIsTerminalDevice stdout
execExtraHelp args
dockerHelpOptName
(dockerOptsParser True)
("Only showing --" ++ Docker.dockerCmdName ++ "* options.")
let versionString' = concat $ concat
[ [$(simpleVersion Meta.version)]
-- Leave out number of commits for --depth=1 clone
-- See https://github.com/commercialhaskell/stack/issues/792
, [" (" ++ $gitCommitCount ++ " commits)" | $gitCommitCount /= ("1"::String) &&
$gitCommitCount /= ("UNKNOWN" :: String)]
, [" ", display buildArch]
]
let numericVersion :: Parser (a -> a)
numericVersion =
infoOption
(showVersion Meta.version)
(long "numeric-version" <>
help "Show only version number")
eGlobalRun <- try $
simpleOptions
versionString'
"stack - The Haskell Tool Stack"
""
(numericVersion <*> extraHelpOption progName (Docker.dockerCmdName ++ "*") dockerHelpOptName <*>
globalOptsParser isTerminal)
(do addCommand "build"
"Build the project(s) in this directory/configuration"
buildCmd
(buildOptsParser Build)
addCommand "install"
"Shortcut for 'build --copy-bins'"
buildCmd
(buildOptsParser Install)
addCommand "uninstall"
"DEPRECATED: This command performs no actions, and is present for documentation only"
uninstallCmd
(many $ strArgument $ metavar "IGNORED")
addCommand "test"
"Shortcut for 'build --test'"
buildCmd
(buildOptsParser Test)
addCommand "bench"
"Shortcut for 'build --bench'"
buildCmd
(buildOptsParser Bench)
addCommand "haddock"
"Shortcut for 'build --haddock'"
buildCmd
(buildOptsParser Haddock)
addCommand "new"
"Create a new project from a template. Run `stack templates' to see available templates."
newCmd
newOptsParser
addCommand "templates"
"List the templates available for `stack new'."
templatesCmd
(pure ())
addCommand "init"
"Initialize a stack project based on one or more cabal packages"
initCmd
initOptsParser
addCommand "solver"
"Use a dependency solver to try and determine missing extra-deps"
solverCmd
solverOptsParser
addCommand "setup"
"Get the appropriate GHC for your project"
setupCmd
setupParser
addCommand "path"
"Print out handy path information"
pathCmd
(fmap
catMaybes
(sequenceA
(map
(\(desc,name,_) ->
flag Nothing
(Just name)
(long (T.unpack name) <>
help desc))
paths)))
addCommand "unpack"
"Unpack one or more packages locally"
unpackCmd
(some $ strArgument $ metavar "PACKAGE")
addCommand "update"
"Update the package index"
updateCmd
(pure ())
addCommand "upgrade"
"Upgrade to the latest stack (experimental)"
upgradeCmd
((,) <$> (switch
( long "git"
<> help "Clone from Git instead of downloading from Hackage (more dangerous)"
))
<*> (strOption
( long "git-repo"
<> help "Clone from specified git repository"
<> value "https://github.com/commercialhaskell/stack"
<> showDefault
)))
addCommand "upload"
"Upload a package to Hackage"
uploadCmd
((,)
<$> (many $ strArgument $ metavar "TARBALL/DIR")
<*> optional pvpBoundsOption)
addCommand "sdist"
"Create source distribution tarballs"
sdistCmd
((,)
<$> (many $ strArgument $ metavar "DIR")
<*> optional pvpBoundsOption)
addCommand "dot"
"Visualize your project's dependency graph using Graphviz dot"
dotCmd
dotOptsParser
addCommand "exec"
"Execute a command"
execCmd
(execOptsParser Nothing)
addCommand "ghc"
"Run ghc"
execCmd
(execOptsParser $ Just "ghc")
addCommand "ghci"
"Run ghci in the context of project(s) (experimental)"
ghciCmd
ghciOptsParser
addCommand "runghc"
"Run runghc"
execCmd
(execOptsParser $ Just "runghc")
addCommand "eval"
"Evaluate some haskell code inline. Shortcut for 'stack exec ghc -- -e CODE'"
evalCmd
(evalOptsParser $ Just "CODE") -- metavar = "CODE"
addCommand "clean"
"Clean the local packages"
cleanCmd
(pure ())
addCommand "list-dependencies"
"List the dependencies"
listDependenciesCmd
(textOption (long "separator" <>
metavar "SEP" <>
help ("Separator between package name " <>
"and package version.") <>
value " " <>
showDefault))
addCommand "query"
"Query general build information (experimental)"
queryCmd
(many $ strArgument $ metavar "SELECTOR...")
addSubCommands
"ide"
"IDE-specific commands"
(do addCommand
"start"
"Start the ide-backend service"
ideCmd
((,) <$> many (textArgument
(metavar "TARGET" <>
help ("If none specified, use all " <>
"packages defined in current directory")))
<*> argsOption (long "ghc-options" <>
metavar "OPTION" <>
help "Additional options passed to GHCi" <>
value []))
addCommand
"packages"
"List all available local loadable packages"
packagesCmd
(pure ())
addCommand
"load-targets"
"List all load targets for a package target"
targetsCmd
(textArgument
(metavar "TARGET")))
addSubCommands
Docker.dockerCmdName
"Subcommands specific to Docker use"
(do addCommand Docker.dockerPullCmdName
"Pull latest version of Docker image from registry"
dockerPullCmd
(pure ())
addCommand "reset"
"Reset the Docker sandbox"
dockerResetCmd
(flag False True (long "keep-home" <>
help "Do not delete sandbox's home directory"))
addCommand Docker.dockerCleanupCmdName
"Clean up Docker images and containers"
dockerCleanupCmd
dockerCleanupOptsParser)
addSubCommands
Image.imgCmdName
"Subcommands specific to imaging (EXPERIMENTAL)"
(addCommand Image.imgDockerCmdName
"Build a Docker image for the project"
imgDockerCmd
(pure ())))
case eGlobalRun of
Left (exitCode :: ExitCode) -> do
when isInterpreter $
hPutStrLn stderr $ concat
[ "\nIf you are trying to use "
, stackProgName
, " as a script interpreter, a\n'-- "
, stackProgName
, " [options] runghc [options]' comment is required."
, "\nSee https://github.com/commercialhaskell/stack/blob/release/doc/GUIDE.md#ghcrunghc" ]
throwIO exitCode
Right (global,run) -> do
when (globalLogLevel global == LevelDebug) $ hPutStrLn stderr versionString'
case globalReExecVersion global of
Just expectVersion
| expectVersion /= showVersion Meta.version ->
throwIO $ InvalidReExecVersion expectVersion (showVersion Meta.version)
_ -> return ()
run global `catch` \e -> do
-- This special handler stops "stack: " from being printed before the
-- exception
case fromException e of
Just ec -> exitWith ec
Nothing -> do
printExceptionStderr e
exitFailure
where
dockerHelpOptName = Docker.dockerCmdName ++ "-help"
-- | Print out useful path information in a human-readable format (and
-- support others later).
pathCmd :: [Text] -> GlobalOpts -> IO ()
pathCmd keys go =
withBuildConfig
go
(do env <- ask
let cfg = envConfig env
bc = envConfigBuildConfig cfg
menv <- getMinimalEnvOverride
snap <- packageDatabaseDeps
local <- packageDatabaseLocal
global <- getGlobalDB menv =<< getWhichCompiler
snaproot <- installationRootDeps
localroot <- installationRootLocal
distDir <- distRelativeDir
forM_
(filter
(\(_,key,_) ->
null keys || elem key keys)
paths)
(\(_,key,path) ->
liftIO $ T.putStrLn
((if length keys == 1
then ""
else key <> ": ") <>
path
(PathInfo
bc
menv
snap
local
global
snaproot
localroot
distDir))))
-- | Passed to all the path printers as a source of info.
data PathInfo = PathInfo
{piBuildConfig :: BuildConfig
,piEnvOverride :: EnvOverride
,piSnapDb :: Path Abs Dir
,piLocalDb :: Path Abs Dir
,piGlobalDb :: Path Abs Dir
,piSnapRoot :: Path Abs Dir
,piLocalRoot :: Path Abs Dir
,piDistDir :: Path Rel Dir
}
-- | The paths of interest to a user. The first tuple string is used
-- for a description that the optparse flag uses, and the second
-- string as a machine-readable key and also for @--foo@ flags. The user
-- can choose a specific path to list like @--global-stack-root@. But
-- really it's mainly for the documentation aspect.
--
-- When printing output we generate @PathInfo@ and pass it to the
-- function to generate an appropriate string. Trailing slashes are
-- removed, see #506
paths :: [(String, Text, PathInfo -> Text)]
paths =
[ ( "Global stack root directory"
, "global-stack-root"
, \pi ->
T.pack (toFilePathNoTrailing (configStackRoot (bcConfig (piBuildConfig pi)))))
, ( "Project root (derived from stack.yaml file)"
, "project-root"
, \pi ->
T.pack (toFilePathNoTrailing (bcRoot (piBuildConfig pi))))
, ( "Configuration location (where the stack.yaml file is)"
, "config-location"
, \pi ->
T.pack (toFilePathNoTrailing (bcStackYaml (piBuildConfig pi))))
, ( "PATH environment variable"
, "bin-path"
, \pi ->
T.pack (intercalate [searchPathSeparator] (eoPath (piEnvOverride pi))))
, ( "Installed GHCs (unpacked and archives)"
, "ghc-paths"
, \pi ->
T.pack (toFilePathNoTrailing (configLocalPrograms (bcConfig (piBuildConfig pi)))))
, ( "Local bin path where stack installs executables"
, "local-bin-path"
, \pi ->
T.pack (toFilePathNoTrailing (configLocalBin (bcConfig (piBuildConfig pi)))))
, ( "Extra include directories"
, "extra-include-dirs"
, \pi ->
T.intercalate
", "
(Set.elems (configExtraIncludeDirs (bcConfig (piBuildConfig pi)))))
, ( "Extra library directories"
, "extra-library-dirs"
, \pi ->
T.intercalate ", " (Set.elems (configExtraLibDirs (bcConfig (piBuildConfig pi)))))
, ( "Snapshot package database"
, "snapshot-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailing (piSnapDb pi)))
, ( "Local project package database"
, "local-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailing (piLocalDb pi)))
, ( "Global package database"
, "global-pkg-db"
, \pi ->
T.pack (toFilePathNoTrailing (piGlobalDb pi)))
, ( "GHC_PACKAGE_PATH environment variable"
, "ghc-package-path"
, \pi -> mkGhcPackagePath True (piLocalDb pi) (piSnapDb pi) (piGlobalDb pi))
, ( "Snapshot installation root"
, "snapshot-install-root"
, \pi ->
T.pack (toFilePathNoTrailing (piSnapRoot pi)))
, ( "Local project installation root"
, "local-install-root"
, \pi ->
T.pack (toFilePathNoTrailing (piLocalRoot pi)))
, ( "Snapshot documentation root"
, "snapshot-doc-root"
, \pi ->
T.pack (toFilePathNoTrailing (piSnapRoot pi </> docDirSuffix)))
, ( "Local project documentation root"
, "local-doc-root"
, \pi ->
T.pack (toFilePathNoTrailing (piLocalRoot pi </> docDirSuffix)))
, ( "Dist work directory"
, "dist-dir"
, \pi ->
T.pack (toFilePathNoTrailing (piDistDir pi)))]
where toFilePathNoTrailing = dropTrailingPathSeparator . toFilePath
data SetupCmdOpts = SetupCmdOpts
{ scoCompilerVersion :: !(Maybe CompilerVersion)
, scoForceReinstall :: !Bool
, scoUpgradeCabal :: !Bool
, scoStackSetupYaml :: !String
, scoGHCBindistURL :: !(Maybe String)
}
setupParser :: Parser SetupCmdOpts
setupParser = SetupCmdOpts
<$> (optional $ argument readVersion
(metavar "GHC_VERSION" <>
help ("Version of GHC to install, e.g. 7.10.2. " ++
"The default is to install the version implied by the resolver.")))
<*> boolFlags False
"reinstall"
"reinstalling GHC, even if available (implies no-system-ghc)"
idm
<*> boolFlags False
"upgrade-cabal"
"installing the newest version of the Cabal library globally"
idm
<*> strOption
( long "stack-setup-yaml"
<> help "Location of the main stack-setup.yaml file"
<> value defaultStackSetupYaml
<> showDefault
)
<*> (optional $ strOption
(long "ghc-bindist"
<> metavar "URL"
<> help "Alternate GHC binary distribution (requires custom --ghc-variant)"
))
where
readVersion = do
s <- readerAsk
case parseCompilerVersion ("ghc-" <> T.pack s) of
Nothing ->
case parseCompilerVersion (T.pack s) of
Nothing -> readerError $ "Invalid version: " ++ s
Just x -> return x
Just x -> return x
setupCmd :: SetupCmdOpts -> GlobalOpts -> IO ()
setupCmd SetupCmdOpts{..} go@GlobalOpts{..} = do
(manager,lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer
(lcProjectRoot lc)
Nothing
(runStackLoggingTGlobal manager go $ do
(wantedCompiler, compilerCheck, mstack) <-
case scoCompilerVersion of
Just v -> return (v, MatchMinor, Nothing)
Nothing -> do
bc <- lcLoadBuildConfig lc globalResolver
return ( bcWantedCompiler bc
, configCompilerCheck (lcConfig lc)
, Just $ bcStackYaml bc
)
miniConfig <- loadMiniConfig (lcConfig lc)
mpaths <- runStackTGlobal manager miniConfig go $
ensureCompiler SetupOpts
{ soptsInstallIfMissing = True
, soptsUseSystem =
(configSystemGHC $ lcConfig lc)
&& not scoForceReinstall
, soptsWantedCompiler = wantedCompiler
, soptsCompilerCheck = compilerCheck
, soptsStackYaml = mstack
, soptsForceReinstall = scoForceReinstall
, soptsSanityCheck = True
, soptsSkipGhcCheck = False
, soptsSkipMsys = configSkipMsys $ lcConfig lc
, soptsUpgradeCabal = scoUpgradeCabal
, soptsResolveMissingGHC = Nothing
, soptsStackSetupYaml = scoStackSetupYaml
, soptsGHCBindistURL = scoGHCBindistURL
}
let compiler = case wantedCompiler of
GhcVersion _ -> "GHC"
GhcjsVersion {} -> "GHCJS"
case mpaths of
Nothing -> $logInfo $ "stack will use the " <> compiler <> " on your PATH"
Just _ -> $logInfo $ "stack will use a locally installed " <> compiler
$logInfo "For more information on paths, see 'stack path' and 'stack exec env'"
$logInfo $ "To use this " <> compiler <> " and packages outside of a project, consider using:"
$logInfo "stack ghc, stack ghci, stack runghc, or stack exec"
)
Nothing
(Just $ munlockFile lk)
-- | Unlock a lock file, if the value is Just
munlockFile :: MonadIO m => Maybe FileLock -> m ()
munlockFile Nothing = return ()
munlockFile (Just lk) = liftIO $ unlockFile lk
-- | Enforce mutual exclusion of every action running via this
-- function, on this path, on this users account.
--
-- A lock file is created inside the given directory. Currently,
-- stack uses locks per-snapshot. In the future, stack may refine
-- this to an even more fine-grain locking approach.
--
withUserFileLock :: (MonadBaseControl IO m, MonadIO m)
=> GlobalOpts
-> Path Abs Dir
-> (Maybe FileLock -> m a)
-> m a
withUserFileLock go@GlobalOpts{} dir act = do
env <- liftIO getEnvironment
let toLock = lookup "STACK_LOCK" env == Just "true"
if toLock
then do
let lockfile = $(mkRelFile "lockfile")
let pth = dir </> lockfile
liftIO $ createDirectoryIfMissing True (toFilePath dir)
-- Just in case of asynchronous exceptions, we need to be careful
-- when using tryLockFile here:
EL.bracket (liftIO $ tryLockFile (toFilePath pth) Exclusive)
(\fstTry -> maybe (return ()) (liftIO . unlockFile) fstTry)
(\fstTry ->
case fstTry of
Just lk -> EL.finally (act $ Just lk) (liftIO $ unlockFile lk)
Nothing ->
do let chatter = globalLogLevel go /= LevelOther "silent"
when chatter $
liftIO $ hPutStrLn stderr $ "Failed to grab lock ("++show pth++
"); other stack instance running. Waiting..."
EL.bracket (liftIO $ lockFile (toFilePath pth) Exclusive)
(liftIO . unlockFile)
(\lk -> do
when chatter $
liftIO $ hPutStrLn stderr "Lock acquired, proceeding."
act $ Just lk))
else act Nothing
withConfigAndLock :: GlobalOpts
-> StackT Config IO ()
-> IO ()
withConfigAndLock go@GlobalOpts{..} inner = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc)
Nothing
(runStackTGlobal manager (lcConfig lc) go inner)
Nothing
(Just $ munlockFile lk)
-- For now the non-locking version just unlocks immediately.
-- That is, there's still a serialization point.
withBuildConfig :: GlobalOpts
-> (StackT EnvConfig IO ())
-> IO ()
withBuildConfig go inner =
withBuildConfigAndLock go (\lk -> do munlockFile lk
inner)
withBuildConfigAndLock :: GlobalOpts
-> (Maybe FileLock -> StackT EnvConfig IO ())
-> IO ()
withBuildConfigAndLock go inner =
withBuildConfigExt go Nothing inner Nothing
withBuildConfigExt
:: GlobalOpts
-> Maybe (StackT Config IO ())
-- ^ Action to perform after before build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> (Maybe FileLock -> StackT EnvConfig IO ())
-- ^ Action that uses the build config. If Docker is enabled for builds,
-- this will be run in a Docker container.
-> Maybe (StackT Config IO ())
-- ^ Action to perform after the build. This will be run on the host
-- OS even if Docker is enabled for builds. The build config is not
-- available in this action, since that would require build tools to be
-- installed on the host OS.
-> IO ()
withBuildConfigExt go@GlobalOpts{..} mbefore inner mafter = do
(manager, lc) <- loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk0 -> do
-- A local bit of state for communication between callbacks:
curLk <- newIORef lk0
let inner' lk =
-- Locking policy: This is only used for build commands, which
-- only need to lock the snapshot, not the global lock. We
-- trade in the lock here.
do dir <- installationRootDeps
-- Hand-over-hand locking:
withUserFileLock go dir $ \lk2 -> do
liftIO $ writeIORef curLk lk2
liftIO $ munlockFile lk
inner lk2
let inner'' lk = do
bconfig <- runStackLoggingTGlobal manager go $
lcLoadBuildConfig lc globalResolver
envConfig <-
runStackTGlobal
manager bconfig go
(setupEnv Nothing)
runStackTGlobal
manager
envConfig
go
(inner' lk)
runStackTGlobal manager (lcConfig lc) go $
Docker.reexecWithOptionalContainer (lcProjectRoot lc) mbefore (inner'' lk0) mafter
(Just $ liftIO $
do lk' <- readIORef curLk
munlockFile lk')
cleanCmd :: () -> GlobalOpts -> IO ()
cleanCmd () go = withBuildConfigAndLock go (\_ -> clean)
-- | Helper for build and install commands
buildCmd :: BuildOpts -> GlobalOpts -> IO ()
buildCmd opts go = do
when (any (("-prof" `elem`) . either (const []) id . parseArgs Escaping) (boptsGhcOptions opts)) $ do
hPutStrLn stderr "When building with stack, you should not use the -prof GHC option"
hPutStrLn stderr "Instead, please use --enable-library-profiling and --enable-executable-profiling"
hPutStrLn stderr "See: https://github.com/commercialhaskell/stack/issues/1015"
error "-prof GHC option submitted"
case boptsFileWatch opts of
FileWatchPoll -> fileWatchPoll getProjectRoot inner
FileWatch -> fileWatch getProjectRoot inner
NoFileWatch -> inner $ const $ return ()
where
inner setLocalFiles = withBuildConfigAndLock go $ \lk ->
Stack.Build.build setLocalFiles lk opts
getProjectRoot = do
(manager, lc) <- loadConfigWithOpts go
bconfig <-
runStackLoggingTGlobal manager go $
lcLoadBuildConfig lc (globalResolver go)
return (bcRoot bconfig)
uninstallCmd :: [String] -> GlobalOpts -> IO ()
uninstallCmd _ go = withConfigAndLock go $ do
$logError "stack does not manage installations in global locations"
$logError "The only global mutation stack performs is executable copying"
$logError "For the default executable destination, please run 'stack path --local-bin-path'"
-- | Unpack packages to the filesystem
unpackCmd :: [String] -> GlobalOpts -> IO ()
unpackCmd names go = withConfigAndLock go $ do
menv <- getMinimalEnvOverride
Stack.Fetch.unpackPackages menv "." names
-- | Update the package index
updateCmd :: () -> GlobalOpts -> IO ()
updateCmd () go = withConfigAndLock go $
getMinimalEnvOverride >>= Stack.PackageIndex.updateAllIndices
upgradeCmd :: (Bool, String) -> GlobalOpts -> IO ()
upgradeCmd (fromGit, repo) go = withConfigAndLock go $
upgrade (if fromGit then Just repo else Nothing) (globalResolver go)
-- | Upload to Hackage
uploadCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
uploadCmd ([], _) _ = error "To upload the current package, please run 'stack upload .'"
uploadCmd (args, mpvpBounds) go = do
let partitionM _ [] = return ([], [])
partitionM f (x:xs) = do
r <- f x
(as, bs) <- partitionM f xs
return $ if r then (x:as, bs) else (as, x:bs)
(files, nonFiles) <- partitionM doesFileExist args
(dirs, invalid) <- partitionM doesDirectoryExist nonFiles
when (not (null invalid)) $ error $
"stack upload expects a list sdist tarballs or cabal directories. Can't find " ++
show invalid
let getUploader :: (HasStackRoot config, HasPlatform config, HasConfig config) => StackT config IO Upload.Uploader
getUploader = do
config <- asks getConfig
manager <- asks envManager
let uploadSettings =
Upload.setGetManager (return manager) $
Upload.defaultUploadSettings
liftIO $ Upload.mkUploader config uploadSettings
if null dirs
then withConfigAndLock go $ do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
else withBuildConfigAndLock go $ \_ -> do
uploader <- getUploader
liftIO $ forM_ files (canonicalizePath >=> Upload.upload uploader)
forM_ dirs $ \dir -> do
pkgDir <- parseAbsDir =<< liftIO (canonicalizePath dir)
(tarName, tarBytes) <- getSDistTarball mpvpBounds pkgDir
liftIO $ Upload.uploadBytes uploader tarName tarBytes
sdistCmd :: ([String], Maybe PvpBounds) -> GlobalOpts -> IO ()
sdistCmd (dirs, mpvpBounds) go =
withBuildConfig go $ do -- No locking needed.
-- If no directories are specified, build all sdist tarballs.
dirs' <- if null dirs
then asks (Map.keys . envConfigPackages . getEnvConfig)
else mapM (parseAbsDir <=< liftIO . canonicalizePath) dirs
forM_ dirs' $ \dir -> do
(tarName, tarBytes) <- getSDistTarball mpvpBounds dir
distDir <- distDirFromDir dir
tarPath <- fmap (distDir </>) $ parseRelFile tarName
liftIO $ createTree $ parent tarPath
liftIO $ L.writeFile (toFilePath tarPath) tarBytes
$logInfo $ "Wrote sdist tarball to " <> T.pack (toFilePath tarPath)
-- | Execute a command.
execCmd :: ExecOpts -> GlobalOpts -> IO ()
execCmd ExecOpts {..} go@GlobalOpts{..} = do
(cmd, args) <-
case (eoCmd, eoArgs) of
(Just cmd, args) -> return (cmd, args)
(Nothing, cmd:args) -> return (cmd, args)
(Nothing, []) -> error "You must provide a command to exec, e.g. 'stack exec echo Hello World'"
case eoExtra of
ExecOptsPlain -> do
(manager,lc) <- liftIO $ loadConfigWithOpts go
withUserFileLock go (configStackRoot $ lcConfig lc) $ \lk ->
runStackTGlobal manager (lcConfig lc) go $
Docker.execWithOptionalContainer
(lcProjectRoot lc)
(\_ _ -> return (cmd, args, [], []))
-- Unlock before transferring control away, whether using docker or not:
(Just $ munlockFile lk)
(runStackTGlobal manager (lcConfig lc) go $ do
exec plainEnvSettings cmd args)
Nothing
Nothing -- Unlocked already above.
ExecOptsEmbellished {..} ->
withBuildConfigAndLock go $ \lk -> do
let targets = concatMap words eoPackages
unless (null targets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack targets
}
munlockFile lk -- Unlock before transferring control away.
exec eoEnvSettings cmd args
-- | Evaluate some haskell code inline.
evalCmd :: EvalOpts -> GlobalOpts -> IO ()
evalCmd EvalOpts {..} go@GlobalOpts {..} = execCmd execOpts go
where
execOpts =
ExecOpts { eoCmd = Just "ghc"
, eoArgs = ["-e", evalArg]
, eoExtra = evalExtra
}
-- | Run GHCi in the context of a project.
ghciCmd :: GhciOpts -> GlobalOpts -> IO ()
ghciCmd ghciOpts go@GlobalOpts{..} =
withBuildConfigAndLock go $ \lk -> do
let packageTargets = concatMap words (ghciAdditionalPackages ghciOpts)
unless (null packageTargets) $
Stack.Build.build (const $ return ()) lk defaultBuildOpts
{ boptsTargets = map T.pack packageTargets
}
munlockFile lk -- Don't hold the lock while in the GHCI.
ghci ghciOpts
-- | Run ide-backend in the context of a project.
ideCmd :: ([Text], [String]) -> GlobalOpts -> IO ()
ideCmd (targets,args) go@GlobalOpts{..} =
withBuildConfig go $ -- No locking needed.
ide targets args
-- | List packages in the project.
packagesCmd :: () -> GlobalOpts -> IO ()
packagesCmd () go@GlobalOpts{..} =
withBuildConfig go $
do econfig <- asks getEnvConfig
locals <-
forM (M.toList (envConfigPackages econfig)) $
\(dir,_) ->
do cabalfp <- getCabalFileName dir
parsePackageNameFromFilePath cabalfp
forM_ locals (liftIO . putStrLn . packageNameString)
-- | List load targets for a package target.
targetsCmd :: Text -> GlobalOpts -> IO ()
targetsCmd target go@GlobalOpts{..} =
withBuildConfig go $
do (_realTargets,_,pkgs) <- ghciSetup Nothing [target]
pwd <- getWorkingDir
targets <-
fmap
(concat . snd . unzip)
(mapM (getPackageOptsAndTargetFiles pwd) pkgs)
forM_ targets (liftIO . putStrLn)
-- | Pull the current Docker image.
dockerPullCmd :: () -> GlobalOpts -> IO ()
dockerPullCmd _ go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer Docker.pull
-- | Reset the Docker sandbox.
dockerResetCmd :: Bool -> GlobalOpts -> IO ()
dockerResetCmd keepHome go@GlobalOpts{..} = do
(manager,lc) <- liftIO (loadConfigWithOpts go)
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackLoggingTGlobal manager go $
Docker.preventInContainer $ Docker.reset (lcProjectRoot lc) keepHome
-- | Cleanup Docker images and containers.
dockerCleanupCmd :: Docker.CleanupOpts -> GlobalOpts -> IO ()
dockerCleanupCmd cleanupOpts go@GlobalOpts{..} = do
(manager,lc) <- liftIO $ loadConfigWithOpts go
-- TODO: can we eliminate this lock if it doesn't touch ~/.stack/?
withUserFileLock go (configStackRoot $ lcConfig lc) $ \_ ->
runStackTGlobal manager (lcConfig lc) go $
Docker.preventInContainer $
Docker.cleanup cleanupOpts
imgDockerCmd :: () -> GlobalOpts -> IO ()
imgDockerCmd () go@GlobalOpts{..} = do
withBuildConfigExt
go
Nothing
(\lk ->
do Stack.Build.build
(const (return ()))
lk
defaultBuildOpts
Image.stageContainerImageArtifacts)
(Just Image.createContainerImageFromStage)
-- | Load the configuration with a manager. Convenience function used
-- throughout this module.
loadConfigWithOpts :: GlobalOpts -> IO (Manager,LoadConfig (StackLoggingT IO))
loadConfigWithOpts go@GlobalOpts{..} = do
manager <- newTLSManager
mstackYaml <-
case globalStackYaml of
Nothing -> return Nothing
Just fp -> do
path <- canonicalizePath fp >>= parseAbsFile
return $ Just path
lc <- runStackLoggingTGlobal
manager
go
(loadConfig globalConfigMonoid mstackYaml)
return (manager,lc)
-- | Project initialization
initCmd :: InitOpts -> GlobalOpts -> IO ()
initCmd initOpts go =
withConfigAndLock go $
do pwd <- getWorkingDir
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject pwd initOpts) miniConfig
-- | Create a project directory structure and initialize the stack config.
newCmd :: (NewOpts,InitOpts) -> GlobalOpts -> IO ()
newCmd (newOpts,initOpts) go@GlobalOpts{..} =
withConfigAndLock go $
do dir <- new newOpts
config <- asks getConfig
miniConfig <- loadMiniConfig config
runReaderT (initProject dir initOpts) miniConfig
-- | List the available templates.
templatesCmd :: () -> GlobalOpts -> IO ()
templatesCmd _ go@GlobalOpts{..} = withConfigAndLock go listTemplates
-- | Fix up extra-deps for a project
solverCmd :: Bool -- ^ modify stack.yaml automatically?
-> GlobalOpts
-> IO ()
solverCmd fixStackYaml go =
withBuildConfigAndLock go (\_ -> solveExtraDeps fixStackYaml)
-- | Visualize dependencies
dotCmd :: DotOpts -> GlobalOpts -> IO ()
dotCmd dotOpts go = withBuildConfigAndLock go (\_ -> dot dotOpts)
-- | List the dependencies
listDependenciesCmd :: Text -> GlobalOpts -> IO ()
listDependenciesCmd sep go = withBuildConfig go (listDependencies sep')
where sep' = T.replace "\\t" "\t" (T.replace "\\n" "\n" sep)
-- | Query build information
queryCmd :: [String] -> GlobalOpts -> IO ()
queryCmd selectors go = withBuildConfig go $ queryBuildInfo $ map T.pack selectors
data MainException = InvalidReExecVersion String String
deriving (Typeable)
instance Exception MainException
instance Show MainException where
show (InvalidReExecVersion expected actual) = concat
[ "When re-executing '"
, stackProgName
, "' in a container, the incorrect version was found\nExpected: "
, expected
, "; found: "
, actual]
| meiersi-11ce/stack | src/main/Main.hs | bsd-3-clause | 42,246 | 0 | 30 | 15,675 | 8,503 | 4,310 | 4,193 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Language.Pylon.Core.CaseTree
-- Copyright : (c) 2014 Lukas Heidemann
-- License : BSD
-- Maintainer : lukasheidemann@gmail.com
-- Stability : experimental
-- Portability : ghc
--
-- Left hand side pattern matching to case tree desugaring.
--
-- Based on:
-- * "The Implementation of Functional Programming Languages"
-- Simon Peyton Jones, published by Prentice Hall, 1987
--------------------------------------------------------------------------------
{-# LANGUAGE MultiParamTypeClasses, FlexibleContexts #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PatternSynonyms #-}
module Language.Pylon.Core.CaseTree
( Pat (..)
, CaseTree (..)
, Clause (..)
, toCaseTree
) where
--------------------------------------------------------------------------------
import Language.Pylon.Core.AST
import Language.Pylon.Core.Monad
import Language.Pylon.Util.Subst
import Language.Pylon.Util.Name
import Language.Pylon.Util
import Data.Maybe
import Data.List
import Control.Arrow
import Control.Monad
import Control.Applicative
import Control.Monad.State.Class (MonadState, gets, modify)
import Control.Monad.Trans.State (StateT, runStateT)
import Control.Monad.Error.Class (MonadError, throwError)
import Control.Concurrent.Supply
--------------------------------------------------------------------------------
-- Interface
--------------------------------------------------------------------------------
-- | Compiles a list of matches and a default expression into a case tree
-- | that scrutinizes a list of variables.
toCaseTree :: (MonadError String m, MonadProgram m, MonadSupply m) => [Match] -> Exp -> m (CaseTree, [Ident])
toCaseTree ms def = do
sp <- supplySplit
runCT sp $ do
let n = fromMaybe 0 $ fmap matchArity $ listToMaybe ms
qs <- mapM matchToEqu ms
vs <- freshNames n
ct <- match vs qs (CExp def)
return (ct, vs)
--------------------------------------------------------------------------------
-- Data Structures
--------------------------------------------------------------------------------
data Pat
= PVar Ident
| PCon Con [Pat]
deriving (Eq, Show)
data CaseTree
= CCase Ident [Clause]
| CExp Exp
deriving (Eq, Show)
data Clause = Clause Con [Ident] CaseTree
deriving (Eq, Show)
data Equ = Equ [Pat] Exp
deriving (Eq, Show)
--------------------------------------------------------------------------------
-- Monad
--------------------------------------------------------------------------------
newtype CT a = CT { fromCT :: StateT CTState (Either String) a }
deriving (Functor, Applicative, Monad, MonadState CTState, MonadError String)
data CTState = CTState
{ ctProgram :: Program
, ctNames :: Supply
} deriving (Eq, Show)
instance MonadProgram CT where
getProgram = gets ctProgram
instance MonadSupply CT where
getSupply = gets ctNames
putSupply s = modify $ \st -> st { ctNames = s }
freshName :: CT Ident
freshName = IGen "CaseTree" <$> supplyId
freshNames :: Int -> CT [Ident]
freshNames n = replicateM n freshName
runCT :: (MonadError String m, MonadProgram m) => Supply -> CT a -> m a
runCT sp go = do
p <- getProgram
liftEither $ fmap fst $ runStateT (fromCT go) $ CTState p sp
--------------------------------------------------------------------------------
-- Equations to Case Trees
--------------------------------------------------------------------------------
-- | Elaborates a group of equations matching a list of scrutinized variables.
-- |
-- | In case of an empty pattern match, an equation with no patterns is selected;
-- | if there is no such equation, the default value will be used.
-- |
-- | Otherwise the equations are grouped by their first pattern; then these groups
-- | are elaborated, with the next group serving as the default alternative of
-- | the former. The default alternative of the last group of equations is the
-- | supplied default alternative then.
match :: [Ident] -> [Equ] -> CaseTree -> CT CaseTree
match [] qs def = return $ fromMaybe def $ listToMaybe [ CExp e | Equ [] e <- qs ]
match vs qs def = foldr ((=<<) . matchVarCon vs) (return def) $ groupBy (liftPred isVar) qs
-- | Elaborates a group of equations with either all match a variable or all
-- | match a constructor.
matchVarCon :: [Ident] -> [Equ] -> CaseTree -> CT CaseTree
matchVarCon vs qs def
| isVar (head qs) = matchVar vs qs def
| otherwise = matchCon vs qs def
-- | Elaborates a group of equations that all match a variable first.
-- | Replaces the pattern variable name with the scrutinized variable in the expression.
matchVar :: [Ident] -> [Equ] -> CaseTree -> CT CaseTree
matchVar (v:vs) qs = match vs qs' where
qs' = [ Equ ps (sub v u e) | Equ (PVar u : ps) e <- qs ]
sub a b = subst (mkSubst a $ EFree b)
-- | Elaborates a group of equations that all match a constructor first.
-- |
-- | Reorders the constructors by grouping equations on the same constructors;
-- | by only moving equations up, semantics are preserved.
matchCon :: [Ident] -> [Equ] -> CaseTree -> CT CaseTree
matchCon (v:vs) qs def = do
let cs = nub [ c | Equ (PCon c _ : _) _ <- qs ]
cls <- forM cs $ \c -> matchConSame c vs qs def
return $ CCase v cls
-- | Elaborates a subgroup of equations that match on the given constructor.
-- |
-- | Introduces new variables for each constructor field and lifts the constructor
-- | field patterns to scrutinized patterns; then creates one clause for all the
-- | equations of that constructor.
matchConSame :: Con -> [Ident] -> [Equ] -> CaseTree -> CT Clause
matchConSame c vs qs def = do
let qs' = [ Equ (ps' ++ ps) e | Equ (PCon d ps' : ps) e <- qs, c == d ]
ws <- freshNames $ conArity c
ct <- match (ws ++ vs) qs' def
return $ Clause c ws ct
--------------------------------------------------------------------------------
-- Matches to Equations
--------------------------------------------------------------------------------
matchToEqu :: Match -> CT Equ
matchToEqu (Match vs lhs rhs) = do
let lhsArgs = appArgs lhs
ps <- mapM lhsArgToPat lhsArgs
return $ Equ ps rhs
lhsArgToPat :: Exp -> CT Pat
lhsArgToPat e
| (EFree v, []) <- appSplit e
= return $ PVar v
| (EConst (CCon c), xs) <- appSplit e
= PCon <$> lookupCon c <*> mapM lhsArgToPat xs
| otherwise
= throwError $ "Illegal expression in pattern: " ++ show e
--------------------------------------------------------------------------------
-- Helpers
--------------------------------------------------------------------------------
isVar :: Equ -> Bool
isVar (Equ (PVar _ : _) _) = True
isVar _ = False
isCon :: Equ -> Bool
isCon (Equ (PCon _ _ : _) _) = True
isCon _ = False
liftPred :: Eq b => (a -> b) -> a -> a -> Bool
liftPred f x y = f x == f y
| zrho/pylon | src/Language/Pylon/Core/CaseTree.hs | bsd-3-clause | 6,909 | 0 | 17 | 1,223 | 1,678 | 891 | 787 | 106 | 1 |
{-# LANGUAGE GADTs #-}
module LearningGADTS () where
data Expr a where
I :: Int -> Expr Int
B :: Bool -> Expr Bool
Add :: Expr Int -> Expr Int -> Expr Int
Mul :: Expr Int -> Expr Int -> Expr Int
Eq :: Expr Int -> Expr Int -> Expr Bool
eval :: Expr a -> a
eval (I n) = n
eval (B b) = b
eval (Add e1 e2) = eval e1 + eval e2
eval (Mul e1 e2) = eval e1 * eval e2
eval (Eq e1 e2) = eval e1 == eval e2
| steveshogren/language-safety-data-collector | src/learningGADTS.hs | bsd-3-clause | 419 | 0 | 8 | 123 | 221 | 108 | 113 | 14 | 1 |
module Eclogues.APIElectionSpec (spec) where
import Eclogues.API (parseZKData)
import Eclogues.APIElection (advertisedData)
import Test.Hspec
import Test.QuickCheck (property)
{-# ANN module ("HLint: ignore Use ." :: String) #-}
spec :: Spec
spec = describe "advertisedData" $
it "is the inverse of parseZKData" $ property $ \(h, p) ->
parseZKData (advertisedData h p) `shouldBe` Just (h, p)
| futufeld/eclogues | eclogues-impl/test/Eclogues/APIElectionSpec.hs | bsd-3-clause | 408 | 0 | 10 | 69 | 112 | 64 | 48 | 10 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP
, NoImplicitPrelude
, ExistentialQuantification
, AutoDeriveTypeable
#-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO.Handle.Types
-- Copyright : (c) The University of Glasgow, 1994-2009
-- License : see libraries/base/LICENSE
--
-- Maintainer : libraries@haskell.org
-- Stability : internal
-- Portability : non-portable
--
-- Basic types for the implementation of IO Handles.
--
-----------------------------------------------------------------------------
module GHC.IO.Handle.Types (
Handle(..), Handle__(..), showHandle,
checkHandleInvariants,
BufferList(..),
HandleType(..),
isReadableHandleType, isWritableHandleType, isReadWriteHandleType,
BufferMode(..),
BufferCodec(..),
NewlineMode(..), Newline(..), nativeNewline,
universalNewlineMode, noNewlineTranslation, nativeNewlineMode
) where
#undef DEBUG
import GHC.Base
import GHC.MVar
import GHC.IO
import GHC.IO.Buffer
import GHC.IO.BufferedIO
import GHC.IO.Encoding.Types
import GHC.IORef
import GHC.Show
import GHC.Read
import GHC.Word
import GHC.IO.Device
import Data.Typeable
#ifdef DEBUG
import Control.Monad
#endif
-- ---------------------------------------------------------------------------
-- Handle type
-- A Handle is represented by (a reference to) a record
-- containing the state of the I/O port/device. We record
-- the following pieces of info:
-- * type (read,write,closed etc.)
-- * the underlying file descriptor
-- * buffering mode
-- * buffer, and spare buffers
-- * user-friendly name (usually the
-- FilePath used when IO.openFile was called)
-- Note: when a Handle is garbage collected, we want to flush its buffer
-- and close the OS file handle, so as to free up a (precious) resource.
-- | Haskell defines operations to read and write characters from and to files,
-- represented by values of type @Handle@. Each value of this type is a
-- /handle/: a record used by the Haskell run-time system to /manage/ I\/O
-- with file system objects. A handle has at least the following properties:
--
-- * whether it manages input or output or both;
--
-- * whether it is /open/, /closed/ or /semi-closed/;
--
-- * whether the object is seekable;
--
-- * whether buffering is disabled, or enabled on a line or block basis;
--
-- * a buffer (whose length may be zero).
--
-- Most handles will also have a current I\/O position indicating where the next
-- input or output operation will occur. A handle is /readable/ if it
-- manages only input or both input and output; likewise, it is /writable/ if
-- it manages only output or both input and output. A handle is /open/ when
-- first allocated.
-- Once it is closed it can no longer be used for either input or output,
-- though an implementation cannot re-use its storage while references
-- remain to it. Handles are in the 'Show' and 'Eq' classes. The string
-- produced by showing a handle is system dependent; it should include
-- enough information to identify the handle for debugging. A handle is
-- equal according to '==' only to itself; no attempt
-- is made to compare the internal state of different handles for equality.
data Handle
= FileHandle -- A normal handle to a file
FilePath -- the file (used for error messages
-- only)
!(MVar Handle__)
| DuplexHandle -- A handle to a read/write stream
FilePath -- file for a FIFO, otherwise some
-- descriptive string (used for error
-- messages only)
!(MVar Handle__) -- The read side
!(MVar Handle__) -- The write side
deriving Typeable
-- NOTES:
-- * A 'FileHandle' is seekable. A 'DuplexHandle' may or may not be
-- seekable.
instance Eq Handle where
(FileHandle _ h1) == (FileHandle _ h2) = h1 == h2
(DuplexHandle _ h1 _) == (DuplexHandle _ h2 _) = h1 == h2
_ == _ = False
data Handle__
= forall dev enc_state dec_state . (IODevice dev, BufferedIO dev, Typeable dev) =>
Handle__ {
haDevice :: !dev,
haType :: HandleType, -- type (read/write/append etc.)
haByteBuffer :: !(IORef (Buffer Word8)),
haBufferMode :: BufferMode,
haLastDecode :: !(IORef (dec_state, Buffer Word8)),
haCharBuffer :: !(IORef (Buffer CharBufElem)), -- the current buffer
haBuffers :: !(IORef (BufferList CharBufElem)), -- spare buffers
haEncoder :: Maybe (TextEncoder enc_state),
haDecoder :: Maybe (TextDecoder dec_state),
haCodec :: Maybe TextEncoding,
haInputNL :: Newline,
haOutputNL :: Newline,
haOtherSide :: Maybe (MVar Handle__) -- ptr to the write side of a
-- duplex handle.
}
deriving Typeable
-- we keep a few spare buffers around in a handle to avoid allocating
-- a new one for each hPutStr. These buffers are *guaranteed* to be the
-- same size as the main buffer.
data BufferList e
= BufferListNil
| BufferListCons (RawBuffer e) (BufferList e)
-- Internally, we classify handles as being one
-- of the following:
data HandleType
= ClosedHandle
| SemiClosedHandle
| ReadHandle
| WriteHandle
| AppendHandle
| ReadWriteHandle
isReadableHandleType :: HandleType -> Bool
isReadableHandleType ReadHandle = True
isReadableHandleType ReadWriteHandle = True
isReadableHandleType _ = False
isWritableHandleType :: HandleType -> Bool
isWritableHandleType AppendHandle = True
isWritableHandleType WriteHandle = True
isWritableHandleType ReadWriteHandle = True
isWritableHandleType _ = False
isReadWriteHandleType :: HandleType -> Bool
isReadWriteHandleType ReadWriteHandle{} = True
isReadWriteHandleType _ = False
-- INVARIANTS on Handles:
--
-- * A handle *always* has a buffer, even if it is only 1 character long
-- (an unbuffered handle needs a 1 character buffer in order to support
-- hLookAhead and hIsEOF).
-- * In a read Handle, the byte buffer is always empty (we decode when reading)
-- * In a wriite Handle, the Char buffer is always empty (we encode when writing)
--
checkHandleInvariants :: Handle__ -> IO ()
#ifdef DEBUG
checkHandleInvariants h_ = do
bbuf <- readIORef (haByteBuffer h_)
checkBuffer bbuf
cbuf <- readIORef (haCharBuffer h_)
checkBuffer cbuf
when (isWriteBuffer cbuf && not (isEmptyBuffer cbuf)) $
error ("checkHandleInvariants: char write buffer non-empty: " ++
summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)
when (isWriteBuffer bbuf /= isWriteBuffer cbuf) $
error ("checkHandleInvariants: buffer modes differ: " ++
summaryBuffer bbuf ++ ", " ++ summaryBuffer cbuf)
#else
checkHandleInvariants _ = return ()
#endif
-- ---------------------------------------------------------------------------
-- Buffering modes
-- | Three kinds of buffering are supported: line-buffering,
-- block-buffering or no-buffering. These modes have the following
-- effects. For output, items are written out, or /flushed/,
-- from the internal buffer according to the buffer mode:
--
-- * /line-buffering/: the entire output buffer is flushed
-- whenever a newline is output, the buffer overflows,
-- a 'System.IO.hFlush' is issued, or the handle is closed.
--
-- * /block-buffering/: the entire buffer is written out whenever it
-- overflows, a 'System.IO.hFlush' is issued, or the handle is closed.
--
-- * /no-buffering/: output is written immediately, and never stored
-- in the buffer.
--
-- An implementation is free to flush the buffer more frequently,
-- but not less frequently, than specified above.
-- The output buffer is emptied as soon as it has been written out.
--
-- Similarly, input occurs according to the buffer mode for the handle:
--
-- * /line-buffering/: when the buffer for the handle is not empty,
-- the next item is obtained from the buffer; otherwise, when the
-- buffer is empty, characters up to and including the next newline
-- character are read into the buffer. No characters are available
-- until the newline character is available or the buffer is full.
--
-- * /block-buffering/: when the buffer for the handle becomes empty,
-- the next block of data is read into the buffer.
--
-- * /no-buffering/: the next input item is read and returned.
-- The 'System.IO.hLookAhead' operation implies that even a no-buffered
-- handle may require a one-character buffer.
--
-- The default buffering mode when a handle is opened is
-- implementation-dependent and may depend on the file system object
-- which is attached to that handle.
-- For most implementations, physical files will normally be block-buffered
-- and terminals will normally be line-buffered.
data BufferMode
= NoBuffering -- ^ buffering is disabled if possible.
| LineBuffering
-- ^ line-buffering should be enabled if possible.
| BlockBuffering (Maybe Int)
-- ^ block-buffering should be enabled if possible.
-- The size of the buffer is @n@ items if the argument
-- is 'Just' @n@ and is otherwise implementation-dependent.
deriving (Eq, Ord, Read, Show)
{-
[note Buffering Implementation]
Each Handle has two buffers: a byte buffer (haByteBuffer) and a Char
buffer (haCharBuffer).
[note Buffered Reading]
For read Handles, bytes are read into the byte buffer, and immediately
decoded into the Char buffer (see
GHC.IO.Handle.Internals.readTextDevice). The only way there might be
some data left in the byte buffer is if there is a partial multi-byte
character sequence that cannot be decoded into a full character.
Note that the buffering mode (haBufferMode) makes no difference when
reading data into a Handle. When reading, we can always just read all
the data there is available without blocking, decode it into the Char
buffer, and then provide it immediately to the caller.
[note Buffered Writing]
Characters are written into the Char buffer by e.g. hPutStr. At the
end of the operation, or when the char buffer is full, the buffer is
decoded to the byte buffer (see writeCharBuffer). This is so that we
can detect encoding errors at the right point.
Hence, the Char buffer is always empty between Handle operations.
[note Buffer Sizing]
The char buffer is always a default size (dEFAULT_CHAR_BUFFER_SIZE).
The byte buffer size is chosen by the underlying device (via its
IODevice.newBuffer). Hence the size of these buffers is not under
user control.
There are certain minimum sizes for these buffers imposed by the
library (but not checked):
- we must be able to buffer at least one character, so that
hLookAhead can work
- the byte buffer must be able to store at least one encoded
character in the current encoding (6 bytes?)
- when reading, the char buffer must have room for two characters, so
that we can spot the \r\n sequence.
How do we implement hSetBuffering?
For reading, we have never used the user-supplied buffer size, because
there's no point: we always pass all available data to the reader
immediately. Buffering would imply waiting until a certain amount of
data is available, which has no advantages. So hSetBuffering is
essentially a no-op for read handles, except that it turns on/off raw
mode for the underlying device if necessary.
For writing, the buffering mode is handled by the write operations
themselves (hPutChar and hPutStr). Every write ends with
writeCharBuffer, which checks whether the buffer should be flushed
according to the current buffering mode. Additionally, we look for
newlines and flush if the mode is LineBuffering.
[note Buffer Flushing]
** Flushing the Char buffer
We must be able to flush the Char buffer, in order to implement
hSetEncoding, and things like hGetBuf which want to read raw bytes.
Flushing the Char buffer on a write Handle is easy: it is always empty.
Flushing the Char buffer on a read Handle involves rewinding the byte
buffer to the point representing the next Char in the Char buffer.
This is done by
- remembering the state of the byte buffer *before* the last decode
- re-decoding the bytes that represent the chars already read from the
Char buffer. This gives us the point in the byte buffer that
represents the *next* Char to be read.
In order for this to work, after readTextHandle we must NOT MODIFY THE
CONTENTS OF THE BYTE OR CHAR BUFFERS, except to remove characters from
the Char buffer.
** Flushing the byte buffer
The byte buffer can be flushed if the Char buffer has already been
flushed (see above). For a read Handle, flushing the byte buffer
means seeking the device back by the number of bytes in the buffer,
and hence it is only possible on a seekable Handle.
-}
-- ---------------------------------------------------------------------------
-- Newline translation
-- | The representation of a newline in the external file or stream.
data Newline = LF -- ^ '\n'
| CRLF -- ^ '\r\n'
deriving (Eq, Ord, Read, Show)
-- | Specifies the translation, if any, of newline characters between
-- internal Strings and the external file or stream. Haskell Strings
-- are assumed to represent newlines with the '\n' character; the
-- newline mode specifies how to translate '\n' on output, and what to
-- translate into '\n' on input.
data NewlineMode
= NewlineMode { inputNL :: Newline,
-- ^ the representation of newlines on input
outputNL :: Newline
-- ^ the representation of newlines on output
}
deriving (Eq, Ord, Read, Show)
-- | The native newline representation for the current platform: 'LF'
-- on Unix systems, 'CRLF' on Windows.
nativeNewline :: Newline
#ifdef mingw32_HOST_OS
nativeNewline = CRLF
#else
nativeNewline = LF
#endif
-- | Map '\r\n' into '\n' on input, and '\n' to the native newline
-- represetnation on output. This mode can be used on any platform, and
-- works with text files using any newline convention. The downside is
-- that @readFile >>= writeFile@ might yield a different file.
--
-- > universalNewlineMode = NewlineMode { inputNL = CRLF,
-- > outputNL = nativeNewline }
--
universalNewlineMode :: NewlineMode
universalNewlineMode = NewlineMode { inputNL = CRLF,
outputNL = nativeNewline }
-- | Use the native newline representation on both input and output
--
-- > nativeNewlineMode = NewlineMode { inputNL = nativeNewline
-- > outputNL = nativeNewline }
--
nativeNewlineMode :: NewlineMode
nativeNewlineMode = NewlineMode { inputNL = nativeNewline,
outputNL = nativeNewline }
-- | Do no newline translation at all.
--
-- > noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
--
noNewlineTranslation :: NewlineMode
noNewlineTranslation = NewlineMode { inputNL = LF, outputNL = LF }
-- ---------------------------------------------------------------------------
-- Show instance for Handles
-- handle types are 'show'n when printing error msgs, so
-- we provide a more user-friendly Show instance for it
-- than the derived one.
instance Show HandleType where
showsPrec _ t =
case t of
ClosedHandle -> showString "closed"
SemiClosedHandle -> showString "semi-closed"
ReadHandle -> showString "readable"
WriteHandle -> showString "writable"
AppendHandle -> showString "writable (append)"
ReadWriteHandle -> showString "read-writable"
instance Show Handle where
showsPrec _ (FileHandle file _) = showHandle file
showsPrec _ (DuplexHandle file _ _) = showHandle file
showHandle :: FilePath -> String -> String
showHandle file = showString "{handle: " . showString file . showString "}"
| spacekitteh/smcghc | libraries/base/GHC/IO/Handle/Types.hs | bsd-3-clause | 16,345 | 0 | 13 | 3,711 | 1,350 | 811 | 539 | 135 | 1 |
module Boids where
import Data.List
type DeltaTime = Double
newtype Vec = V { unVec :: (Double, Double) } deriving (Eq, Ord)
instance Show Vec where
show (V p) = show p
instance Num Vec where
(V (a, b)) + (V (x, y)) = V (a + x, b + y)
negate (V (a, b)) = V (negate a, negate b)
fromInteger a = scale (fromInteger a) $ V (1, 0)
normalise :: (Double, Double) -> (Double, Double)
normalise (0, 0) = (0, 0)
normalise (a, b) =
let m = sqrt (a**2 + b**2) in
(a / m, b / m)
mag :: Vec -> Double
mag (V (a, b)) = sqrt (a**2 + b**2)
scale :: Double -> Vec -> Vec
scale s (V (a, b)) = V (s * a, s * b)
norm :: Vec -> Vec
norm (V (0, 0)) = V (0, 0)
norm v = scale (recip (mag v)) v
angle :: Vec -> Double
angle (V (0, 0)) = 0
angle (V (x, y)) = let ang = atan (y / x)
in if x < 0 then ang + pi else ang
origin :: Vec
origin = V (0, 0)
data Boid = Boid { velocity :: Vec
, position :: Vec
} deriving (Show, Eq, Ord)
boid :: (Double, Double) -> (Double, Double) -> Boid
boid p v = Boid (V v) (V p)
posX :: Boid -> Double
posX = fst . unVec . position
posY :: Boid -> Double
posY = snd . unVec . position
update :: DeltaTime -> [Boid] -> [Boid]
update dt bds = [ b { position = position b + scale dt (velocity b) } | b <- bds ]
type Flock = [Boid]
-- | A `BoidTransform` takes a boid,
-- a list of boids representing the entire
-- flock (apart from the boid under consideration)
-- and produces a velocity
type BoidTransform = Boid -> [Boid] -> Vec
(<+>) :: BoidTransform -> BoidTransform -> BoidTransform
(f <+> g) b bs = (f b bs) + (g b bs)
infixl 3 <+>
applyBT :: BoidTransform -> [Boid] -> [Boid]
applyBT bt bds =
let bds' = zip [0..] bds in
[ b { velocity = bt b (snd <$> (filter (/=(idx, b)) bds'))} | (idx, b) <- bds' ]
remain :: BoidTransform
remain b _ = velocity b
averageBy :: (Boid -> Vec) -> BoidTransform
averageBy f b bds =
scale (recip (genericLength bds + 1))
(sum [f boid | boid <- (b:bds)])
cohesion :: BoidTransform
cohesion b bds = averageBy position b bds - position b
align :: BoidTransform
align = averageBy velocity
constant :: Vec -> BoidTransform
constant v _ _ = v
avoidance :: BoidTransform
avoidance b bs = sum [ let v = position b - position b' in
scale (recip ((mag v) + 0.01)) (norm v)
| b' <- bs ]
within :: BoidTransform -> Double -> BoidTransform
within transform r b bds =
transform b
(filter (\b' -> mag (position b' - position b) <= r) bds)
infixl 4 `within`
upto :: BoidTransform -> Double -> BoidTransform
upto bt lim b bds = let v = bt b bds in
if mag v > lim then
scale lim (norm v)
else
v
infixl 4 `upto`
blend :: Double -> BoidTransform -> BoidTransform -> BoidTransform
blend sf f g b bts = scale sf (f b bts) + scale (1 - sf) (g b bts)
avoid :: Vec -> BoidTransform
avoid p b _ = scale (recip $ 0.01 + mag (position b - p)) (position b - p)
along :: ((Double, Double) -> (Double, Double)) -> BoidTransform
along f b _ = V (f (unVec (position b)))
scaledBy :: BoidTransform -> Double -> BoidTransform
scaledBy f s b bs = scale s (f b bs)
| MaximilianAlgehed/Boids | src/Boids.hs | bsd-3-clause | 3,229 | 0 | 16 | 898 | 1,569 | 835 | 734 | 83 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
{-| Make Type (see "AST") an instance of @Translatable@ (see
"CodeGen.Typeclasses"). -}
module CodeGen.Type where
import CodeGen.Typeclasses
import CodeGen.CCodeNames
import CCode.Main
import CCode.PrettyCCode ()
import qualified Types as Ty
translatePrimitive :: Ty.Type -> CCode Ty
translatePrimitive ty
| Ty.isUnitType ty = Ptr void
| Ty.isIntType ty = int
| Ty.isUIntType ty = uint
| Ty.isRealType ty = double
| Ty.isBoolType ty = bool
| Ty.isCharType ty = char
| Ty.isStringType ty = Ptr char
| otherwise = error $ show ty ++ " is not a primitive"
instance Translatable Ty.Type (CCode Ty) where
translate ty
| Ty.isPrimitive ty = translatePrimitive ty
| Ty.isRefAtomType ty = Ptr . AsType $ classTypeName ty
| Ty.isCapabilityType ty = capability
| Ty.isUnionType ty = capability
| Ty.isArrowType ty = closure
| Ty.isTypeVar ty = encoreArgT
| Ty.isFutureType ty = future
| Ty.isStreamType ty = stream
| Ty.isArrayType ty = array
| Ty.isRangeType ty = range
| Ty.isMaybeType ty = option
| Ty.isTupleType ty = tuple
| Ty.isCType ty = Embed $ Ty.getId ty
| Ty.isParType ty = par
| otherwise = error $ "I don't know how to translate "++ show ty ++" to pony.c"
runtimeType :: Ty.Type -> CCode Expr
runtimeType ty
| Ty.isActiveSingleType ty = AsExpr encoreActive
| Ty.isClassType ty = Amp $ runtimeTypeName ty
| Ty.isFutureType ty ||
Ty.isStreamType ty = Amp futureTypeRecName
| Ty.isArrowType ty = Amp closureTypeRecName
| Ty.isArrayType ty = Amp arrayTypeRecName
| Ty.isRangeType ty = Amp rangeTypeRecName
| Ty.isParType ty = Amp partyTypeRecName
| Ty.isPrimitive ty = AsExpr encorePrimitive
| Ty.isMaybeType ty = Amp optionTypeRecName
| Ty.isTupleType ty = Amp tupleTypeRecName
| Ty.isTypeVar ty = AsExpr . AsLval $ typeVarRefName ty
| otherwise = AsExpr encorePrimitive
encoreArgTTag :: CCode Ty -> CCode Name
encoreArgTTag (Ptr _) = Nam "p"
encoreArgTTag (Typ "int64_t") = Nam "i"
encoreArgTTag (Typ "uint64_t") = Nam "i"
encoreArgTTag (Typ "double") = Nam "d"
encoreArgTTag (Embed _) = Nam "p"
encoreArgTTag (Typ "char") = Nam "i"
encoreArgTTag other =
error $ "Type.hs: no encoreArgTTag for " ++ show other
asEncoreArgT :: UsableAs e Expr => CCode Ty -> CCode e -> CCode Expr
asEncoreArgT ty expr
| isEncoreArgT ty = EmbedC expr
| otherwise = Cast encoreArgT $ UnionInst (encoreArgTTag ty) expr
fromEncoreArgT :: CCode Ty -> CCode Expr -> CCode Lval
fromEncoreArgT ty expr
| isEncoreArgT ty = EmbedC expr
| otherwise = expr `Dot` (encoreArgTTag ty)
| Paow/encore | src/back/CodeGen/Type.hs | bsd-3-clause | 2,879 | 0 | 10 | 766 | 966 | 433 | 533 | -1 | -1 |
{-# LANGUAGE LambdaCase #-}
module Database.Concelo.TrieLike
( TrieLike(value, member, foldrPairs, foldrPaths) ) where
import qualified Database.Concelo.Path as P
class TrieLike t where
value :: t k v -> Maybe v
member :: Ord k => P.Path k v0 -> t k v -> Bool
foldrPairs :: ((k, t k v) -> b -> b) -> b -> t k v -> b
foldrPaths :: (P.Path k v -> b -> b) -> b -> t k v -> b
instance TrieLike P.Path where
value = P.valueHere
member a b = (P.keys a) == (P.keys b)
foldrPairs visit seed p = case P.keys p of
k:ks -> visit (k, P.toPath ks $ P.value p) seed
_ -> seed
foldrPaths visit seed p = visit p seed
| Concelo/concelo | src/Database/Concelo/TrieLike.hs | bsd-3-clause | 633 | 0 | 13 | 157 | 300 | 157 | 143 | 19 | 0 |
module Buzz
( speed
) where
import Data.ByteString ( ByteString )
import Criterion.Main ( bgroup, bench, nf, Benchmark )
import Algorithm.OptimalBlocks.BuzzHash ( hashes, h )
speed :: ByteString -> [Benchmark]
speed bytes =
[ bgroup "BuzzHash"
[ bgroup "h" $
[ bench (show n) (nf h n) | n <- 0:[7,15..255]]
, bgroup "windows"
[ bench (show n) $ nf (hashes n) bytes | n <- 64:[128, 256..2048]]
]
]
| tsuraan/optimal-blocks | benches/Buzz.hs | bsd-3-clause | 444 | 0 | 13 | 117 | 187 | 103 | 84 | 12 | 1 |
-------------------------------------------------------------------------------
-- |
-- Module : Text.SmallCaps.ConfigParser
-- Copyright : (c) Stefan Berthold 2014-2015
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : stefan.berthold@gmx.net
-- Stability : unstable
-- Portability : GHC
--
-- This module specifies inline configuration parsers. The parsers are also
-- used for the arguments in the command line interface.
--
-------------------------------------------------------------------------------
module Text.SmallCaps.ConfigParser where
import Prelude hiding ( lex, takeWhile )
import Data.Char ( isAlpha, isAlphaNum, isPunctuation )
import Data.Text hiding ( replace, takeWhile )
import Data.Map ( Map )
import qualified Data.Map as Map ( lookup )
import Data.Attoparsec.Text ( Parser, parseOnly, char, takeWhile1, asciiCI, skipSpace, isEndOfLine )
import Data.Attoparsec.Combinator ( many' )
import Control.Monad ( mplus, msum )
import Text.SmallCaps.LaTeX ( LaTeXElement, name )
import Text.SmallCaps.Config ( ParserState (..), Config (..), PatternReplace (..), defaultReplaceTemplate, defaultReplaceTemplate', blacklist, whitelist )
import Text.SmallCaps.TeXParser ( macroBegin, macroName )
reconfigure :: ParserState -> Text -> Either (Text, Config) Config
reconfigure state = either (const (Right (config state))) id . parseOnly (reconfiguration state)
reconfiguration :: ParserState -> Parser (Either (Text, Config) Config)
reconfiguration state = preamble >> msum
[ fmap Right $ profileMain (profile state)
, fmap Left $ storeMain conf
, fmap Right $ periodMain conf
, fmap Right $ replaceMain conf
, fmap Right $ searchMain conf
, fmap Right $ isolateMain conf
, fmap Right $ skipMain conf
, fmap Right $ unskipMain conf
, fmap Right $ eosMain conf
, fmap Right $ exceptMain conf
] where conf = config state
-- ** Lexer
lex :: Parser a -> Parser a
lex p = skipSpace >> p
-- ** Preamble
preamble :: Parser Text
preamble = char '%' >> lex (asciiCI (pack "smallcaps"))
-- ** Restore profile
profileMain :: Map Text Config -> Parser Config
profileMain ps = profilePre >> profileName ps
profilePre :: Parser Text
profilePre = lex (asciiCI (pack "reset") `mplus` asciiCI (pack "restore")) >> lex (asciiCI (pack "profile"))
profileName :: Map Text Config -> Parser Config
profileName ps = maybe (fail "profile not found") return . flip Map.lookup ps =<< lex (takeWhile1 isAlphaNum)
-- ** Store profile
storeMain :: Config -> Parser (Text, Config)
storeMain = (storePre >>) . storeName
storePre :: Parser Text
storePre = lex (asciiCI (pack "store")) >> lex (asciiCI (pack "profile"))
storeName :: Config -> Parser (Text, Config)
storeName conf = fmap (flip (,) conf) (lex $ takeWhile1 isAlphaNum)
-- ** Period chars
periodMain :: Config -> Parser Config
periodMain = (periodPre >>) . periodSigns
periodPre :: Parser Text
periodPre = lex (asciiCI (pack "periods")) >> lex (asciiCI (pack "are"))
periodSigns :: Config -> Parser Config
periodSigns conf = lex (takeWhile1 isPunctuation) >>= \s -> return $ conf { periodChars = unpack s }
-- ** Replace string
replaceMain :: Config -> Parser Config
replaceMain conf = replacePre >> msum
[ replaceStyleNoarg
, replaceStyleInarg
] >>= replaceMacro conf
replacePre :: Parser Text
replacePre = lex $ asciiCI (pack "substitution")
data Style = NoArg | InArg deriving (Show, Eq)
replaceStyleNoarg :: Parser Style
replaceStyleNoarg = lex (asciiCI (pack "in")) >> lex (asciiCI (pack "block")) >> lex (asciiCI (pack "with")) >> return NoArg
replaceStyleInarg :: Parser Style
replaceStyleInarg = lex (asciiCI (pack "as")) >> lex (asciiCI (pack "argument")) >> lex (asciiCI (pack "of")) >> return InArg
replaceMacro :: Config -> Style -> Parser Config
replaceMacro conf style
| style == NoArg = fun defaultReplaceTemplate
| otherwise = fun defaultReplaceTemplate'
where fun gun = lex $ macroBegin >> macroName >>= \macro -> return $ conf { replace = gun (cons '\\' macro) }
-- ** Search filter
searchMain :: Config -> Parser Config
searchMain = (searchPre >>) . searchList
searchPre :: Parser Text
searchPre = lex $ asciiCI (pack "search")
searchList :: Config -> Parser Config
searchList conf = list' (search conf) >>= \fun -> return $ conf { search = fun }
-- ** Isolate filter
isolateMain :: Config -> Parser Config
isolateMain = (isolatePre >>) . isolateList
isolatePre :: Parser Text
isolatePre = lex $ asciiCI (pack "isolate")
isolateList :: Config -> Parser Config
isolateList conf = iList (isolate conf) >>= \fun -> return $ conf { isolate = fun }
-- ** Skip filter
skipMain :: Config -> Parser Config
skipMain = (skipPre >>) . skipList
skipPre :: Parser Text
skipPre = lex $ asciiCI (pack "skip")
skipList :: Config -> Parser Config
skipList conf = list (skip conf) >>= \fun -> return $ conf { skip = fun }
-- ** Unskip filter
unskipMain :: Config -> Parser Config
unskipMain = (unskipPre >>) . unskipList
unskipPre :: Parser Text
unskipPre = lex $ asciiCI (pack "unskip")
unskipList :: Config -> Parser Config
unskipList conf = list (unskip conf) >>= \fun -> return $ conf { unskip = fun }
-- ** End of sentence filter
eosMain :: Config -> Parser Config
eosMain = (eosPre >>) . eosList
eosPre :: Parser Text
eosPre = lex $ asciiCI (pack "eos")
eosList :: Config -> Parser Config
eosList conf = list (eos conf) >>= \fun -> return $ conf { eos = fun }
-- ** Except and replace words
exceptMain :: Config -> Parser Config
exceptMain = (exceptPre >>) . exceptTuple
exceptPre :: Parser Text
exceptPre = lex (asciiCI (pack "except"))
exceptTuple :: Config -> Parser Config
exceptTuple conf = do
word <- lex (takeWhile1 isAlphaNum)
repl <- (lex (asciiCI (pack "put")) >> lex (takeWhile1 (not . isEndOfLine))) `mplus` return word
return $ conf { exceptions = PatternReplace
{ pattern = word
, replacement = repl
} : exceptions conf }
-- ** Macro/environment name list parser
list :: (LaTeXElement -> Bool) -> Parser (LaTeXElement -> Bool)
list fun = msum [listBlack fun, listWhite fun, listConstAll, listConstNone]
list' :: (LaTeXElement -> Bool) -> Parser (LaTeXElement -> Bool)
list' fun = msum [listBlack fun, listWhite fun, listConstAll', listConstNone']
listBlack :: (LaTeXElement -> Bool) -> Parser (LaTeXElement -> Bool)
listBlack fun = lex (char '-') >> listItems >>= \xs -> return (\x -> not (name x `elem` xs) && fun x)
listWhite :: (LaTeXElement -> Bool) -> Parser (LaTeXElement -> Bool)
listWhite fun = lex $ char '+' >> listItems >>= \xs -> return (\x -> name x `elem` xs || fun x)
listConstAll :: Parser (a -> Bool)
listConstAll = lex (char '*') >> return (const True)
listConstAll' :: Parser (LaTeXElement -> Bool)
listConstAll' = lex (char '*') >> return (blacklist [])
listConstNone :: Parser (a -> Bool)
listConstNone = lex (char '/') >> return (const False)
listConstNone' :: Parser (LaTeXElement -> Bool)
listConstNone' = lex (char '/') >> return (whitelist [])
-- ** Isolate list parser
iList :: (LaTeXElement -> Maybe Text) -> Parser (LaTeXElement -> Maybe Text)
iList fun = msum [iListBlack fun, iListWhite fun, iListConstAll, iListConstNone]
iListBlack :: (LaTeXElement -> Maybe Text) -> Parser (LaTeXElement -> Maybe Text)
iListBlack fun = do
_ <- lex $ char '-'
xs <- listItems
return $ \x -> if x `isElement` xs
then Nothing
else fun x
iListWhite :: (LaTeXElement -> Maybe Text) -> Parser (LaTeXElement -> Maybe Text)
iListWhite fun = do
c <- lex $ takeWhile1 isAlphaNum `mplus` return (pack "default")
_ <- lex $ char '+'
xs <- listItems
return $ \x -> if x `isElement` xs
then Just c
else fun x
iListConstAll :: Parser (LaTeXElement -> Maybe Text)
iListConstAll = do
c <- lex $ takeWhile1 isAlphaNum `mplus` return (pack "default")
_ <- lex $ char '*'
return $ const (Just c)
iListConstNone :: Parser (LaTeXElement -> Maybe Text)
iListConstNone = do
_ <- lex $ char '/'
return $ const Nothing
-- ** List item parser
listItems :: Parser [Text]
listItems = do
x <- listItem
xs <- many' (listItemSeparator >> listItem)
return (x:xs)
listItem :: Parser Text
listItem = listItemMacro `mplus` listItemEnvironment
listItemMacro :: Parser Text
listItemMacro = lex (macroBegin >> fmap (cons '\\') macroName)
listItemEnvironment :: Parser Text
listItemEnvironment = lex (takeWhile1 isAlpha)
listItemSeparator :: Parser Char
listItemSeparator = lex $ char ','
isElement :: LaTeXElement -> [Text] -> Bool
isElement = elem . name
-- vim: ft=haskell:sts=2:sw=2:et:nu:ai
| ZjMNZHgG5jMXw/smallcaps | src/smallcaps/Text/SmallCaps/ConfigParser.hs | bsd-3-clause | 8,808 | 0 | 15 | 1,794 | 2,995 | 1,555 | 1,440 | 165 | 2 |
{-# Language CPP #-}
module CopySpec ( copySpec ) where
import TestInit
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 706
import Prelude hiding ( FilePath, catch)
#else
import Prelude hiding ( FilePath)
#endif
import Control.Monad (forM_)
import System.IO.Error
import Help
copySpec :: Spec
copySpec = do
let b = "b"
let c = "c"
describe "cp file" $ do
it "cp to same dir" $
forM_ [cp, cp_r] $ \copier -> do
res <- shelly $
within_dir "test/a" $ do
writefile b "testing"
copier b c
readfile c
res @?= "testing"
it "cp to other dir" $
forM_ [cp, cp_r] $ \copier -> do
res <- shelly $
within_dir "test/a" $ do
writefile b "testing"
mkdir c
copier b c
readfile "c/b"
res @?= "testing"
describe "cp dir" $ do
it "to dir does not exist: create the to dir" $ do
res <- shelly $
within_dir "test/a" $ do
mkdir b
writefile "b/d" ""
cp_r b c
cIsDir <- test_d c
liftIO $ assert $ cIsDir
test_f "c/d"
assert res
it "to dir exists: creates a nested directory, full to path given" $ do
res <- shelly $
within_dir "test/a" $ do
mkdir b
mkdir c
writefile "b/d" ""
cp_r b $ c</>b
cIsDir <- test_d c
liftIO $ assert $ cIsDir
bIsDir <- test_d $ c</>b
liftIO $ assert $ bIsDir
test_f "c/b/d"
assert res
it "to dir exists: creates a nested directory, partial to path given" $ do
res <- shelly $
within_dir "test/a" $ do
mkdir b
mkdir c
writefile "b/d" ""
cp_r b $ c
cIsDir <- test_d c
liftIO $ assert $ cIsDir
bIsDir <- test_d $ c</>b
liftIO $ assert $ bIsDir
test_f "c/b/d"
assert res
it "copies the same dir" $ do
shelly $
within_dir "test/a" $ do
mkdir b
writefile "b/d" ""
cp_r b b `catch_sh` (\e -> liftIO $ assert $ isUserError e)
assert True
| adinapoli/Shelly.hs | test/src/CopySpec.hs | bsd-3-clause | 2,180 | 0 | 21 | 852 | 650 | 287 | 363 | 73 | 1 |
module Language.Induction (runDerive, getInd) where
import Language.Syntax
import Language.PrettyPrint
import Control.Monad.Reader
import Control.Monad.Identity
import Control.Monad.State.Lazy
import Data.List
import Data.Char
-- take in a inductive set def and return
-- rename a set var in formula
rename :: PreTerm -> PreTerm -> PreTerm -> PreTerm
rename (PVar y) (PVar x) (PVar z) = if x == z then PVar y else PVar z
rename (PVar y) (PVar x) (Forall z f) =
if x == z then Forall y $ rename (PVar y) (PVar x) f
else Forall z $ rename (PVar y) (PVar x) f
rename (PVar y) (PVar x) (Iota z f) =
if x == z then Forall y $ rename (PVar y) (PVar x) f
else Iota z $ rename (PVar y) (PVar x) f
rename (PVar y) (PVar x) (Imply f1 f2) =
let a1 = rename (PVar y) (PVar x) f1
a2 = rename (PVar y) (PVar x) f2 in
Imply a1 a2
rename (PVar y) (PVar x) (In f1 f2) =
let a2 = rename (PVar y) (PVar x) f2 in
In f1 a2
rename (PVar y) (PVar x) (SApp f1 f2) =
let a1 = rename (PVar y) (PVar x) f1
a2 = rename (PVar y) (PVar x) f2 in
SApp a1 a2
rename (PVar y) (PVar x) (TApp f1 f2) =
let a1 = rename (PVar y) (PVar x) f1 in
TApp a1 f2
tailAppend x (Imply f1 f2) y = Imply f1 (tailAppend x f2 y)
tailAppend x f2 y=
Forall x (Imply (rename (PVar $ y++ show 1) (PVar y) f2) f2)
-- tailAppend x f = error $ show f
-- change (In x (PVar y)) = In x (PVar (y++show 1))
-- change (In x (SApp (PVar y) s)) = In x (SApp (PVar (y++show 1)) s)
-- change (In x (TApp (PVar y) s)) = In x (TApp (PVar (y++show 1)) s)
-- change (In x (SApp s1 s2)) =
-- set to ind principle
-- set -> formula
toFormula :: PreTerm -> PreTerm
toFormula (Iota x (Forall y p)) = Forall y $ tailAppend x p y
toFormula (Iota x p) = Forall x (toFormula p)
--toFormula p = error $ show p
-- getInduction prin from a set
getInd :: PreTerm -> PreTerm
getInd t =
let
name@(PVar n) = getName t
f = toFormula t
p = rename (PVar $ n ++ show 0) name f
p1 = rename name (PVar $ n ++ show 1) p in
p1
type Env a = ReaderT [VName] (StateT Int Identity) a
-- runDerive take in a inductive set and return a proof of its ind
runDerive :: PreTerm -> PreTerm
runDerive t =
fst $ runIdentity $ runStateT (runReaderT (deriveInd t) []) 0
getName (Iota x (Forall z f)) = PVar z
getName (Iota x f) = getName f
deriveInd :: PreTerm -> Env PreTerm
deriveInd (Forall x f) = do
f1 <- deriveInd f
return $ UG x f1
deriveInd (Imply f1 f2) = do
n <- get
modify (+1)
f3 <- local (\l -> ("a"++ show n):l) $ deriveInd f2
return $ Discharge ("a"++ show n) (Just f1) f3
deriveInd (In m s) = do
env <- ask
let n:t = env
sp = Inst (Cmp (PVar n)) (spine s)
l = map (\ x -> PVar x) t
r = foldr helper sp l
return r
where helper a sp = MP sp (Cmp a)
spine (PVar x) = PVar x
spine (SApp t1 t) = spine t1
spine (TApp t1 t) = spine t1
test11 = Forall "C" (Imply (In (PVar "z") (PVar "C")) (Imply (Forall "y" (Imply (In (PVar "y") (PVar "C")) (In (App (PVar "s") (PVar "y")) (PVar "C")))) (Forall "m" (Imply (In (PVar "m") (PVar "Nat")) (In (PVar "m") (PVar "C"))))))
test12 = Iota "m" (Forall "Nat" (Imply (In (PVar "z") (PVar "Nat")) (Imply (Forall "y" (Imply (In (PVar "y") (PVar "Nat")) (In (App (PVar "s") (PVar "y")) (PVar "Nat")))) (In (PVar "m") (PVar "Nat")))))
| Fermat/Gottlob | Language/Induction.hs | bsd-3-clause | 3,318 | 1 | 21 | 814 | 1,452 | 753 | 699 | 72 | 4 |
module Data.Powermap where
import qualified Data.Map as M
import Control.Applicative
import Data.Binary
import Data.Text (Text, pack, unpack)
newtype Powermap = Powermap { getPowermap :: M.Map Vertex OutE } deriving Show
type OutE = [Vertex]
type Vertex = Text
instance Binary Powermap where
put = put . getPowermap
get = Powermap <$> get
instance Binary Text where
put = put . unpack
get = pack <$> get
-- | Map from new assoc list
fromList :: [(Vertex, OutE)] -> Powermap
fromList = Powermap . M.fromList
-- | Outbound edges for all vertices in map
allOutE :: Powermap -> OutE
allOutE = concat . M.elems . getPowermap
-- | The empty map
empty :: Powermap
empty = Powermap $ M.empty
-- | Combine two maps into one
union :: Powermap -> Powermap -> Powermap
union a b = Powermap $ M.unionWith (++) (getPowermap a) (getPowermap b)
-- | Pretty-print assoc-list view of map
pretty :: Powermap -> String
pretty = unlines . map vertex . M.toList . getPowermap where
vertex (from, to) = (unpack from) ++ ":\n" ++ (unlines $ map outE to)
outE = ("\t" ++) . unpack
| awagner83/powermap | src/Data/Powermap.hs | bsd-3-clause | 1,105 | 0 | 10 | 236 | 340 | 194 | 146 | 26 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
module PropertyGeneric ( genericTests ) where
import Prelude.Compat
#if !MIN_VERSION_base(4,16,0)
import Data.Semigroup (Option(..))
#endif
import Encoders
import Instances ()
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
#if !MIN_VERSION_base(4,16,0)
import Test.QuickCheck ( (===) )
import Types
#endif
import PropUtils
genericTests :: TestTree
genericTests =
testGroup "generic" [
testGroup "toJSON" [
testGroup "Nullary" [
testProperty "string" (isString . gNullaryToJSONString)
, testProperty "2ElemArray" (is2ElemArray . gNullaryToJSON2ElemArray)
, testProperty "TaggedObject" (isNullaryTaggedObject . gNullaryToJSONTaggedObject)
, testProperty "ObjectWithSingleField" (isObjectWithSingleField . gNullaryToJSONObjectWithSingleField)
, testGroup "roundTrip" [
testProperty "string" (toParseJSON gNullaryParseJSONString gNullaryToJSONString)
, testProperty "2ElemArray" (toParseJSON gNullaryParseJSON2ElemArray gNullaryToJSON2ElemArray)
, testProperty "TaggedObject" (toParseJSON gNullaryParseJSONTaggedObject gNullaryToJSONTaggedObject)
, testProperty "ObjectWithSingleField" (toParseJSON gNullaryParseJSONObjectWithSingleField gNullaryToJSONObjectWithSingleField)
]
]
, testGroup "EitherTextInt" [
testProperty "UntaggedValue" (isUntaggedValueETI . gEitherTextIntToJSONUntaggedValue)
, testProperty "roundtrip" (toParseJSON gEitherTextIntParseJSONUntaggedValue gEitherTextIntToJSONUntaggedValue)
]
, testGroup "SomeType" [
testProperty "2ElemArray" (is2ElemArray . gSomeTypeToJSON2ElemArray)
, testProperty "TaggedObject" (isTaggedObject . gSomeTypeToJSONTaggedObject)
, testProperty "ObjectWithSingleField" (isObjectWithSingleField . gSomeTypeToJSONObjectWithSingleField)
, testGroup "roundTrip" [
testProperty "2ElemArray" (toParseJSON gSomeTypeParseJSON2ElemArray gSomeTypeToJSON2ElemArray)
, testProperty "TaggedObject" (toParseJSON gSomeTypeParseJSONTaggedObject gSomeTypeToJSONTaggedObject)
, testProperty "ObjectWithSingleField" (toParseJSON gSomeTypeParseJSONObjectWithSingleField gSomeTypeToJSONObjectWithSingleField)
, testProperty "2ElemArray unary" (toParseJSON1 gSomeTypeLiftParseJSON2ElemArray gSomeTypeLiftToJSON2ElemArray)
, testProperty "TaggedObject unary" (toParseJSON1 gSomeTypeLiftParseJSONTaggedObject gSomeTypeLiftToJSONTaggedObject)
, testProperty "ObjectWithSingleField unary" (toParseJSON1 gSomeTypeLiftParseJSONObjectWithSingleField gSomeTypeLiftToJSONObjectWithSingleField)
]
]
, testGroup "OneConstructor" [
testProperty "default" (isEmptyArray . gOneConstructorToJSONDefault)
, testProperty "Tagged" (isTaggedObject . gOneConstructorToJSONTagged)
, testGroup "roundTrip" [
testProperty "default" (toParseJSON gOneConstructorParseJSONDefault gOneConstructorToJSONDefault)
, testProperty "Tagged" (toParseJSON gOneConstructorParseJSONTagged gOneConstructorToJSONTagged)
]
]
#if !MIN_VERSION_base(4,16,0)
, testGroup "OptionField" [
testProperty "like Maybe" $
\x -> gOptionFieldToJSON (OptionField (Option x)) === thMaybeFieldToJSON (MaybeField x)
, testProperty "roundTrip" (toParseJSON gOptionFieldParseJSON gOptionFieldToJSON)
]
#endif
]
, testGroup "toEncoding" [
testProperty "NullaryString" $
gNullaryToJSONString `sameAs` gNullaryToEncodingString
, testProperty "Nullary2ElemArray" $
gNullaryToJSON2ElemArray `sameAs` gNullaryToEncoding2ElemArray
, testProperty "NullaryTaggedObject" $
gNullaryToJSONTaggedObject `sameAs` gNullaryToEncodingTaggedObject
, testProperty "NullaryObjectWithSingleField" $
gNullaryToJSONObjectWithSingleField `sameAs`
gNullaryToEncodingObjectWithSingleField
-- , testProperty "ApproxUnwrap" $
-- gApproxToJSONUnwrap `sameAs` gApproxToEncodingUnwrap
, testProperty "ApproxDefault" $
gApproxToJSONDefault `sameAs` gApproxToEncodingDefault
, testProperty "EitherTextInt UntaggedValue" $
gEitherTextIntToJSONUntaggedValue `sameAs` gEitherTextIntToEncodingUntaggedValue
, testProperty "SomeType2ElemArray" $
gSomeTypeToJSON2ElemArray `sameAs` gSomeTypeToEncoding2ElemArray
, testProperty "SomeType2ElemArray unary" $
gSomeTypeLiftToJSON2ElemArray `sameAs1` gSomeTypeLiftToEncoding2ElemArray
, testProperty "SomeType2ElemArray unary agree" $
gSomeTypeToEncoding2ElemArray `sameAs1Agree` gSomeTypeLiftToEncoding2ElemArray
, testProperty "SomeTypeTaggedObject" $
gSomeTypeToJSONTaggedObject `sameAs` gSomeTypeToEncodingTaggedObject
, testProperty "SomeTypeTaggedObject unary" $
gSomeTypeLiftToJSONTaggedObject `sameAs1` gSomeTypeLiftToEncodingTaggedObject
, testProperty "SomeTypeTaggedObject unary agree" $
gSomeTypeToEncodingTaggedObject `sameAs1Agree` gSomeTypeLiftToEncodingTaggedObject
, testProperty "SomeTypeObjectWithSingleField" $
gSomeTypeToJSONObjectWithSingleField `sameAs` gSomeTypeToEncodingObjectWithSingleField
, testProperty "SomeTypeObjectWithSingleField unary" $
gSomeTypeLiftToJSONObjectWithSingleField `sameAs1` gSomeTypeLiftToEncodingObjectWithSingleField
, testProperty "SomeTypeObjectWithSingleField unary agree" $
gSomeTypeToEncodingObjectWithSingleField `sameAs1Agree` gSomeTypeLiftToEncodingObjectWithSingleField
, testProperty "SomeTypeOmitNothingFields" $
gSomeTypeToJSONOmitNothingFields `sameAs` gSomeTypeToEncodingOmitNothingFields
, testProperty "OneConstructorDefault" $
gOneConstructorToJSONDefault `sameAs` gOneConstructorToEncodingDefault
, testProperty "OneConstructorTagged" $
gOneConstructorToJSONTagged `sameAs` gOneConstructorToEncodingTagged
#if !MIN_VERSION_base(4,16,0)
, testProperty "OptionField" $
gOptionFieldToJSON `sameAs` gOptionFieldToEncoding
#endif
]
]
| dmjio/aeson | tests/PropertyGeneric.hs | bsd-3-clause | 6,293 | 0 | 18 | 1,144 | 907 | 495 | 412 | 90 | 1 |
module GameObject where
import Graphics.Rendering.OpenGL
import Data.IORef
import Textures
-------------------------------------------------------------
data GameObject = GameObject {
location :: IORef (GLfloat, GLfloat, GLfloat)
--rotation :: IORef (GLfloat, GLfloat, GLfloat),
--textures :: IORef [Maybe TextureGameObject]
}
makeGameObject :: IO GameObject
makeGameObject = do
-- initilize parameters for new object
location' <- newIORef (0.0::GLfloat, 0.0, (-1.0) )
-- create and return
return $ GameObject {
location = location'
}
| gbluma/opengl1 | src/GameObject.hs | bsd-3-clause | 579 | 0 | 11 | 109 | 105 | 63 | 42 | 11 | 1 |
{-# LANGUAGE RecordWildCards, MultiParamTypeClasses #-}
module Network.ZDNS.Util where
import Data.Tuple (swap)
import Data.Maybe (fromJust, fromMaybe)
import Data.Bits
import System.Random (getStdRandom, randomR)
import Data.Word
import Data.Bits (shiftL)
import Data.List (intersperse)
-- | A mapper from type to Integeral(Int, Word)
class (Eq c, Integral i) => CodeMapper c i where
getMapper :: [(c, i)]
unknownCode :: i -> c
toWord :: c -> i
fromWord :: i -> c
fromWord n =
fromMaybe (unknownCode n) $ lookup n (swapMapper getMapper)
where swapMapper m = map swap $ m
knownCodeToWord:: c -> i
knownCodeToWord t = fromJust $ lookup t getMapper
intToWord :: (Integral a) => Int -> a
intToWord = fromInteger . toInteger
{-# INLINE intToWord #-}
data FlagDescriptor = FlagDescriptor Int Int
allOne :: (Bits a, Integral a) => Int -> a
allOne w = (1 `shiftL` w) - 1
flagMask :: (Bits a, Integral a) => FlagDescriptor -> a
flagMask (FlagDescriptor w p) =
(allOne w) `shiftL` p
getFlag :: (Bits a, Integral a) => a -> FlagDescriptor -> Int
getFlag flag fd@(FlagDescriptor _ p) =
fromIntegral $ (flag .&. (flagMask fd)) `shiftR` p
setFlag :: (Bits a, Integral a) => a -> FlagDescriptor -> Int -> a
setFlag flag fd@(FlagDescriptor _ p) val =
flag .|. valInFlag
where valInFlag = ((intToWord val) `shiftL` p) .&. (flagMask fd)
rand :: Int -> IO Int
rand m = randRange 0 m
randRange :: Int -> Int -> IO Int
randRange l u = getStdRandom (randomR (l, u))
ntohs :: [Word8] -> Word16
ntohs bs = let (a:b:[]) = bs
in (shiftL (fromIntegral a) 8) + (fromIntegral b)
ntohl :: [Word8] -> Word32
ntohl bs = let (a:b:c:d:[]) = bs
ab = ntohs [a,b]
cd = ntohs [c,d]
in (shiftL (fromIntegral ab) 16) + (fromIntegral cd)
join :: String -> [String] -> String
join sep strs = concat $ intersperse sep strs
| ben-han-cn/hdns | Network/ZDNS/Util.hs | bsd-3-clause | 1,925 | 0 | 14 | 454 | 791 | 424 | 367 | 49 | 1 |
-------------------------------------------------------------------------
--
-- Haskell: The Craft of Functional Programming, 3e
-- Simon Thompson
-- (c) Addison-Wesley, 1996-2011.
--
-- Chapter 17
--
-- Lazy programming.
--
-------------------------------------------------------------------------
-- Lazy programming
-- ^^^^^^^^^^^^^^^^
module Chapter17 where
import Data.List ((\\))
import Craft.Chapter13 (iSort) -- for iSort
import Set -- for Relation
import Relation -- for graphs
-- Lazy evaluation
-- ^^^^^^^^^^^^^^^
-- Some example functions illustrating aspects of laziness.
f x y = x+y
g x y = x+12
switch :: Int -> a -> a -> a
switch n x y
| n>0 = x
| otherwise = y
h x y = x+x
pm (x,y) = x+1
-- Calculation rules and lazy evaluation
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Some more examples.
f1 :: [Int] -> [Int] -> Int
f1 [] ys = 0
f1 (x:xs) [] = 0
f1 (x:xs) (y:ys) = x+y
f2 :: Int -> Int -> Int -> Int
f2 m n p
| m>=n && m>=p = m
| n>=m && n>=p = n
| otherwise = p
f3 :: Int -> Int -> Int
f3 a b
| notNil xs = front xs
| otherwise = b
where
xs = [a .. b]
front (x:y:zs) = x+y
front [x] = x
notNil [] = False
notNil (_:_) = True
-- List comprehensions revisited
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Simpler examples
-- ^^^^^^^^^^^^^^^^
-- All pairs formed from elements of two lists
pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = [ (x,y) | x<-xs , y<-ys ]
pairEg = pairs [1,2,3] [4,5]
-- Illustrating the order in which elements are chosen in multiple
-- generators.
triangle :: Int -> [(Int,Int)]
triangle n = [ (x,y) | x <- [1 .. n] , y <- [1 .. x] ]
-- Pythagorean triples
pyTriple n
= [ (x,y,z) | x <- [2 .. n] , y <- [x+1 .. n] ,
z <- [y+1 .. n] , x*x + y*y == z*z ]
-- Calculating with list comprehensions
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- The running example from this section.
runningExample = [ x+y | x <- [1,2] , isEven x , y <- [x .. 2*x] ]
isEven :: Int -> Bool
isEven n = (n `mod` 2 == 0)
-- List permutations
-- ^^^^^^^^^^^^^^^^^
-- One definition of the list of all permutations.
perms :: Eq a => [a] -> [[a]]
perms [] = [[]]
perms xs = [ x:ps | x <- xs , ps <- perms (xs\\[x]) ]
-- Another algorithm for permutations
perm :: [a] -> [[a]]
perm [] = [[]]
perm (x:xs) = [ ps++[x]++qs | rs <- perm xs ,
(ps,qs) <- splits rs ]
-- All the splits of a list into two halves.
splits :: [a]->[([a],[a])]
splits [] = [ ([],[]) ]
splits (y:ys) = ([],y:ys) : [ (y:ps,qs) | (ps,qs) <- splits ys]
-- Vectors and Matrices
-- ^^^^^^^^^^^^^^^^^^^^
-- A vector is a sequence of real numbers,
type Vector = [Float]
-- and the scalar product of two vectors.
scalarProduct :: Vector -> Vector -> Float
scalarProduct xs ys = sum [ x*y | (x,y) <- zip xs ys ]
-- The type of matrices.
type Matrix = [Vector]
-- and matrix product.
matrixProduct :: Matrix -> Matrix -> Matrix
matrixProduct m p
= [ [scalarProduct r c | c <- columns p] | r <- m ]
-- where the function columns gives the representation of a matrix as a
-- list of columns.
columns :: Matrix -> Matrix
columns y = [ [ z!!j | z <- y ] | j <- [0 .. s] ]
where
s = length (head y)-1
-- Refutable patterns: an example
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
refPattEx = [ x | (x:xs) <- [[],[2],[],[4,5]] ]
-- Data-directed programming
-- ^^^^^^^^^^^^^^^^^^^^^^^^^
-- Summing fourth powers of numbers up to n.
sumFourthPowers :: Int -> Int
sumFourthPowers n = sum (map (^4) [1 .. n])
-- List minimum: take the head of the sorted list. Only makes sense in an
-- lazy context.
minList :: [Int] -> Int
minList = head . iSort
-- Example: routes through a graph
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- A example graph.
graphEx = makeSet [(1,2),(1,3),(2,4),(3,5),(5,6),(3,6)]
-- Look for all paths from one point to another. (Assumes the graph is acyclic.)
routes :: Ord a => Relation a -> a -> a -> [[a]]
routes rel x y
| x==y = [[x]]
| otherwise = [ x:r | z <- nbhrs rel x ,
r <- routes rel z y ]
--
-- The neighbours of a point in a graph.
nbhrs :: Ord a => Relation a -> a -> [a]
nbhrs rel x = flatten (image rel x)
-- Example evaluations
routeEx1 = routes graphEx 1 4
routeEx2 = routes graphEx 1 6
-- Accommodating cyclic graphs.
routesC :: Ord a => Relation a -> a -> a -> [a] -> [[a]]
routesC rel x y avoid
| x==y = [[x]]
| otherwise = [ x:r | z <- nbhrs rel x \\ avoid ,
r <- routesC rel z y (x:avoid) ]
-- Case study: Parsing expressions
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- See under case studies for parsing and the calculator..
-- Infinite lists
-- ^^^^^^^^^^^^^^
-- The infinite list of ones.
ones :: [Int]
ones = 1 : ones
-- Add the first two elements of a list.
addFirstTwo :: [Int] -> Int
addFirstTwo (x:y:zs) = x+y
-- Example, applied to ones.
infEx1 = addFirstTwo ones
-- Arithmetic progressions
from :: Int -> [Int]
from n = n : from (n+1)
fromStep :: Int -> Int -> [Int]
fromStep n m = n : fromStep (n+m) m
-- and an example.
infEx2 = fromStep 3 2
-- Infinite list comprehensions.
-- Pythagorean triples
pythagTriples =
[ (x,y,z) | z <- [2 .. ] , y <- [2 .. z-1] ,
x <- [2 .. y-1] , x*x + y*y == z*z ]
-- The powers of an integer
powers :: Int -> [Int]
powers n = [ n^x | x <- [0 .. ] ]
-- Iterating a function (from the Prelude)
-- iterate :: (a -> a) -> a -> [a]
-- iterate f x = x : iterate f (f x)
-- Sieve of Eratosthenes
primes :: [Int]
primes = sieve [2 .. ]
sieve (x:xs) = x : sieve [ y | y <- xs , y `mod` x > 0]
-- Membership of an ordered list.
memberOrd :: Ord a => [a] -> a -> Bool
memberOrd (x:xs) n
| x<n = memberOrd xs n
| x==n = True
| otherwise = False
-- Example: Generating random numbers
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Find the next (pseudo-)random number in the sequence.
nextRand :: Int -> Int
nextRand n = (multiplier*n + increment) `mod` modulus
-- A (pseudo-)random sequence is given by iterating this function,
randomSequence :: Int -> [Int]
randomSequence = iterate nextRand
-- Suitable values for the constants.
seed, multiplier, increment, modulus :: Int
seed = 17489
multiplier = 25173
increment = 13849
modulus = 65536
-- Scaling the numbers to come in the (integer) range a to b (inclusive).
scaleSequence :: Int -> Int -> [Int] -> [Int]
scaleSequence s t
= map scale
where
scale n = n `div` denom + s
range = t-s+1
denom = modulus `div` range
-- Turn a distribution into a function.
makeFunction :: [(a,Double)] -> (Double -> a)
makeFunction dist = makeFun dist 0.0
makeFun ((ob,p):dist) nLast rand
| nNext >= rand && rand > nLast
= ob
| otherwise
= makeFun dist nNext rand
where
nNext = p*fromIntegral modulus + nLast
-- Random numbers from 1 to 6 according to the example distribution, dist.
randomTimes = map (makeFunction dist . fromIntegral) (randomSequence seed)
-- The distribution in question
dist = [(1,0.2), (2,0.25), (3,0.25), (4,0.15), (5,0.1), (6,0.05)]
-- A pitfall of infinite list generators
-- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- An incorrect Pythagorean triples program.
pythagTriples2
= [ (x,y,z) | x <- [2 .. ] ,
y <- [x+1 .. ] ,
z <- [y+1 .. ] ,
x*x + y*y == z*z ]
-- Why infinite lists?
-- ^^^^^^^^^^^^^^^^^^^
-- Running sums of a list of numbers.
listSums :: [Int] -> [Int]
listSums iList = out
where
out = 0 : zipWith (+) iList out
-- We give a calculation of an example now.
listSumsEx = listSums [1 .. ]
-- Another definition of listSums which uses scanl1', a generalisation of the
-- original function.
listSums' = scanl' (+) 0
-- A function which combines values from the list
-- using the function f, and whose first output is st.
scanl' :: (a -> b -> b) -> b -> [a] -> [b]
scanl' f st iList
= out
where
out = st : zipWith f iList out
-- Factorial Values
facVals = scanl' (*) 1 [1 .. ]
-- Case study: Simulation
-- ^^^^^^^^^^^^^^^^^^^^^^
-- See case studies.
-- Two factorial lists
-- ^^^^^^^^^^^^^^^^^^^
-- The factorial function
fac :: Int -> Int
fac 0 = 1
fac m = m * fac (m-1)
--
-- Two factorial lists
facMap, facs :: [Int]
facMap = map fac [0 .. ]
facs = 1 : zipWith (*) [1 .. ] facs
| Numberartificial/workflow | snipets/src/Craft/Chapter17.hs | mit | 8,565 | 0 | 11 | 2,243 | 2,896 | 1,629 | 1,267 | 151 | 1 |
module Data.Aeson.Config
( load
) where
import qualified Control.Lens as Lens
import Control.Monad.IO.Class (MonadIO(..))
import Control.Monad.Trans.FastWriter (WriterT)
import qualified Control.Monad.Trans.FastWriter as Writer
import Data.Aeson (FromJSON(..), Result(..), eitherDecode', fromJSON)
import Data.Aeson.Lens (_Object, _String, key, values)
import Data.Aeson.Types (Value(..))
import qualified Data.ByteString.Lazy as LBS
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import System.FilePath (takeDirectory, isRelative, (</>))
import Lamdu.Prelude
-- | Left argument overrides right argument (like `<>` for `Map`)
override :: Value -> Value -> Value
override (Object x) (Object y) = HashMap.unionWith override x y & Object
override x _ = x
importsKey :: Text
importsKey = "imports"
imports :: FilePath -> Value -> WriterT [FilePath] IO Value
imports dirName x =
x ^.. key importsKey . values . _String
<&> Text.unpack
<&> addDir
& traverse load
<&> foldl override (x & _Object . Lens.at importsKey .~ Nothing)
where
addDir path
| isRelative path = dirName </> path
| otherwise = path
load :: FromJSON a => FilePath -> WriterT [FilePath] IO a
load path =
Writer.tell [path] *>
liftIO (LBS.readFile path)
<&> eitherDecode'
>>= either (error . mappend msg) (imports (takeDirectory path))
<&> fromJSON
>>=
\case
Error x -> error (msg <> x)
Success x -> pure x
where
msg = "Failed to parse config file contents at " ++ show path ++ ": "
| lamdu/lamdu | src/Data/Aeson/Config.hs | gpl-3.0 | 1,668 | 0 | 13 | 406 | 515 | 286 | 229 | -1 | -1 |
import CPi.Lib
import Tests
import CPi.ODE
import CPi.Matlab
import CPi.Semantics
import CPi.Logic
import CPi.Signals
import System.Environment (getArgs)
-- Time points
--tps = (100,(0,25))
-- Basic
f1 = Pos (0,25) (ValGT (Conc (Def "P" [])) (R 0.05))
f2 = Pos (0,25) (ValLE (Conc (Def "S" ["s"])) (R 0.01))
f3 = Nec (0,25) (ValGT (Conc (Def "E" ["e"])) (R 0.01))
f4 = Nec (0,25) (ValGT (Conc (Def "E" ["e"])) (R 0.4))
-- 1-nested TL
f5 = Nec (0,25) f1
f6 = Nec (0,25) f2
f7 = Pos (0,25) f3
f8 = Pos (0,25) f4
-- 2-nested TL
f9 = Pos (0,25) f5
f10 = Pos (0,25) f6
f11 = Nec (0,25) f7
f12 = Nec (0,25) f8
-- 3-nested TL
f13 = Nec (0,25) f9
f14 = Nec (0,25) f10
f15 = Pos (0,25) f11
f16 = Pos (0,25) f12
-- 4-nested TL
f14b = Pos (0,25) f14
-- Basic Gtee
f17 = Gtee "In" f1
f18 = Gtee "In" f2
f19 = Gtee "In" f3
f20 = Gtee "In" f4
-- 1-nested Gtee
f21 = Pos (0,25) f17
f22 = Pos (0,25) f18
f23 = Pos (0,25) f19
f24 = Pos (0,25) f20
f25 = Nec (0,25) f17
f26 = Nec (0,25) f18
f27 = Nec (0,25) f19
f28 = Nec (0,25) f20
-- nested Gtee and nested TL
f29 = Nec (0,25) f21
f30 = Nec (0,25) f22
f31 = Nec (0,25) f23
f32 = Nec (0,25) f24
f33 = Pos (0,25) f25
f34 = Pos (0,25) f26
f35 = Pos (0,25) f27
f36 = Pos (0,25) f28
-- 2 nested Gtees
f37 = Gtee "Q'" f21
f38 = Gtee "Q'" f22
f39 = Gtee "Q'" f23
f40 = Gtee "Q'" f24
f41 = Gtee "Q'" f25
f42 = Gtee "Q'" f26
f43 = Gtee "Q'" f27
f44 = Gtee "Q'" f28
-- sandwich nested Gtees
f45 = Pos (0,25) f37
f46 = Pos (0,25) f38
f47 = Pos (0,25) f39
f48 = Pos (0,25) f40
f49 = Pos (0,25) f41
f50 = Pos (0,25) f42
f51 = Pos (0,25) f43
f52 = Pos (0,25) f44
f53 = Nec (0,25) f37
f54 = Nec (0,25) f38
f55 = Nec (0,25) f39
f56 = Nec (0,25) f40
f57 = Nec (0,25) f41
f58 = Nec (0,25) f42
f59 = Nec (0,25) f43
f60 = Nec (0,25) f44
main = do env <- tEnv "models/testGT.cpi"
res <- getArgs
let tps = (read(res!!0),(0,25))
let pi = tProc env "Pi"
let trace = solve env solveODEoctave tps pi
let r1 = {-# SCC "f37-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f37
r2 = {-# SCC "f37-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f37
print $ pretty f37
print r1
print r2
let r1 = {-# SCC "f38-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f38
r2 = {-# SCC "f38-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f38
print $ pretty f38
print r1
print r2
let r1 = {-# SCC "f39-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f39
r2 = {-# SCC "f39-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f39
print $ pretty f39
print r1
print r2
let r1 = {-# SCC "f40-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f40
r2 = {-# SCC "f40-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f40
print $ pretty f40
print r1
print r2
let r1 = {-# SCC "f41-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f41
r2 = {-# SCC "f41-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f41
print $ pretty f41
print r1
print r2
let r1 = {-# SCC "f42-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f42
r2 = {-# SCC "f42-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f42
print $ pretty f42
print r1
print r2
let r1 = {-# SCC "f43-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f43
r2 = {-# SCC "f43-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f43
print $ pretty f43
print r1
print r2
let r1 = {-# SCC "f44-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f44
r2 = {-# SCC "f44-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f44
print $ pretty f44
print r1
print r2
let r1 = {-# SCC "f45-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f45
r2 = {-# SCC "f45-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f45
print $ pretty f45
print r1
print r2
let r1 = {-# SCC "f46-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f46
r2 = {-# SCC "f46-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f46
print $ pretty f46
print r1
print r2
let r1 = {-# SCC "f47-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f47
r2 = {-# SCC "f47-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f47
print $ pretty f47
print r1
print r2
let r1 = {-# SCC "f48-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f48
r2 = {-# SCC "f48-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f48
print $ pretty f48
print r1
print r2
let r1 = {-# SCC "f49-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f49
r2 = {-# SCC "f49-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f49
print $ pretty f49
print r1
print r2
let r1 = {-# SCC "f50-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f50
r2 = {-# SCC "f50-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f50
print $ pretty f50
print r1
print r2
let r1 = {-# SCC "f51-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f51
r2 = {-# SCC "f51-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f51
print $ pretty f51
print r1
print r2
let r1 = {-# SCC "f52-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f52
r2 = {-# SCC "f52-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f52
print $ pretty f52
print r1
print r2
let r1 = {-# SCC "f53-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f53
r2 = {-# SCC "f53-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f53
print $ pretty f53
print r1
print r2
let r1 = {-# SCC "f54-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f54
r2 = {-# SCC "f54-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f54
print $ pretty f54
print r1
print r2
let r1 = {-# SCC "f55-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f55
r2 = {-# SCC "f55-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f55
print $ pretty f55
print r1
print r2
let r1 = {-# SCC "f56-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f56
r2 = {-# SCC "f56-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f56
print $ pretty f56
print r1
print r2
let r1 = {-# SCC "f57-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f57
r2 = {-# SCC "f57-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f57
print $ pretty f57
print r1
print r2
let r1 = {-# SCC "f58-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f58
r2 = {-# SCC "f58-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f58
print $ pretty f58
print r1
print r2
let r1 = {-# SCC "f59-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f59
r2 = {-# SCC "f59-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f59
print $ pretty f59
print r1
print r2
let r1 = {-# SCC "f60-Signal" #-} modelCheckSig
env solveODE (Just trace) pi tps f60
r2 = {-# SCC "f60-Trace" #-} modelCheck
env solveODE (Just trace) pi tps f60
print $ pretty f60
print r1
print r2
| continuouspi/cpiwb | profileSig3.hs | gpl-3.0 | 9,004 | 0 | 13 | 3,623 | 2,992 | 1,483 | 1,509 | 242 | 1 |
{-# LANGUAGE MagicHash,
UnboxedTuples,
ScopedTypeVariables #-}
module UU.Scanner.GenTokenParser where
import GHC.Base
import UU.Parsing.Interface(IsParser(pCostSym, pSym), (<$>))
import UU.Scanner.GenToken(GenToken(..))
import UU.Scanner.Position(Pos, noPos)
pCostReserved' :: IsParser p (GenToken key tp val)
=> Int -> key -> p (GenToken key tp val)
pCostReserved' (I# c) key
= let tok = Reserved key noPos
in pCostSym c tok tok
pReserved' :: IsParser p (GenToken key tp val)
=> key -> p (GenToken key tp val)
pReserved' key = let tok = Reserved key noPos
in pSym tok
pCostValToken' :: IsParser p (GenToken key tp val)
=> Int -> tp -> val -> p (GenToken key tp val)
pCostValToken' (I# c) tp val
= let tok = ValToken tp val noPos
in pCostSym c tok tok
pValToken' :: IsParser p (GenToken key tp val)
=> tp -> val -> p (GenToken key tp val)
pValToken' tp val = let tok = ValToken tp val noPos
in pSym tok
pCostReserved :: IsParser p (GenToken key tp val)
=> Int -> key -> p Pos
pCostReserved c key = let getPos x = case x of
Reserved _ p -> p
ValToken _ _ p -> p
in getPos <$> pCostReserved' c key
pCostValToken :: IsParser p (GenToken key tp val)
=> Int -> tp -> val -> p (val,Pos)
pCostValToken c tp val = let getVal x = case x of
ValToken _ v p -> (v,p)
_ -> error "pValToken: cannot get value of Reserved"
in getVal <$> pCostValToken' c tp val
pReserved :: IsParser p (GenToken key tp val)
=> key -> p Pos
pReserved = pCostReserved 5
pValToken :: IsParser p (GenToken key tp val)
=> tp -> val -> p (val,Pos)
pValToken = pCostValToken 5
pValTokenNoPos :: IsParser p (GenToken key tp val)
=> tp -> val -> p val
pValTokenNoPos tp val = fst <$> pValToken tp val
| UU-ComputerScience/uulib | src/UU/Scanner/GenTokenParser.hs | bsd-3-clause | 2,505 | 0 | 12 | 1,151 | 736 | 367 | 369 | -1 | -1 |
module Pure (module Export) where
-- from pure-core
import Pure.Data.View as Export hiding (On,content)
import Pure.Data.View.Patterns as Export
-- from pure-default
import Pure.Data.Default as Export
-- from pure-dom
import Pure.DOM as Export
-- from pure-lifted
import Pure.Data.Lifted as Export (JSV,Win(..),Doc(..),Head(..),Body(..),Element(..),Text(..),Node(..),Frag(..),IsNode(..),toJSV,Evt(..),Options(Options),prevDef,prevProp,onRaw,(.#),findByTag,findById,same,isNull,getWindow,getBody,getDocument,getHead,body,window,document,head)
import Pure.Animation as Export (addAnimation)
import Pure.IdleWork as Export (addIdleWork)
-- from pure-time
import Pure.Data.Time as Export
-- from pure-txt
import Pure.Data.Txt as Export (Txt,ToTxt(..),FromTxt(..))
-- from pure-events
import Pure.Data.Events as Export hiding (button,Accept,Alt,Select)
-- from pure-html
import Pure.Data.HTML as Export hiding (Head,Body,Style,Time)
import Pure.Data.HTML.Properties as Export hiding (Children,Data,Style,ContextMenu,Cite,Code,Form,Label,Span,Summary,Title,Bgcolor,Border,Color,Content,Height,Sizes,Width,Target)
-- from pure-theme; exports Pure.Data.Styles
import Pure.Theme as Export hiding (target,delay)
-- from pure-styles
import Pure.Data.Styles.Patterns as Export
| grumply/nuclear | src/Pure.hs | bsd-3-clause | 1,276 | 0 | 6 | 118 | 403 | 285 | 118 | 15 | 0 |
blank :: Int -> Int -> [String]
blank x y = replicate x $ replicate y '_'
vertical :: Int -> [String]
vertical n = replicate n (replicate n '_' ++ ['1'] ++ replicate n '_')
left_slant :: Int -> [String]
left_slant n = [replicate i '_' ++ ['1'] ++ replicate (n - i - 1) '_' | i <- [0..n - 1]]
right_slant :: Int -> [String]
right_slant n = [replicate (n - i - 1) '_' ++ ['1'] ++ replicate i '_' | i <- [0..n - 1]]
tree :: Int -> [String]
tree n = foldl1 (zipWith (++)) [left_slant n, blank n 1, right_slant n] ++
vertical n
big_tree :: Int -> Int -> [String]
big_tree n m
| m == 1 = tree n
| otherwise = (foldl1 (zipWith (++)) [half, blank l (2 * n - r), half]) ++
(foldl1 (zipWith (++)) [blank (2 * n) (r `div` 2), tree n, blank (2 * n) (r `div` 2)])
where half = big_tree (n `div` 2) (m - 1)
l = length half
r = length (half !! 0)
solve :: Int -> Int -> Int -> [String]
solve n m x = blank (n - l) m ++
(map func t)
where t = big_tree 16 x
l = length t
func line = replicate ((m - w) `div` 2) '_' ++
line ++
replicate (m - w - ((m - w) `div` 2)) '_'
where w = length line
main :: IO()
main = do
g <- getContents
putStr $ unlines $ solve 63 100 (read g :: Int)
| EdisonAlgorithms/HackerRank | practice/fp/recursion/fractal-trees/fractal-trees.hs | mit | 1,344 | 0 | 14 | 448 | 710 | 373 | 337 | 32 | 1 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP #-}
-- | Highly random utility functions
--
module Util (
-- * Flags dependent on the compiler build
ghciSupported, debugIsOn, ncgDebugIsOn,
ghciTablesNextToCode,
isWindowsHost, isDarwinHost,
-- * General list processing
zipEqual, zipWithEqual, zipWith3Equal, zipWith4Equal,
zipLazy, stretchZipWith, zipWithAndUnzip,
zipWithLazy, zipWith3Lazy,
filterByList, filterByLists, partitionByList,
unzipWith,
mapFst, mapSnd, chkAppend,
mapAndUnzip, mapAndUnzip3, mapAccumL2,
nOfThem, filterOut, partitionWith, splitEithers,
dropWhileEndLE, spanEnd,
foldl1', foldl2, count, all2,
lengthExceeds, lengthIs, lengthAtLeast,
listLengthCmp, atLength,
equalLength, compareLength, leLength,
isSingleton, only, singleton,
notNull, snocView,
isIn, isn'tIn,
chunkList,
-- * Tuples
fstOf3, sndOf3, thdOf3,
firstM, first3M,
fst3, snd3, third3,
uncurry3,
liftFst, liftSnd,
-- * List operations controlled by another list
takeList, dropList, splitAtList, split,
dropTail,
-- * For loop
nTimes,
-- * Sorting
sortWith, minWith, nubSort,
-- * Comparisons
isEqual, eqListBy, eqMaybeBy,
thenCmp, cmpList,
removeSpaces,
(<&&>), (<||>),
-- * Edit distance
fuzzyMatch, fuzzyLookup,
-- * Transitive closures
transitiveClosure,
-- * Strictness
seqList,
-- * Module names
looksLikeModuleName,
looksLikePackageName,
-- * Argument processing
getCmd, toCmdArgs, toArgs,
-- * Floating point
readRational,
-- * read helpers
maybeRead, maybeReadFuzzy,
-- * IO-ish utilities
doesDirNameExist,
getModificationUTCTime,
modificationTimeIfExists,
hSetTranslit,
global, consIORef, globalM,
-- * Filenames and paths
Suffix,
splitLongestPrefix,
escapeSpaces,
Direction(..), reslash,
makeRelativeTo,
-- * Utils for defining Data instances
abstractConstr, abstractDataType, mkNoRepType,
-- * Utils for printing C code
charToC,
-- * Hashing
hashString,
) where
#include "HsVersions.h"
import Exception
import Panic
import Data.Data
import Data.IORef ( IORef, newIORef, atomicModifyIORef' )
import System.IO.Unsafe ( unsafePerformIO )
import Data.List hiding (group)
import GHC.Exts
import Control.Applicative ( liftA2 )
import Control.Monad ( liftM )
import GHC.IO.Encoding (mkTextEncoding, textEncodingName)
import System.IO (Handle, hGetEncoding, hSetEncoding)
import System.IO.Error as IO ( isDoesNotExistError )
import System.Directory ( doesDirectoryExist, getModificationTime )
import System.FilePath
import Data.Char ( isUpper, isAlphaNum, isSpace, chr, ord, isDigit )
import Data.Int
import Data.Ratio ( (%) )
import Data.Ord ( comparing )
import Data.Bits
import Data.Word
import qualified Data.IntMap as IM
import qualified Data.Set as Set
import Data.Time
infixr 9 `thenCmp`
{-
************************************************************************
* *
\subsection{Is DEBUG on, are we on Windows, etc?}
* *
************************************************************************
These booleans are global constants, set by CPP flags. They allow us to
recompile a single module (this one) to change whether or not debug output
appears. They sometimes let us avoid even running CPP elsewhere.
It's important that the flags are literal constants (True/False). Then,
with -0, tests of the flags in other modules will simplify to the correct
branch of the conditional, thereby dropping debug code altogether when
the flags are off.
-}
ghciSupported :: Bool
#ifdef GHCI
ghciSupported = True
#else
ghciSupported = False
#endif
debugIsOn :: Bool
#ifdef DEBUG
debugIsOn = True
#else
debugIsOn = False
#endif
ncgDebugIsOn :: Bool
#ifdef NCG_DEBUG
ncgDebugIsOn = True
#else
ncgDebugIsOn = False
#endif
ghciTablesNextToCode :: Bool
#ifdef GHCI_TABLES_NEXT_TO_CODE
ghciTablesNextToCode = True
#else
ghciTablesNextToCode = False
#endif
isWindowsHost :: Bool
#ifdef mingw32_HOST_OS
isWindowsHost = True
#else
isWindowsHost = False
#endif
isDarwinHost :: Bool
#ifdef darwin_HOST_OS
isDarwinHost = True
#else
isDarwinHost = False
#endif
{-
************************************************************************
* *
\subsection{A for loop}
* *
************************************************************************
-}
-- | Compose a function with itself n times. (nth rather than twice)
nTimes :: Int -> (a -> a) -> (a -> a)
nTimes 0 _ = id
nTimes 1 f = f
nTimes n f = f . nTimes (n-1) f
fstOf3 :: (a,b,c) -> a
sndOf3 :: (a,b,c) -> b
thdOf3 :: (a,b,c) -> c
fstOf3 (a,_,_) = a
sndOf3 (_,b,_) = b
thdOf3 (_,_,c) = c
fst3 :: (a -> d) -> (a, b, c) -> (d, b, c)
fst3 f (a, b, c) = (f a, b, c)
snd3 :: (b -> d) -> (a, b, c) -> (a, d, c)
snd3 f (a, b, c) = (a, f b, c)
third3 :: (c -> d) -> (a, b, c) -> (a, b, d)
third3 f (a, b, c) = (a, b, f c)
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c
liftFst :: (a -> b) -> (a, c) -> (b, c)
liftFst f (a,c) = (f a, c)
liftSnd :: (a -> b) -> (c, a) -> (c, b)
liftSnd f (c,a) = (c, f a)
firstM :: Monad m => (a -> m c) -> (a, b) -> m (c, b)
firstM f (x, y) = liftM (\x' -> (x', y)) (f x)
first3M :: Monad m => (a -> m d) -> (a, b, c) -> m (d, b, c)
first3M f (x, y, z) = liftM (\x' -> (x', y, z)) (f x)
{-
************************************************************************
* *
\subsection[Utils-lists]{General list processing}
* *
************************************************************************
-}
filterOut :: (a->Bool) -> [a] -> [a]
-- ^ Like filter, only it reverses the sense of the test
filterOut _ [] = []
filterOut p (x:xs) | p x = filterOut p xs
| otherwise = x : filterOut p xs
partitionWith :: (a -> Either b c) -> [a] -> ([b], [c])
-- ^ Uses a function to determine which of two output lists an input element should join
partitionWith _ [] = ([],[])
partitionWith f (x:xs) = case f x of
Left b -> (b:bs, cs)
Right c -> (bs, c:cs)
where (bs,cs) = partitionWith f xs
splitEithers :: [Either a b] -> ([a], [b])
-- ^ Teases a list of 'Either's apart into two lists
splitEithers [] = ([],[])
splitEithers (e : es) = case e of
Left x -> (x:xs, ys)
Right y -> (xs, y:ys)
where (xs,ys) = splitEithers es
chkAppend :: [a] -> [a] -> [a]
-- Checks for the second arguemnt being empty
-- Used in situations where that situation is common
chkAppend xs ys
| null ys = xs
| otherwise = xs ++ ys
{-
A paranoid @zip@ (and some @zipWith@ friends) that checks the lists
are of equal length. Alastair Reid thinks this should only happen if
DEBUGging on; hey, why not?
-}
zipEqual :: String -> [a] -> [b] -> [(a,b)]
zipWithEqual :: String -> (a->b->c) -> [a]->[b]->[c]
zipWith3Equal :: String -> (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith4Equal :: String -> (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
#ifndef DEBUG
zipEqual _ = zip
zipWithEqual _ = zipWith
zipWith3Equal _ = zipWith3
zipWith4Equal _ = zipWith4
#else
zipEqual _ [] [] = []
zipEqual msg (a:as) (b:bs) = (a,b) : zipEqual msg as bs
zipEqual msg _ _ = panic ("zipEqual: unequal lists:"++msg)
zipWithEqual msg z (a:as) (b:bs)= z a b : zipWithEqual msg z as bs
zipWithEqual _ _ [] [] = []
zipWithEqual msg _ _ _ = panic ("zipWithEqual: unequal lists:"++msg)
zipWith3Equal msg z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3Equal msg z as bs cs
zipWith3Equal _ _ [] [] [] = []
zipWith3Equal msg _ _ _ _ = panic ("zipWith3Equal: unequal lists:"++msg)
zipWith4Equal msg z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4Equal msg z as bs cs ds
zipWith4Equal _ _ [] [] [] [] = []
zipWith4Equal msg _ _ _ _ _ = panic ("zipWith4Equal: unequal lists:"++msg)
#endif
-- | 'zipLazy' is a kind of 'zip' that is lazy in the second list (observe the ~)
zipLazy :: [a] -> [b] -> [(a,b)]
zipLazy [] _ = []
zipLazy (x:xs) ~(y:ys) = (x,y) : zipLazy xs ys
-- | 'zipWithLazy' is like 'zipWith' but is lazy in the second list.
-- The length of the output is always the same as the length of the first
-- list.
zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWithLazy _ [] _ = []
zipWithLazy f (a:as) ~(b:bs) = f a b : zipWithLazy f as bs
-- | 'zipWith3Lazy' is like 'zipWith3' but is lazy in the second and third lists.
-- The length of the output is always the same as the length of the first
-- list.
zipWith3Lazy :: (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3Lazy _ [] _ _ = []
zipWith3Lazy f (a:as) ~(b:bs) ~(c:cs) = f a b c : zipWith3Lazy f as bs cs
-- | 'filterByList' takes a list of Bools and a list of some elements and
-- filters out these elements for which the corresponding value in the list of
-- Bools is False. This function does not check whether the lists have equal
-- length.
filterByList :: [Bool] -> [a] -> [a]
filterByList (True:bs) (x:xs) = x : filterByList bs xs
filterByList (False:bs) (_:xs) = filterByList bs xs
filterByList _ _ = []
-- | 'filterByLists' takes a list of Bools and two lists as input, and
-- outputs a new list consisting of elements from the last two input lists. For
-- each Bool in the list, if it is 'True', then it takes an element from the
-- former list. If it is 'False', it takes an element from the latter list.
-- The elements taken correspond to the index of the Bool in its list.
-- For example:
--
-- @
-- filterByLists [True, False, True, False] \"abcd\" \"wxyz\" = \"axcz\"
-- @
--
-- This function does not check whether the lists have equal length.
filterByLists :: [Bool] -> [a] -> [a] -> [a]
filterByLists (True:bs) (x:xs) (_:ys) = x : filterByLists bs xs ys
filterByLists (False:bs) (_:xs) (y:ys) = y : filterByLists bs xs ys
filterByLists _ _ _ = []
-- | 'partitionByList' takes a list of Bools and a list of some elements and
-- partitions the list according to the list of Bools. Elements corresponding
-- to 'True' go to the left; elements corresponding to 'False' go to the right.
-- For example, @partitionByList [True, False, True] [1,2,3] == ([1,3], [2])@
-- This function does not check whether the lists have equal
-- length.
partitionByList :: [Bool] -> [a] -> ([a], [a])
partitionByList = go [] []
where
go trues falses (True : bs) (x : xs) = go (x:trues) falses bs xs
go trues falses (False : bs) (x : xs) = go trues (x:falses) bs xs
go trues falses _ _ = (reverse trues, reverse falses)
stretchZipWith :: (a -> Bool) -> b -> (a->b->c) -> [a] -> [b] -> [c]
-- ^ @stretchZipWith p z f xs ys@ stretches @ys@ by inserting @z@ in
-- the places where @p@ returns @True@
stretchZipWith _ _ _ [] _ = []
stretchZipWith p z f (x:xs) ys
| p x = f x z : stretchZipWith p z f xs ys
| otherwise = case ys of
[] -> []
(y:ys) -> f x y : stretchZipWith p z f xs ys
mapFst :: (a->c) -> [(a,b)] -> [(c,b)]
mapSnd :: (b->c) -> [(a,b)] -> [(a,c)]
mapFst f xys = [(f x, y) | (x,y) <- xys]
mapSnd f xys = [(x, f y) | (x,y) <- xys]
mapAndUnzip :: (a -> (b, c)) -> [a] -> ([b], [c])
mapAndUnzip _ [] = ([], [])
mapAndUnzip f (x:xs)
= let (r1, r2) = f x
(rs1, rs2) = mapAndUnzip f xs
in
(r1:rs1, r2:rs2)
mapAndUnzip3 :: (a -> (b, c, d)) -> [a] -> ([b], [c], [d])
mapAndUnzip3 _ [] = ([], [], [])
mapAndUnzip3 f (x:xs)
= let (r1, r2, r3) = f x
(rs1, rs2, rs3) = mapAndUnzip3 f xs
in
(r1:rs1, r2:rs2, r3:rs3)
zipWithAndUnzip :: (a -> b -> (c,d)) -> [a] -> [b] -> ([c],[d])
zipWithAndUnzip f (a:as) (b:bs)
= let (r1, r2) = f a b
(rs1, rs2) = zipWithAndUnzip f as bs
in
(r1:rs1, r2:rs2)
zipWithAndUnzip _ _ _ = ([],[])
mapAccumL2 :: (s1 -> s2 -> a -> (s1, s2, b)) -> s1 -> s2 -> [a] -> (s1, s2, [b])
mapAccumL2 f s1 s2 xs = (s1', s2', ys)
where ((s1', s2'), ys) = mapAccumL (\(s1, s2) x -> case f s1 s2 x of
(s1', s2', y) -> ((s1', s2'), y))
(s1, s2) xs
nOfThem :: Int -> a -> [a]
nOfThem n thing = replicate n thing
-- | @atLength atLen atEnd ls n@ unravels list @ls@ to position @n@. Precisely:
--
-- @
-- atLength atLenPred atEndPred ls n
-- | n < 0 = atLenPred ls
-- | length ls < n = atEndPred (n - length ls)
-- | otherwise = atLenPred (drop n ls)
-- @
atLength :: ([a] -> b) -- Called when length ls >= n, passed (drop n ls)
-- NB: arg passed to this function may be []
-> b -- Called when length ls < n
-> [a]
-> Int
-> b
atLength atLenPred atEnd ls n
| n < 0 = atLenPred ls
| otherwise = go n ls
where
-- go's first arg n >= 0
go 0 ls = atLenPred ls
go _ [] = atEnd -- n > 0 here
go n (_:xs) = go (n-1) xs
-- Some special cases of atLength:
lengthExceeds :: [a] -> Int -> Bool
-- ^ > (lengthExceeds xs n) = (length xs > n)
lengthExceeds = atLength notNull False
lengthAtLeast :: [a] -> Int -> Bool
lengthAtLeast = atLength (const True) False
lengthIs :: [a] -> Int -> Bool
lengthIs = atLength null False
listLengthCmp :: [a] -> Int -> Ordering
listLengthCmp = atLength atLen atEnd
where
atEnd = LT -- Not yet seen 'n' elts, so list length is < n.
atLen [] = EQ
atLen _ = GT
equalLength :: [a] -> [b] -> Bool
equalLength [] [] = True
equalLength (_:xs) (_:ys) = equalLength xs ys
equalLength _ _ = False
compareLength :: [a] -> [b] -> Ordering
compareLength [] [] = EQ
compareLength (_:xs) (_:ys) = compareLength xs ys
compareLength [] _ = LT
compareLength _ [] = GT
leLength :: [a] -> [b] -> Bool
-- ^ True if length xs <= length ys
leLength xs ys = case compareLength xs ys of
LT -> True
EQ -> True
GT -> False
----------------------------
singleton :: a -> [a]
singleton x = [x]
isSingleton :: [a] -> Bool
isSingleton [_] = True
isSingleton _ = False
notNull :: [a] -> Bool
notNull [] = False
notNull _ = True
only :: [a] -> a
#ifdef DEBUG
only [a] = a
#else
only (a:_) = a
#endif
only _ = panic "Util: only"
-- Debugging/specialising versions of \tr{elem} and \tr{notElem}
isIn, isn'tIn :: Eq a => String -> a -> [a] -> Bool
# ifndef DEBUG
isIn _msg x ys = x `elem` ys
isn'tIn _msg x ys = x `notElem` ys
# else /* DEBUG */
isIn msg x ys
= elem100 0 x ys
where
elem100 :: Eq a => Int -> a -> [a] -> Bool
elem100 _ _ [] = False
elem100 i x (y:ys)
| i > 100 = trace ("Over-long elem in " ++ msg) (x `elem` (y:ys))
| otherwise = x == y || elem100 (i + 1) x ys
isn'tIn msg x ys
= notElem100 0 x ys
where
notElem100 :: Eq a => Int -> a -> [a] -> Bool
notElem100 _ _ [] = True
notElem100 i x (y:ys)
| i > 100 = trace ("Over-long notElem in " ++ msg) (x `notElem` (y:ys))
| otherwise = x /= y && notElem100 (i + 1) x ys
# endif /* DEBUG */
-- | Split a list into chunks of /n/ elements
chunkList :: Int -> [a] -> [[a]]
chunkList _ [] = []
chunkList n xs = as : chunkList n bs where (as,bs) = splitAt n xs
{-
************************************************************************
* *
\subsubsection{Sort utils}
* *
************************************************************************
-}
minWith :: Ord b => (a -> b) -> [a] -> a
minWith get_key xs = ASSERT( not (null xs) )
head (sortWith get_key xs)
nubSort :: Ord a => [a] -> [a]
nubSort = Set.toAscList . Set.fromList
{-
************************************************************************
* *
\subsection[Utils-transitive-closure]{Transitive closure}
* *
************************************************************************
This algorithm for transitive closure is straightforward, albeit quadratic.
-}
transitiveClosure :: (a -> [a]) -- Successor function
-> (a -> a -> Bool) -- Equality predicate
-> [a]
-> [a] -- The transitive closure
transitiveClosure succ eq xs
= go [] xs
where
go done [] = done
go done (x:xs) | x `is_in` done = go done xs
| otherwise = go (x:done) (succ x ++ xs)
_ `is_in` [] = False
x `is_in` (y:ys) | eq x y = True
| otherwise = x `is_in` ys
{-
************************************************************************
* *
\subsection[Utils-accum]{Accumulating}
* *
************************************************************************
A combination of foldl with zip. It works with equal length lists.
-}
foldl2 :: (acc -> a -> b -> acc) -> acc -> [a] -> [b] -> acc
foldl2 _ z [] [] = z
foldl2 k z (a:as) (b:bs) = foldl2 k (k z a b) as bs
foldl2 _ _ _ _ = panic "Util: foldl2"
all2 :: (a -> b -> Bool) -> [a] -> [b] -> Bool
-- True if the lists are the same length, and
-- all corresponding elements satisfy the predicate
all2 _ [] [] = True
all2 p (x:xs) (y:ys) = p x y && all2 p xs ys
all2 _ _ _ = False
-- Count the number of times a predicate is true
count :: (a -> Bool) -> [a] -> Int
count _ [] = 0
count p (x:xs) | p x = 1 + count p xs
| otherwise = count p xs
{-
@splitAt@, @take@, and @drop@ but with length of another
list giving the break-off point:
-}
takeList :: [b] -> [a] -> [a]
-- (takeList as bs) trims bs to the be same length
-- as as, unless as is longer in which case it's a no-op
takeList [] _ = []
takeList (_:xs) ls =
case ls of
[] -> []
(y:ys) -> y : takeList xs ys
dropList :: [b] -> [a] -> [a]
dropList [] xs = xs
dropList _ xs@[] = xs
dropList (_:xs) (_:ys) = dropList xs ys
splitAtList :: [b] -> [a] -> ([a], [a])
splitAtList [] xs = ([], xs)
splitAtList _ xs@[] = (xs, xs)
splitAtList (_:xs) (y:ys) = (y:ys', ys'')
where
(ys', ys'') = splitAtList xs ys
-- drop from the end of a list
dropTail :: Int -> [a] -> [a]
-- Specification: dropTail n = reverse . drop n . reverse
-- Better implemention due to Joachim Breitner
-- http://www.joachim-breitner.de/blog/archives/600-On-taking-the-last-n-elements-of-a-list.html
dropTail n xs
= go (drop n xs) xs
where
go (_:ys) (x:xs) = x : go ys xs
go _ _ = [] -- Stop when ys runs out
-- It'll always run out before xs does
-- dropWhile from the end of a list. This is similar to Data.List.dropWhileEnd,
-- but is lazy in the elements and strict in the spine. For reasonably short lists,
-- such as path names and typical lines of text, dropWhileEndLE is generally
-- faster than dropWhileEnd. Its advantage is magnified when the predicate is
-- expensive--using dropWhileEndLE isSpace to strip the space off a line of text
-- is generally much faster than using dropWhileEnd isSpace for that purpose.
-- Specification: dropWhileEndLE p = reverse . dropWhile p . reverse
-- Pay attention to the short-circuit (&&)! The order of its arguments is the only
-- difference between dropWhileEnd and dropWhileEndLE.
dropWhileEndLE :: (a -> Bool) -> [a] -> [a]
dropWhileEndLE p = foldr (\x r -> if null r && p x then [] else x:r) []
-- | @spanEnd p l == reverse (span p (reverse l))@. The first list
-- returns actually comes after the second list (when you look at the
-- input list).
spanEnd :: (a -> Bool) -> [a] -> ([a], [a])
spanEnd p l = go l [] [] l
where go yes _rev_yes rev_no [] = (yes, reverse rev_no)
go yes rev_yes rev_no (x:xs)
| p x = go yes (x : rev_yes) rev_no xs
| otherwise = go xs [] (x : rev_yes ++ rev_no) xs
snocView :: [a] -> Maybe ([a],a)
-- Split off the last element
snocView [] = Nothing
snocView xs = go [] xs
where
-- Invariant: second arg is non-empty
go acc [x] = Just (reverse acc, x)
go acc (x:xs) = go (x:acc) xs
go _ [] = panic "Util: snocView"
split :: Char -> String -> [String]
split c s = case rest of
[] -> [chunk]
_:rest -> chunk : split c rest
where (chunk, rest) = break (==c) s
{-
************************************************************************
* *
\subsection[Utils-comparison]{Comparisons}
* *
************************************************************************
-}
isEqual :: Ordering -> Bool
-- Often used in (isEqual (a `compare` b))
isEqual GT = False
isEqual EQ = True
isEqual LT = False
thenCmp :: Ordering -> Ordering -> Ordering
{-# INLINE thenCmp #-}
thenCmp EQ ordering = ordering
thenCmp ordering _ = ordering
eqListBy :: (a->a->Bool) -> [a] -> [a] -> Bool
eqListBy _ [] [] = True
eqListBy eq (x:xs) (y:ys) = eq x y && eqListBy eq xs ys
eqListBy _ _ _ = False
eqMaybeBy :: (a ->a->Bool) -> Maybe a -> Maybe a -> Bool
eqMaybeBy _ Nothing Nothing = True
eqMaybeBy eq (Just x) (Just y) = eq x y
eqMaybeBy _ _ _ = False
cmpList :: (a -> a -> Ordering) -> [a] -> [a] -> Ordering
-- `cmpList' uses a user-specified comparer
cmpList _ [] [] = EQ
cmpList _ [] _ = LT
cmpList _ _ [] = GT
cmpList cmp (a:as) (b:bs)
= case cmp a b of { EQ -> cmpList cmp as bs; xxx -> xxx }
removeSpaces :: String -> String
removeSpaces = dropWhileEndLE isSpace . dropWhile isSpace
-- Boolean operators lifted to Applicative
(<&&>) :: Applicative f => f Bool -> f Bool -> f Bool
(<&&>) = liftA2 (&&)
infixr 3 <&&> -- same as (&&)
(<||>) :: Applicative f => f Bool -> f Bool -> f Bool
(<||>) = liftA2 (||)
infixr 2 <||> -- same as (||)
{-
************************************************************************
* *
\subsection{Edit distance}
* *
************************************************************************
-}
-- | Find the "restricted" Damerau-Levenshtein edit distance between two strings.
-- See: <http://en.wikipedia.org/wiki/Damerau-Levenshtein_distance>.
-- Based on the algorithm presented in "A Bit-Vector Algorithm for Computing
-- Levenshtein and Damerau Edit Distances" in PSC'02 (Heikki Hyyro).
-- See http://www.cs.uta.fi/~helmu/pubs/psc02.pdf and
-- http://www.cs.uta.fi/~helmu/pubs/PSCerr.html for an explanation
restrictedDamerauLevenshteinDistance :: String -> String -> Int
restrictedDamerauLevenshteinDistance str1 str2
= restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
where
m = length str1
n = length str2
restrictedDamerauLevenshteinDistanceWithLengths
:: Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistanceWithLengths m n str1 str2
| m <= n
= if n <= 32 -- n must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) m n str1 str2
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) m n str1 str2
| otherwise
= if m <= 32 -- m must be larger so this check is sufficient
then restrictedDamerauLevenshteinDistance' (undefined :: Word32) n m str2 str1
else restrictedDamerauLevenshteinDistance' (undefined :: Integer) n m str2 str1
restrictedDamerauLevenshteinDistance'
:: (Bits bv, Num bv) => bv -> Int -> Int -> String -> String -> Int
restrictedDamerauLevenshteinDistance' _bv_dummy m n str1 str2
| [] <- str1 = n
| otherwise = extractAnswer $
foldl' (restrictedDamerauLevenshteinDistanceWorker
(matchVectors str1) top_bit_mask vector_mask)
(0, 0, m_ones, 0, m) str2
where
m_ones@vector_mask = (2 ^ m) - 1
top_bit_mask = (1 `shiftL` (m - 1)) `asTypeOf` _bv_dummy
extractAnswer (_, _, _, _, distance) = distance
restrictedDamerauLevenshteinDistanceWorker
:: (Bits bv, Num bv) => IM.IntMap bv -> bv -> bv
-> (bv, bv, bv, bv, Int) -> Char -> (bv, bv, bv, bv, Int)
restrictedDamerauLevenshteinDistanceWorker str1_mvs top_bit_mask vector_mask
(pm, d0, vp, vn, distance) char2
= seq str1_mvs $ seq top_bit_mask $ seq vector_mask $
seq pm' $ seq d0' $ seq vp' $ seq vn' $
seq distance'' $ seq char2 $
(pm', d0', vp', vn', distance'')
where
pm' = IM.findWithDefault 0 (ord char2) str1_mvs
d0' = ((((sizedComplement vector_mask d0) .&. pm') `shiftL` 1) .&. pm)
.|. ((((pm' .&. vp) + vp) .&. vector_mask) `xor` vp) .|. pm' .|. vn
-- No need to mask the shiftL because of the restricted range of pm
hp' = vn .|. sizedComplement vector_mask (d0' .|. vp)
hn' = d0' .&. vp
hp'_shift = ((hp' `shiftL` 1) .|. 1) .&. vector_mask
hn'_shift = (hn' `shiftL` 1) .&. vector_mask
vp' = hn'_shift .|. sizedComplement vector_mask (d0' .|. hp'_shift)
vn' = d0' .&. hp'_shift
distance' = if hp' .&. top_bit_mask /= 0 then distance + 1 else distance
distance'' = if hn' .&. top_bit_mask /= 0 then distance' - 1 else distance'
sizedComplement :: Bits bv => bv -> bv -> bv
sizedComplement vector_mask vect = vector_mask `xor` vect
matchVectors :: (Bits bv, Num bv) => String -> IM.IntMap bv
matchVectors = snd . foldl' go (0 :: Int, IM.empty)
where
go (ix, im) char = let ix' = ix + 1
im' = IM.insertWith (.|.) (ord char) (2 ^ ix) im
in seq ix' $ seq im' $ (ix', im')
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Word32 -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE INLINE restrictedDamerauLevenshteinDistance'
:: Integer -> Int -> Int -> String -> String -> Int #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Word32 -> Word32 -> Word32
-> (Word32, Word32, Word32, Word32, Int)
-> Char -> (Word32, Word32, Word32, Word32, Int) #-}
{-# SPECIALIZE restrictedDamerauLevenshteinDistanceWorker
:: IM.IntMap Integer -> Integer -> Integer
-> (Integer, Integer, Integer, Integer, Int)
-> Char -> (Integer, Integer, Integer, Integer, Int) #-}
{-# SPECIALIZE INLINE sizedComplement :: Word32 -> Word32 -> Word32 #-}
{-# SPECIALIZE INLINE sizedComplement :: Integer -> Integer -> Integer #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Word32 #-}
{-# SPECIALIZE matchVectors :: String -> IM.IntMap Integer #-}
fuzzyMatch :: String -> [String] -> [String]
fuzzyMatch key vals = fuzzyLookup key [(v,v) | v <- vals]
-- | Search for possible matches to the users input in the given list,
-- returning a small number of ranked results
fuzzyLookup :: String -> [(String,a)] -> [a]
fuzzyLookup user_entered possibilites
= map fst $ take mAX_RESULTS $ sortBy (comparing snd)
[ (poss_val, distance) | (poss_str, poss_val) <- possibilites
, let distance = restrictedDamerauLevenshteinDistance
poss_str user_entered
, distance <= fuzzy_threshold ]
where
-- Work out an approriate match threshold:
-- We report a candidate if its edit distance is <= the threshold,
-- The threshhold is set to about a quarter of the # of characters the user entered
-- Length Threshold
-- 1 0 -- Don't suggest *any* candidates
-- 2 1 -- for single-char identifiers
-- 3 1
-- 4 1
-- 5 1
-- 6 2
--
fuzzy_threshold = truncate $ fromIntegral (length user_entered + 2) / (4 :: Rational)
mAX_RESULTS = 3
{-
************************************************************************
* *
\subsection[Utils-pairs]{Pairs}
* *
************************************************************************
-}
unzipWith :: (a -> b -> c) -> [(a, b)] -> [c]
unzipWith f pairs = map ( \ (a, b) -> f a b ) pairs
seqList :: [a] -> b -> b
seqList [] b = b
seqList (x:xs) b = x `seq` seqList xs b
-- Global variables:
global :: a -> IORef a
global a = unsafePerformIO (newIORef a)
consIORef :: IORef [a] -> a -> IO ()
consIORef var x = do
atomicModifyIORef' var (\xs -> (x:xs,()))
globalM :: IO a -> IORef a
globalM ma = unsafePerformIO (ma >>= newIORef)
-- Module names:
looksLikeModuleName :: String -> Bool
looksLikeModuleName [] = False
looksLikeModuleName (c:cs) = isUpper c && go cs
where go [] = True
go ('.':cs) = looksLikeModuleName cs
go (c:cs) = (isAlphaNum c || c == '_' || c == '\'') && go cs
-- Similar to 'parse' for Distribution.Package.PackageName,
-- but we don't want to depend on Cabal.
looksLikePackageName :: String -> Bool
looksLikePackageName = all (all isAlphaNum <&&> not . (all isDigit)) . split '-'
{-
Akin to @Prelude.words@, but acts like the Bourne shell, treating
quoted strings as Haskell Strings, and also parses Haskell [String]
syntax.
-}
getCmd :: String -> Either String -- Error
(String, String) -- (Cmd, Rest)
getCmd s = case break isSpace $ dropWhile isSpace s of
([], _) -> Left ("Couldn't find command in " ++ show s)
res -> Right res
toCmdArgs :: String -> Either String -- Error
(String, [String]) -- (Cmd, Args)
toCmdArgs s = case getCmd s of
Left err -> Left err
Right (cmd, s') -> case toArgs s' of
Left err -> Left err
Right args -> Right (cmd, args)
toArgs :: String -> Either String -- Error
[String] -- Args
toArgs str
= case dropWhile isSpace str of
s@('[':_) -> case reads s of
[(args, spaces)]
| all isSpace spaces ->
Right args
_ ->
Left ("Couldn't read " ++ show str ++ " as [String]")
s -> toArgs' s
where
toArgs' :: String -> Either String [String]
-- Remove outer quotes:
-- > toArgs' "\"foo\" \"bar baz\""
-- Right ["foo", "bar baz"]
--
-- Keep inner quotes:
-- > toArgs' "-DFOO=\"bar baz\""
-- Right ["-DFOO=\"bar baz\""]
toArgs' s = case dropWhile isSpace s of
[] -> Right []
('"' : _) -> do
-- readAsString removes outer quotes
(arg, rest) <- readAsString s
(arg:) `fmap` toArgs' rest
s' -> case break (isSpace <||> (== '"')) s' of
(argPart1, s''@('"':_)) -> do
(argPart2, rest) <- readAsString s''
-- show argPart2 to keep inner quotes
((argPart1 ++ show argPart2):) `fmap` toArgs' rest
(arg, s'') -> (arg:) `fmap` toArgs' s''
readAsString :: String -> Either String (String, String)
readAsString s = case reads s of
[(arg, rest)]
-- rest must either be [] or start with a space
| all isSpace (take 1 rest) ->
Right (arg, rest)
_ ->
Left ("Couldn't read " ++ show s ++ " as String")
{-
-- -----------------------------------------------------------------------------
-- Floats
-}
readRational__ :: ReadS Rational -- NB: doesn't handle leading "-"
readRational__ r = do
(n,d,s) <- readFix r
(k,t) <- readExp s
return ((n%1)*10^^(k-d), t)
where
readFix r = do
(ds,s) <- lexDecDigits r
(ds',t) <- lexDotDigits s
return (read (ds++ds'), length ds', t)
readExp (e:s) | e `elem` "eE" = readExp' s
readExp s = return (0,s)
readExp' ('+':s) = readDec s
readExp' ('-':s) = do (k,t) <- readDec s
return (-k,t)
readExp' s = readDec s
readDec s = do
(ds,r) <- nonnull isDigit s
return (foldl1 (\n d -> n * 10 + d) [ ord d - ord '0' | d <- ds ],
r)
lexDecDigits = nonnull isDigit
lexDotDigits ('.':s) = return (span isDigit s)
lexDotDigits s = return ("",s)
nonnull p s = do (cs@(_:_),t) <- return (span p s)
return (cs,t)
readRational :: String -> Rational -- NB: *does* handle a leading "-"
readRational top_s
= case top_s of
'-' : xs -> - (read_me xs)
xs -> read_me xs
where
read_me s
= case (do { (x,"") <- readRational__ s ; return x }) of
[x] -> x
[] -> error ("readRational: no parse:" ++ top_s)
_ -> error ("readRational: ambiguous parse:" ++ top_s)
-----------------------------------------------------------------------------
-- read helpers
maybeRead :: Read a => String -> Maybe a
maybeRead str = case reads str of
[(x, "")] -> Just x
_ -> Nothing
maybeReadFuzzy :: Read a => String -> Maybe a
maybeReadFuzzy str = case reads str of
[(x, s)]
| all isSpace s ->
Just x
_ ->
Nothing
-----------------------------------------------------------------------------
-- Verify that the 'dirname' portion of a FilePath exists.
--
doesDirNameExist :: FilePath -> IO Bool
doesDirNameExist fpath = doesDirectoryExist (takeDirectory fpath)
-----------------------------------------------------------------------------
-- Backwards compatibility definition of getModificationTime
getModificationUTCTime :: FilePath -> IO UTCTime
getModificationUTCTime = getModificationTime
-- --------------------------------------------------------------
-- check existence & modification time at the same time
modificationTimeIfExists :: FilePath -> IO (Maybe UTCTime)
modificationTimeIfExists f = do
(do t <- getModificationUTCTime f; return (Just t))
`catchIO` \e -> if isDoesNotExistError e
then return Nothing
else ioError e
-- --------------------------------------------------------------
-- Change the character encoding of the given Handle to transliterate
-- on unsupported characters instead of throwing an exception
hSetTranslit :: Handle -> IO ()
hSetTranslit h = do
menc <- hGetEncoding h
case fmap textEncodingName menc of
Just name | '/' `notElem` name -> do
enc' <- mkTextEncoding $ name ++ "//TRANSLIT"
hSetEncoding h enc'
_ -> return ()
-- split a string at the last character where 'pred' is True,
-- returning a pair of strings. The first component holds the string
-- up (but not including) the last character for which 'pred' returned
-- True, the second whatever comes after (but also not including the
-- last character).
--
-- If 'pred' returns False for all characters in the string, the original
-- string is returned in the first component (and the second one is just
-- empty).
splitLongestPrefix :: String -> (Char -> Bool) -> (String,String)
splitLongestPrefix str pred
| null r_pre = (str, [])
| otherwise = (reverse (tail r_pre), reverse r_suf)
-- 'tail' drops the char satisfying 'pred'
where (r_suf, r_pre) = break pred (reverse str)
escapeSpaces :: String -> String
escapeSpaces = foldr (\c s -> if isSpace c then '\\':c:s else c:s) ""
type Suffix = String
--------------------------------------------------------------
-- * Search path
--------------------------------------------------------------
data Direction = Forwards | Backwards
reslash :: Direction -> FilePath -> FilePath
reslash d = f
where f ('/' : xs) = slash : f xs
f ('\\' : xs) = slash : f xs
f (x : xs) = x : f xs
f "" = ""
slash = case d of
Forwards -> '/'
Backwards -> '\\'
makeRelativeTo :: FilePath -> FilePath -> FilePath
this `makeRelativeTo` that = directory </> thisFilename
where (thisDirectory, thisFilename) = splitFileName this
thatDirectory = dropFileName that
directory = joinPath $ f (splitPath thisDirectory)
(splitPath thatDirectory)
f (x : xs) (y : ys)
| x == y = f xs ys
f xs ys = replicate (length ys) ".." ++ xs
{-
************************************************************************
* *
\subsection[Utils-Data]{Utils for defining Data instances}
* *
************************************************************************
These functions helps us to define Data instances for abstract types.
-}
abstractConstr :: String -> Constr
abstractConstr n = mkConstr (abstractDataType n) ("{abstract:"++n++"}") [] Prefix
abstractDataType :: String -> DataType
abstractDataType n = mkDataType n [abstractConstr n]
{-
************************************************************************
* *
\subsection[Utils-C]{Utils for printing C code}
* *
************************************************************************
-}
charToC :: Word8 -> String
charToC w =
case chr (fromIntegral w) of
'\"' -> "\\\""
'\'' -> "\\\'"
'\\' -> "\\\\"
c | c >= ' ' && c <= '~' -> [c]
| otherwise -> ['\\',
chr (ord '0' + ord c `div` 64),
chr (ord '0' + ord c `div` 8 `mod` 8),
chr (ord '0' + ord c `mod` 8)]
{-
************************************************************************
* *
\subsection[Utils-Hashing]{Utils for hashing}
* *
************************************************************************
-}
-- | A sample hash function for Strings. We keep multiplying by the
-- golden ratio and adding. The implementation is:
--
-- > hashString = foldl' f golden
-- > where f m c = fromIntegral (ord c) * magic + hashInt32 m
-- > magic = 0xdeadbeef
--
-- Where hashInt32 works just as hashInt shown above.
--
-- Knuth argues that repeated multiplication by the golden ratio
-- will minimize gaps in the hash space, and thus it's a good choice
-- for combining together multiple keys to form one.
--
-- Here we know that individual characters c are often small, and this
-- produces frequent collisions if we use ord c alone. A
-- particular problem are the shorter low ASCII and ISO-8859-1
-- character strings. We pre-multiply by a magic twiddle factor to
-- obtain a good distribution. In fact, given the following test:
--
-- > testp :: Int32 -> Int
-- > testp k = (n - ) . length . group . sort . map hs . take n $ ls
-- > where ls = [] : [c : l | l <- ls, c <- ['\0'..'\xff']]
-- > hs = foldl' f golden
-- > f m c = fromIntegral (ord c) * k + hashInt32 m
-- > n = 100000
--
-- We discover that testp magic = 0.
hashString :: String -> Int32
hashString = foldl' f golden
where f m c = fromIntegral (ord c) * magic + hashInt32 m
magic = fromIntegral (0xdeadbeef :: Word32)
golden :: Int32
golden = 1013904242 -- = round ((sqrt 5 - 1) * 2^32) :: Int32
-- was -1640531527 = round ((sqrt 5 - 1) * 2^31) :: Int32
-- but that has bad mulHi properties (even adding 2^32 to get its inverse)
-- Whereas the above works well and contains no hash duplications for
-- [-32767..65536]
-- | A sample (and useful) hash function for Int32,
-- implemented by extracting the uppermost 32 bits of the 64-bit
-- result of multiplying by a 33-bit constant. The constant is from
-- Knuth, derived from the golden ratio:
--
-- > golden = round ((sqrt 5 - 1) * 2^32)
--
-- We get good key uniqueness on small inputs
-- (a problem with previous versions):
-- (length $ group $ sort $ map hashInt32 [-32767..65536]) == 65536 + 32768
--
hashInt32 :: Int32 -> Int32
hashInt32 x = mulHi x golden + x
-- hi 32 bits of a x-bit * 32 bit -> 64-bit multiply
mulHi :: Int32 -> Int32 -> Int32
mulHi a b = fromIntegral (r `shiftR` 32)
where r :: Int64
r = fromIntegral a * fromIntegral b
| tjakway/ghcjvm | compiler/utils/Util.hs | bsd-3-clause | 42,098 | 0 | 19 | 12,604 | 10,937 | 5,986 | 4,951 | 614 | 7 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
module Stack.NixSpec where
import Test.Hspec
import Control.Monad.Logger
import Control.Exception
import Data.Monoid
import Network.HTTP.Conduit (Manager)
import System.Environment
import Path
import System.Directory
import System.IO.Temp (withSystemTempDirectory)
import Stack.Config
import Stack.Types.Config
import Stack.Types.StackT
import Stack.Types.Nix
import Prelude -- to remove the warning about Data.Monoid being redundant on GHC 7.10
sampleConfig :: String
sampleConfig =
"resolver: lts-2.10\n" ++
"packages: ['.']\n" ++
"nix:\n" ++
" enable: True\n" ++
" packages: [glpk]"
stackDotYaml :: Path Rel File
stackDotYaml = $(mkRelFile "stack.yaml")
data T = T
{ manager :: Manager
}
setup :: IO T
setup = do
manager <- newTLSManager
unsetEnv "STACK_YAML"
return T{..}
teardown :: T -> IO ()
teardown _ = return ()
spec :: Spec
spec = beforeAll setup $ afterAll teardown $ do
let loadConfig' m = runStackLoggingT m LevelDebug False False (loadConfig mempty Nothing Nothing)
inTempDir action = do
currentDirectory <- getCurrentDirectory
withSystemTempDirectory "Stack_ConfigSpec" $ \tempDir -> do
let enterDir = setCurrentDirectory tempDir
exitDir = setCurrentDirectory currentDirectory
bracket_ enterDir exitDir action
describe "nix" $ do
it "sees that the nix shell is enabled" $ \T{..} -> inTempDir $ do
writeFile (toFilePath stackDotYaml) sampleConfig
lc <- loadConfig' manager
(nixEnable $ configNix $ lcConfig lc) `shouldBe` True
it "sees that the only package asked for is glpk and adds GHC from nixpkgs mirror of LTS resolver" $ \T{..} -> inTempDir $ do
writeFile (toFilePath stackDotYaml) sampleConfig
lc <- loadConfig' manager
(nixPackages $ configNix $ lcConfig lc) `shouldBe` ["glpk"]
(nixCompiler $ configNix $ lcConfig lc) Nothing Nothing `shouldBe` "haskell.packages.lts-2_10.ghc"
| harendra-kumar/stack | src/test/Stack/NixSpec.hs | bsd-3-clause | 2,067 | 0 | 20 | 403 | 521 | 266 | 255 | 55 | 1 |
module Main (main) where
import Ros.Service.ServiceTypes
import Ros.Service (callService)
import qualified Ros.Rospy_tutorials.AddTwoIntsRequest as Req
import Ros.Rospy_tutorials.AddTwoIntsResponse as Res
type Response a = IO (Either ServiceResponseExcept a)
main :: IO ()
main = do
response <- callService "/add_two_ints" Req.AddTwoIntsRequest { Req._a=10, Req._b=5 }
case response of
Right result -> print (result :: Res.AddTwoIntsResponse)
Left e -> error (show e)
| bitemyapp/roshask | Examples/AddTwoIntsClient/src/Main.hs | bsd-3-clause | 489 | 0 | 12 | 79 | 152 | 85 | 67 | 12 | 2 |
{-# OPTIONS -Wall -Werror #-}
module InferCombinators where
import Control.Arrow ((***))
import Control.Lens (Lens')
import Control.Lens.Operators
import Control.Monad (void)
import Data.Map ((!))
import Data.Maybe (fromMaybe)
import Data.Store.Guid (Guid)
import InferWrappers
import Lamdu.Data.Arbitrary () -- Arbitrary instance
import Lamdu.Data.Expression (Kind(..))
import Lamdu.Data.Expression.IRef (DefI)
import Lamdu.Data.Expression.Utils (pureHole, pureSet, pureIntegerType)
import Utils
import qualified Control.Lens as Lens
import qualified Data.Store.Guid as Guid
import qualified Data.Store.IRef as IRef
import qualified Lamdu.Data.Expression as Expr
import qualified Lamdu.Data.Expression.Lens as ExprLens
import qualified Lamdu.Data.Expression.Utils as ExprUtil
iexpr ::
PureExprDefI t ->
PureExprDefI t ->
Expr.Body (DefI t) (InferResults t) -> InferResults t
iexpr val typ body =
Expr.Expression body (val, typ)
five :: PureExprDefI t
five = pureLiteralInt # 5
iVal :: Lens' (InferResults t) (PureExprDefI t)
iVal = Expr.ePayload . Lens._1
iType :: Lens' (InferResults t) (PureExprDefI t)
iType = Expr.ePayload . Lens._2
bodyToPureExpr :: Expr.Body (DefI t) (InferResults t) -> PureExprDefI t
bodyToPureExpr exprBody = ExprLens.pureExpr # fmap (^. iVal) exprBody
-- inferred-val is simply equal to the expr. Type is given
simple :: Expr.Body (DefI t) (InferResults t) -> PureExprDefI t -> InferResults t
simple body typ = iexpr (bodyToPureExpr body) typ body
getParamPure :: String -> PureExprDefI t -> InferResults t
getParamPure name = simple $ ExprLens.bodyParameterRef # Guid.fromString name
getRecursiveDef :: PureExprDefI t
getRecursiveDef =
ExprLens.pureExpr . ExprLens.bodyDefinitionRef # recursiveDefI
-- New-style:
recurse :: InferResults t -> InferResults t
recurse typ = simple (ExprLens.bodyDefinitionRef # recursiveDefI) $ typ ^. iVal
literalInteger :: Integer -> InferResults t
literalInteger x = simple (ExprLens.bodyLiteralInteger # x) pureIntegerType
piType ::
String -> InferResults t ->
(InferResults t -> InferResults t) -> InferResults t
piType name paramType mkResultType =
simple (ExprUtil.makePi (Guid.fromString name) paramType result) pureSet
where
result = mkResultType $ getParam name paramType
infixr 4 ~>
(~>) :: InferResults t -> InferResults t -> InferResults t
(~>) src dest =
simple (ExprUtil.makePi (Guid.fromString "") src dest) pureSet
lambda ::
String -> InferResults t ->
(InferResults t -> InferResults t) ->
InferResults t
lambda name paramType mkResult =
simple (ExprUtil.makeLambda guid paramType result) $
ExprUtil.pureLam KType guid (paramType ^. iVal) (result ^. iType)
where
guid = Guid.fromString name
result = mkResult $ getParam name paramType
-- Sometimes we have an inferred type that comes outside-in but cannot
-- be inferred inside-out:
setInferredType :: InferResults t -> InferResults t -> InferResults t
setInferredType typ val = val & iType .~ typ ^. iVal
getField :: InferResults t -> InferResults t -> InferResults t
getField recordVal tagVal
| allFieldsMismatch = error "getField on record with only mismatching field tags"
| otherwise = simple (Expr._BodyGetField # Expr.GetField recordVal tagVal) pureFieldType
where
mFields = recordVal ^? iType . ExprLens.exprKindedRecordFields KType
allFieldsMismatch =
case mFields of
Nothing -> False
Just fields -> all (tagMismatch . fst) fields
tagMismatch fieldTag =
Lens.nullOf ExprLens.exprHole fieldTag &&
Lens.nullOf ExprLens.exprHole tagVal &&
(fieldTag ^?! ExprLens.exprTag /= tagVal ^?! ExprLens.exprTag)
mPureFieldType tagGuid =
mFields ^?
Lens._Just . Lens.traversed .
Lens.filtered
(Lens.has (Lens._1 . ExprLens.exprTag . Lens.filtered (tagGuid ==))) .
Lens._2
pureFieldType =
fromMaybe pureHole $
mPureFieldType =<< tagVal ^? ExprLens.exprTag
lambdaRecord ::
String -> [(String, InferResults t)] ->
([InferResults t] -> InferResults t) -> InferResults t
lambdaRecord paramsName strFields mkResult =
lambda paramsName (record KType fields) $ \params ->
mkResult $ map (getField params) fieldTags
where
fields = strFields & Lens.traversed . Lens._1 %~ tagStr
fieldTags = map fst fields
whereItem ::
String -> InferResults t -> (InferResults t -> InferResults t) -> InferResults t
whereItem name val mkBody =
lambda name (iexpr (val ^. iType) pureSet bodyHole) mkBody $$ val
holeWithInferredType :: InferResults t -> InferResults t
holeWithInferredType = simple bodyHole . (^. iVal)
hole :: InferResults t
hole = simple bodyHole pureHole
getGuidParam :: Guid -> InferResults t -> InferResults t
getGuidParam guid typ =
simple (ExprLens.bodyParameterRef # guid) $
typ ^. iVal
getParam :: String -> InferResults t -> InferResults t
getParam = getGuidParam . Guid.fromString
listOf :: InferResults t -> InferResults t
listOf = (getDef "List" $$)
-- Uses inferred holes for cons type
list :: [InferResults t] -> InferResults t
list [] = getDef "[]" $$ hole
list items@(x:_) =
foldr cons nil items
where
cons h t = getDef ":" $$ typ $$: [h, t]
nil = getDef "[]" $$ typ
typ = iexpr (x ^. iType) pureSet (ExprLens.bodyHole # ())
maybeOf :: InferResults t -> InferResults t
maybeOf = (getDef "Maybe" $$)
getDef :: String -> InferResults t
getDef name =
simple
(ExprLens.bodyDefinitionRef # IRef.unsafeFromGuid g)
(void (definitionTypes ! g))
where
g = Guid.fromString name
tag :: Guid -> InferResults t
tag guid =
simple (ExprLens.bodyTag # guid) $
ExprLens.pureExpr . ExprLens.bodyTagType # ()
tagStr :: String -> InferResults t
tagStr = tag . Guid.fromString
set :: InferResults t
set = simple bodySet pureSet
tagType :: InferResults t
tagType = simple (ExprLens.bodyTagType # ()) pureSet
integerType :: InferResults t
integerType = simple bodyIntegerType pureSet
infixl 4 $$
infixl 3 $$:
($$:) :: InferResults t -> [InferResults t] -> InferResults t
($$:) f args =
f $$ record KVal (zip tags args)
where
tags = recType ^.. Lens.traversed . Lens._1 . ExprLens.exprTag . Lens.to tag
recType =
fromMaybe (error msg) $
f ^? iType . ExprLens.exprKindedLam KType . Lens._2 . ExprLens.exprKindedRecordFields KType
msg = "$$: must be applied on a func of record type, not: " ++ show (f ^. iType)
($$) :: InferResults t -> InferResults t -> InferResults t
($$) func@(Expr.Expression _ (funcVal, funcType)) nextArg =
iexpr applyVal applyType application
where
application = ExprUtil.makeApply func nextArg
handleLam e k seeHole seeOther =
case e ^. Expr.eBody of
Expr.BodyLeaf Expr.Hole -> seeHole
Expr.BodyLam (Expr.Lam k1 paramGuid _ result)
| k == k1 -> ExprUtil.substGetPar paramGuid (nextArg ^. iVal) result
_ -> seeOther
applyVal =
handleLam funcVal KVal pureHole $
if ExprUtil.isTypeConstructorType applyType
then bodyToPureExpr application
else pureHole
applyType = handleLam funcType KType piErr piErr
piErr = error "Apply of non-Pi type!"
record :: Kind -> [(InferResults t, InferResults t)] -> InferResults t
record k fields =
simple (ExprLens.bodyKindedRecordFields k # fields) typ
where
typ = case k of
KVal ->
ExprLens.pureExpr . ExprLens.bodyKindedRecordFields KType #
map (void *** (^. iType)) fields
KType -> pureSet
asHole :: InferResults t -> InferResults t
asHole expr =
iexpr val typ $ ExprLens.bodyHole # ()
where
(val, typ) = expr ^. Expr.ePayload
| schell/lamdu | test/InferCombinators.hs | gpl-3.0 | 7,581 | 0 | 15 | 1,432 | 2,481 | 1,278 | 1,203 | -1 | -1 |
module Main where
import Control.Concurrent
import Control.Exception
--import GlaExts
data Result = Died SomeException | Finished
-- Test stack overflow catching. Should print "Died: stack overflow".
stackoverflow :: Int -> Int
stackoverflow 0 = 1
stackoverflow n = n + stackoverflow n
main = do
let x = stackoverflow 1
result <- newEmptyMVar
forkIO $ Control.Exception.catch (evaluate x >> putMVar result Finished) $
\e -> putMVar result (Died e)
res <- takeMVar result
case res of
Died e -> putStr ("Died: " ++ show e ++ "\n")
Finished -> putStr "Ok.\n"
| ezyang/ghc | testsuite/tests/concurrent/should_run/conc012.hs | bsd-3-clause | 609 | 0 | 14 | 144 | 184 | 91 | 93 | 16 | 2 |
{-# LANGUAGE CPP #-}
-- | @unsafe@ variants of the "Language.C.Inline" quasi-quoters, to call the C code
-- unsafely in the sense of
-- <https://www.haskell.org/onlinereport/haskell2010/haskellch8.html#x15-1590008.4.3>.
-- In GHC, unsafe foreign calls are faster than safe foreign calls, but the user
-- must guarantee the control flow will never enter Haskell code (via a callback
-- or otherwise) before the call is done.
--
-- This module is intended to be imported qualified:
--
-- @
-- import qualified "Language.C.Inline.Unsafe" as CU
-- @
module Language.C.Inline.Unsafe
( exp
, pure
, block
) where
#if __GLASGOW_HASKELL__ < 710
import Prelude hiding (exp)
#else
import Prelude hiding (exp, pure)
#endif
import qualified Language.Haskell.TH.Quote as TH
import qualified Language.Haskell.TH.Syntax as TH
import Language.C.Inline.Context
import Language.C.Inline.Internal
-- | C expressions.
exp :: TH.QuasiQuoter
exp = genericQuote IO $ inlineExp TH.Unsafe
-- | Variant of 'exp', for use with expressions known to have no side effects.
--
-- __BEWARE__: Use this function with caution, only when you know what you are
-- doing. If an expression does in fact have side-effects, then indiscriminate
-- use of 'pure' may endanger referential transparency, and in principle even
-- type safety. Also note that the function may run more than once and that it
-- may run in parallel with itself, given that
-- 'System.IO.Unsafe.unsafeDupablePerformIO' is used to call the provided C
-- code [to ensure good performance using the threaded
-- runtime](https://github.com/fpco/inline-c/issues/115). Please refer to the
-- documentation for 'System.IO.Unsafe.unsafeDupablePerformIO' for more
-- details.
pure :: TH.QuasiQuoter
pure = genericQuote Pure $ inlineExp TH.Unsafe
-- | C code blocks (i.e. statements).
block :: TH.QuasiQuoter
block = genericQuote IO $ inlineItems TH.Unsafe False Nothing
| fpco/inline-c | inline-c/src/Language/C/Inline/Unsafe.hs | mit | 1,952 | 0 | 7 | 333 | 168 | 113 | 55 | 16 | 1 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module JSONInstances where
import Types
import GHC.Generics (Generic)
import Data.Aeson
import Data.Text (Text)
import Control.Applicative
import Control.Monad (MonadPlus, mzero)
import qualified Data.HashMap.Strict as M
import Data.Vector (fromList)
instance FromJSON MessageFromClient where
parseJSON (Object v)
| Just "MapBoundsUpdated" <- M.lookup "type" v = MapBoundsUpdated <$> ((,) <$> v .: "latSW" <*> v .: "lngSW") <*> ((,) <$> v .: "latNE" <*> v .: "lngNE")
| Just "ListActiveRooms" <- M.lookup "type" v = ListActiveRooms <$> ((,) <$> v .: "latSW" <*> v .: "lngSW") <*> ((,) <$> v .: "latNE" <*> v .: "lngNE")
| Just "ChangeNickname" <- M.lookup "type" v = ChangeNickname <$> v .: "nickname"
| Just "CreateRoom" <- M.lookup "type" v = CreateRoom <$> ((,) <$> v .: "lat" <*> v .: "lng")
| Just "ChangeNickname" <- M.lookup "type" v = ChangeNickname <$> v .: "nickname"
| Just "JoinRoom" <- M.lookup "type" v = JoinRoom <$> v .: "roomId"
| Just "PostMessage" <- M.lookup "type" v = PostMessage <$> v .: "content"
| otherwise = mzero
parseJSON _ = mzero
instance ToJSON MessageFromServer where
toJSON (Handshake cid) = object ["type" .= ("Handshake" :: Text), "clientId" .= cid]
toJSON (UpdatedRoom latLng room change) =
object ["type" .= ("UpdatedRoom" :: Text), "room" .= room, "change" .= change, "latLng" .= latLng]
toJSON (Broadcast latLng client roomId text) =
object ["type" .= ("Broadcast" :: Text), "client" .= client, "roomId" .= roomId, "latLng" .= latLng, "text" .= text]
toJSON (ErrorMessage text) = object ["type" .= ("ErrorMessage" :: Text), "content" .= text]
instance ToJSON RoomChange where
toJSON (ChangedNickname c) = object ["type" .= ("ChangedNickname" :: Text), "client" .= c]
toJSON InitRoom = object ["type" .= ("InitRoom" :: Text)]
toJSON (EnterRoom c) = object ["type" .= ("EnterRoom" :: Text), "client" .= c]
toJSON (ExitRoom c) = object ["type" .= ("ExitRoom" :: Text), "client" .= c]
{-
(decode $ pack "{\"type\": \"Enter\", \"clientId\": 2, \"roomId\": 3}")::Maybe MessageFromClient
Just (Enter 2 3)
(decode $ pack "{\"type\": \"CreateRoom\", \"lat\": 43.3, \"lng\": -70.1}")::Maybe MessageFromClient
Just (CreateRoom (43.3,-70.1))
encode (NewClientCreated Client { clientId = 12, nickname = Text.pack "dan" , clientSink = Nothing , clientRoom = Nothing})
Chunk "{\"clientId\":12,\"type\":\"NewClientCreated\"}" Empty
Experiment:
encode (ListOfActiveRooms [])
encode (ListOfActiveRooms [Room { roomId = 3 , latLng = (40.2, -71.2), numParticipants = 0}])
Chunk "{\"rooms\":[{\"latLng\":[40.2,-71.2],\"numParticipants\":0,\"roomId\":3}],\"type\":\"ListOfActiveRooms\"}" Empty
encode (RoomActivity Room { roomId = 3 , latLng = (40.2, -71.2), numParticipants = 0})
-}
| danchoi/geochat | src/JSONInstances.hs | mit | 2,848 | 0 | 14 | 488 | 774 | 405 | 369 | 33 | 0 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.OESVertexArrayObject (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.OESVertexArrayObject
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.OESVertexArrayObject
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/OESVertexArrayObject.hs | mit | 373 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
import Control.Monad
import Data.Char
-- sumDigits :: [Int] -> Int
sumDigits n = sum $ map digitToInt $ show n
primesSieve n = sieve [2..n]
where
sieve [] = []
sieve (p:xs) = p : sieve [x | x <- xs, x `mod` p > 0]
-- round or ceiling?
intSqrt = floor . sqrt . fromIntegral
squeeze n p
| n `mod` p == 0 = (fst rec, p : (snd rec))
| otherwise = (n, [])
where
rec = squeeze (n `div` p) p
-- wrong, matches for loop only, needs a nested while loop
primeFactors n i primes =
-- let (r, factors) = foldl (\(n, acc) p -> if n `mod` p == 0 then (n `div` p, acc) else (n, acc ++ [p])) (n , i) primes
let (r, factors) = foldl (\(n, acc) p -> (fst (squeeze n p), acc ++ (snd (squeeze n p)))) (n , i) primes
in factors ++ [r | r > 1]
-- http://en.wikipedia.org/wiki/Trial_division
trialDivision n
| n < 2 = []
| otherwise = primeFactors n [] smallPrimes
where
primes = primesSieve n
smallPrimes = takeWhile (\p -> p * p <= n) primes
main :: IO ()
main = do
n <- readLn :: IO Int
let factors = trialDivision n
let ans = if sumDigits n == sum (map sumDigits factors) then 1 else 0
print ans
| mgrebenets/hackerrank | alg/warmup/identify-smith-numbers.hs | mit | 1,200 | 0 | 17 | 354 | 475 | 244 | 231 | 25 | 2 |
module Map
( Map
, Room ( .. )
, numberRooms
, generateMap
, Wumpus ( .. )
) where
-- | Data types
data Room = Room { number :: Int, connections :: [Int] }
instance Show Room where
show r = "Room number: " ++ show (number r) ++ ", " ++ "Connected rooms: " ++ show (connections r) ++ "\n"
type Map = [Room]
data Wumpus = Wumpus { wloc :: Int, moved :: Int }
-- | Map functions
numberRooms :: IO Int
numberRooms = do
putStrLn "What size would you like your map? "
putStrLn "(small/medium/large)"
line <- getLine
if line == "small"
then return 6
else if line == "medium"
then return 12
else if line == "large"
then return 20
else do
putStrLn "Sorry, but that's not a map size! "
numberRooms
generateMap :: Int -> Int -> Map
generateMap x half
| x == (2 * half) = generateMap (x - 1) half ++ [Room x [1, x - half, x - 1]]
| x > half = generateMap (x - 1) half ++ [Room x [x - half, x - 1, x + 1]]
| x == 1 = [Room 1 [2, 1 + half, 2 * half]]
| otherwise = generateMap (x - 1) half ++ [Room x [x - 1, x + 1, x + half]]
| garrettoreilly/Hunt-The-Wumpus | Map.hs | mit | 1,167 | 0 | 13 | 381 | 459 | 244 | 215 | 31 | 4 |
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# LANGUAGE TemplateHaskell #-}
import Prelude
import GLSL
import Test.DocTest
-- | >>> shaderName simpleVert
-- "test/res/simple.vert"
--
-- >>> shaderType simpleVert
-- VertexShader
simpleVert :: ShaderSource VertexShader
simpleVert = $("test/res/simple.vert" `shaderFile` VertexShader)
main :: IO ()
main = doctest ["test/Example.hs"]
| MaxDaten/vinyl-glsl | test/Example.hs | mit | 390 | 0 | 7 | 53 | 63 | 38 | 25 | 9 | 1 |
module Raytracer where
import GHC.Float
import Graphics.Gloss
import Math.Geom.Primitives hiding (Point)
import Math.Geom.Shapes
import Math.Geom.Intersections
import qualified Math.Vec as V
import Math.Vec (( *** ), ( /// ))
import Math.Matrix
import Scene
-- TODO: make accumulate readable
-- sort intersect results by t, no conditional in accumulate
raytrace :: V.Vec3 -> Ray -> [(Shape, Material, Mat4)] -> Rig -> Color
raytrace eye ray [] rig = ka rig
raytrace eye ray objs rig = accumulate (ka rig, 1/0) rig (map (\(shape, mat, xf) -> (intersect ray (shape, xf), mat)) objs)
where accumulate :: (Color, Double) -> Rig -> [(XsectResult, Material)] -> Color
accumulate (c, t) rig ((Miss, _):xs) = accumulate (c, t) rig xs
accumulate (c, t) rig ((Hit res, mat):xs) = let (t', pt, n) = head res --ignore rest of res
acc = if t' < t then (computeLight (ka rig + ke mat) (lights rig) (eye) pt n mat, t') else (c, t)
in accumulate acc rig xs
accumulate (c, _) rig [] = c
computeLight :: Color -> [Light] -> V.Vec3 -> V.Vec3 -> V.Vec3 -> Material -> Color
computeLight acc (light:ls) eye pos normal mat
= let col = case light of PointLight _ lightcol -> lightcol
DirectionalLight _ lightcol -> lightcol
l = case light of PointLight lightpos _ -> V.norm (lightpos - pos)
DirectionalLight lightdir _ -> V.norm lightdir
h = V.norm (V.norm (eye - pos) + l)
diffuse = (kd mat) * (greyN $ double2Float (max (normal `V.dot` l) 0))
specular = (ks mat) * (greyN $ double2Float ((max (normal `V.dot` h) 0) ** (sh mat)))
acc' = acc + col * (diffuse + specular)
in computeLight acc' ls eye pos normal mat
computeLight acc [] eye pos normal mat = acc
| davidyu/Slowpoke | hs/src/raytracer.hs | mit | 1,999 | 0 | 20 | 653 | 762 | 417 | 345 | -1 | -1 |
module Y2016.M07.D05.Exercise where
{--
So, let's say, for example, hypothetically speaking, that we have a set of
jUnit test cases as XML, or some other sensitive data that you wish to obscure
before you share with a larger public audience?
How do you translates "sensitive data" to 'coded data'?
--}
import Control.Monad.State
import Text.HTML.TagSoup
import Data.SymbolTable
-- convert every name and classname to an encoded value and then save out the
-- result as the same XML structure.
encodeXMLnames :: FilePath -> IO ()
encodeXMLnames = undefined
-- do this for test.xml in the Y2016/M07/D01/ directory
-- hint: SymbolTable takes a string and returns an enumerated value for it
-- (an Int), a possible encoding, then, for "foo" could be "S1", for "bar"
-- could be "S2" ... etc.
-- We'll look at more clever encodings throughout this week.
{-- BONUS -----------------------------------------------------------------
You see in test.xml that the qualified names follow this pattern
a.b.c.d.e...
Instead of encoding the entire qualified name, encode each of the qualifying
names of a qualified name. Do you have more or less symbols that way? Is that
encoding more or less sensical?
--}
encodeQname :: String -> State SymbolTable ()
encodeQname qualifiedName = undefined
-- so "a.b.c.d.e" adds or verifies 5 symbols to the SymbolTable
| geophf/1HaskellADay | exercises/HAD/Y2016/M07/D05/Exercise.hs | mit | 1,356 | 0 | 7 | 224 | 78 | 49 | 29 | 8 | 1 |
isSingleElement index = index == 0
middle list = quot (length list) 2
handleSingle a = case a of
EQ -> Just 0
_ -> Nothing
binarySearch element sortedList =
let middleIndex = middle sortedList
middleElement = sortedList !! middleIndex
comparison = compare element middleElement
in if isSingleElement middleIndex
then handleSingle comparison
else case comparison of
LT -> binarySearch element $ take middleIndex sortedList
EQ -> Just middleIndex
GT -> let newLeft = middleIndex + 1
rightIndex = binarySearch element $ drop middleIndex sortedList
in fmap (+newLeft) rightIndex
| diminishedprime/.org | programmey_stuff/algorithms/binary_search.hs | mit | 684 | 0 | 16 | 197 | 194 | 93 | 101 | 17 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Anonymous.TorSpec where
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar
import qualified Network.Anonymous.Tor as Tor
import qualified Network.Socks5.Types as SocksT
import qualified Data.Base32String.Default as B32
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import Test.Hspec
whichPort :: IO Integer
whichPort = do
let ports = [9051, 9151]
availability <- mapM Tor.isAvailable ports
return . fst . head . filter ((== Tor.Available) . snd) $ zip ports availability
spec :: Spec
spec = do
describe "when starting a new server" $ do
it "should accept connections through a hidden server" $ do
clientDone <- newEmptyMVar
serverDone <- newEmptyMVar
port <- whichPort
Tor.withSession port (withinSession clientDone serverDone)
takeMVar clientDone `shouldReturn` True
takeMVar serverDone `shouldReturn` True
where
withinSession clientDone serverDone sock = do
onion <- Tor.accept sock 4321 Nothing (serverWorker serverDone)
putStrLn ("Got Tor hidden server: " ++ show onion)
putStrLn ("waiting 30 seconds..")
threadDelay 30000000
putStrLn ("waited 30 seconds, connecting..")
Tor.connect' sock (constructDestination onion 4321) (clientWorker clientDone)
destinationAddress onion =
TE.encodeUtf8 $ T.concat [B32.toText onion, T.pack ".ONION"]
constructDestination onion port =
SocksT.SocksAddress (SocksT.SocksAddrDomainName (destinationAddress onion)) port
serverWorker serverDone _ = do
putStrLn "Accepted connection"
putMVar serverDone True
clientWorker clientDone _ = do
putStrLn "Connected to hidden service!"
putMVar clientDone True
| solatis/haskell-network-anonymous-tor | test/Network/Anonymous/TorSpec.hs | mit | 2,002 | 0 | 15 | 569 | 466 | 236 | 230 | 42 | 1 |
{-
Euler discovered the remarkable quadratic formula:
n² + n + 41
It turns out that the formula will produce 40 primes for the consecutive values
n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible
by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.
The incredible formula n² − 79n + 1601 was discovered, which produces 80 primes
for the consecutive values n = 0 to 79. The product of the coefficients, −79 and
1601, is −126479.
Considering quadratics of the form:
n² + an + b, where |a| < 1000 and |b| < 1000
where |n| is the modulus/absolute value of n e.g. |11| = 11 and |−4| = 4
Find the product of the coefficients, a and b, for the quadratic expression that
produces the maximum number of primes for consecutive values of n, starting with
n = 0.
Solution
--------
Let p_n = n² + an + b. To generate a long list of odd numbers, a and b must be
odd.
b = p_0 => b is a prime.
As b must be odd, b is one of the primes from 3 up to 997 (the last prime before
1000).
p_1 = 1 + a + b => a = p_1 - 1 - b
a in [-999 999] => p_1 in [-998+b 1000+b] => p_1 is a prime <= 1000+b.
Then, test all pairs (a, b) verifying what's written above and retain the one
producing the longest sequences of prime numbers.
-}
import Data.List (foldl')
import Math.NumberTheory.Primes.Testing (isPrime)
import Math.NumberTheory.Primes.Sieve (primes)
{-------------------------------------------------------------------------------
best_a:
Given a value for b, compute the value of 'a' for which p_n generates the
longest prime sequence, within the allowed bounds.
input: b - the value of b
return: (a, l) - the value of a for which the length l of the sequence of primes
generated by p_n is the longest
-------------------------------------------------------------------------------}
best_a :: Integer -> (Integer, Int)
best_a b = foldl' update (0, 0) p1s where
p1s = takeWhile (<(1000+b)) (tail primes)
update :: (Integer, Int) -> Integer -> (Integer, Int)
update (a, l) p1 = if l < l' then (a', l') else (a, l)
where
a' = p1 - 1 - b
l' = length (takeWhile isPrime (map (\n -> (n+a')*n + b) [2..]))
{-------------------------------------------------------------------------------
best_a_b
Compute the values of 'a' and 'b' for which p_n generates the longest sequence,
within the allowed bounds.
return: (a, b, l) - the values of 'a' and 'b' for which the length 'l' of the
sequence of primes generated by p_n is the longest
-------------------------------------------------------------------------------}
best_a_b :: (Integer, Integer, Int)
best_a_b = foldl' update (0, 0, 0) (takeWhile (<997) (tail primes))
where
update (a, b, l) b' = if l < l' then (a', b', l') else (a, b, l)
where
(a', l') = best_a b'
--------------------------------------------------------------------------------
euler_27 = a * b where (a, b, l) = best_a_b | dpieroux/euler | 0/0027.hs | mit | 3,004 | 0 | 19 | 629 | 388 | 223 | 165 | 15 | 2 |
import System.Environment (getArgs)
import System.Exit
import System.IO
import Control.Exception
import Network
import Control.Concurrent (forkIO)
import Data.IORef
import Control.Monad
errorMessage = "Unknown command: "
exitMessage = "Client killed service. Byeeeee......"
maxConnections = 2000 -- some arbritrary constant for exposition
main :: IO ()
main = withSocketsDo $ do
(portString : _) <- getArgs
sock <- listenOn $ PortNumber $ fromIntegral (read portString :: Int)
putStrLn $ "Server listening on port " ++ portString
sem <- newSem maxConnections -- initialise our semaphore
handleConnections sock sem -- start server loop
handleConnections :: Socket -> Semaphore -> IO ()
handleConnections sock sem = do
res <- try $ accept sock :: IO (Either IOError (Handle, HostName, PortNumber))
case res of
Left _ -> exitSuccess -- we're done, exit(0)
Right (client, host, port) -> do
hSetBuffering client NoBuffering -- don't buffer output to client
areResourcesAvailable <- pullSem sem -- check if there are enough resources
if areResourcesAvailable then do
forkIO $ processRequest sock client host port sem -- spawn new thread to process request
handleConnections sock sem -- (tail) recurse (ie. wait for next request)
else do
putStrLn $ serverLog host port "[Connection dropped, server overloaded]"
hPutStr client "Server overloaded." >> hClose client
handleConnections sock sem -- (tail) recurse (ie. wait for next request)
processRequest :: Socket -> Handle -> HostName -> PortNumber -> Semaphore -> IO ()
processRequest sock client host port sem = do
req <- try $ hGetLine client :: IO (Either IOError String)
case req of
Left _ -> putStrLn $ serverLog host port "[closed connection without sending data]"
Right request -> do
putStrLn $ serverLog host port request -- log
case head $ words request of -- pattern match the first 'word' in request
"KILL_SERVICE" -> hPutStr client exitMessage >> sClose sock -- close the socket
"HELO" -> hPutStr client $ buildResponse request host port
otherwise -> hPutStr client $ errorMessage ++ request
hClose client
signalSem sem -- free up the 'resources' this 'thread' is using
serverLog :: HostName -> PortNumber -> String -> String
serverLog host port message = host ++ ":" ++ show port ++ " -> " ++ message
buildResponse :: String -> HostName -> PortNumber -> String
buildResponse message host port = unlines [message,
"IP: " ++ host,
"Port: " ++ show port] ++
"StudentID: 11420952"
-- semaphore implementation
newtype Semaphore = Semaphore (IORef Int)
newSem :: Int -> IO Semaphore
newSem i = liftM Semaphore $ newIORef i
pullSem :: Semaphore -> IO Bool
pullSem (Semaphore s) = atomicModifyIORef s $ \x -> if x == 0 then
(x, False)
else let !z = x - 1 -- make the decrement happen right now
in (z, True)
signalSem :: Semaphore -> IO ()
signalSem (Semaphore s) = atomicModifyIORef s $ \x -> let !z = x + 1 -- make the increment happen right now
in (z, ())
| IanConnolly/CS4032 | lab2/server.hs | mit | 3,547 | 0 | 17 | 1,114 | 857 | 426 | 431 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Web.Mackerel.Types.Role where
import Data.Aeson.TH (deriveJSON)
import Web.Mackerel.Internal.TH
data Role
= Role {
roleName :: String,
roleMemo :: String
} deriving (Eq, Show)
$(deriveJSON options ''Role)
| itchyny/mackerel-client-hs | src/Web/Mackerel/Types/Role.hs | mit | 261 | 0 | 8 | 46 | 73 | 44 | 29 | 10 | 0 |
{-# LANGUAGE ExistentialQuantification, Rank2Types, ImpredicativeTypes #-}
module Database.Siege.DoStore where
import Control.Monad
import Control.Monad.Trans
import Data.Word
import Data.Char
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Control.Monad.Trans.Store as S
-- import qualified Database.Redis.Redis as R
import Database.Siege.Hash
import qualified Database.Siege.DBNode as N
import Database.Siege.DBNodeBinary
import qualified Data.Binary as Bin
import System.Random
import Database.Siege.StringHelper
randRef :: IO N.Ref
randRef = do
s <- replicateM 20 $ do
r <- randomIO :: IO Int
let r' = fromIntegral r :: Word8
return $ r'
return $ N.Ref $ B.pack s
refLocation :: N.Ref -> B.ByteString
refLocation arg = B.snoc (N.unRef arg) 0
invertLocation :: N.Ref -> B.ByteString
invertLocation arg = B.snoc (N.unRef arg) 1
get :: [(forall x. (R.Redis -> IO x) -> IO x)] -> B.ByteString -> IO (Maybe B.ByteString)
get fns k = do
let fn = head fns
v <- fn (\redis -> R.get redis k)
case v of
R.RBulk v -> return v
_ -> return Nothing
store :: [(forall x. (R.Redis -> IO x) -> IO x)] -> B.ByteString -> B.ByteString -> IO ()
store fns k v = do
let fn = head fns
fn (\redis -> R.set redis k v)
return ()
withRedis :: [(forall x. (R.Redis -> IO x) -> IO x)] -> S.StoreT N.Ref (N.Node N.Ref) IO a -> IO a
withRedis redisfns op = do
step <- S.runStoreT op
case step of
S.Done a -> return a
S.Get k c -> do
let k' = refLocation k
v <- get redisfns k'
case v of
(Just v') ->
(withRedis redisfns . c . Bin.decode . L.fromChunks . (\i -> [i])) v'
_ ->
error $ show ("lookup error", k)
S.Store v c -> do
k <- randRef
out <- withRedis redisfns $ c k
store redisfns (refLocation k) ((B.concat . L.toChunks . Bin.encode) v)
return out
| DanielWaterworth/siege | src/Database/Siege/DoStore.hs | mit | 1,915 | 7 | 24 | 445 | 787 | 397 | 390 | 56 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import LispVal ( LispVal )
import Eval
( basicEnv,
getFileContents,
runASTinEnv,
safeExec,
textToEvalForm )
import qualified Data.Text as T
import Test.Tasty ( defaultMain, testGroup, TestName, TestTree )
import Test.Tasty.Golden ( goldenVsString )
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Functor ((<&>))
main :: IO ()
main = defaultMain tests
tests :: TestTree
tests = testGroup "Golden Tests"
[ tastyGoldenRun "add" "test/add.scm" "test/ans/add.txt"
, tastyGoldenRun "if/then" "test/if_alt.scm" "test/ans/if_alt.txt"
, tastyGoldenRun "let" "test/let.scm" "test/ans/let.txt"
, tastyGoldenRun "lambda let" "test/test_let.scm" "test/ans/test_let.txt"
, tastyGoldenRun "eval bool" "test/eval_boolean.scm" "test/ans/eval_boolean.txt"
, tastyGoldenRun "eval bool ops" "test/eval_boolean_ops.scm" "test/ans/eval_boolean_ops.txt"
, tastyGoldenRun "eval lambda" "test/eval_lambda.scm" "test/ans/eval_lambda.txt"
, tastyGoldenRun "quote" "test/test_quote.scm" "test/ans/test_quote.txt"
, tastyGoldenRun "car" "test/test_car.scm" "test/ans/test_car.txt"
, tastyGoldenRun "cdr" "test/test_cdr.scm" "test/ans/test_cdr.txt"
, tastyGoldenRun "cadadr" "test/test_cadadr.scm" "test/ans/test_cadadr.txt"
, tastyGoldenRun "greater than" "test/test_gt.scm" "test/ans/test_gt.txt"
, tastyGoldenRun "lexical scope 1" "test/test_scope1.scm" "test/ans/test_scope1.txt"
, tastyGoldenRun "lexical scope 2" "test/test_scope2.scm" "test/ans/test_scope2.txt"
, tastyGoldenFail "issue #23" "test/test_scope3.scm" "test/ans/test_scope3.txt"
, tastyGoldenRun "issue #25" "test/test_scope4.scm" "test/ans/test_scope4.txt"
, tastyGoldenRun "Recursion 1" "test/test_fix.scm" "test/ans/test_fix.txt"
, tastyGoldenRun "Recursion 2" "test/test_fix2.scm" "test/ans/test_fix2.txt"
, tastyGoldenRun "Mutual Recursion 2" "test/test_mutual_rec.scm" "test/ans/test_mutual_rec.txt"
, tastyGoldenRun "fn args" "test/test_args.scm" "test/ans/test_args.txt"
, tastyGoldenRun "fold" "test/test_fold.scm" "test/ans/test_fold.txt"
]
tastyGoldenRun :: TestName -> T.Text -> FilePath -> TestTree
tastyGoldenRun testName testFile correct =
goldenVsString testName correct $
evalTextTest "lib/stdlib.scm" testFile <&> C.pack . show
tastyGoldenFail :: TestName -> T.Text -> FilePath -> TestTree
tastyGoldenFail testName testFile correct =
goldenVsString testName correct $
safeExec (evalTextTest "lib/stdlib.scm" testFile) <&>
either C.pack (C.pack . show)
evalTextTest :: T.Text -> T.Text -> IO LispVal --REPL
evalTextTest stdlib file= do
stdlib' <- getFileContents $ T.unpack stdlib
f <- getFileContents $ T.unpack file
runASTinEnv basicEnv $ textToEvalForm stdlib' f
| write-you-a-scheme-v2/scheme | test-hs/Golden/Main.hs | mit | 3,075 | 0 | 10 | 649 | 545 | 286 | 259 | -1 | -1 |
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Protolude.Bifunctor
( Bifunctor,
bimap,
first,
second,
)
where
import Control.Applicative (Const (Const))
import Data.Either (Either (Left, Right))
import Data.Function ((.), id)
class Bifunctor p where
{-# MINIMAL bimap | first, second #-}
bimap :: (a -> b) -> (c -> d) -> p a c -> p b d
bimap f g = first f . second g
first :: (a -> b) -> p a c -> p b c
first f = bimap f id
second :: (b -> c) -> p a b -> p a c
second = bimap id
instance Bifunctor (,) where
bimap f g ~(a, b) = (f a, g b)
instance Bifunctor ((,,) x1) where
bimap f g ~(x1, a, b) = (x1, f a, g b)
instance Bifunctor ((,,,) x1 x2) where
bimap f g ~(x1, x2, a, b) = (x1, x2, f a, g b)
instance Bifunctor ((,,,,) x1 x2 x3) where
bimap f g ~(x1, x2, x3, a, b) = (x1, x2, x3, f a, g b)
instance Bifunctor ((,,,,,) x1 x2 x3 x4) where
bimap f g ~(x1, x2, x3, x4, a, b) = (x1, x2, x3, x4, f a, g b)
instance Bifunctor ((,,,,,,) x1 x2 x3 x4 x5) where
bimap f g ~(x1, x2, x3, x4, x5, a, b) = (x1, x2, x3, x4, x5, f a, g b)
instance Bifunctor Either where
bimap f _ (Left a) = Left (f a)
bimap _ g (Right b) = Right (g b)
instance Bifunctor Const where
bimap f _ (Const a) = Const (f a)
| sdiehl/protolude | src/Protolude/Bifunctor.hs | mit | 1,271 | 0 | 10 | 329 | 724 | 400 | 324 | 35 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Ocram.Analysis.CallGraph
-- exports {{{1
(
BlockingFunctions, StartFunctions, CriticalFunctions, Footprint
, call_graph, from_test_graph, to_test_graph
, blocking_functions, start_functions, critical_functions
, is_blocking, is_start, is_critical
, call_chain, call_order, get_callees, get_callers, dependency_list, footprint
, get_all_callers, get_all_callees
, to_string
) where
-- imports {{{1
import Control.Arrow (first, second)
import Control.Monad (guard)
import Data.Generics (mkQ, everything)
import Data.Maybe (isJust, maybeToList)
import Data.Tuple (swap)
import Language.C.Data.Ident (Ident(Ident))
import Language.C.Data.Node (undefNode, NodeInfo)
import Language.C.Syntax.AST
import Ocram.Analysis.Types
import Ocram.Query (is_function_declaration, is_blocking_function, is_start_function, function_definition)
import Ocram.Symbols (symbol, Symbol)
import Ocram.Util (tmap, fromJust_s, lookup_s)
import Prelude hiding (pred)
import qualified Data.Graph.Inductive.Basic as G
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.Query.BFS as G
import qualified Data.List as List
import qualified Data.Map as Map
import qualified Data.Set as Set
-- types {{{1
type BlockingFunctions = [Symbol]
type StartFunctions = [Symbol]
type CriticalFunctions = [Symbol]
type NonCriticalFunctions = [Symbol]
type Footprint = [[Symbol]]
call_graph :: CTranslUnit -> CallGraph -- {{{1
call_graph ast =
let
labels = createLabels ast
nodes = createNodes labels
gi = createGraphIndex nodes
edges = createEdges ast gi nodes
gd = G.mkGraph nodes edges
gd' = updateLabels gd
in
CallGraph gd' gi
from_test_graph :: [(Symbol, Symbol)] -> CallGraph -- {{{1
from_test_graph edges =
let
(callers, callees) = unzip edges
nodes = createNodes $ map (\name -> Label name [Critical]) $ List.nub $ callers ++ callees
gi = createGraphIndex nodes
resolve = $lookup_s gi
edges' = map (\e -> ((resolve . fst) e, (resolve . snd) e, undefNode)) edges
gd = G.mkGraph nodes edges'
in
CallGraph gd gi
to_test_graph :: CallGraph -> [(Symbol, Symbol)] -- {{{1
to_test_graph (CallGraph gd _) =
map (tmap (gnode2symbol gd)) $ G.edges gd
to_string :: CallGraph -> String
to_string (CallGraph gd _) = show (
map snd (G.labNodes gd)
, map edge (G.labEdges gd)
)
where edge (from, to, _) = map ($fromJust_s . G.lab gd) [from, to]
blocking_functions :: CallGraph -> BlockingFunctions -- {{{1
blocking_functions = functionsWith (any attrBlocking)
start_functions :: CallGraph -> StartFunctions -- {{{1
start_functions = functionsWith (any attrStart)
critical_functions :: CallGraph -> CriticalFunctions -- {{{1
critical_functions = functionsWith (any attrCritical)
non_critical_functions :: CallGraph -> NonCriticalFunctions
non_critical_functions = functionsWith null
is_blocking :: CallGraph -> Symbol -> Bool -- {{{1
is_blocking = functionIs attrBlocking
is_start :: CallGraph -> Symbol -> Bool -- {{{1
is_start = functionIs attrStart
is_critical :: CallGraph -> Symbol -> Bool -- {{{1
-- XXX: in the thesis, critical functions do not include blocking functions.
-- In contrast, in this implementation they do. I might have to clean this up at some point.
is_critical = functionIs attrCritical
call_chain :: CallGraph -> Symbol -> Symbol -> Maybe [Symbol] -- {{{1
call_chain (CallGraph gd gi) start end = do
gstart <- Map.lookup start gi
gend <- Map.lookup end gi
return $ criticalSubset gd $ G.esp gstart gend gd
call_order :: CallGraph -> Symbol -> Maybe [Symbol] -- {{{1
call_order (CallGraph gd gi) start =
Map.lookup start gi >>= return . List.nub . criticalSubset gd . flip G.bfs gd
dependency_list :: CallGraph -> [Symbol] -- {{{1
dependency_list (CallGraph gd _) =
List.nub $ concatMap depList $ nodesByAttr gd attrStart
where
depList = List.reverse . criticalSubset gd . flip G.bfs gd
get_callees :: CallGraph -> Symbol -> [(Symbol, NodeInfo)] -- {{{1
get_callees (CallGraph gd gi) caller = do
gcaller <- maybeToList $ Map.lookup caller gi
(_, gcallee, ni) <- G.out gd gcaller
let label = $fromJust_s $ G.lab gd gcallee
guard $ (any attrCritical . lblAttr) label
return $ (lblName label, ni)
get_callers :: CallGraph -> Symbol -> [(Symbol, NodeInfo)] -- {{{1
get_callers (CallGraph gd gi) caller = do
gcaller <- maybeToList $ Map.lookup caller gi
(gcallee, _, ni) <- G.inn gd gcaller
let label = $fromJust_s $ G.lab gd gcallee
guard $ (any attrCritical . lblAttr) label
return $ (lblName label, ni)
get_all_callees :: CallGraph -> Symbol -> [(Symbol, NodeInfo)] -- {{{1
get_all_callees (CallGraph gd gi) caller = do
gcaller <- maybeToList $ Map.lookup caller gi
(_, gcallee, ni) <- G.out gd gcaller
return $ (gnode2symbol gd gcallee, ni)
get_all_callers :: CallGraph -> Symbol -> [(Symbol, NodeInfo)] -- {{{1
get_all_callers (CallGraph gd gi) caller = do
gcaller <- maybeToList $ Map.lookup caller gi
(gcallee, _, ni) <- G.inn gd gcaller
return $ (gnode2symbol gd gcallee, ni)
footprint :: CallGraph -> Footprint -- {{{1
footprint cg@(CallGraph gd gi) = map footprint' $ start_functions cg
where
footprint' sf = filter (is_blocking cg) $ $fromJust_s $ call_order cg sf
-- utils {{{1
gnode2symbol :: GraphData -> G.Node -> Symbol -- {{{2
gnode2symbol gd = lblName . $fromJust_s . G.lab gd
criticalSubset :: GraphData -> [G.Node] -> [Symbol]
criticalSubset gd =
map lblName . filter (any attrCritical . lblAttr) . map ($fromJust_s . G.lab gd)
createNodes :: [Label] -> [Node] -- {{{2
createNodes = zip [0..]
createLabels :: CTranslUnit -> [Label] -- {{{2
createLabels (CTranslUnit ds _) = foldr go [] ds
where
go (CDeclExt x) labels
| is_function_declaration x && is_blocking_function x =
Label (symbol x) [Blocking] : labels
| otherwise = labels
go (CFDefExt x) labels =
let
attr = [Start | is_start_function x]
label = Label (symbol x) attr
in
label : labels
go _ labels = labels
updateLabels :: GraphData -> GraphData -- {{{2
updateLabels gd = G.gmap update gd
where
update o@(ine, gnode, label, oute)
| Set.member gnode sg = (ine, gnode, label {lblAttr = Critical : lblAttr label}, oute)
| otherwise = o
sg = reachableSubGraph (G.grev gd) $ nodesByAttr gd attrBlocking
reachableSubGraph :: GraphData -> [G.Node] -> Set.Set G.Node -- {{{3
reachableSubGraph gd ns = Set.fromList $ G.bfsn ns gd
nodesByAttr :: GraphData -> (Attribute -> Bool) -> [G.Node] -- {{{3
nodesByAttr g attr = map fst $ filter (any attr . lblAttr . snd) $ G.labNodes g
createGraphIndex :: [Node] -> GraphIndex -- {{{2
createGraphIndex nodes = Map.fromList $ map (swap . second lblName) nodes
createEdges :: CTranslUnit -> GraphIndex -> [Node] -> [Edge] -- {{{2
createEdges ast gi nodes = foldl go [] nodes
where
go es (gcaller, Label caller _) =
case function_definition ast caller of
Nothing -> es
Just fd ->
let
calls = filter (isJust . fst) $ map (first (flip Map.lookup gi)) $ everything (++) (mkQ [] call) fd
edges = map (\(x, y) -> (gcaller, $fromJust_s x, y)) calls
in
es ++ edges
call (CCall (CVar (Ident callee _ _) _) _ ni) = [(callee, ni)]
call _ = []
functionsWith :: ([Attribute] -> Bool) -> CallGraph -> [Symbol] -- {{{2
functionsWith pred cg = map lblName $ filter (pred . lblAttr) $ map snd $ G.labNodes $ grData cg
attrBlocking :: Attribute -> Bool -- {{{2
attrBlocking = (==Blocking)
attrStart :: Attribute -> Bool -- {{{2
attrStart = (==Start)
attrCritical :: Attribute -> Bool -- {{{2
attrCritical = (==Critical)
functionIs :: (Attribute -> Bool) -> CallGraph -> Symbol -> Bool -- {{{2
functionIs pred (CallGraph gd gi) name =
case Map.lookup name gi of
Nothing -> False
Just gnode -> any pred . lblAttr . $fromJust_s $ G.lab gd gnode
| copton/ocram | ocram/src/Ocram/Analysis/CallGraph.hs | gpl-2.0 | 7,971 | 0 | 21 | 1,547 | 2,774 | 1,478 | 1,296 | 171 | 3 |
---------------------------------------------------------
--
-- Module : Sample
-- Copyright : Bartosz Wójcik (2011)
-- License : Private
--
-- Maintainer : bartek@sudety.it
-- Stability : Unstable
-- Portability : portable
--
-- Part of ELCA. Quick Check sample test cases.
---------------------------------------------------------
module Main
where
import ElcaUI
import Data.IORef
import Data.List
import Data.Time
import Control.Monad.Reader
import Test.QuickCheck
import ElcaQCTestL
main = putStrLn "Product \
\Capital \
\Balloon \
\Dur \
\De \
\Rate \
\2nd R \
\Fee% \
\Day\
\ Financing \
\Early Payment Details" >>
sample (arbitrary :: Gen TestL)
| bartoszw/elca | Sample.hs | gpl-2.0 | 912 | 14 | 7 | 349 | 128 | 81 | 47 | 11 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Telegram
import qualified Data.ByteString.Lazy.Char8 as L
import Control.Monad (mapM_)
import Data.List (isInfixOf)
import Data.Char (toLower)
--[ ("who.*fat", "I'm fat!")
--, ("harrison.*fat", "No you")
--, ("harrison is", "No you")
--, ("rock", "RRROOCCKKSS!") ]
main :: IO ()
main = do
loopForUpdates 0
| ayron/telegram-haskell-bot | Main.hs | gpl-2.0 | 373 | 0 | 7 | 71 | 70 | 43 | 27 | 9 | 1 |
---------------
-- xmonad.hs --
--- by DaeS ---
---------------
-- Import -------------------------------------------------
import XMonad -- XMonad
import XMonad.Hooks.DynamicLog -- Xmobar
import qualified XMonad.StackSet as W -- Keys
import qualified Data.Map as M -- Keys
import Data.Monoid
import Data.Ratio ((%))
import System.Exit -- Exit
import XMonad.Util.Themes
import XMonad.Layout.ResizableTile -- Rezise
import XMonad.Layout.Tabbed -- Tabs for Windows
import XMonad.Layout.Grid -- Grid
import XMonad.Layout.Renamed -- Rename Layouts
import XMonad.Layout.IM -- IM-Layout
import XMonad.Layout.NoBorders -- turn off borders for full layout
import XMonad.Layout.PerWorkspace -- Assign Layot per Workspace
import XMonad.Layout.SubLayouts -- Sub layouts
import XMonad.Layout.Simplest -- Simple Layout
import XMonad.Layout.WindowNavigation -- Windows navigaton -- not really needed
import XMonad.Hooks.UrgencyHook -- Urgent
import XMonad.Hooks.InsertPosition -- Focus windows
import XMonad.Hooks.ManageHelpers -- Helper functions
import XMonad.Hooks.ManageDocks -- App workspace
import XMonad.Hooks.SetWMName
import XMonad.Actions.GridSelect -- Grid
import XMonad.Actions.FindEmptyWorkspace
import XMonad.Actions.WindowBringer
-----------------------------------------------------------
-- Main -------------------------------------------------------
main = do
spawn "/usr/bin/feh --bg-max ~/mm/image/wp/arch-dark.png"
spawn "xsetroot -cursor_name left_ptr -bg gray"
spawn "llk"
-- spawn "compton -cfFb -i 0.8 -t 0.7 -r 5 -I 0.02 -D 10"
xmonad =<< statusBar myBar myPP toggleStrutsKey myConfig
---------------------------------------------------------------
-- Bar ---------
myBar = "xmobar"
---------------
-- Tab Theme
myTabConfig = defaultTheme { inactiveBorderColor = "#333344"
, activeBorderColor = "#556655" }
-- Custom Bar ---------------------------------------------------------
-- previeous colors
-- ppCurrent #6587a8
-- ppTitle #afafaf
myPP = xmobarPP { ppCurrent = xmobarColor "#6587a8" "" . wrap "›" "‹"
, ppUrgent = xmobarColor "#fab20c" "" . wrap "[" "]"
, ppTitle = shorten 60
, ppSep = xmobarColor "#6587a8" "" " » "
, ppLayout = xmobarColor "#a83030" ""
, ppVisible = xmobarColor "#6587b8" "" . wrap "-" "-"
}
-----------------------------------------------------------------------
-- Main Conf --------------------------------------------
-- previous colors
-- normalBorderColor #262728
-- focusedBorderColor #404040
myConfig = defaultConfig
{ terminal = "lilyterm"
, borderWidth = 2
-- , normalBorderColor = "#262728"
-- , normalBorderColor = "#161719"
, normalBorderColor = "#000000"
, focusedBorderColor = "#ca4418"
-- , focusedBorderColor = "#6587a8"
, modMask = mod1Mask
, keys = myKeys
, layoutHook = myLayout
, manageHook = myManage
, workspaces = myWorkspaces
-- , focusFollowsMouse = True
, mouseBindings = myMouseBindings
-- , handleEventHook = myEventHook -- myEventHook = mempty
-- , logHook = myLogHook -- myLogHook = return ()
-- , startupHook = myStartupHook
, startupHook = setWMName "LG3D"
}
---------------------------------------------------------
-- Workspaces ----------------------------------------------------------------------------------------
myWorkspaces = ["1:web", "2:term", "3:code", "4:hdd", "5:other", "6:work", "7:mail", "8:media", "9:im", "0:tmp"]
------------------------------------------------------------------------------------------------------
-- Layouts --------------------------------------------------------------------
myLayout = windowNavigation $ onWorkspace "9:im" (myIMGrid ||| myTab) $
myTall ||| myMTall ||| myFull ||| myTab ||| myGrid
where
rt = ResizableTall 1 (3/100) (55/100) []
myFull = renamed [Replace "full"] $ (noBorders Full)
myGrid = renamed [Replace "grid"] $ (smartBorders Grid)
myTab = renamed [Replace "tabbed"] $ (smartBorders $ (tabbed shrinkText (theme wfarrTheme)))
-- mySimpleTab = renamed [Replace "tabbed"] $ (tabbed shrinkText (theme wfarrTheme))
-- myIMGrid = renamed [Replace "im-grid"] $ (smartBorders $ (gridIM (1%7) (And (Resource "main") (ClassName "psi"))))
myIMGrid = renamed [Replace "im-grid"] $ (smartBorders $ (gridIM (1%7) (ClassName "Pidgin" `And` Role "buddy_list")))
myTall = renamed [Replace "tall"] $ (smartBorders $ (subLayout [0,1,2] (Simplest) $ rt))
myMTall = renamed [Replace "mirror"] $ (smartBorders $ (subLayout [0,1,2] (Simplest) $ Mirror rt))
-------------------------------------------------------------------------------
-- Manage --------------------------------------------------------------
myManage = composeAll [ isFullscreen --> doFullFloat
, className =? "Gimp-2.6" --> doFloat
, className =? "qiv" --> doFloat
, className =? "MPlayer" --> doFloat
, className =? "mupdf" --> doFloat
, className =? "surf" --> doShift "1:web"
, className =? "Firefox" --> doShift "1:web"
, className =? "Gimp-2.8" --> doShift "6:work"
, className =? "claws-mail" --> doShift "7:mail"
, className =? "pidgin" --> doShift "9:im"
, className =? "Mumble" --> doShift "9:im"
, className =? "psi" --> doShift "9:im"
]
-------------------------------------------------------------------------
-- Custom Tab----------------------------------------------
tabTheme = defaultTheme { decoHeight = 14
, activeColor = "#303030"
, activeBorderColor = "#404040"
, activeTextColor = "#050505"
, inactiveTextColor = "#454545"
, inactiveColor = "#252525"
, inactiveBorderColor = "#404040"
}
-----------------------------------------------------------
-- Grid -------------------------------------------
myGSConfig = defaultGSConfig { gs_cellwidth = 120 }
---------------------------------------------------
-- Keys ------------------------------------------------------------
toggleStrutsKey XConfig {XMonad.modMask = modMask} = (modMask, xK_z)
myKeys conf@(XConfig {XMonad.modMask = modm}) = M.fromList $
--------------------------------------------------------------------
-- Launch and Kill
--------------------------------------------------------------------------------------------------------------------------------------------------------
[ ((modm .|. shiftMask, xK_Return), spawn $ XMonad.terminal conf)
, ((modm .|. controlMask, xK_Return), spawn "lilyterm -e dchroot -d")
-- , ((modm .|. controlMask, xK_Return), spawn "urxvt -name LURxvt")
, ((0 , 0x1008ff33), spawn "xfe")
, ((0 , 0x1008ff18), spawn "xfe")
, ((0 , 0x1008ff32), spawn "urxvt -e ncmpcpp")
, ((0 , 0x1008ff81), spawn "urxvt -e ncmpcpp")
, ((0 , 0x1008ff19), spawn "claws-mail")
, ((0 , 0x1008ff2a), spawn "oblogout")
, ((0 , 0x1008ff2f), spawn "pm-suspend")
, ((modm, xK_BackSpace), spawn "dmenu_run -fn 'snap-7' -nb '#151515' -nf '#919191' -sb '#151515' -sf '#c98f0a'")
, ((modm .|. shiftMask, xK_adiaeresis ), kill)
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-- Print -----------------------------------------------------------------------------------
, ((0, 0xff61), spawn "scrot -e 'mv $f ~/tmp/scrot/ 2>/dev/null'")
-- , ((0, xK_Print ), spawn "scrot -e 'mv $f ~/tmp/scrot/ 2>/dev/null'")
--------------------------------------------------------------------------------------------
-- Vol ----------------------------------------------------------------
, ((0 , 0x1008ff13), spawn "amixer sset Master 5%+")
, ((0 , 0x1008ff11), spawn "amixer sset Master 5%-")
, ((0 , 0x1008ff12), spawn "amixer sset Master toggle")
, ((shiftMask, 0x1008ff13), spawn "mpc -h 192.168.178.35 -P passwd volume +5")
, ((shiftMask, 0x1008ff11), spawn "mpc -h 192.168.178.35 -P passwd volume -5")
, ((shiftMask, 0x1008ff12), spawn "mpc -h 192.168.178.35 -P passwd volume 0")
-----------------------------------------------------------------------
-- Mpd ----------------------------------------------------
-- TODO: find out media keys, configure with global mpc variable
, ((0 , 0x1008ff14), spawn "mpc -h 192.168.178.35 -P passwd toggle")
, ((0 , 0x1008ff15), spawn "mpc -h 192.168.178.35 -P passwd stop")
, ((0 , 0x1008ff16), spawn "mpc -h 192.168.178.35 -P passwd prev")
, ((0 , 0x1008ff17), spawn "mpc -h 192.168.178.35 -P passwd next")
, ((shiftMask, 0x1008ff14), spawn "mpc -P passwd toggle")
, ((shiftMask, 0x1008ff15), spawn "mpc -P passwd stop")
, ((shiftMask, 0x1008ff16), spawn "mpc -P passwd prev")
, ((shiftMask, 0x1008ff17), spawn "mpc -P passwd next")
-----------------------------------------------------------
-- Grid --------------------------------------------------------
, ((modm, xK_g ), goToSelected myGSConfig)
----------------------------------------------------------------
-- Layouts ----------------------------------------------------------------
, ((modm, xK_space ), sendMessage NextLayout)
, ((modm .|. shiftMask, xK_space ), setLayout $ XMonad.layoutHook conf)
---------------------------------------------------------------------------
-- Sub Layout ------------------------------------------------------------
, ((modm .|. controlMask, xK_Left), sendMessage $ pullGroup L)
, ((modm .|. controlMask, xK_Right), sendMessage $ pullGroup R)
, ((modm .|. controlMask, xK_Up), sendMessage $ pullGroup U)
, ((modm .|. controlMask, xK_Down), sendMessage $ pullGroup D)
--
, ((modm .|. controlMask, xK_m), withFocused (sendMessage . MergeAll))
, ((modm .|. controlMask, xK_u), withFocused (sendMessage . UnMerge))
--
, ((modm .|. controlMask, xK_period), onGroup W.focusUp')
, ((modm .|. controlMask, xK_comma), onGroup W.focusDown')
-------------------------------------------------------------------------
-- Resize viewed windows to the correct size ---
, ((modm, xK_j ), refresh)
------------------------------------------------
-- Move focus ---------------------------------------------------------
, ((modm, xK_Tab ), windows W.focusDown)
, ((modm .|. shiftMask, xK_Tab ), windows W.focusUp)
, ((modm, xK_n ), windows W.focusDown)
, ((modm, xK_r ), windows W.focusUp )
, ((modm, xK_m ), windows W.focusMaster)
, ((modm, xK_w ), withFocused $ windows . W.sink)
-----------------------------------------------------------------------
-- Swap focused ---------------------------------------------
, ((modm, xK_Return), windows W.swapMaster)
, ((modm .|. shiftMask, xK_Down ), windows W.swapDown )
, ((modm .|. shiftMask, xK_n ), windows W.swapDown )
, ((modm .|. shiftMask, xK_Up ), windows W.swapUp )
, ((modm .|. shiftMask, xK_r ), windows W.swapUp )
-------------------------------------------------------------
-- Resizing -------------------- --------------------------------
, ((modm, xK_Left ), sendMessage Shrink)
, ((modm, xK_s ), sendMessage Shrink)
, ((modm, xK_Right ), sendMessage Expand)
, ((modm, xK_t ), sendMessage Expand)
, ((modm, xK_Down ), sendMessage MirrorShrink)
, ((modm, xK_b ), sendMessage MirrorShrink)
, ((modm, xK_Up ), sendMessage MirrorExpand)
, ((modm, xK_h ), sendMessage MirrorExpand)
-----------------------------------------------------------------
-- Increment/Deincrement the number of windows in the master area ----
, ((modm , xK_comma ), sendMessage (IncMasterN 1))
, ((modm , xK_period), sendMessage (IncMasterN (-1)))
----------------------------------------------------------------------
-- Quit/Restart xmonad --------------------------------------------------------------
, ((modm .|. shiftMask, xK_x ), io (exitWith ExitSuccess))
, ((modm, xK_x ), spawn "xmonad --recompile; xmonad --restart")
]
-------------------------------------------------------------------------------------
-- Move client to workspace -----------------------------------
++
[((m .|. modm, k), windows $ f i)
| (i, k) <- zip (XMonad.workspaces conf) $ [xK_1 .. xK_9] ++ [xK_0]
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]]
++
[((m .|. modm, key), screenWorkspace sc >>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_v, xK_l, xK_c] [0..]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]]
---------------------------------------------------------------
------------------------------------------------------------------------
-- Mouse bindings: default actions bound to mouse events
--
myMouseBindings (XConfig {XMonad.modMask = modm}) = M.fromList $
-- mod-button1, Set the window to floating mode and move by dragging
[ ((modm, button1), (\w -> focus w >> mouseMoveWindow w
>> windows W.shiftMaster))
-- mod-button2, Raise the window to the top of the stack
, ((modm, button2), (\w -> focus w >> windows W.shiftMaster))
-- mod-button3, Set the window to floating mode and resize by dragging
, ((modm, button3), (\w -> focus w >> mouseResizeWindow w
>> windows W.shiftMaster))
-- you may also bind events to the mouse scroll wheel (button4 and button5)
]
| procrastonos/dotfiles | xmonad/xmonad.hs | gpl-2.0 | 14,873 | 53 | 15 | 3,699 | 2,808 | 1,673 | 1,135 | 159 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-- Copyright (c) 2012, Diego Souza
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of the <ORGANIZATION> nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module SSSFS.Filesystem.Types
( -- | Types
OID
, Timestamp
, Metadata
, Blocks
, INode(..)
, StorageUnit(..)
, IType(..)
, Block
, BlockSeek
, BlockSize
, BlockIx
, Seek
-- | INode functions
, mkINode
, ensureDirectory
, ensureFile
, isFile
, isDirectory
, putBlock
, truncateI
, address
-- | Metadata String Functions
, encode
, decode
, encodePair
, decodePair
, singleton
, fromList
, toList
-- | Unique IDs
, newid
, oidOne
, keyOne
-- | Date/Time Functions
, now
-- | StorageUnit Functions
, dFromOID
, iFromOID
, dFromINode
, iFromINode
, fromDirEnt
, iFromDirEnt
, keyToINode
, keyToDBlock
, fromStorageUnit
, isDirEnt
, value
, eulav
, eulavM
, inodeToUnit
, inodeToDirEntUnit
, unitToINode
) where
import Control.Exception
import Control.Applicative
import Data.UUID
import Data.UUID.V1
import Data.Maybe
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Text as T
import Data.Text.Encoding
import qualified Data.Serialize as S
import System.Posix.Clock
import SSSFS.Except
import SSSFS.Storage
type OID = B.ByteString
type Block = B.ByteString
type Timestamp = (Int,Int)
type Seek = Integer
type BlockSeek = Int
type BlockSize = Int
type BlockIx = Integer
type Blocks = (OID, Integer)
-- | Arbirtrary information held as a key-value pair
type Metadata = [(B.ByteString, B.ByteString)]
data IType = File
| Directory
deriving (Eq,Show)
-- | The information about an object in the filesystem. This mimics
-- the tradicional UNIX inode data structure.
data INode = INode { inode :: OID -- ^ Unique id of this inode
, itype :: IType -- ^ The type of this file (e.g. File, Directory)
, atime :: Timestamp -- ^ Access time
, ctime :: Timestamp -- ^ Creation time
, mtime :: Timestamp -- ^ Modification time
, meta :: Metadata -- ^ Arbitrary metadata information
, blksz :: BlockSize -- ^ Fixed size of each datablock
, size :: Seek -- ^ Size of this file in bytes
, blocks :: Blocks -- ^ The actual file contents
}
deriving (Eq,Show)
data StorageUnit = INodeUnit OID Metadata Metadata
| DataBlockUnit OID BlockIx B.ByteString
| DirEntUnit String OID
newid :: IO OID
newid = fmap (B8.pack . toString . fromJust) nextUUID
oidOne :: OID
oidOne = B8.pack "1"
keyOne :: Key
keyOne = iFromOID oidOne
now :: IO Timestamp
now = do { t <- getTime Realtime
; return (sec t, nsec t)
}
isFile :: INode -> Bool
isFile = (==File) . itype
isDirectory :: INode -> Bool
isDirectory = (==Directory) . itype
encode :: T.Text -> B.ByteString
encode = encodeUtf8
decode :: B.ByteString -> T.Text
decode = decodeUtf8
putBlock :: INode -> BlockIx -> Block -> INode
putBlock inum ix bytes
| ix+1 >= nblocks = inum { size = uSize
, blocks = (oblocks, ix+1)
}
| otherwise = inum
where (oblocks, nblocks) = blocks inum
uSize = (fromIntegral $ blksz inum) * ix + (fromIntegral $ B.length bytes)
address :: BlockSize -> Seek -> (BlockIx, BlockSeek)
address bsz offset = let (blk, inOffset) = offset `divMod` (fromIntegral bsz)
in (fromIntegral blk, fromIntegral inOffset)
truncateI :: INode -> Seek -> INode
truncateI inum offset = inum { blocks = (oblocks, blkIx)
, size = offset
}
where (oblocks, _) = blocks inum
(blkIx, _) = address (blksz inum) offset
encodePair :: (T.Text, T.Text) -> (B.ByteString, B.ByteString)
encodePair (a,b) = (encode a, encode b)
decodePair :: (B.ByteString, B.ByteString) -> (T.Text, T.Text)
decodePair (a,b) = (decode a, decode b)
singleton :: (T.Text, T.Text) -> Metadata
singleton v = [encodePair v]
fromList :: [(T.Text, T.Text)] -> Metadata
fromList = map encodePair
toList :: Metadata -> [(T.Text, T.Text)]
toList = map decodePair
fromOID :: OID -> Key
fromOID o = fromStr (B8.unpack o)
dFromOID :: OID -> BlockIx -> Key
dFromOID o ix = fromStr "d" ++ fromOID o ++ fromStr (show ix)
dFromINode :: INode -> BlockIx -> Key
dFromINode i = dFromOID (fst (blocks i))
iFromOID :: OID -> Key
iFromOID = (fromStr "i" ++) . fromOID
iFromINode :: INode -> Key
iFromINode = (fromStr "i" ++) . fromOID . inode
keyToINode :: Key -> Bool
keyToINode ["i",_] = True
keyToINode _ = False
keyToDBlock :: Key -> Bool
keyToDBlock ["d",_,_] = True
keyToDBlock _ = False
isDirEnt :: Key -> Bool
isDirEnt ["i",_,_] = True
isDirEnt _ = False
fromDirEnt :: OID -> String -> Key
fromDirEnt o n = iFromOID o ++ fromStr n
iFromDirEnt :: INode -> String -> Key
iFromDirEnt i n = fromDirEnt (inode i) n
fromStorageUnit :: StorageUnit -> Either Key (OID -> Key)
fromStorageUnit u = case u
of INodeUnit o _ _
-> Left $ iFromOID o
DataBlockUnit o ix _
-> Left $ dFromOID o ix
DirEntUnit n _
-> Right $ \o -> fromDirEnt o n
value :: (S.Serialize a) => a -> B.ByteString
value = S.encode
eulav :: (S.Serialize a) => B.ByteString -> Either String a
eulav = S.decode
eulavM :: (S.Serialize a, Monad m) => B.ByteString -> m a
eulavM raw = case (eulav raw)
of Left msg
-> throw (DataCorruptionExcept msg)
Right u
-> return u
mkINode :: Maybe OID -> IType -> BlockSize -> IO INode
mkINode moid ftype bsz = do { time <- now
; ioid <- fmap pure newid
; boid <- newid
; return $ INode { inode = fromJust (moid <|> ioid)
, itype = ftype
, atime = time
, ctime = time
, mtime = time
, meta = []
, size = 0
, blksz = bsz
, blocks = (boid, 0)
}
}
inodeToUnit :: INode -> StorageUnit
inodeToUnit i = let core = [ (encode "inode", inode i)
, (encode "itype", value (itype i))
, (encode "atime", value (atime i))
, (encode "ctime", value (ctime i))
, (encode "mtime", value (mtime i))
, (encode "blksz", value (blksz i))
, (encode "size", value (size i))
, (encode "blocks", value (blocks i))
]
user = meta i
in INodeUnit (inode i) core user
inodeToDirEntUnit :: String -> INode -> StorageUnit
inodeToDirEntUnit n i = DirEntUnit n (inode i)
unitToINode :: StorageUnit -> Maybe INode
unitToINode (INodeUnit _ c u) = INode <$> (lookup "inode" core)
<*> (lookup "itype" core >>= eulavM)
<*> (lookup "atime" core >>= eulavM)
<*> (lookup "ctime" core >>= eulavM)
<*> (lookup "mtime" core >>= eulavM)
<*> (Just u)
<*> (lookup "blksz" core >>= eulavM)
<*> (lookup "size" core >>= eulavM)
<*> (lookup "blocks" core >>= eulavM)
where core = map (\(k,v) -> (decode k, v)) c
unitToINode _ = Nothing
ensureDirectory :: FilePath -> INode -> INode
ensureDirectory path inum
| isDirectory inum = inum
| otherwise = throw $ NotADir path
ensureFile :: FilePath -> INode -> INode
ensureFile path inum
| isFile inum = inum
| otherwise = throw $ IsDir path
instance S.Serialize IType where
put File = S.putWord8 0
put Directory = S.putWord8 1
get = do { opcode <- S.getWord8
; case opcode
of 0 -> return File
1 -> return Directory
_ -> fail "unknow opcode"
}
instance S.Serialize StorageUnit where
put (INodeUnit o c u) =
do { S.putWord8 0
; S.put o
; S.put c
; S.put u
}
put (DataBlockUnit o ix raw) =
do { S.putWord8 1
; S.put o
; S.put ix
; S.put raw
}
put (DirEntUnit name oid) =
do { S.putWord8 2
; S.put name
; S.put oid
}
get =
do { opcode <- S.getWord8
; case opcode
of 0 -> liftA3 INodeUnit S.get S.get S.get
1 -> liftA3 DataBlockUnit S.get S.get S.get
2 -> liftA2 DirEntUnit S.get S.get
_ -> fail "unknown opcode"
}
| dgvncsz0f/sssfs | src/SSSFS/Filesystem/Types.hs | gpl-3.0 | 11,257 | 0 | 15 | 4,162 | 2,774 | 1,518 | 1,256 | 247 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Freenet.Chk (
-- * Working with CHKs
ChkRequest(..), ChkBlock(..), mkChkBlock, decompressChk,
encryptChk, chkBlockUri, chkDataSize,
decryptChk,
-- * CHK Headers
ChkHeader, mkChkHeader, unChkHeader, chkHeaderHashId,
chkHeaderHash, chkHeaderCipherLen
) where
import Control.Applicative ( (<$>), (<*>) )
import Control.Monad ( mzero )
import Control.Monad.ST ( runST )
import Crypto.Cipher.AES
import Data.Aeson
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put ( putByteString, putWord16be, runPut )
import Data.Bits ( (.&.), shiftL )
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import Data.Digest.Pure.SHA
import qualified Data.Text as T
import Freenet.Base64
import Freenet.Compression
import Freenet.Pcfb
import qualified Freenet.Rijndael as RD
import Freenet.Types
import Freenet.URI
import Utils
------------------------------------------------------------------------------
-- CHK headers
------------------------------------------------------------------------------
-- |
-- The header required to verify a CHK data block, consisting of
-- 0 2 word16, hash id, always 1 for SHA256
-- 2 32 SHA256(payload)
-- 34 2 encrypted(word16) true payload size, before padding to 32kiB block size
-- ------
-- 36 bytes total
newtype ChkHeader = ChkHeader { unChkHeader :: BS.ByteString } deriving ( Eq )
-- |
-- The size of a CHK block's header, which is 36 bytes.
chkHeaderSize :: Int
chkHeaderSize = 36
instance Show ChkHeader where
show (ChkHeader bs) = T.unpack $ toBase64' bs
instance Binary ChkHeader where
put (ChkHeader h) = putByteString h
get = ChkHeader <$> getByteString chkHeaderSize
-- |
-- Creates right the header from a bytestring of 36 bytes.
mkChkHeader :: BS.ByteString -> Either T.Text ChkHeader
mkChkHeader bs
| BS.length bs == chkHeaderSize = Right $ ChkHeader bs
| otherwise = Left $ "CHK header length must be 36 bytes"
-- |
-- Returns the payload's SHA256 digest.
chkHeaderHash :: ChkHeader -> BS.ByteString
chkHeaderHash = BS.take 32 . BS.drop 2 . unChkHeader
-- |
-- The length of the CHK plaintext is stored encrypted
-- in it's header, and this function extracts it.
chkHeaderCipherLen :: ChkHeader -> BS.ByteString
chkHeaderCipherLen = BS.drop 34 . unChkHeader
-- |
-- The hash algoritm used to generate the digest at offset 2,
-- only a value of 1, indicating SHA256, is currently used.
chkHeaderHashId :: ChkHeader -> Word16
chkHeaderHashId = runGet get . bsFromStrict . unChkHeader
data ChkBlock = ChkBlock
{ chkBlockKey :: ! Key -- ^ location
, chkBlockCrypto :: ! Word8 -- ^ crypto algorithm, 2 -> AES_PCFB_256_SHA256, 3 -> AES_CTR_256_SHA256
, chkBlockHeader :: ! ChkHeader -- ^ headers
, chkBlockData :: ! BS.ByteString -- ^ data
}
instance Show ChkBlock where
show (ChkBlock k _ h d) = "ChkFound {k=" ++ show k ++ ", h=" ++ (show h) ++ ", len=" ++ (show $ BS.length d) ++ "}"
instance ToJSON ChkBlock where
toJSON (ChkBlock k c h d) = object
[ "location" .= k
, "algorithm" .= c
, "header" .= (toJSON . toBase64' . unChkHeader) h
, "data" .= (toJSON . toBase64') d
]
-- |
-- Size of the CHK payload, which is 32kiB.
chkDataSize :: Num a => a
chkDataSize = 32768
instance StorePersistable ChkBlock where
storeSize = const $ 32 + chkHeaderSize + chkDataSize + 1 -- first is key and last is crypto
storePut = \(ChkBlock k calg h d) -> put k >> put calg >> put h >> putByteString d
storeGet = do
(k, calg, h, d) <- (,,,) <$> get <*> get <*> get <*> getByteString chkDataSize
case mkChkBlock k h d calg of
Right df -> return df
Left e -> fail $ T.unpack e
-- | find the routing key for a DataFound
instance DataBlock ChkBlock where
dataBlockLocation (ChkBlock k c _ _) = freenetLocation k $ (1 `shiftL` 8) + (fromIntegral $ c .&. 0xff)
decryptDataBlock = decryptChk
instance Binary ChkBlock where
put = storePut
get = storeGet
chkBlockUri
:: ChkBlock
-> Key
-> URI
chkBlockUri blk ck = CHK (chkBlockKey blk) ck (mkChkExtra 3 (-1) False) []
-- |
-- creates a @ChkBlock@ from it's ingredients, verifying the hash and size of
-- the data block
mkChkBlock :: Key -> ChkHeader -> BS.ByteString -> Word8 -> Either T.Text ChkBlock
mkChkBlock k h d calg
| hash /= (bsFromStrict $ unKey k) = Left "hash mismatch"
| BS.length d /= chkDataSize = Left "CHK data must be 32kiB"
| otherwise = Right $ ChkBlock k calg h d
where
hash = bytestringDigest $ sha256 $ BSL.fromChunks [unChkHeader h, d]
-- |
-- given the secret crypto key (second part of URIs), data found can be
-- decrypted to get the source data back
decryptChk
:: ChkBlock -- ^ the encrypted data together with their headers
-> Key -- ^ the secret crypto key (second part of URIs)
-> Either T.Text (BS.ByteString, Int) -- ^ (decrypted payload, original length)
decryptChk (ChkBlock _ calg header ciphertext) key
| calg == 3 = decryptChkAesCtr header ciphertext key
| calg == 2 = decryptChkAesPcfb header ciphertext key
| otherwise = Left $ T.pack $ "unknown CHK crypto algorithm " ++ show calg
decryptChkAesPcfb :: ChkHeader -> BS.ByteString -> Key -> Either T.Text (BS.ByteString, Int)
decryptChkAesPcfb header ciphertext key
| predIv /= iv = Left "CHK hash mismatch"
| len > BS.length plaintext' = Left $ T.pack $ "invalid CHK length " ++ show len
| otherwise = Right (plaintext, len)
where
(plaintext', headers') = runST $ do
pcfb <- mkPCFB (RD.initKey 32 $ unKey key) $ BS.replicate 32 0 -- ^ the IV is all zero, but
h' <- pcfbDecipher pcfb $ BS.drop 2 $ unChkHeader header -- ^ this is said to serve as IV
p <- pcfbDecipher pcfb ciphertext
return (p, h')
plaintext = plaintext' -- BS.take len plaintext'
iv = BS.take 32 headers'
predIv = bsToStrict $ bytestringDigest $ sha256 (bsFromStrict $ unKey key)
len = fromIntegral $ runGet getWord16be $ bsFromStrict $ BS.drop 32 headers'
decryptChkAesCtr :: ChkHeader -> BS.ByteString -> Key -> Either T.Text (BS.ByteString, Int)
decryptChkAesCtr header ciphertext key
| len > BS.length plaintext' = Left "invalid length"
| mac /= bsFromStrict hash = Left "mac mismatch when verifying CHK payload"
| otherwise = Right (plaintext', len)
where
hash = chkHeaderHash header
cipherLen = chkHeaderCipherLen header
iv = BS.take 16 hash
aes = initAES $ unKey key
plaintext'' = decryptCTR aes iv $ BS.concat [ciphertext, cipherLen] -- TODO get rid of the concat
(plaintext', lenbytes) = BS.splitAt (BS.length ciphertext) plaintext''
len = fromIntegral $ runGet getWord16be $ bsFromStrict lenbytes
mac = bytestringDigest (hmacSha256 (bsFromStrict $ unKey key) (bsFromStrict plaintext''))
-- |
-- encrypts some data (which must be <= chkDataSize in length) using some encryption
-- key, and returns the resulting @ChkBlock@
encryptChk :: BS.ByteString -> Key -> ChkBlock
encryptChk d k
| payloadSize > chkDataSize = error "CHK payload > 32kiB"
| otherwise = ChkBlock loc 3 hdr ciphertext
where
hdr = ChkHeader $ bsToStrict $ runPut $ putWord16be 1 >> putByteString mac >> putByteString cipherLen
payloadSize = BS.length d
padding = BS.replicate (chkDataSize - payloadSize) 0
plaintext = BS.concat [d, padding, bsToStrict $ runPut $ putWord16be $ fromIntegral payloadSize]
(ciphertext, cipherLen) = BS.splitAt chkDataSize $ encryptCTR aes iv plaintext
aes = initAES $ unKey k
iv = BS.take 16 mac
mac = bsToStrict $ bytestringDigest $ hmacSha256 (bsFromStrict $ unKey k) (bsFromStrict plaintext)
loc = mkKey' $ bsToStrict $ bytestringDigest $ sha256 $ BSL.fromChunks [unChkHeader hdr, ciphertext]
-------------------------------------------------------------------------------------------------
-- Requesting CHKs
-------------------------------------------------------------------------------------------------
data ChkRequest = ChkRequest
{ chkReqLocation :: ! Key -- ^ the location of the data
, chkReqHashAlg :: ! Word8 -- ^ the hash algorithm to use
} deriving ( Show )
instance Binary ChkRequest where
put (ChkRequest l h) = put l >> put h
get = ChkRequest <$> get <*> get
instance FromJSON ChkRequest where
parseJSON (Object v) = ChkRequest
<$> v .: "location"
<*> v .: "algorithm"
parseJSON _ = mzero
instance DataRequest ChkRequest where
dataRequestLocation (ChkRequest l a) = freenetLocation l $ (1 `shiftL` 8) + (fromIntegral $ a .&. 0xff)
decompressChk
:: CompressionCodec -- ^ codec to use
-> BS.ByteString -- ^ compressed data
-> Int -- ^ true compressed data length
-> IO (Either T.Text (BS.ByteString, Int))
decompressChk codec inp inpl
| codec == None = return $ Right (inp, inpl)
| otherwise = do
dec <- decompress codec $ BSL.drop 4 $ bsFromStrict (BS.take inpl inp)
case dec of
Left e -> return $ Left $ "error decompressing data: " `T.append` e
Right dec' -> return $ Right (bsToStrict dec', fromIntegral $ BSL.length dec')
| waldheinz/ads | src/lib/Freenet/Chk.hs | gpl-3.0 | 9,519 | 12 | 16 | 2,244 | 2,468 | 1,296 | 1,172 | 171 | 2 |
{-# 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.AndroidPublisher.Edits.Tracks.List
-- 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)
--
-- Lists all the track configurations for this edit.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.edits.tracks.list@.
module Network.Google.Resource.AndroidPublisher.Edits.Tracks.List
(
-- * REST Resource
EditsTracksListResource
-- * Creating a Request
, editsTracksList
, EditsTracksList
-- * Request Lenses
, etlPackageName
, etlEditId
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.edits.tracks.list@ method which the
-- 'EditsTracksList' request conforms to.
type EditsTracksListResource =
"androidpublisher" :>
"v2" :>
"applications" :>
Capture "packageName" Text :>
"edits" :>
Capture "editId" Text :>
"tracks" :>
QueryParam "alt" AltJSON :>
Get '[JSON] TracksListResponse
-- | Lists all the track configurations for this edit.
--
-- /See:/ 'editsTracksList' smart constructor.
data EditsTracksList = EditsTracksList'
{ _etlPackageName :: !Text
, _etlEditId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EditsTracksList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'etlPackageName'
--
-- * 'etlEditId'
editsTracksList
:: Text -- ^ 'etlPackageName'
-> Text -- ^ 'etlEditId'
-> EditsTracksList
editsTracksList pEtlPackageName_ pEtlEditId_ =
EditsTracksList'
{ _etlPackageName = pEtlPackageName_
, _etlEditId = pEtlEditId_
}
-- | Unique identifier for the Android app that is being updated; for
-- example, \"com.spiffygame\".
etlPackageName :: Lens' EditsTracksList Text
etlPackageName
= lens _etlPackageName
(\ s a -> s{_etlPackageName = a})
-- | Unique identifier for this edit.
etlEditId :: Lens' EditsTracksList Text
etlEditId
= lens _etlEditId (\ s a -> s{_etlEditId = a})
instance GoogleRequest EditsTracksList where
type Rs EditsTracksList = TracksListResponse
type Scopes EditsTracksList =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient EditsTracksList'{..}
= go _etlPackageName _etlEditId (Just AltJSON)
androidPublisherService
where go
= buildClient
(Proxy :: Proxy EditsTracksListResource)
mempty
| rueshyna/gogol | gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/Tracks/List.hs | mpl-2.0 | 3,365 | 0 | 15 | 794 | 387 | 233 | 154 | 65 | 1 |
{-# LANGUAGE PatternSynonyms #-}
pattern x :> y = [x, y]
| lspitzner/brittany | data/Test243.hs | agpl-3.0 | 57 | 0 | 6 | 11 | 20 | 11 | 9 | 2 | 0 |
-- Copyright (C) 2016 Red Hat, Inc.
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library 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
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, see <http://www.gnu.org/licenses/>.
module BDCS.KeyValue(findKeyValue,
insertKeyValue)
where
import Control.Monad.IO.Class(MonadIO)
import qualified Data.Text as T
import Database.Esqueleto
import BDCS.DB
findKeyValue :: MonadIO m => T.Text -> T.Text -> Maybe T.Text -> SqlPersistT m (Maybe (Key KeyVal))
findKeyValue k v e = firstResult $
select $ from $ \kv -> do
where_ $ kv ^. KeyValKey_value ==. val k &&.
kv ^. KeyValVal_value ==. val v &&.
kv ^. KeyValExt_value ==. val e
limit 1
return $ kv ^. KeyValId
insertKeyValue :: MonadIO m => T.Text -> T.Text -> Maybe T.Text -> SqlPersistT m (Key KeyVal)
insertKeyValue k v e =
insert (KeyVal k v e)
| dashea/bdcs | importer/BDCS/KeyValue.hs | lgpl-2.1 | 1,414 | 0 | 17 | 317 | 271 | 144 | 127 | 17 | 1 |
module LSystem (
LSystem(..),
interpretLSystem,
parseLSystem,
parseAndEvalSymbols
) where
import Data.List
import Data.Maybe
import LSystem.Utils
import LSystem.DataTypes
import LSystem.Expressions
import LSystem.ShowReadUtils
----------------------------------------------------------------------------------------------------
iterateLSystem :: Int -> LSystem -> [SymbolDouble] -> [SymbolDouble]
iterateLSystem 0 _ axiom = axiom
iterateLSystem i lsys@(LSystem rrs) axiom =
let xs = rewriteSymbols rrs axiom
in iterateLSystem (i-1) lsys xs
rewriteSymbols :: [RewriteRule] -> [SymbolDouble] -> [SymbolDouble]
rewriteSymbols rrs ss = foldr rewrite [] ss where
rewrite s acc = (rewriteSymbol rrs s) ++ acc
-- | Rewrites given symbol with appropriate rewrite rule from given list.
rewriteSymbol :: [RewriteRule] -> SymbolDouble -> [SymbolDouble]
rewriteSymbol rrs s@(SymbolDouble _ params) =
case pickRr (findRrsForSymbol s rrs) of
Just (RewriteRule _ names _ replac) -> evalSymbolsVar (zip names params) replac
Nothing -> [s]
-- | Picks randomly one rewrite rule from given list. Randomness is based on probability of each
-- rewrite rule. Returns Nothing if input list is empty.
-- TODO: implement stochastism
pickRr :: [RewriteRule] -> Maybe RewriteRule
pickRr [] = Nothing
pickRr rrs = Just (head rrs) -- TODO
-- | Finds all rewrite rules from given list which can rewrite given symbol. Filtres by symbol and
-- condition.
findRrsForSymbol :: SymbolDouble -> [RewriteRule] -> [RewriteRule]
findRrsForSymbol (SymbolDouble symbol params) rrs =
let symbolMatching = filter (\ rr -> getRrPattern rr == symbol ) rrs in
filter checkRrCondition symbolMatching where
checkRrCondition :: RewriteRule -> Bool
checkRrCondition (RewriteRule _ names cond _) =
if isPeEmpty cond then
True
else
let vs = zip names params in
case evalPeVarAsBool vs cond of
Just b -> b
Nothing -> False
parseRewriteRule :: String -> Maybe RewriteRule
parseRewriteRule = parse readsRewriteRule
parseAndEvalSymbols :: [String] -> Maybe [SymbolDouble]
parseAndEvalSymbols [] = Just []
parseAndEvalSymbols ([]:ss) = parseAndEvalSymbols ss
parseAndEvalSymbols (s:ss) = do
symbols <- parse readsSymbolsExprs s
sDouble <- parseAndEvalSymbols ss
Just $ evalSymbols symbols ++ sDouble
----------------------------------------------------------------------------------------------------
-- | L-system is list of rewrite rules.
newtype LSystem = LSystem [RewriteRule]
deriving (Show)
-- | Interprets given string of symbols by given L-system.
interpretLSystem :: LSystem -> Int -> [String] -> [SymbolDouble]
interpretLSystem lsys iters lines =
case parseAndEvalSymbols lines of
Just a -> iterateLSystem iters lsys a
Nothing -> []
parseLSystem :: [String] -> Maybe LSystem
parseLSystem lines =
let maybeRrs = map parseRewriteRule $ filterNonEmpty lines in
if all isJust maybeRrs then
Just $ LSystem $ map fromJust maybeRrs
else
Nothing
| NightElfik/L-systems-in-Haskell | src/LSystem.hs | unlicense | 3,183 | 0 | 13 | 685 | 787 | 408 | 379 | 61 | 3 |
module ProjectM36.TransactionDiffs where
import ProjectM36.Base
import Data.List.NonEmpty
import Data.UUID as U
{-
root :: TransactionDiffs
root = single U.nil NoOperation
single :: TransactionId -> TransactionDiffExpr -> TransactionDiffs
single tid expr = (tid, expr) :| []
-}
| agentm/project-m36 | src/lib/ProjectM36/TransactionDiffs.hs | unlicense | 280 | 0 | 4 | 38 | 25 | 17 | 8 | 4 | 0 |
import Data.List
tr _ [] = []
tr tab (x:xs) = (tab!!x):(tr tab xs)
ans' x =
let u = sort $ nub x
r = case u of
[1,2,3] -> replicate 5 3
[1] -> replicate 5 3
[2] -> replicate 5 3
[3] -> replicate 5 3
[1,2] -> tr [0,1,2,0] x
[1,3] -> tr [0,2,0,1] x
[2,3] -> tr [0,0,1,2] x
otherwise -> replicate 5 0
in
r
ans [0] = []
ans x =
let f = ans' $ take 5 x
b = ans $ drop 5 x
in
f ++ b
main = do
c <- getContents
let i = map read $ lines c :: [Int]
o = ans i
mapM_ print o
| a143753/AOJ | 0205.hs | apache-2.0 | 637 | 0 | 13 | 293 | 363 | 188 | 175 | 25 | 8 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-unused-binds -fno-warn-unused-imports -fcontext-stack=590 #-}
module Openshift.OapivApi (
connectPostNamespacedBinaryBuildRequestOptionsInstantiatebinary
, connectPostNamespacedStatusWebhooks
, connectPostNamespacedStatusWebhooks_0
, createBuild
, createBuildConfig
, createDeploymentConfig
, createDeploymentConfigRollback
, createImageStream
, createImageStreamImport
, createImageStreamMapping
, createLocalResourceAccessReview
, createLocalSubjectAccessReview
, createNamespacedBuild
, createNamespacedBuildConfig
, createNamespacedBuildRequestClone
, createNamespacedBuildRequestInstantiate
, createNamespacedClusterNetwork
, createNamespacedClusterPolicy
, createNamespacedClusterPolicyBinding
, createNamespacedClusterRole
, createNamespacedClusterRoleBinding
, createNamespacedDeploymentConfig
, createNamespacedDeploymentConfigRollback
, createNamespacedGroup
, createNamespacedHostSubnet
, createNamespacedIdentity
, createNamespacedImage
, createNamespacedImageStream
, createNamespacedImageStreamImport
, createNamespacedImageStreamMapping
, createNamespacedLocalResourceAccessReview
, createNamespacedLocalSubjectAccessReview
, createNamespacedNetNamespace
, createNamespacedOAuthAccessToken
, createNamespacedOAuthAuthorizeToken
, createNamespacedOAuthClient
, createNamespacedOAuthClientAuthorization
, createNamespacedPolicy
, createNamespacedPolicyBinding
, createNamespacedProject
, createNamespacedProjectRequest
, createNamespacedResourceAccessReview
, createNamespacedRole
, createNamespacedRoleBinding
, createNamespacedRoute
, createNamespacedSubjectAccessReview
, createNamespacedTemplate
, createNamespacedTemplate_0
, createNamespacedUser
, createNamespacedUserIdentityMapping
, createPolicy
, createPolicyBinding
, createResourceAccessReview
, createRole
, createRoleBinding
, createRoute
, createSubjectAccessReview
, createTemplate
, createTemplate_0
, deleteNamespacedBuild
, deleteNamespacedBuildConfig
, deleteNamespacedClusterNetwork
, deleteNamespacedClusterPolicy
, deleteNamespacedClusterPolicyBinding
, deleteNamespacedClusterRole
, deleteNamespacedClusterRoleBinding
, deleteNamespacedDeploymentConfig
, deleteNamespacedGroup
, deleteNamespacedHostSubnet
, deleteNamespacedIdentity
, deleteNamespacedImage
, deleteNamespacedImageStream
, deleteNamespacedImageStreamTag
, deleteNamespacedNetNamespace
, deleteNamespacedOAuthAccessToken
, deleteNamespacedOAuthAuthorizeToken
, deleteNamespacedOAuthClient
, deleteNamespacedOAuthClientAuthorization
, deleteNamespacedPolicy
, deleteNamespacedPolicyBinding
, deleteNamespacedProject
, deleteNamespacedRole
, deleteNamespacedRoleBinding
, deleteNamespacedRoute
, deleteNamespacedTemplate
, deleteNamespacedUser
, deleteNamespacedUserIdentityMapping
, deletecollectionNamespacedBuild
, deletecollectionNamespacedBuildConfig
, deletecollectionNamespacedClusterNetwork
, deletecollectionNamespacedClusterPolicy
, deletecollectionNamespacedClusterPolicyBinding
, deletecollectionNamespacedDeploymentConfig
, deletecollectionNamespacedGroup
, deletecollectionNamespacedHostSubnet
, deletecollectionNamespacedIdentity
, deletecollectionNamespacedImage
, deletecollectionNamespacedImageStream
, deletecollectionNamespacedNetNamespace
, deletecollectionNamespacedOAuthClient
, deletecollectionNamespacedOAuthClientAuthorization
, deletecollectionNamespacedPolicy
, deletecollectionNamespacedPolicyBinding
, deletecollectionNamespacedRoute
, deletecollectionNamespacedTemplate
, deletecollectionNamespacedUser
, getAPIResources
, listBuild
, listBuildConfig
, listDeploymentConfig
, listImageStream
, listImageStreamTag
, listNamespacedBuild
, listNamespacedBuildConfig
, listNamespacedClusterNetwork
, listNamespacedClusterPolicy
, listNamespacedClusterPolicyBinding
, listNamespacedClusterRole
, listNamespacedClusterRoleBinding
, listNamespacedDeploymentConfig
, listNamespacedGroup
, listNamespacedHostSubnet
, listNamespacedIdentity
, listNamespacedImage
, listNamespacedImageStream
, listNamespacedImageStreamTag
, listNamespacedNetNamespace
, listNamespacedOAuthAccessToken
, listNamespacedOAuthAuthorizeToken
, listNamespacedOAuthClient
, listNamespacedOAuthClientAuthorization
, listNamespacedPolicy
, listNamespacedPolicyBinding
, listNamespacedProject
, listNamespacedProjectRequest
, listNamespacedRole
, listNamespacedRoleBinding
, listNamespacedRoute
, listNamespacedTemplate
, listNamespacedUser
, listPolicy
, listPolicyBinding
, listRole
, listRoleBinding
, listRoute
, listTemplate
, patchNamespacedBuild
, patchNamespacedBuildConfig
, patchNamespacedClusterNetwork
, patchNamespacedClusterPolicy
, patchNamespacedClusterPolicyBinding
, patchNamespacedClusterRole
, patchNamespacedClusterRoleBinding
, patchNamespacedDeploymentConfig
, patchNamespacedGroup
, patchNamespacedHostSubnet
, patchNamespacedIdentity
, patchNamespacedImage
, patchNamespacedImageStream
, patchNamespacedImageStreamTag
, patchNamespacedNetNamespace
, patchNamespacedOAuthClient
, patchNamespacedOAuthClientAuthorization
, patchNamespacedPolicy
, patchNamespacedPolicyBinding
, patchNamespacedProject
, patchNamespacedRole
, patchNamespacedRoleBinding
, patchNamespacedRoute
, patchNamespacedScaleScale
, patchNamespacedTemplate
, patchNamespacedUser
, patchNamespacedUserIdentityMapping
, readNamespacedBuild
, readNamespacedBuildConfig
, readNamespacedBuildLogLog
, readNamespacedClusterNetwork
, readNamespacedClusterPolicy
, readNamespacedClusterPolicyBinding
, readNamespacedClusterRole
, readNamespacedClusterRoleBinding
, readNamespacedDeploymentConfig
, readNamespacedDeploymentConfig_0
, readNamespacedDeploymentLogLog
, readNamespacedGroup
, readNamespacedHostSubnet
, readNamespacedIdentity
, readNamespacedImage
, readNamespacedImageStream
, readNamespacedImageStreamImage
, readNamespacedImageStreamTag
, readNamespacedNetNamespace
, readNamespacedOAuthAccessToken
, readNamespacedOAuthAuthorizeToken
, readNamespacedOAuthClient
, readNamespacedOAuthClientAuthorization
, readNamespacedPolicy
, readNamespacedPolicyBinding
, readNamespacedProject
, readNamespacedRole
, readNamespacedRoleBinding
, readNamespacedRoute
, readNamespacedScaleScale
, readNamespacedSecretListSecrets
, readNamespacedTemplate
, readNamespacedUser
, readNamespacedUserIdentityMapping
, replaceNamespacedBuild
, replaceNamespacedBuildConfig
, replaceNamespacedBuildDetails
, replaceNamespacedClusterNetwork
, replaceNamespacedClusterPolicy
, replaceNamespacedClusterPolicyBinding
, replaceNamespacedClusterRole
, replaceNamespacedClusterRoleBinding
, replaceNamespacedDeploymentConfig
, replaceNamespacedGroup
, replaceNamespacedHostSubnet
, replaceNamespacedIdentity
, replaceNamespacedImage
, replaceNamespacedImageStream
, replaceNamespacedImageStreamStatus
, replaceNamespacedImageStreamTag
, replaceNamespacedNetNamespace
, replaceNamespacedOAuthClient
, replaceNamespacedOAuthClientAuthorization
, replaceNamespacedPolicy
, replaceNamespacedPolicyBinding
, replaceNamespacedProject
, replaceNamespacedRole
, replaceNamespacedRoleBinding
, replaceNamespacedRoute
, replaceNamespacedRouteStatus
, replaceNamespacedScaleScale
, replaceNamespacedTemplate
, replaceNamespacedUser
, replaceNamespacedUserIdentityMapping
, watchBuildConfigList
, watchBuildList
, watchDeploymentConfigList
, watchImageStreamList
, watchNamespacedBuild
, watchNamespacedBuildConfig
, watchNamespacedBuildConfigList
, watchNamespacedBuildList
, watchNamespacedClusterNetwork
, watchNamespacedClusterNetworkList
, watchNamespacedClusterPolicy
, watchNamespacedClusterPolicyBinding
, watchNamespacedClusterPolicyBindingList
, watchNamespacedClusterPolicyList
, watchNamespacedDeploymentConfig
, watchNamespacedDeploymentConfigList
, watchNamespacedGroup
, watchNamespacedGroupList
, watchNamespacedHostSubnet
, watchNamespacedHostSubnetList
, watchNamespacedIdentity
, watchNamespacedIdentityList
, watchNamespacedImage
, watchNamespacedImageList
, watchNamespacedImageStream
, watchNamespacedImageStreamList
, watchNamespacedNetNamespace
, watchNamespacedNetNamespaceList
, watchNamespacedOAuthClient
, watchNamespacedOAuthClientAuthorization
, watchNamespacedOAuthClientAuthorizationList
, watchNamespacedOAuthClientList
, watchNamespacedPolicy
, watchNamespacedPolicyBinding
, watchNamespacedPolicyBindingList
, watchNamespacedPolicyList
, watchNamespacedRoute
, watchNamespacedRouteList
, watchNamespacedTemplate
, watchNamespacedTemplateList
, watchNamespacedUser
, watchNamespacedUserList
, watchPolicyBindingList
, watchPolicyList
, watchRouteList
, watchTemplateList
, proxyOapivApi
, OapivApi
) where
import GHC.Generics
import Data.Proxy
import qualified Servant.API as Servant
import Network.HTTP.Client (Manager)
import Servant.API ((:<|>)(..),(:>))
import Servant.Common.BaseUrl (BaseUrl(..))
import Servant.Client
import Control.Monad.Except (ExceptT)
import Openshift.Utils
import Data.Text
import Openshift.V1.Build
import Openshift.V1.BuildConfig
import Openshift.V1.DeploymentConfig
import Openshift.V1.DeploymentConfigRollback
import Openshift.V1.ImageStream
import Openshift.V1.ImageStreamImport
import Openshift.V1.ImageStreamMapping
import Openshift.V1.LocalResourceAccessReview
import Openshift.V1.LocalSubjectAccessReview
import Openshift.V1.BuildRequest
import Openshift.V1.ClusterNetwork
import Openshift.V1.ClusterPolicy
import Openshift.V1.ClusterPolicyBinding
import Openshift.V1.ClusterRole
import Openshift.V1.ClusterRoleBinding
import Openshift.V1.Group
import Openshift.V1.HostSubnet
import Openshift.V1.Identity
import Openshift.V1.Image
import Openshift.V1.NetNamespace
import Openshift.V1.OAuthAccessToken
import Openshift.V1.OAuthAuthorizeToken
import Openshift.V1.OAuthClient
import Openshift.V1.OAuthClientAuthorization
import Openshift.V1.Policy
import Openshift.V1.PolicyBinding
import Openshift.V1.Project
import Openshift.V1.ProjectRequest
import Openshift.V1.ResourceAccessReview
import Openshift.V1.Role
import Openshift.V1.RoleBinding
import Openshift.V1.Route
import Openshift.V1.SubjectAccessReview
import Openshift.V1.Template
import Openshift.V1.User
import Openshift.V1.UserIdentityMapping
import Openshift.Unversioned.Status
import Openshift.V1.DeleteOptions
import Openshift.V1.BuildList
import Openshift.V1.BuildConfigList
import Openshift.V1.DeploymentConfigList
import Openshift.V1.ImageStreamList
import Openshift.V1.ImageStreamTagList
import Openshift.V1.ClusterNetworkList
import Openshift.V1.ClusterPolicyList
import Openshift.V1.ClusterPolicyBindingList
import Openshift.V1.ClusterRoleList
import Openshift.V1.ClusterRoleBindingList
import Openshift.V1.GroupList
import Openshift.V1.HostSubnetList
import Openshift.V1.IdentityList
import Openshift.V1.ImageList
import Openshift.V1.NetNamespaceList
import Openshift.V1.OAuthAccessTokenList
import Openshift.V1.OAuthAuthorizeTokenList
import Openshift.V1.OAuthClientList
import Openshift.V1.OAuthClientAuthorizationList
import Openshift.V1.PolicyList
import Openshift.V1.PolicyBindingList
import Openshift.V1.ProjectList
import Openshift.V1.RoleList
import Openshift.V1.RoleBindingList
import Openshift.V1.RouteList
import Openshift.V1.TemplateList
import Openshift.V1.UserList
import Openshift.Unversioned.Patch
import Openshift.V1.ImageStreamTag
import Openshift.V1beta1.Scale
import Openshift.V1.BuildLog
import Openshift.V1.DeploymentLog
import Openshift.V1.ImageStreamImage
import Openshift.V1.SecretList
import Openshift.Json.WatchEvent
type OapivApi = "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> "instantiatebinary" :> Servant.QueryParam "asFile" Text :> Servant.QueryParam "revision.commit" Text :> Servant.QueryParam "revision.message" Text :> Servant.QueryParam "revision.authorName" Text :> Servant.QueryParam "revision.authorEmail" Text :> Servant.QueryParam "revision.committerName" Text :> Servant.QueryParam "revision.committerEmail" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Text -- connectPostNamespacedBinaryBuildRequestOptionsInstantiatebinary
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> "webhooks" :> Servant.QueryParam "path" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Text -- connectPostNamespacedStatusWebhooks
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> "webhooks" :> Servant.Capture "path" Text :> Servant.QueryParam "path" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Text -- connectPostNamespacedStatusWebhooks_0
:<|> "oapi" :> "v1" :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Build :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Build -- createBuild
:<|> "oapi" :> "v1" :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] BuildConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] BuildConfig -- createBuildConfig
:<|> "oapi" :> "v1" :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeploymentConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] DeploymentConfig -- createDeploymentConfig
:<|> "oapi" :> "v1" :> "deploymentconfigrollbacks" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeploymentConfigRollback :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] DeploymentConfigRollback -- createDeploymentConfigRollback
:<|> "oapi" :> "v1" :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStream :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStream -- createImageStream
:<|> "oapi" :> "v1" :> "imagestreamimports" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStreamImport :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStreamImport -- createImageStreamImport
:<|> "oapi" :> "v1" :> "imagestreammappings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStreamMapping :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStreamMapping -- createImageStreamMapping
:<|> "oapi" :> "v1" :> "localresourceaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] LocalResourceAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] LocalResourceAccessReview -- createLocalResourceAccessReview
:<|> "oapi" :> "v1" :> "localsubjectaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] LocalSubjectAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] LocalSubjectAccessReview -- createLocalSubjectAccessReview
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Build :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Build -- createNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] BuildConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] BuildConfig -- createNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> "clone" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] BuildRequest :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] BuildRequest -- createNamespacedBuildRequestClone
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> "instantiate" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] BuildRequest :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] BuildRequest -- createNamespacedBuildRequestInstantiate
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterNetwork :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ClusterNetwork -- createNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterPolicy :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ClusterPolicy -- createNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterPolicyBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ClusterPolicyBinding -- createNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterRole :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ClusterRole -- createNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterRoleBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ClusterRoleBinding -- createNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeploymentConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] DeploymentConfig -- createNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigrollbacks" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeploymentConfigRollback :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] DeploymentConfigRollback -- createNamespacedDeploymentConfigRollback
:<|> "oapi" :> "v1" :> "groups" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Group :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Group -- createNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] HostSubnet :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] HostSubnet -- createNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Identity :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Identity -- createNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Image :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Image -- createNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStream :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStream -- createNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamimports" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStreamImport :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStreamImport -- createNamespacedImageStreamImport
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreammappings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStreamMapping :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ImageStreamMapping -- createNamespacedImageStreamMapping
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "localresourceaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] LocalResourceAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] LocalResourceAccessReview -- createNamespacedLocalResourceAccessReview
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "localsubjectaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] LocalSubjectAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] LocalSubjectAccessReview -- createNamespacedLocalSubjectAccessReview
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] NetNamespace :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] NetNamespace -- createNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthaccesstokens" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthAccessToken :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] OAuthAccessToken -- createNamespacedOAuthAccessToken
:<|> "oapi" :> "v1" :> "oauthauthorizetokens" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthAuthorizeToken :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] OAuthAuthorizeToken -- createNamespacedOAuthAuthorizeToken
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthClient :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] OAuthClient -- createNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthClientAuthorization :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] OAuthClientAuthorization -- createNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Policy :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Policy -- createNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] PolicyBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] PolicyBinding -- createNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Project :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Project -- createNamespacedProject
:<|> "oapi" :> "v1" :> "projectrequests" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ProjectRequest :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ProjectRequest -- createNamespacedProjectRequest
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "resourceaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ResourceAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ResourceAccessReview -- createNamespacedResourceAccessReview
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Role :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Role -- createNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] RoleBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] RoleBinding -- createNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Route :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Route -- createNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "subjectaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] SubjectAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] SubjectAccessReview -- createNamespacedSubjectAccessReview
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "processedtemplates" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Template :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Template -- createNamespacedTemplate
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Template :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Template -- createNamespacedTemplate_0
:<|> "oapi" :> "v1" :> "users" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] User :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] User -- createNamespacedUser
:<|> "oapi" :> "v1" :> "useridentitymappings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] UserIdentityMapping :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] UserIdentityMapping -- createNamespacedUserIdentityMapping
:<|> "oapi" :> "v1" :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Policy :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Policy -- createPolicy
:<|> "oapi" :> "v1" :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] PolicyBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] PolicyBinding -- createPolicyBinding
:<|> "oapi" :> "v1" :> "resourceaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ResourceAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] ResourceAccessReview -- createResourceAccessReview
:<|> "oapi" :> "v1" :> "roles" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Role :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Role -- createRole
:<|> "oapi" :> "v1" :> "rolebindings" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] RoleBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] RoleBinding -- createRoleBinding
:<|> "oapi" :> "v1" :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Route :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Route -- createRoute
:<|> "oapi" :> "v1" :> "subjectaccessreviews" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] SubjectAccessReview :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] SubjectAccessReview -- createSubjectAccessReview
:<|> "oapi" :> "v1" :> "processedtemplates" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Template :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Template -- createTemplate
:<|> "oapi" :> "v1" :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Template :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.POST 200 '[Servant.JSON] Template -- createTemplate_0
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "groups" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamtags" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedImageStreamTag
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthaccesstokens" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedOAuthAccessToken
:<|> "oapi" :> "v1" :> "oauthauthorizetokens" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedOAuthAuthorizeToken
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedProject
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeleteOptions :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedUser
:<|> "oapi" :> "v1" :> "useridentitymappings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deleteNamespacedUserIdentityMapping
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "groups" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedImageStream
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.DELETE 200 '[Servant.JSON] Status -- deletecollectionNamespacedUser
:<|> "oapi" :> "v1" :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] () -- getAPIResources
:<|> "oapi" :> "v1" :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildList -- listBuild
:<|> "oapi" :> "v1" :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildConfigList -- listBuildConfig
:<|> "oapi" :> "v1" :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] DeploymentConfigList -- listDeploymentConfig
:<|> "oapi" :> "v1" :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamList -- listImageStream
:<|> "oapi" :> "v1" :> "imagestreamtags" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamTagList -- listImageStreamTag
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildList -- listNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildConfigList -- listNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterNetworkList -- listNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterPolicyList -- listNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterPolicyBindingList -- listNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterRoleList -- listNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterRoleBindingList -- listNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] DeploymentConfigList -- listNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "groups" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] GroupList -- listNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] HostSubnetList -- listNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] IdentityList -- listNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageList -- listNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamList -- listNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamtags" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamTagList -- listNamespacedImageStreamTag
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] NetNamespaceList -- listNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthaccesstokens" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthAccessTokenList -- listNamespacedOAuthAccessToken
:<|> "oapi" :> "v1" :> "oauthauthorizetokens" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthAuthorizeTokenList -- listNamespacedOAuthAuthorizeToken
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthClientList -- listNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthClientAuthorizationList -- listNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] PolicyList -- listNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] PolicyBindingList -- listNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ProjectList -- listNamespacedProject
:<|> "oapi" :> "v1" :> "projectrequests" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Status -- listNamespacedProjectRequest
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RoleList -- listNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RoleBindingList -- listNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RouteList -- listNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] TemplateList -- listNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] UserList -- listNamespacedUser
:<|> "oapi" :> "v1" :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] PolicyList -- listPolicy
:<|> "oapi" :> "v1" :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] PolicyBindingList -- listPolicyBinding
:<|> "oapi" :> "v1" :> "roles" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RoleList -- listRole
:<|> "oapi" :> "v1" :> "rolebindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RoleBindingList -- listRoleBinding
:<|> "oapi" :> "v1" :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RouteList -- listRoute
:<|> "oapi" :> "v1" :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] TemplateList -- listTemplate
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Build -- patchNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] BuildConfig -- patchNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ClusterNetwork -- patchNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ClusterPolicy -- patchNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ClusterPolicyBinding -- patchNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ClusterRole -- patchNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ClusterRoleBinding -- patchNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] DeploymentConfig -- patchNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "groups" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Group -- patchNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] HostSubnet -- patchNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Identity -- patchNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Image -- patchNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ImageStream -- patchNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamtags" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] ImageStreamTag -- patchNamespacedImageStreamTag
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] NetNamespace -- patchNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] OAuthClient -- patchNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] OAuthClientAuthorization -- patchNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Policy -- patchNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] PolicyBinding -- patchNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Project -- patchNamespacedProject
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Role -- patchNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] RoleBinding -- patchNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Route -- patchNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> "scale" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Scale -- patchNamespacedScaleScale
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] Template -- patchNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] User -- patchNamespacedUser
:<|> "oapi" :> "v1" :> "useridentitymappings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Patch :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PATCH 200 '[Servant.JSON] UserIdentityMapping -- patchNamespacedUserIdentityMapping
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Build -- readNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildConfig -- readNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> "log" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "container" Text :> Servant.QueryParam "follow" Bool :> Servant.QueryParam "previous" Bool :> Servant.QueryParam "sinceSeconds" Integer :> Servant.QueryParam "sinceTime" Text :> Servant.QueryParam "timestamps" Bool :> Servant.QueryParam "tailLines" Integer :> Servant.QueryParam "limitBytes" Integer :> Servant.QueryParam "nowait" Bool :> Servant.QueryParam "version" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] BuildLog -- readNamespacedBuildLogLog
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterNetwork -- readNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterPolicy -- readNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterPolicyBinding -- readNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterRole -- readNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ClusterRoleBinding -- readNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] DeploymentConfig -- readNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "generatedeploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] DeploymentConfig -- readNamespacedDeploymentConfig_0
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> "log" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "container" Text :> Servant.QueryParam "follow" Bool :> Servant.QueryParam "previous" Bool :> Servant.QueryParam "sinceSeconds" Integer :> Servant.QueryParam "sinceTime" Text :> Servant.QueryParam "timestamps" Bool :> Servant.QueryParam "tailLines" Integer :> Servant.QueryParam "limitBytes" Integer :> Servant.QueryParam "nowait" Bool :> Servant.QueryParam "version" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] DeploymentLog -- readNamespacedDeploymentLogLog
:<|> "oapi" :> "v1" :> "groups" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Group -- readNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] HostSubnet -- readNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Identity -- readNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Image -- readNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStream -- readNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamimages" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamImage -- readNamespacedImageStreamImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamtags" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] ImageStreamTag -- readNamespacedImageStreamTag
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] NetNamespace -- readNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthaccesstokens" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthAccessToken -- readNamespacedOAuthAccessToken
:<|> "oapi" :> "v1" :> "oauthauthorizetokens" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthAuthorizeToken -- readNamespacedOAuthAuthorizeToken
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthClient -- readNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] OAuthClientAuthorization -- readNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Policy -- readNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] PolicyBinding -- readNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Project -- readNamespacedProject
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Role -- readNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] RoleBinding -- readNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Route -- readNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> "scale" :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Scale -- readNamespacedScaleScale
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> "secrets" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] SecretList -- readNamespacedSecretListSecrets
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] Template -- readNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] User -- readNamespacedUser
:<|> "oapi" :> "v1" :> "useridentitymappings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] UserIdentityMapping -- readNamespacedUserIdentityMapping
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Build :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Build -- replaceNamespacedBuild
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] BuildConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] BuildConfig -- replaceNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> "details" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Build :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Build -- replaceNamespacedBuildDetails
:<|> "oapi" :> "v1" :> "clusternetworks" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterNetwork :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ClusterNetwork -- replaceNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "clusterpolicies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterPolicy :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ClusterPolicy -- replaceNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "clusterpolicybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterPolicyBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ClusterPolicyBinding -- replaceNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "clusterroles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterRole :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ClusterRole -- replaceNamespacedClusterRole
:<|> "oapi" :> "v1" :> "clusterrolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ClusterRoleBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ClusterRoleBinding -- replaceNamespacedClusterRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] DeploymentConfig :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] DeploymentConfig -- replaceNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "groups" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Group :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Group -- replaceNamespacedGroup
:<|> "oapi" :> "v1" :> "hostsubnets" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] HostSubnet :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] HostSubnet -- replaceNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "identities" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Identity :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Identity -- replaceNamespacedIdentity
:<|> "oapi" :> "v1" :> "images" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Image :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Image -- replaceNamespacedImage
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStream :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ImageStream -- replaceNamespacedImageStream
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> "status" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStream :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ImageStream -- replaceNamespacedImageStreamStatus
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreamtags" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] ImageStreamTag :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] ImageStreamTag -- replaceNamespacedImageStreamTag
:<|> "oapi" :> "v1" :> "netnamespaces" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] NetNamespace :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] NetNamespace -- replaceNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "oauthclients" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthClient :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] OAuthClient -- replaceNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "oauthclientauthorizations" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] OAuthClientAuthorization :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] OAuthClientAuthorization -- replaceNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Policy :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Policy -- replaceNamespacedPolicy
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] PolicyBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] PolicyBinding -- replaceNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "projects" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Project :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Project -- replaceNamespacedProject
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "roles" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Role :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Role -- replaceNamespacedRole
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "rolebindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] RoleBinding :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] RoleBinding -- replaceNamespacedRoleBinding
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Route :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Route -- replaceNamespacedRoute
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> "status" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Route :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Route -- replaceNamespacedRouteStatus
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> "scale" :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Scale :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Scale -- replaceNamespacedScaleScale
:<|> "oapi" :> "v1" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] Template :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] Template -- replaceNamespacedTemplate
:<|> "oapi" :> "v1" :> "users" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] User :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] User -- replaceNamespacedUser
:<|> "oapi" :> "v1" :> "useridentitymappings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.ReqBody '[Servant.JSON] UserIdentityMapping :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.PUT 200 '[Servant.JSON] UserIdentityMapping -- replaceNamespacedUserIdentityMapping
:<|> "oapi" :> "v1" :> "watch" :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchBuildConfigList
:<|> "oapi" :> "v1" :> "watch" :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchBuildList
:<|> "oapi" :> "v1" :> "watch" :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchDeploymentConfigList
:<|> "oapi" :> "v1" :> "watch" :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchImageStreamList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedBuild
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedBuildConfig
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "buildconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedBuildConfigList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "builds" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedBuildList
:<|> "oapi" :> "v1" :> "watch" :> "clusternetworks" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterNetwork
:<|> "oapi" :> "v1" :> "watch" :> "clusternetworks" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterNetworkList
:<|> "oapi" :> "v1" :> "watch" :> "clusterpolicies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterPolicy
:<|> "oapi" :> "v1" :> "watch" :> "clusterpolicybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterPolicyBinding
:<|> "oapi" :> "v1" :> "watch" :> "clusterpolicybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterPolicyBindingList
:<|> "oapi" :> "v1" :> "watch" :> "clusterpolicies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedClusterPolicyList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedDeploymentConfig
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "deploymentconfigs" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedDeploymentConfigList
:<|> "oapi" :> "v1" :> "watch" :> "groups" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedGroup
:<|> "oapi" :> "v1" :> "watch" :> "groups" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedGroupList
:<|> "oapi" :> "v1" :> "watch" :> "hostsubnets" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedHostSubnet
:<|> "oapi" :> "v1" :> "watch" :> "hostsubnets" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedHostSubnetList
:<|> "oapi" :> "v1" :> "watch" :> "identities" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedIdentity
:<|> "oapi" :> "v1" :> "watch" :> "identities" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedIdentityList
:<|> "oapi" :> "v1" :> "watch" :> "images" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedImage
:<|> "oapi" :> "v1" :> "watch" :> "images" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedImageList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedImageStream
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "imagestreams" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedImageStreamList
:<|> "oapi" :> "v1" :> "watch" :> "netnamespaces" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedNetNamespace
:<|> "oapi" :> "v1" :> "watch" :> "netnamespaces" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedNetNamespaceList
:<|> "oapi" :> "v1" :> "watch" :> "oauthclients" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedOAuthClient
:<|> "oapi" :> "v1" :> "watch" :> "oauthclientauthorizations" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedOAuthClientAuthorization
:<|> "oapi" :> "v1" :> "watch" :> "oauthclientauthorizations" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedOAuthClientAuthorizationList
:<|> "oapi" :> "v1" :> "watch" :> "oauthclients" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedOAuthClientList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedPolicy
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedPolicyBinding
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedPolicyBindingList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedPolicyList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedRoute
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedRouteList
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedTemplate
:<|> "oapi" :> "v1" :> "watch" :> "namespaces" :> Servant.Capture "namespace" Text :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedTemplateList
:<|> "oapi" :> "v1" :> "watch" :> "users" :> Servant.Capture "name" Text :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedUser
:<|> "oapi" :> "v1" :> "watch" :> "users" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchNamespacedUserList
:<|> "oapi" :> "v1" :> "watch" :> "policybindings" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchPolicyBindingList
:<|> "oapi" :> "v1" :> "watch" :> "policies" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchPolicyList
:<|> "oapi" :> "v1" :> "watch" :> "routes" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchRouteList
:<|> "oapi" :> "v1" :> "watch" :> "templates" :> Servant.QueryParam "pretty" Text :> Servant.QueryParam "labelSelector" Text :> Servant.QueryParam "fieldSelector" Text :> Servant.QueryParam "watch" Bool :> Servant.QueryParam "resourceVersion" Text :> Servant.QueryParam "timeoutSeconds" Integer :> Servant.Header "Authorization" Text :> Servant.Verb 'Servant.GET 200 '[Servant.JSON] WatchEvent -- watchTemplateList
-- | connect POST requests to instantiatebinary of BinaryBuildRequestOptions
connectPostNamespacedBinaryBuildRequestOptionsInstantiatebinary :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Text
-- | connect POST requests to webhooks of Status
connectPostNamespacedStatusWebhooks :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Text
-- | connect POST requests to webhooks of Status
connectPostNamespacedStatusWebhooks_0 :: Text -> Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Text
-- | create a Build
createBuild :: Maybe Text -> Build -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | create a BuildConfig
createBuildConfig :: Maybe Text -> BuildConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfig
-- | create a DeploymentConfig
createDeploymentConfig :: Maybe Text -> DeploymentConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | create a DeploymentConfigRollback
createDeploymentConfigRollback :: Maybe Text -> DeploymentConfigRollback -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfigRollback
-- | create a ImageStream
createImageStream :: Maybe Text -> ImageStream -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | create a ImageStreamImport
createImageStreamImport :: Maybe Text -> ImageStreamImport -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamImport
-- | create a ImageStreamMapping
createImageStreamMapping :: Maybe Text -> ImageStreamMapping -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamMapping
-- | create a LocalResourceAccessReview
createLocalResourceAccessReview :: Maybe Text -> LocalResourceAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO LocalResourceAccessReview
-- | create a LocalSubjectAccessReview
createLocalSubjectAccessReview :: Maybe Text -> LocalSubjectAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO LocalSubjectAccessReview
-- | create a Build
createNamespacedBuild :: Text -> Maybe Text -> Build -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | create a BuildConfig
createNamespacedBuildConfig :: Text -> Maybe Text -> BuildConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfig
-- | create clone of a BuildRequest
createNamespacedBuildRequestClone :: Text -> Text -> Maybe Text -> BuildRequest -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildRequest
-- | create instantiate of a BuildRequest
createNamespacedBuildRequestInstantiate :: Text -> Text -> Maybe Text -> BuildRequest -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildRequest
-- | create a ClusterNetwork
createNamespacedClusterNetwork :: Maybe Text -> ClusterNetwork -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterNetwork
-- | create a ClusterPolicy
createNamespacedClusterPolicy :: Maybe Text -> ClusterPolicy -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicy
-- | create a ClusterPolicyBinding
createNamespacedClusterPolicyBinding :: Maybe Text -> ClusterPolicyBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyBinding
-- | create a ClusterRole
createNamespacedClusterRole :: Maybe Text -> ClusterRole -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRole
-- | create a ClusterRoleBinding
createNamespacedClusterRoleBinding :: Maybe Text -> ClusterRoleBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleBinding
-- | create a DeploymentConfig
createNamespacedDeploymentConfig :: Text -> Maybe Text -> DeploymentConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | create a DeploymentConfigRollback
createNamespacedDeploymentConfigRollback :: Text -> Maybe Text -> DeploymentConfigRollback -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfigRollback
-- | create a Group
createNamespacedGroup :: Maybe Text -> Group -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Group
-- | create a HostSubnet
createNamespacedHostSubnet :: Maybe Text -> HostSubnet -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO HostSubnet
-- | create a Identity
createNamespacedIdentity :: Maybe Text -> Identity -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Identity
-- | create a Image
createNamespacedImage :: Maybe Text -> Image -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Image
-- | create a ImageStream
createNamespacedImageStream :: Text -> Maybe Text -> ImageStream -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | create a ImageStreamImport
createNamespacedImageStreamImport :: Text -> Maybe Text -> ImageStreamImport -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamImport
-- | create a ImageStreamMapping
createNamespacedImageStreamMapping :: Text -> Maybe Text -> ImageStreamMapping -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamMapping
-- | create a LocalResourceAccessReview
createNamespacedLocalResourceAccessReview :: Text -> Maybe Text -> LocalResourceAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO LocalResourceAccessReview
-- | create a LocalSubjectAccessReview
createNamespacedLocalSubjectAccessReview :: Text -> Maybe Text -> LocalSubjectAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO LocalSubjectAccessReview
-- | create a NetNamespace
createNamespacedNetNamespace :: Maybe Text -> NetNamespace -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO NetNamespace
-- | create a OAuthAccessToken
createNamespacedOAuthAccessToken :: Maybe Text -> OAuthAccessToken -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAccessToken
-- | create a OAuthAuthorizeToken
createNamespacedOAuthAuthorizeToken :: Maybe Text -> OAuthAuthorizeToken -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAuthorizeToken
-- | create a OAuthClient
createNamespacedOAuthClient :: Maybe Text -> OAuthClient -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClient
-- | create a OAuthClientAuthorization
createNamespacedOAuthClientAuthorization :: Maybe Text -> OAuthClientAuthorization -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientAuthorization
-- | create a Policy
createNamespacedPolicy :: Text -> Maybe Text -> Policy -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Policy
-- | create a PolicyBinding
createNamespacedPolicyBinding :: Text -> Maybe Text -> PolicyBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBinding
-- | create a Project
createNamespacedProject :: Maybe Text -> Project -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Project
-- | create a ProjectRequest
createNamespacedProjectRequest :: Maybe Text -> ProjectRequest -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ProjectRequest
-- | create a ResourceAccessReview
createNamespacedResourceAccessReview :: Text -> Maybe Text -> ResourceAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ResourceAccessReview
-- | create a Role
createNamespacedRole :: Text -> Maybe Text -> Role -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Role
-- | create a RoleBinding
createNamespacedRoleBinding :: Text -> Maybe Text -> RoleBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBinding
-- | create a Route
createNamespacedRoute :: Text -> Maybe Text -> Route -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | create a SubjectAccessReview
createNamespacedSubjectAccessReview :: Text -> Maybe Text -> SubjectAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO SubjectAccessReview
-- | create a Template
createNamespacedTemplate :: Text -> Maybe Text -> Template -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | create a Template
createNamespacedTemplate_0 :: Text -> Maybe Text -> Template -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | create a User
createNamespacedUser :: Maybe Text -> User -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO User
-- | create a UserIdentityMapping
createNamespacedUserIdentityMapping :: Maybe Text -> UserIdentityMapping -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO UserIdentityMapping
-- | create a Policy
createPolicy :: Maybe Text -> Policy -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Policy
-- | create a PolicyBinding
createPolicyBinding :: Maybe Text -> PolicyBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBinding
-- | create a ResourceAccessReview
createResourceAccessReview :: Maybe Text -> ResourceAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ResourceAccessReview
-- | create a Role
createRole :: Maybe Text -> Role -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Role
-- | create a RoleBinding
createRoleBinding :: Maybe Text -> RoleBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBinding
-- | create a Route
createRoute :: Maybe Text -> Route -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | create a SubjectAccessReview
createSubjectAccessReview :: Maybe Text -> SubjectAccessReview -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO SubjectAccessReview
-- | create a Template
createTemplate :: Maybe Text -> Template -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | create a Template
createTemplate_0 :: Maybe Text -> Template -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | delete a Build
deleteNamespacedBuild :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a BuildConfig
deleteNamespacedBuildConfig :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ClusterNetwork
deleteNamespacedClusterNetwork :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ClusterPolicy
deleteNamespacedClusterPolicy :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ClusterPolicyBinding
deleteNamespacedClusterPolicyBinding :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ClusterRole
deleteNamespacedClusterRole :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ClusterRoleBinding
deleteNamespacedClusterRoleBinding :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a DeploymentConfig
deleteNamespacedDeploymentConfig :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Group
deleteNamespacedGroup :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a HostSubnet
deleteNamespacedHostSubnet :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Identity
deleteNamespacedIdentity :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Image
deleteNamespacedImage :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ImageStream
deleteNamespacedImageStream :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a ImageStreamTag
deleteNamespacedImageStreamTag :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a NetNamespace
deleteNamespacedNetNamespace :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a OAuthAccessToken
deleteNamespacedOAuthAccessToken :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a OAuthAuthorizeToken
deleteNamespacedOAuthAuthorizeToken :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a OAuthClient
deleteNamespacedOAuthClient :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a OAuthClientAuthorization
deleteNamespacedOAuthClientAuthorization :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Policy
deleteNamespacedPolicy :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a PolicyBinding
deleteNamespacedPolicyBinding :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Project
deleteNamespacedProject :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Role
deleteNamespacedRole :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a RoleBinding
deleteNamespacedRoleBinding :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Route
deleteNamespacedRoute :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a Template
deleteNamespacedTemplate :: Text -> Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a User
deleteNamespacedUser :: Text -> Maybe Text -> DeleteOptions -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete a UserIdentityMapping
deleteNamespacedUserIdentityMapping :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Build
deletecollectionNamespacedBuild :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of BuildConfig
deletecollectionNamespacedBuildConfig :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of ClusterNetwork
deletecollectionNamespacedClusterNetwork :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of ClusterPolicy
deletecollectionNamespacedClusterPolicy :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of ClusterPolicyBinding
deletecollectionNamespacedClusterPolicyBinding :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of DeploymentConfig
deletecollectionNamespacedDeploymentConfig :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Group
deletecollectionNamespacedGroup :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of HostSubnet
deletecollectionNamespacedHostSubnet :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Identity
deletecollectionNamespacedIdentity :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Image
deletecollectionNamespacedImage :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of ImageStream
deletecollectionNamespacedImageStream :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of NetNamespace
deletecollectionNamespacedNetNamespace :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of OAuthClient
deletecollectionNamespacedOAuthClient :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of OAuthClientAuthorization
deletecollectionNamespacedOAuthClientAuthorization :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Policy
deletecollectionNamespacedPolicy :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of PolicyBinding
deletecollectionNamespacedPolicyBinding :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Route
deletecollectionNamespacedRoute :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of Template
deletecollectionNamespacedTemplate :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | delete collection of User
deletecollectionNamespacedUser :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | get available resources
getAPIResources :: Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ()
-- | list or watch objects of kind Build
listBuild :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildList
-- | list or watch objects of kind BuildConfig
listBuildConfig :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfigList
-- | list or watch objects of kind DeploymentConfig
listDeploymentConfig :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfigList
-- | list or watch objects of kind ImageStream
listImageStream :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamList
-- | list objects of kind ImageStreamTag
listImageStreamTag :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamTagList
-- | list or watch objects of kind Build
listNamespacedBuild :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildList
-- | list or watch objects of kind BuildConfig
listNamespacedBuildConfig :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfigList
-- | list or watch objects of kind ClusterNetwork
listNamespacedClusterNetwork :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterNetworkList
-- | list or watch objects of kind ClusterPolicy
listNamespacedClusterPolicy :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyList
-- | list or watch objects of kind ClusterPolicyBinding
listNamespacedClusterPolicyBinding :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyBindingList
-- | list objects of kind ClusterRole
listNamespacedClusterRole :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleList
-- | list objects of kind ClusterRoleBinding
listNamespacedClusterRoleBinding :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleBindingList
-- | list or watch objects of kind DeploymentConfig
listNamespacedDeploymentConfig :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfigList
-- | list or watch objects of kind Group
listNamespacedGroup :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO GroupList
-- | list or watch objects of kind HostSubnet
listNamespacedHostSubnet :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO HostSubnetList
-- | list or watch objects of kind Identity
listNamespacedIdentity :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO IdentityList
-- | list or watch objects of kind Image
listNamespacedImage :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageList
-- | list or watch objects of kind ImageStream
listNamespacedImageStream :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamList
-- | list objects of kind ImageStreamTag
listNamespacedImageStreamTag :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamTagList
-- | list or watch objects of kind NetNamespace
listNamespacedNetNamespace :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO NetNamespaceList
-- | list objects of kind OAuthAccessToken
listNamespacedOAuthAccessToken :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAccessTokenList
-- | list objects of kind OAuthAuthorizeToken
listNamespacedOAuthAuthorizeToken :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAuthorizeTokenList
-- | list or watch objects of kind OAuthClient
listNamespacedOAuthClient :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientList
-- | list or watch objects of kind OAuthClientAuthorization
listNamespacedOAuthClientAuthorization :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientAuthorizationList
-- | list or watch objects of kind Policy
listNamespacedPolicy :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyList
-- | list or watch objects of kind PolicyBinding
listNamespacedPolicyBinding :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBindingList
-- | list objects of kind Project
listNamespacedProject :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ProjectList
-- | list objects of kind ProjectRequest
listNamespacedProjectRequest :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Status
-- | list objects of kind Role
listNamespacedRole :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleList
-- | list objects of kind RoleBinding
listNamespacedRoleBinding :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBindingList
-- | list or watch objects of kind Route
listNamespacedRoute :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RouteList
-- | list or watch objects of kind Template
listNamespacedTemplate :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO TemplateList
-- | list or watch objects of kind User
listNamespacedUser :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO UserList
-- | list or watch objects of kind Policy
listPolicy :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyList
-- | list or watch objects of kind PolicyBinding
listPolicyBinding :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBindingList
-- | list objects of kind Role
listRole :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleList
-- | list objects of kind RoleBinding
listRoleBinding :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBindingList
-- | list or watch objects of kind Route
listRoute :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RouteList
-- | list or watch objects of kind Template
listTemplate :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO TemplateList
-- | partially update the specified Build
patchNamespacedBuild :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | partially update the specified BuildConfig
patchNamespacedBuildConfig :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfig
-- | partially update the specified ClusterNetwork
patchNamespacedClusterNetwork :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterNetwork
-- | partially update the specified ClusterPolicy
patchNamespacedClusterPolicy :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicy
-- | partially update the specified ClusterPolicyBinding
patchNamespacedClusterPolicyBinding :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyBinding
-- | partially update the specified ClusterRole
patchNamespacedClusterRole :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRole
-- | partially update the specified ClusterRoleBinding
patchNamespacedClusterRoleBinding :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleBinding
-- | partially update the specified DeploymentConfig
patchNamespacedDeploymentConfig :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | partially update the specified Group
patchNamespacedGroup :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Group
-- | partially update the specified HostSubnet
patchNamespacedHostSubnet :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO HostSubnet
-- | partially update the specified Identity
patchNamespacedIdentity :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Identity
-- | partially update the specified Image
patchNamespacedImage :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Image
-- | partially update the specified ImageStream
patchNamespacedImageStream :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | partially update the specified ImageStreamTag
patchNamespacedImageStreamTag :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamTag
-- | partially update the specified NetNamespace
patchNamespacedNetNamespace :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO NetNamespace
-- | partially update the specified OAuthClient
patchNamespacedOAuthClient :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClient
-- | partially update the specified OAuthClientAuthorization
patchNamespacedOAuthClientAuthorization :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientAuthorization
-- | partially update the specified Policy
patchNamespacedPolicy :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Policy
-- | partially update the specified PolicyBinding
patchNamespacedPolicyBinding :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBinding
-- | partially update the specified Project
patchNamespacedProject :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Project
-- | partially update the specified Role
patchNamespacedRole :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Role
-- | partially update the specified RoleBinding
patchNamespacedRoleBinding :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBinding
-- | partially update the specified Route
patchNamespacedRoute :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | partially update scale of the specified Scale
patchNamespacedScaleScale :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Scale
-- | partially update the specified Template
patchNamespacedTemplate :: Text -> Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | partially update the specified User
patchNamespacedUser :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO User
-- | partially update the specified UserIdentityMapping
patchNamespacedUserIdentityMapping :: Text -> Maybe Text -> Patch -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO UserIdentityMapping
-- | read the specified Build
readNamespacedBuild :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | read the specified BuildConfig
readNamespacedBuildConfig :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfig
-- | read log of the specified BuildLog
readNamespacedBuildLogLog :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Bool -> Maybe Integer -> Maybe Text -> Maybe Bool -> Maybe Integer -> Maybe Integer -> Maybe Bool -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildLog
-- | read the specified ClusterNetwork
readNamespacedClusterNetwork :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterNetwork
-- | read the specified ClusterPolicy
readNamespacedClusterPolicy :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicy
-- | read the specified ClusterPolicyBinding
readNamespacedClusterPolicyBinding :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyBinding
-- | read the specified ClusterRole
readNamespacedClusterRole :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRole
-- | read the specified ClusterRoleBinding
readNamespacedClusterRoleBinding :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleBinding
-- | read the specified DeploymentConfig
readNamespacedDeploymentConfig :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | read the specified DeploymentConfig
readNamespacedDeploymentConfig_0 :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | read log of the specified DeploymentLog
readNamespacedDeploymentLogLog :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Bool -> Maybe Integer -> Maybe Text -> Maybe Bool -> Maybe Integer -> Maybe Integer -> Maybe Bool -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentLog
-- | read the specified Group
readNamespacedGroup :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Group
-- | read the specified HostSubnet
readNamespacedHostSubnet :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO HostSubnet
-- | read the specified Identity
readNamespacedIdentity :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Identity
-- | read the specified Image
readNamespacedImage :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Image
-- | read the specified ImageStream
readNamespacedImageStream :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | read the specified ImageStreamImage
readNamespacedImageStreamImage :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamImage
-- | read the specified ImageStreamTag
readNamespacedImageStreamTag :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamTag
-- | read the specified NetNamespace
readNamespacedNetNamespace :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO NetNamespace
-- | read the specified OAuthAccessToken
readNamespacedOAuthAccessToken :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAccessToken
-- | read the specified OAuthAuthorizeToken
readNamespacedOAuthAuthorizeToken :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthAuthorizeToken
-- | read the specified OAuthClient
readNamespacedOAuthClient :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClient
-- | read the specified OAuthClientAuthorization
readNamespacedOAuthClientAuthorization :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientAuthorization
-- | read the specified Policy
readNamespacedPolicy :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Policy
-- | read the specified PolicyBinding
readNamespacedPolicyBinding :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBinding
-- | read the specified Project
readNamespacedProject :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Project
-- | read the specified Role
readNamespacedRole :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Role
-- | read the specified RoleBinding
readNamespacedRoleBinding :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBinding
-- | read the specified Route
readNamespacedRoute :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | read scale of the specified Scale
readNamespacedScaleScale :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Scale
-- | read secrets of the specified SecretList
readNamespacedSecretListSecrets :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO SecretList
-- | read the specified Template
readNamespacedTemplate :: Text -> Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | read the specified User
readNamespacedUser :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO User
-- | read the specified UserIdentityMapping
readNamespacedUserIdentityMapping :: Text -> Maybe Text -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO UserIdentityMapping
-- | replace the specified Build
replaceNamespacedBuild :: Text -> Text -> Maybe Text -> Build -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | replace the specified BuildConfig
replaceNamespacedBuildConfig :: Text -> Text -> Maybe Text -> BuildConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO BuildConfig
-- | replace details of the specified Build
replaceNamespacedBuildDetails :: Text -> Text -> Maybe Text -> Build -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Build
-- | replace the specified ClusterNetwork
replaceNamespacedClusterNetwork :: Text -> Maybe Text -> ClusterNetwork -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterNetwork
-- | replace the specified ClusterPolicy
replaceNamespacedClusterPolicy :: Text -> Maybe Text -> ClusterPolicy -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicy
-- | replace the specified ClusterPolicyBinding
replaceNamespacedClusterPolicyBinding :: Text -> Maybe Text -> ClusterPolicyBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterPolicyBinding
-- | replace the specified ClusterRole
replaceNamespacedClusterRole :: Text -> Maybe Text -> ClusterRole -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRole
-- | replace the specified ClusterRoleBinding
replaceNamespacedClusterRoleBinding :: Text -> Maybe Text -> ClusterRoleBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ClusterRoleBinding
-- | replace the specified DeploymentConfig
replaceNamespacedDeploymentConfig :: Text -> Text -> Maybe Text -> DeploymentConfig -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO DeploymentConfig
-- | replace the specified Group
replaceNamespacedGroup :: Text -> Maybe Text -> Group -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Group
-- | replace the specified HostSubnet
replaceNamespacedHostSubnet :: Text -> Maybe Text -> HostSubnet -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO HostSubnet
-- | replace the specified Identity
replaceNamespacedIdentity :: Text -> Maybe Text -> Identity -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Identity
-- | replace the specified Image
replaceNamespacedImage :: Text -> Maybe Text -> Image -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Image
-- | replace the specified ImageStream
replaceNamespacedImageStream :: Text -> Text -> Maybe Text -> ImageStream -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | replace status of the specified ImageStream
replaceNamespacedImageStreamStatus :: Text -> Text -> Maybe Text -> ImageStream -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStream
-- | replace the specified ImageStreamTag
replaceNamespacedImageStreamTag :: Text -> Text -> Maybe Text -> ImageStreamTag -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO ImageStreamTag
-- | replace the specified NetNamespace
replaceNamespacedNetNamespace :: Text -> Maybe Text -> NetNamespace -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO NetNamespace
-- | replace the specified OAuthClient
replaceNamespacedOAuthClient :: Text -> Maybe Text -> OAuthClient -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClient
-- | replace the specified OAuthClientAuthorization
replaceNamespacedOAuthClientAuthorization :: Text -> Maybe Text -> OAuthClientAuthorization -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO OAuthClientAuthorization
-- | replace the specified Policy
replaceNamespacedPolicy :: Text -> Text -> Maybe Text -> Policy -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Policy
-- | replace the specified PolicyBinding
replaceNamespacedPolicyBinding :: Text -> Text -> Maybe Text -> PolicyBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO PolicyBinding
-- | replace the specified Project
replaceNamespacedProject :: Text -> Maybe Text -> Project -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Project
-- | replace the specified Role
replaceNamespacedRole :: Text -> Text -> Maybe Text -> Role -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Role
-- | replace the specified RoleBinding
replaceNamespacedRoleBinding :: Text -> Text -> Maybe Text -> RoleBinding -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO RoleBinding
-- | replace the specified Route
replaceNamespacedRoute :: Text -> Text -> Maybe Text -> Route -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | replace status of the specified Route
replaceNamespacedRouteStatus :: Text -> Text -> Maybe Text -> Route -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Route
-- | replace scale of the specified Scale
replaceNamespacedScaleScale :: Text -> Text -> Maybe Text -> Scale -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Scale
-- | replace the specified Template
replaceNamespacedTemplate :: Text -> Text -> Maybe Text -> Template -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO Template
-- | replace the specified User
replaceNamespacedUser :: Text -> Maybe Text -> User -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO User
-- | replace the specified UserIdentityMapping
replaceNamespacedUserIdentityMapping :: Text -> Maybe Text -> UserIdentityMapping -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO UserIdentityMapping
-- | watch individual changes to a list of BuildConfig
watchBuildConfigList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Build
watchBuildList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of DeploymentConfig
watchDeploymentConfigList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of ImageStream
watchImageStreamList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Build
watchNamespacedBuild :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind BuildConfig
watchNamespacedBuildConfig :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of BuildConfig
watchNamespacedBuildConfigList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Build
watchNamespacedBuildList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind ClusterNetwork
watchNamespacedClusterNetwork :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of ClusterNetwork
watchNamespacedClusterNetworkList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind ClusterPolicy
watchNamespacedClusterPolicy :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind ClusterPolicyBinding
watchNamespacedClusterPolicyBinding :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of ClusterPolicyBinding
watchNamespacedClusterPolicyBindingList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of ClusterPolicy
watchNamespacedClusterPolicyList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind DeploymentConfig
watchNamespacedDeploymentConfig :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of DeploymentConfig
watchNamespacedDeploymentConfigList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Group
watchNamespacedGroup :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Group
watchNamespacedGroupList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind HostSubnet
watchNamespacedHostSubnet :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of HostSubnet
watchNamespacedHostSubnetList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Identity
watchNamespacedIdentity :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Identity
watchNamespacedIdentityList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Image
watchNamespacedImage :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Image
watchNamespacedImageList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind ImageStream
watchNamespacedImageStream :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of ImageStream
watchNamespacedImageStreamList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind NetNamespace
watchNamespacedNetNamespace :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of NetNamespace
watchNamespacedNetNamespaceList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind OAuthClient
watchNamespacedOAuthClient :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind OAuthClientAuthorization
watchNamespacedOAuthClientAuthorization :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of OAuthClientAuthorization
watchNamespacedOAuthClientAuthorizationList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of OAuthClient
watchNamespacedOAuthClientList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Policy
watchNamespacedPolicy :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind PolicyBinding
watchNamespacedPolicyBinding :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of PolicyBinding
watchNamespacedPolicyBindingList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Policy
watchNamespacedPolicyList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Route
watchNamespacedRoute :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Route
watchNamespacedRouteList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind Template
watchNamespacedTemplate :: Text -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Template
watchNamespacedTemplateList :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch changes to an object of kind User
watchNamespacedUser :: Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of User
watchNamespacedUserList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of PolicyBinding
watchPolicyBindingList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Policy
watchPolicyList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Route
watchRouteList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
-- | watch individual changes to a list of Template
watchTemplateList :: Maybe Text -> Maybe Text -> Maybe Text -> Maybe Bool -> Maybe Text -> Maybe Integer -> Maybe Text -> Manager -> BaseUrl -> ExceptT ServantError IO WatchEvent
proxyOapivApi :: Proxy OapivApi
proxyOapivApi = Proxy
connectPostNamespacedBinaryBuildRequestOptionsInstantiatebinary
:<|> connectPostNamespacedStatusWebhooks
:<|> connectPostNamespacedStatusWebhooks_0
:<|> createBuild
:<|> createBuildConfig
:<|> createDeploymentConfig
:<|> createDeploymentConfigRollback
:<|> createImageStream
:<|> createImageStreamImport
:<|> createImageStreamMapping
:<|> createLocalResourceAccessReview
:<|> createLocalSubjectAccessReview
:<|> createNamespacedBuild
:<|> createNamespacedBuildConfig
:<|> createNamespacedBuildRequestClone
:<|> createNamespacedBuildRequestInstantiate
:<|> createNamespacedClusterNetwork
:<|> createNamespacedClusterPolicy
:<|> createNamespacedClusterPolicyBinding
:<|> createNamespacedClusterRole
:<|> createNamespacedClusterRoleBinding
:<|> createNamespacedDeploymentConfig
:<|> createNamespacedDeploymentConfigRollback
:<|> createNamespacedGroup
:<|> createNamespacedHostSubnet
:<|> createNamespacedIdentity
:<|> createNamespacedImage
:<|> createNamespacedImageStream
:<|> createNamespacedImageStreamImport
:<|> createNamespacedImageStreamMapping
:<|> createNamespacedLocalResourceAccessReview
:<|> createNamespacedLocalSubjectAccessReview
:<|> createNamespacedNetNamespace
:<|> createNamespacedOAuthAccessToken
:<|> createNamespacedOAuthAuthorizeToken
:<|> createNamespacedOAuthClient
:<|> createNamespacedOAuthClientAuthorization
:<|> createNamespacedPolicy
:<|> createNamespacedPolicyBinding
:<|> createNamespacedProject
:<|> createNamespacedProjectRequest
:<|> createNamespacedResourceAccessReview
:<|> createNamespacedRole
:<|> createNamespacedRoleBinding
:<|> createNamespacedRoute
:<|> createNamespacedSubjectAccessReview
:<|> createNamespacedTemplate
:<|> createNamespacedTemplate_0
:<|> createNamespacedUser
:<|> createNamespacedUserIdentityMapping
:<|> createPolicy
:<|> createPolicyBinding
:<|> createResourceAccessReview
:<|> createRole
:<|> createRoleBinding
:<|> createRoute
:<|> createSubjectAccessReview
:<|> createTemplate
:<|> createTemplate_0
:<|> deleteNamespacedBuild
:<|> deleteNamespacedBuildConfig
:<|> deleteNamespacedClusterNetwork
:<|> deleteNamespacedClusterPolicy
:<|> deleteNamespacedClusterPolicyBinding
:<|> deleteNamespacedClusterRole
:<|> deleteNamespacedClusterRoleBinding
:<|> deleteNamespacedDeploymentConfig
:<|> deleteNamespacedGroup
:<|> deleteNamespacedHostSubnet
:<|> deleteNamespacedIdentity
:<|> deleteNamespacedImage
:<|> deleteNamespacedImageStream
:<|> deleteNamespacedImageStreamTag
:<|> deleteNamespacedNetNamespace
:<|> deleteNamespacedOAuthAccessToken
:<|> deleteNamespacedOAuthAuthorizeToken
:<|> deleteNamespacedOAuthClient
:<|> deleteNamespacedOAuthClientAuthorization
:<|> deleteNamespacedPolicy
:<|> deleteNamespacedPolicyBinding
:<|> deleteNamespacedProject
:<|> deleteNamespacedRole
:<|> deleteNamespacedRoleBinding
:<|> deleteNamespacedRoute
:<|> deleteNamespacedTemplate
:<|> deleteNamespacedUser
:<|> deleteNamespacedUserIdentityMapping
:<|> deletecollectionNamespacedBuild
:<|> deletecollectionNamespacedBuildConfig
:<|> deletecollectionNamespacedClusterNetwork
:<|> deletecollectionNamespacedClusterPolicy
:<|> deletecollectionNamespacedClusterPolicyBinding
:<|> deletecollectionNamespacedDeploymentConfig
:<|> deletecollectionNamespacedGroup
:<|> deletecollectionNamespacedHostSubnet
:<|> deletecollectionNamespacedIdentity
:<|> deletecollectionNamespacedImage
:<|> deletecollectionNamespacedImageStream
:<|> deletecollectionNamespacedNetNamespace
:<|> deletecollectionNamespacedOAuthClient
:<|> deletecollectionNamespacedOAuthClientAuthorization
:<|> deletecollectionNamespacedPolicy
:<|> deletecollectionNamespacedPolicyBinding
:<|> deletecollectionNamespacedRoute
:<|> deletecollectionNamespacedTemplate
:<|> deletecollectionNamespacedUser
:<|> getAPIResources
:<|> listBuild
:<|> listBuildConfig
:<|> listDeploymentConfig
:<|> listImageStream
:<|> listImageStreamTag
:<|> listNamespacedBuild
:<|> listNamespacedBuildConfig
:<|> listNamespacedClusterNetwork
:<|> listNamespacedClusterPolicy
:<|> listNamespacedClusterPolicyBinding
:<|> listNamespacedClusterRole
:<|> listNamespacedClusterRoleBinding
:<|> listNamespacedDeploymentConfig
:<|> listNamespacedGroup
:<|> listNamespacedHostSubnet
:<|> listNamespacedIdentity
:<|> listNamespacedImage
:<|> listNamespacedImageStream
:<|> listNamespacedImageStreamTag
:<|> listNamespacedNetNamespace
:<|> listNamespacedOAuthAccessToken
:<|> listNamespacedOAuthAuthorizeToken
:<|> listNamespacedOAuthClient
:<|> listNamespacedOAuthClientAuthorization
:<|> listNamespacedPolicy
:<|> listNamespacedPolicyBinding
:<|> listNamespacedProject
:<|> listNamespacedProjectRequest
:<|> listNamespacedRole
:<|> listNamespacedRoleBinding
:<|> listNamespacedRoute
:<|> listNamespacedTemplate
:<|> listNamespacedUser
:<|> listPolicy
:<|> listPolicyBinding
:<|> listRole
:<|> listRoleBinding
:<|> listRoute
:<|> listTemplate
:<|> patchNamespacedBuild
:<|> patchNamespacedBuildConfig
:<|> patchNamespacedClusterNetwork
:<|> patchNamespacedClusterPolicy
:<|> patchNamespacedClusterPolicyBinding
:<|> patchNamespacedClusterRole
:<|> patchNamespacedClusterRoleBinding
:<|> patchNamespacedDeploymentConfig
:<|> patchNamespacedGroup
:<|> patchNamespacedHostSubnet
:<|> patchNamespacedIdentity
:<|> patchNamespacedImage
:<|> patchNamespacedImageStream
:<|> patchNamespacedImageStreamTag
:<|> patchNamespacedNetNamespace
:<|> patchNamespacedOAuthClient
:<|> patchNamespacedOAuthClientAuthorization
:<|> patchNamespacedPolicy
:<|> patchNamespacedPolicyBinding
:<|> patchNamespacedProject
:<|> patchNamespacedRole
:<|> patchNamespacedRoleBinding
:<|> patchNamespacedRoute
:<|> patchNamespacedScaleScale
:<|> patchNamespacedTemplate
:<|> patchNamespacedUser
:<|> patchNamespacedUserIdentityMapping
:<|> readNamespacedBuild
:<|> readNamespacedBuildConfig
:<|> readNamespacedBuildLogLog
:<|> readNamespacedClusterNetwork
:<|> readNamespacedClusterPolicy
:<|> readNamespacedClusterPolicyBinding
:<|> readNamespacedClusterRole
:<|> readNamespacedClusterRoleBinding
:<|> readNamespacedDeploymentConfig
:<|> readNamespacedDeploymentConfig_0
:<|> readNamespacedDeploymentLogLog
:<|> readNamespacedGroup
:<|> readNamespacedHostSubnet
:<|> readNamespacedIdentity
:<|> readNamespacedImage
:<|> readNamespacedImageStream
:<|> readNamespacedImageStreamImage
:<|> readNamespacedImageStreamTag
:<|> readNamespacedNetNamespace
:<|> readNamespacedOAuthAccessToken
:<|> readNamespacedOAuthAuthorizeToken
:<|> readNamespacedOAuthClient
:<|> readNamespacedOAuthClientAuthorization
:<|> readNamespacedPolicy
:<|> readNamespacedPolicyBinding
:<|> readNamespacedProject
:<|> readNamespacedRole
:<|> readNamespacedRoleBinding
:<|> readNamespacedRoute
:<|> readNamespacedScaleScale
:<|> readNamespacedSecretListSecrets
:<|> readNamespacedTemplate
:<|> readNamespacedUser
:<|> readNamespacedUserIdentityMapping
:<|> replaceNamespacedBuild
:<|> replaceNamespacedBuildConfig
:<|> replaceNamespacedBuildDetails
:<|> replaceNamespacedClusterNetwork
:<|> replaceNamespacedClusterPolicy
:<|> replaceNamespacedClusterPolicyBinding
:<|> replaceNamespacedClusterRole
:<|> replaceNamespacedClusterRoleBinding
:<|> replaceNamespacedDeploymentConfig
:<|> replaceNamespacedGroup
:<|> replaceNamespacedHostSubnet
:<|> replaceNamespacedIdentity
:<|> replaceNamespacedImage
:<|> replaceNamespacedImageStream
:<|> replaceNamespacedImageStreamStatus
:<|> replaceNamespacedImageStreamTag
:<|> replaceNamespacedNetNamespace
:<|> replaceNamespacedOAuthClient
:<|> replaceNamespacedOAuthClientAuthorization
:<|> replaceNamespacedPolicy
:<|> replaceNamespacedPolicyBinding
:<|> replaceNamespacedProject
:<|> replaceNamespacedRole
:<|> replaceNamespacedRoleBinding
:<|> replaceNamespacedRoute
:<|> replaceNamespacedRouteStatus
:<|> replaceNamespacedScaleScale
:<|> replaceNamespacedTemplate
:<|> replaceNamespacedUser
:<|> replaceNamespacedUserIdentityMapping
:<|> watchBuildConfigList
:<|> watchBuildList
:<|> watchDeploymentConfigList
:<|> watchImageStreamList
:<|> watchNamespacedBuild
:<|> watchNamespacedBuildConfig
:<|> watchNamespacedBuildConfigList
:<|> watchNamespacedBuildList
:<|> watchNamespacedClusterNetwork
:<|> watchNamespacedClusterNetworkList
:<|> watchNamespacedClusterPolicy
:<|> watchNamespacedClusterPolicyBinding
:<|> watchNamespacedClusterPolicyBindingList
:<|> watchNamespacedClusterPolicyList
:<|> watchNamespacedDeploymentConfig
:<|> watchNamespacedDeploymentConfigList
:<|> watchNamespacedGroup
:<|> watchNamespacedGroupList
:<|> watchNamespacedHostSubnet
:<|> watchNamespacedHostSubnetList
:<|> watchNamespacedIdentity
:<|> watchNamespacedIdentityList
:<|> watchNamespacedImage
:<|> watchNamespacedImageList
:<|> watchNamespacedImageStream
:<|> watchNamespacedImageStreamList
:<|> watchNamespacedNetNamespace
:<|> watchNamespacedNetNamespaceList
:<|> watchNamespacedOAuthClient
:<|> watchNamespacedOAuthClientAuthorization
:<|> watchNamespacedOAuthClientAuthorizationList
:<|> watchNamespacedOAuthClientList
:<|> watchNamespacedPolicy
:<|> watchNamespacedPolicyBinding
:<|> watchNamespacedPolicyBindingList
:<|> watchNamespacedPolicyList
:<|> watchNamespacedRoute
:<|> watchNamespacedRouteList
:<|> watchNamespacedTemplate
:<|> watchNamespacedTemplateList
:<|> watchNamespacedUser
:<|> watchNamespacedUserList
:<|> watchPolicyBindingList
:<|> watchPolicyList
:<|> watchRouteList
:<|> watchTemplateList
= client proxyOapivApi
| minhdoboi/deprecated-openshift-haskell-api | openshift/lib/Openshift/OapivApi.hs | apache-2.0 | 180,190 | 0 | 2,822 | 24,318 | 47,202 | 22,875 | 24,327 | 1,228 | 1 |
-- Copyright 2017 Ondrej Sykora
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
-- | Contains definitions of data types for the state of the player.
module HBodies.Player.State
(
State(..)
, isCollision
, collisionSphere
) where
import qualified HBodies.Game.Params as Params
import qualified HBodies.Geometry as Geometry
import qualified HBodies.Time as Time
-- | Contains information about the current state of the player.
data State = State
{ -- | The current position of the player.
getPosition :: !Geometry.Position
-- | The current direction of the player.
, getDirection :: !Geometry.Direction
-- | The current health of the player. The health is a value between 0 and
-- 100. When the health reaches 0, the player is dead and the game ends.
, getHealth :: !Double
-- | The timestamp of the last frame when the player is invincible.
, getInvincibilityEnd :: !Time.Time
-- | The last time when the player fired from the weapon.
, getLastShot :: !Time.Time }
deriving (Read, Show)
collisionSphere :: State -> (Geometry.Position, Double)
collisionSphere player = (getPosition player, Params.player_radius)
-- | Returns true if the player collides with the given sphere.
isCollision :: (Geometry.Position, Double)
-> State
-> Bool
isCollision sphere player = Geometry.isCollision player_sphere sphere
where
player_sphere = (getPosition player, Params.player_radius)
| ondrasej/heavenly-bodies | src/HBodies/Player/State.hs | apache-2.0 | 1,996 | 0 | 10 | 410 | 224 | 141 | 83 | 32 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Codec.Sarsi.Scala where
import Codec.Sarsi (Level (..), Location (..), Message (..))
import Data.Attoparsec.Combinator (lookAhead)
import Data.Attoparsec.Text
import Data.Text (Text)
import qualified Data.Text as Text
import System.FilePath (makeRelative)
messageParser :: FilePath -> Parser Message
messageParser root = f <$> messageParserAbsolute
where
f (Message loc lvl txts) =
(Message (loc {filePath = Text.pack $ makeRelative root (Text.unpack $ filePath loc)}) lvl txts)
messageParserAbsolute :: Parser Message
messageParserAbsolute = do
lvl <- lineStart
fp <- takeWhile1 (\c -> c /= sepChar && c /= '\n') <* char sepChar
ln <- decimal <* char sepChar
col <- decimal <* char sepChar
t <- space *> (untilLineBreak <* "\n")
ts <- manyTill' (lineStart *> (untilLineBreak <* "\n")) (lookAhead $ column')
_ <- column' -- ignored as it was parsed above
_ <- end
return $ Message (Location fp col ln) lvl $ formatTxts t ts
where
level = choice [string "[error]" *> return Error, string "[warn]" *> return Warning]
lineStart = level <* space
sepChar = ':'
formatTxts t [] = [t]
formatTxts t ts = t : init ts
column' = level *> ((length <$> many1 space) <* "^\n")
untilLineBreak :: Parser Text
untilLineBreak = takeWhile1 $ \w -> w /= '\n'
end :: Parser ()
end = choice [const () <$> "\n", endOfInput, return ()]
| aloiscochard/sarsi | src/Codec/Sarsi/Scala.hs | apache-2.0 | 1,416 | 0 | 16 | 278 | 526 | 276 | 250 | 33 | 2 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies,FlexibleInstances, UndecidableInstances #-}
module Lib.Distance where
import Data.Map as M
import Data.List
------------------------------------------------ Distances --------------------------------
class Num b => Distance a b | a -> b where
dist :: a -> a -> b
dista cachedist x y = case M.lookup (x,y) cachedist of
Just l -> l
Nothing -> case M.lookup (y,x) cachedist of
Just l -> l
Nothing -> error ("Out of cachedist lookup for " ++ show x ++ "," ++ show y)
mkCacheDistance xs = M.fromList [((x,y),dist x y) | (x:xs') <- init . init . tails $ xs, y <- xs']
------------------------------------------------------------------------------------------
instance Distance Double Double where
dist x y = abs (x - y)
instance Distance Float Float where
dist x y = abs (x - y)
| paolino/hgen | Lib/Distance.hs | bsd-2-clause | 854 | 0 | 16 | 148 | 286 | 149 | 137 | 16 | 3 |
module HEP.Util.QQ.Verbatim where
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
import Language.Haskell.TH.Lib
verbatim :: QuasiQuoter
verbatim = QuasiQuoter {
quoteExp = litE . stringL
-- , quotePat = litP . stringP
}
| wavewave/HEPUtil | src/HEP/Util/QQ/Verbatim.hs | bsd-2-clause | 279 | 0 | 7 | 68 | 52 | 35 | 17 | 7 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-- |
-- Module : Criterion.Monad.Internal
-- Copyright : (c) 2009 Neil Brown
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- The environment in which most criterion code executes.
module Criterion.Monad.Internal
(
Criterion(..)
, Crit(..)
) where
import Control.Monad.Catch (MonadThrow, MonadCatch, MonadMask)
import qualified Control.Monad.Fail as Fail (MonadFail(..))
import Control.Monad.Reader (MonadReader(..), ReaderT)
import Control.Monad.Trans (MonadIO)
import Control.Monad.Trans.Instances ()
import Criterion.Types (Config)
import Data.IORef (IORef)
import Prelude ()
import Prelude.Compat
import System.Random.MWC (GenIO)
data Crit = Crit {
config :: !Config
, gen :: !(IORef (Maybe GenIO))
}
-- | The monad in which most criterion code executes.
newtype Criterion a = Criterion {
runCriterion :: ReaderT Crit IO a
} deriving ( Functor, Applicative, Monad, Fail.MonadFail, MonadIO
, MonadThrow, MonadCatch, MonadMask )
instance MonadReader Config Criterion where
ask = config `fmap` Criterion ask
local f = Criterion . local fconfig . runCriterion
where fconfig c = c { config = f (config c) }
| bos/criterion | Criterion/Monad/Internal.hs | bsd-2-clause | 1,377 | 0 | 13 | 269 | 315 | 192 | 123 | 31 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Exception (Exception, SomeException,
toException)
import Control.Monad (unless)
import Control.Monad.Catch (Handler (..), MonadThrow, catches,
throwM)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Except (ExceptT, runExceptT, throwE)
import Data.Aeson
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as B
import Data.Either (isLeft)
import Data.Foldable (maximum, traverse_)
import Data.HashMap.Lazy (HashMap, keys)
import Data.List (intercalate)
import Data.Maybe (fromJust, mapMaybe)
import qualified Data.Text as T (unpack)
import Network.HTTP
import qualified Network.Stream as S (Result)
import Network.URI (parseURI)
import Options.Applicative
import System.Directory
import System.Exit (ExitCode)
import System.IO (IOMode (ReadWriteMode), hClose,
hGetContents, openFile)
import System.Process (readProcess, runInteractiveCommand,
waitForProcess)
import Text.Megaparsec (parseMaybe)
import PSBT.Bower
import qualified PSBT.SemVer as S
data Command = Init String
| Build (Maybe String)
initParser :: Parser Command
initParser = Init <$> strArgument
(metavar "DIRECTORY")
initInfo :: ParserInfo Command
initInfo = info initParser
(progDesc "Initialize a PureScript project directory")
buildParser :: Parser Command
buildParser = Build <$> optional (strOption
(long "output"
<> short 'o'
<> metavar "OUTPUT"
<> help "Output a JavaScript file suitable for a browser"))
buildInfo :: ParserInfo Command
buildInfo = info buildParser
(progDesc "Download missing dependencies and build commonJS modules")
argsParser :: Parser Command
argsParser = subparser
(command "init" initInfo
<> command "build" buildInfo)
argsInfo :: ParserInfo Command
argsInfo = info argsParser
(progDesc "A package manager for the PureScript programming language")
parserPrefs :: ParserPrefs
parserPrefs = prefs showHelpOnError
runInit :: MonadIO m => String -> m ()
runInit name = liftIO $ do
createDirectory name
setCurrentDirectory name
createBowerFile $ minimalBower name
createDirectory "src"
createDirectory "test"
putStrLn $ "Project created in " ++ name
data PackageListing = PackageListing {
pkgName :: String
, url :: String
} deriving Show
instance FromJSON PackageListing where
parseJSON (Object v) = PackageListing <$>
v .: "name" <*>
v .: "url"
parseJSON _ = empty
registry :: String
registry = "http://bower.herokuapp.com/packages/search/"
data BuildError = ListingNotFound String
| MultipleListingsFound [PackageListing]
| ConnectionError
| JSONParseError
deriving Show
instance Exception BuildError where
getListing :: (MonadIO m, MonadThrow m) => String -> m PackageListing
getListing pkg = do
res <- liftIO $ fmap (fmap parseResponse) response
case res of
Left _ -> throwM ConnectionError
Right Nothing -> throwM JSONParseError
Right (Just []) -> throwM $ ListingNotFound pkg
Right (Just [ps]) -> return ps
Right (Just (p:ps)) -> if pkgName p == pkg
then return p
else throwM $ MultipleListingsFound (p:ps)
where
request = defaultGETRequest_ . fromJust . parseURI $ registry ++ pkg
response = simpleHTTP request :: IO (S.Result (Response ByteString))
parseResponse = decode . rspBody :: Response ByteString -> Maybe [PackageListing]
runSilently :: FilePath -> [String] -> IO ()
runSilently fp args = do
(stdin, stdout, stderr, ph) <- runInteractiveCommand (unwords $ fp : args)
hClose stdin
hClose stdout
waitForProcess ph
hGetContents stderr >>= putStrLn
hClose stderr
checkoutCorrectVersion :: MonadIO m => Dependency -> m ()
checkoutCorrectVersion dep = liftIO $ do
setCurrentDirectory $ "dependencies/" ++ T.unpack (packageName dep)
tags <- readProcess "git" ["tag"] ""
let versions = mapMaybe (parseMaybe S.version) . lines $ tags
let max = case version dep of
Nothing -> maximum versions
Just range -> foldr (maxInRange range) S.emptyVersion versions
let versionString = 'v' : S.displayVersion max
putStrLn $ "Checking out " ++ versionString ++ "..."
runSilently "git" ["checkout", versionString]
setCurrentDirectory "../../"
where
maxInRange range ver currentMax
| ver > currentMax && S.inRange ver range = ver
| otherwise = currentMax
download :: (MonadIO m, MonadThrow m) => Dependency -> m [Dependency]
download dep = do
let pkg = T.unpack . packageName $ dep
b <- liftIO $ do
createDirectoryIfMissing False "dependencies"
doesDirectoryExist $ "dependencies/" ++ pkg
unless b $ do
(PackageListing pkgName url) <- getListing pkg
let gitArgs = ["clone", url, "dependencies/" ++ pkgName]
liftIO $ do
putStrLn $ "Downloading " ++ pkgName ++ "..."
runSilently "git" gitArgs
checkoutCorrectVersion dep
downloadBowerDeps ("dependencies/" ++ pkg ++ "/bower.json")
downloadBowerDeps :: (MonadIO m, MonadThrow m) => FilePath -> m [Dependency]
downloadBowerDeps fp = do
bower <- readBowerFile fp
case dependencies bower of
Just deps -> do
traverse_ download deps
return deps
Nothing -> return []
pscArgs :: [String]
pscArgs = ["src/Main.purs"
, "dependencies/purescript-*/src/**/*.purs"
, "--ffi"
, "dependencies/purescript-*/src/**/*.js"
]
pscBundleArgs :: String -> [String]
pscBundleArgs str = ["output/*/index.js"
, "output/*/foreign.js"
, "--module", "Main"
, "--main", "Main"
, "-o", str
]
runBuild :: (MonadIO m, MonadThrow m) => Maybe String -> m ()
runBuild out = do
deps <- downloadBowerDeps "bower.json"
liftIO $ do
putStrLn ""
readProcess "psc" pscArgs "" >>= putStrLn
case out of
Just s -> readProcess "psc-bundle" (pscBundleArgs s) "" >>= putStrLn
Nothing -> return ()
putStrLn "Build complete."
runCommand :: (MonadIO m, MonadThrow m) => Command -> m ()
runCommand (Init dir) = runInit dir
runCommand (Build out) = runBuild out
buildErrorMessage :: BuildError -> String
buildErrorMessage (ListingNotFound str) = "Package " ++ str ++ " not found."
buildErrorMessage (MultipleListingsFound pkgs) = "Multiple packages found: \n" ++ unlines (map pkgName pkgs)
buildErrorMessage ConnectionError = "There was a problem with the connection"
buildErrorMessage JSONParseError = "Malformed JSON received"
buildErrorHandler :: MonadIO m => Handler m ()
buildErrorHandler = Handler $ liftIO . putStrLn . buildErrorMessage
main = do
command <- liftIO $ customExecParser parserPrefs argsInfo
catches (runCommand command) [bowerErrorHandler, buildErrorHandler]
| LightAndLight/psbt | app/Main.hs | bsd-3-clause | 7,699 | 11 | 19 | 2,229 | 2,039 | 1,027 | 1,012 | 176 | 6 |
import Test.QuickCheck
(
quickCheck
,verboseCheck
,shrink
,forAll
,listOf
)
import Test.QuickCheck.Gen
(
choose
,Gen (..)
)
import Test.QuickCheck.Property
(
Property (..)
)
import System.Random
(
Random (..)
)
import Data.List (sort)
sum' :: Num a => [a] -> a
sum' [] = 0
sum' (x:xs) = x + sum' xs
posIntList :: (System.Random.Random a, Num a) => Gen [a]
posIntList = listOf $ choose (1,1000000)
gen_sumPos :: Property
gen_sumPos = forAll posIntList prop_sumPos
prop_sumAsso :: [Int] -> Bool
prop_sumAsso xs = sum' xs + sum' xs == sum' (xs ++ xs)
prop_sumComm :: [Int] -> Bool
prop_sumComm xs = sum' xs == sum' (reverse xs)
prop_sumPos :: [Int] -> Bool
prop_sumPos xs = sum' xs >= 0
prop_idem :: [Int] -> Bool
prop_idem xs = sort xs == sort (sort xs)
| simone-trubian/blog-posts | QuickCheck/Quick.hs | bsd-3-clause | 800 | 0 | 8 | 179 | 336 | 183 | 153 | 33 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -Wall #-}
{-| This module contains the core machinery for the Annah language, which is a
medium-level language that desugars to Morte.
The main high-level features that Annah does not provide compared to Haskell
are:
* type classes
* type inference
You cannot type-check or normalize Annah expressions directly. Instead,
you `desugar` Annah expressions to Morte, and then type-check or normalize
the Morte expressions using `M.typeOf` and `M.normalize`.
Annah does everything through Morte for two reasons:
* to ensure the soundness of type-checking and normalization, and:
* to interoperate with other languages that compile to Morte.
The typical workflow is:
* You parse a `Text` source using `Annah.Parser.exprFromText`
* You `desugar` the Annah expression to Morte
* You resolve all imports using `M.load`
* You type-check the Morte expression using `M.typeOf`
* You `M.normalize` the Morte expression
-}
module Annah.Core (
-- * Syntax
M.Var(..)
, M.Const(..)
, Arg(..)
, Let(..)
, Data(..)
, Type(..)
, Bind(..)
, Expr(..)
-- * Desugaring
, desugar
, desugarFamily
, desugarNatural
, desugarDo
, desugarList
, desugarPath
, desugarLets
) where
import Control.Applicative (pure, empty)
import Data.String (IsString(..))
import Data.Text.Lazy (Text)
import qualified Morte.Core as M
import Prelude hiding (pi)
{-| Argument for function or constructor definitions
> Arg "_" _A ~ _A
> Arg x _A ~ (x : _A)
-}
data Arg = Arg
{ argName :: Text
, argType :: Expr
} deriving (Show)
{-|
> Let f [a1, a2] _A rhs ~ let f a1 a2 : _A = rhs
-}
data Let = Let
{ letName :: Text
, letArgs :: [Arg]
, letType :: Expr
, letRhs :: Expr
} deriving (Show)
{-|
> Type t [d1, d2] f ~ type t d1 d2 fold f
-}
data Type = Type
{ typeName :: Text
, typeDatas :: [Data]
, typeFold :: Text
} deriving (Show)
{-|
> Data c [a1, a2] ~ data c a1 a2
-}
data Data = Data
{ dataName :: Text
, dataArgs :: [Arg]
} deriving (Show)
{-|
> Bind arg e ~ arg <- e;
-}
data Bind = Bind
{ bindLhs :: Arg
, bindRhs :: Expr
} deriving (Show)
-- | Syntax tree for expressions
data Expr
-- | > Const c ~ c
= Const M.Const
-- | > Var (V x 0) ~ x
-- > Var (V x n) ~ x@n
| Var M.Var
-- | > Lam x _A b ~ λ(x : _A) → b
| Lam Text Expr Expr
-- | > Pi x _A _B ~ ∀(x : _A) → _B
| Pi Text Expr Expr
-- | > App f a ~ f a
| App Expr Expr
-- | > Annot a _A ~ a : _A
| Annot Expr Expr
-- | > Lets [l1, l2] e ~ l1 l2 in e
| Lets [Let] Expr
-- | > Family f e ~ f in e
| Family [Type] Expr
-- | > Natural n ~ n
| Natural Integer
-- | > List t [x, y, z] ~ [nil t,x,y,z]
| List Expr [Expr]
-- | > Path c [(o1, m1), (o2, m2)] o3 ~ [id c {o1} m1 {o2} m2 {o3}]
| Path Expr [(Expr, Expr)] Expr
-- | > Do m [b1, b2] b3 ~ do m { b1 b2 b3 }
| Do Expr [Bind] Bind
| Embed M.Path
deriving (Show)
instance IsString Expr where
fromString str = Var (fromString str)
-- | Convert an Annah expression to a Morte expression
desugar
:: Expr
-- ^ Annah expression
-> M.Expr M.Path
-- ^ Morte expression
desugar (Const c ) = M.Const c
desugar (Var v ) = M.Var v
desugar (Lam x _A b ) = M.Lam x (desugar _A) (desugar b)
desugar (Pi x _A _B ) = M.Pi x (desugar _A) (desugar _B)
desugar (App f a ) = M.App (desugar f) (desugar a)
desugar (Embed p ) = M.Embed p
desugar (Annot a _A ) = desugar (Lets [Let "x" [] _A a] "x")
desugar (Lets ls e ) = desugarLets ls e
desugar (Family ts e ) = desugarLets (desugarFamily ts) e
desugar (Natural n ) = desugarNatural n
desugar (List t es ) = desugarList t es
desugar (Path t oms o) = desugarPath t oms o
desugar (Do m bs b ) = desugarDo m bs b
{-| Convert a natural number to a Morte expression
For example, this natural number:
> 4
... desugars to this Morte expression:
> λ(Nat : * )
> → λ(Succ : ∀(pred : Nat) → Nat)
> → λ(Zero : Nat )
> → Succ (Succ (Succ (Succ Zero)))
-}
desugarNatural :: Integer -> M.Expr M.Path
desugarNatural n0 =
M.Lam "Nat" (M.Const M.Star)
(M.Lam "Succ" (M.Pi "pred" (M.Var (M.V "Nat" 0)) (M.Var (M.V "Nat" 0)))
(M.Lam "Zero" (M.Var (M.V "Nat" 0))
(go0 n0) ) )
where
go0 n | n <= 0 = M.Var (M.V "Zero" 0)
| otherwise = M.App (M.Var (M.V "Succ" 0)) (go0 (n - 1))
{-| Convert a list into a Morte expression
For example, this list:
> [nil Bool, True, False, False]
... desugars to this Morte expression:
> λ(List : *)
> → λ(Cons : ∀(head : Bool) → ∀(tail : List) → List)
> → λ(Nil : List)
> → Cons True (Cons False (Cons False Nil))
-}
desugarList :: Expr -> [Expr] -> M.Expr M.Path
desugarList e0 ts0 =
M.Lam "List" (M.Const M.Star)
(M.Lam "Cons" (M.Pi "head" (desugar0 e0) (M.Pi "tail" "List" "List"))
(M.Lam "Nil" "List" (go ts0)) )
where
go [] = "Nil"
go (t:ts) = M.App (M.App "Cons" (desugar1 t)) (go ts)
desugar0 = M.shift 1 "List" . desugar
desugar1 = M.shift 1 "List" . M.shift 1 "Cons" . M.shift 1 "Nil" . desugar
{-| Convert a path into a Morte expression
For example, this path:
> [id cat {a} f {b} g {c}]
... desugars to this Morte expression:
> λ(Path : ∀(a : *) → ∀(b : *) → *)
> → λ( Step
> : ∀(a : *)
> → ∀(b : *)
> → ∀(c : *)
> → ∀(head : cat a b)
> → ∀(tail : Path b c)
> → Path a c
> )
> → λ(End : ∀(a : *) → Path a a)
> → Step a b c f (Step b c c g (End c))
-}
desugarPath
:: Expr
-> [(Expr, Expr)]
-> Expr
-> M.Expr M.Path
desugarPath c0 oms0 o0 =
M.Lam "Path"
(M.Pi "a" (M.Const M.Star) (M.Pi "b" (M.Const M.Star) (M.Const M.Star)))
(M.Lam "Step"
(M.Pi "a" (M.Const M.Star)
(M.Pi "b" (M.Const M.Star)
(M.Pi "c" (M.Const M.Star)
(M.Pi "head" (M.App (M.App (desugar0 c0) "a") "b")
(M.Pi "tail" (M.App (M.App "Path" "b") "c")
(M.App (M.App "Path" "a") "c") ) ) ) ) )
(M.Lam "End"
(M.Pi "a" (M.Const M.Star) (M.App (M.App "Path" "a") "a"))
(go oms0) ) )
where
desugar0
= M.shift 1 "Path"
. M.shift 1 "a"
. M.shift 1 "b"
. M.shift 1 "c"
. desugar
desugar1
= M.shift 1 "Path"
. M.shift 1 "Step"
. M.shift 1 "End"
. desugar
go [] = M.App "End" (desugar1 o0)
go [(o1, m1)] =
M.App (M.App (M.App (M.App (M.App "Step" o1') o0') o0') m1') (go [] )
where
o0' = desugar1 o0
o1' = desugar1 o1
m1' = desugar1 m1
go ((o1, m1):oms@((o2, _):_)) =
M.App (M.App (M.App (M.App (M.App "Step" o1') o2') o0') m1') (go oms)
where
o0' = desugar1 o0
o1' = desugar1 o1
o2' = desugar1 o2
m1' = desugar1 m1
{-| Convert a command (i.e. do-notation) into a Morte expression
For example, this command:
> do m
> { x0 : _A0 <- e0;
> x1 : _A1 <- e1;
> }
.. desugars to this Morte expression:
> λ(Cmd : *)
> → λ(Bind : ∀(b : *) → m b → (b → Cmd) → Cmd)
> → λ(Pure : ∀(x1 : _A1) → Cmd)
> → Bind _A0 e0
> ( λ(x0 : _A0)
> → Bind _A1 e1
> Pure
> )
-}
desugarDo :: Expr -> [Bind] -> Bind -> M.Expr M.Path
desugarDo m bs0 (Bind (Arg x0 _A0) e0) =
M.Lam "Cmd" (M.Const M.Star)
(M.Lam "Bind"
(M.Pi "b" (M.Const M.Star)
(M.Pi "_" (M.App (desugar0 m) "b")
(M.Pi "_" (M.Pi "_" "b" "Cmd") "Cmd") ) )
(M.Lam "Pure" (M.Pi x0 (desugar1 _A0) "Cmd")
(go bs0 (0 :: Int) (0 :: Int)) ) )
where
desugar0
= M.shift 1 "b"
. M.shift 1 "Cmd"
. desugar
desugar1
= M.shift 1 "Bind"
. M.shift 1 "Cmd"
. desugar
desugar2
= M.shift 1 "Pure"
. M.shift 1 "Bind"
. M.shift 1 "Cmd"
. desugar
go [] numPure numBind =
M.App
(M.App (M.App (M.Var (M.V "Bind" numBind)) (desugar2 _A0))
(desugar2 e0) )
(M.Var (M.V "Pure" numPure))
go (Bind (Arg x _A) e:bs) numPure numBind = numBind' `seq` numPure' `seq`
M.App
(M.App
(M.App (M.Var (M.V "Bind" numBind)) (desugar2 _A))
(desugar2 e) )
(M.Lam x (desugar2 _A) (go bs numBind' numPure'))
where
numBind' = if x == "Bind" then numBind + 1 else numBind
numPure' = if x == "Pure" then numPure + 1 else numPure
{-| Convert a let expression into a Morte expression
For example, this let expression:
> let f0 (x00 : _A00) ... (x0j : _A0j) _B0 = b0
> ..
> let fi (xi0 : _Ai0) ... (xij : _Aij) _Bi = bi
> in e
... desugars to this Morte expression:
> ( \(f0 : forall (x00 : _A00) -> ... -> forall (x0j : _A0j) -> _B0)
> -> ...
> -> \(fi : forall (xi0 : _Ai0) -> ... -> forall (xij : _Aij) -> _Bi)
> -> e
> )
>
> (\(x00 : _A00) -> ... -> \(x0j : _A0j) -> b0)
> ...
> (\(xi0 : _Ai0) -> ... -> \(xij : _Aij) -> bi)
-}
desugarLets :: [Let] -> Expr -> M.Expr M.Path
desugarLets lets e = apps
where
-- > ( \(f0 : forall (x00 : _A00) -> ... -> forall (x0j : _A0j) -> _B0)
-- > -> ...
-- > -> \(fi : forall (xi0 : _Ai0) -> ... -> forall (xij : _Aij) -> _Bi)
-- > -> e
-- > )
lams = foldr
(\(Let fn args _Bn _) rest ->
-- > forall (xn0 : _An0) -> ... -> forall (xnj : _Anj) -> _Bn
let rhsType = pi args _Bn
-- > \(fn : rhsType) -> rest
in M.Lam fn (desugar rhsType) rest )
(desugar e)
lets
-- > lams
-- > (\(x00 : _A00) -> ... -> \(x0j : _A0j) -> b0)
-- > ...
-- > (\(xi0 : _Ai0) -> ... -> \(xij : _Aij) -> bi)
apps = foldr
(\(Let _ args _ bn) rest ->
-- > rest (\(xn0 : _An0) -> ... -> \(xnj : _Anj) -> bn)
M.App rest (desugar (lam args bn)) )
lams
(reverse lets)
-- | A type or data constructor
data Cons = Cons
{ consName :: Text
, consArgs :: [Arg]
, consType :: Expr
}
{-| This translates datatype definitions to let expressons using the
Boehm-Berarducci encoding.
For example, this mutually recursive datatype definition:
> type Even
> data Zero
> data SuccE (predE : Odd)
> fold foldEven
>
> type Odd
> data SuccO (predO : Even)
> fold foldOdd
>
> in SuccE
... desugars to seven let expressions:
> let Even : * = ...
> let Odd : *
> let Zero : Even = ...
> let SuccE : ∀(predE : Odd ) → Even = ...
> let SuccO : ∀(predO : Even) → Odd = ...
> let foldEven : ∀(x : Even) → ... = ...
> let foldOdd : ∀(x : Odd ) → ... = ...
> in SuccE
... and normalizes to:
> λ( predE
> : ∀(Even : *)
> → ∀(Odd : *)
> → ∀(Zero : Even)
> → ∀(SuccE : ∀(predE : Odd ) → Even)
> → ∀(SuccO : ∀(predO : Even) → Odd)
> → Odd
> )
> → λ(Even : *)
> → λ(Odd : *)
> → λ(Zero : Even)
> → λ(SuccE : ∀(predE : Odd) → Even)
> → λ(SuccO : ∀(predO : Even) → Odd)
> → SuccE (predE Even Odd Zero SuccE SuccO)
-}
desugarFamily :: [Type] -> [Let]
desugarFamily familyTypes = typeLets ++ dataLets ++ foldLets
{- Annah permits data constructors to have duplicate names and Annah also
permits data constructors to share the same name as type constructors. A
lot of the complexity of this code is due to avoiding name collisions.
Constructor fields can also have duplicate field names, too. This is
particularly useful for constructors with multiple fields where the user
omits the field name and defaults to @\"_\"@, like in this example:
> \(a : *)
> -> \(b : *)
> -> type Pair
> data MakePair a b
> in MakePair
... which compiles to:
> \(a : *)
> -> \(b : *)
> -> \(_ : a)
> -> \(_ : b)
> -> \(Pair : *)
> -> \(MakePair : a -> b -> Pair)
> -> MakePair _@1 _
-}
where
typeConstructors :: [Cons]
typeConstructors = do
t <- familyTypes
return (Cons (typeName t) [] (Const M.Star))
dataConstructors :: [Cons]
dataConstructors = do
(tsBefore , t, tsAfter) <- zippers familyTypes
(dsBefore1, d, _ ) <- zippers (typeDatas t)
let dsBefore0 = do
t' <- tsBefore
typeDatas t'
let names1 = map typeName tsAfter
let names2 = map dataName dsBefore0
let names3 = map dataName dsBefore1
let names4 = map argName (dataArgs d)
let typeVar =
typeName t `isShadowedBy` (names1 ++ names2 ++ names3 ++ names4)
return (Cons (dataName d) (dataArgs d) typeVar)
constructors :: [Cons]
constructors = typeConstructors ++ dataConstructors
makeRhs piOrLam con = foldr cons con constructors
where
cons (Cons x args _A) = piOrLam x (pi args _A)
typeLets, foldLets :: [Let]
(typeLets, foldLets) = unzip (do
let folds = map typeFold familyTypes
((_, t, tsAfter), fold) <- zip (zippers typeConstructors) folds
let names1 = map consName tsAfter
let names2 = map consName dataConstructors
let con = consName t `isShadowedBy` (names1 ++ names2)
let typeRhs = makeRhs Pi con
let foldType = Pi "x" con typeRhs
let foldRhs = Lam "x" typeRhs "x"
return ( Let (consName t) [] (consType t) typeRhs
, Let fold [] foldType foldRhs
) )
-- TODO: Enforce that argument types are `Var`s?
desugarType :: Expr -> Maybe ([Arg], Expr, Expr)
desugarType (Pi x _A e ) = do
~(args, f, f') <- desugarType e
return (Arg x _A:args, f, f')
desugarType f@(Var (M.V x0 n0)) = do
f' <- go0 dataConstructors x0 n0
return ([], f, f')
where
go0 (d:ds) x n | consName d == x =
if n > 0 then go0 ds x $! n - 1 else empty
| otherwise = go0 ds x n
go0 [] x n = go1 (reverse typeLets) x n
go1 (t:ts) x n | letName t == x =
if n > 0 then go1 ts x $! n - 1 else pure (letRhs t)
| otherwise = go1 ts x n
go1 [] _ _ = empty
desugarType _ = empty
consVars :: [Text] -> [Expr]
consVars argNames = do
(_, name, namesAfter) <- zippers (map consName constructors)
return (name `isShadowedBy` (argNames ++ namesAfter))
dataLets :: [Let]
dataLets = do
(_, d, dsAfter) <- zippers dataConstructors
let conVar = consName d `isShadowedBy` map consName dsAfter
let conArgs = do
(_, arg, argsAfter) <- zippers (consArgs d)
let names1 = map argName argsAfter
let names2 = map consName constructors
return (case desugarType (argType arg) of
Nothing -> argVar
where
names = names1 ++ names2
argVar = argName arg `isShadowedBy` names
Just (args, _, _) ->
lam args (apply argVar (argExprs ++ consVars names3))
where
names3 = map argName args
names = names1 ++ names2 ++ names3
argVar = argName arg `isShadowedBy` names
argExprs = do
(_, name, namesAfter) <- zippers names3
return (name `isShadowedBy` namesAfter) )
let (lhsArgs, rhsArgs) = unzip (do
arg@(Arg x _A) <- consArgs d
return (case desugarType _A of
Just (args, _B, _B') -> (lhsArg, rhsArg)
where
lhsArg = Arg x (pi args _B )
rhsArg = Arg x (pi args _B')
Nothing -> ( arg, arg) ) )
let letType' = pi lhsArgs (consType d)
let letRhs' = lam rhsArgs (makeRhs Lam (apply conVar conArgs))
return (Let (consName d) [] letType' letRhs')
-- | Apply an expression to a list of arguments
apply :: Expr -> [Expr] -> Expr
apply f as = foldr (flip App) f (reverse as)
{-| Compute the correct DeBruijn index for a synthetic `Var` (@x@) by providing
all variables bound in between when @x@ is introduced and when @x@ is used.
-}
isShadowedBy :: Text -> [Text] -> Expr
x `isShadowedBy` vars = Var (M.V x (length (filter (== x) vars)))
pi, lam :: [Arg] -> Expr -> Expr
pi args e = foldr (\(Arg x _A) -> Pi x _A) e args
lam args e = foldr (\(Arg x _A) -> Lam x _A) e args
-- | > zippers [1, 2, 3] = [([], 1, [2, 3]), ([1], 2, [3]), ([2, 1], 3, [])]
zippers :: [a] -> [([a], a, [a])]
zippers [] = []
zippers (stmt:stmts') = z:go z
where
z = ([], stmt, stmts')
go ( _, _, [] ) = []
go (ls, m, r:rs) = z':go z'
where
z' = (m:ls, r, rs)
| Gabriel439/Haskell-Annah-Library | src/Annah/Core.hs | bsd-3-clause | 17,887 | 32 | 22 | 6,380 | 4,593 | 2,395 | 2,198 | 289 | 9 |
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-}
import System.Environment
import qualified Data.Text as T
import Data.Enumerator (joinI, ($$), run_)
import Text.XML.Enumerator.Parse (parseBytes)
import Data.Enumerator.Binary (enumFile)
import Text.Roundtrip
import Text.Roundtrip.Xml
import Text.Roundtrip.Xml.Enumerator
import Control.Isomorphism.Partial.TH
type Text = T.Text
data NewsList = NewsList [NewsItem]
deriving (Show)
data NewsItem = NewsItem Int Text
deriving (Show)
$(defineIsomorphisms ''NewsList)
$(defineIsomorphisms ''NewsItem)
newsListSpec :: XmlSyntax x => x NewsList
newsListSpec = newsList <$> xmlElem "news" (many newsItemSpec)
newsItemSpec :: XmlSyntax x => x NewsItem
newsItemSpec =
newsItem <$> xmlElem "newsitem" (xmlAttr "seq" readShowIso <*>
xmlAttr "object" idIso)
main :: IO ()
main =
do args <- getArgs
x <- parseFromFile (args!!0) newsListSpec
print x
parseFromFile fname p =
do run_ $ joinI $
enumFile fname $$
parseBytes $$
parseXml fname defaultEntityRenderer p
| skogsbaer/roundtrip | test/Test.hs | bsd-3-clause | 1,146 | 0 | 10 | 268 | 322 | 170 | 152 | 33 | 1 |
module Config.File (T(..), load) where
import Control.Monad
import Data.Text
import Data.Yaml
data T = ConfigFile
{ serverUrl :: Text
, serverPort :: Int
, serverAllowOrigins :: [Text]
, proxyHost :: Text
, proxyPort :: Int
, proxyKeyFile :: FilePath
, postmarkKey :: Text
, postmarkSender :: Text
, authCookie :: Text
, authKeyFile :: FilePath
, authEmailDomain :: Text
, authTitle :: Text
, debug :: Bool
} deriving (Eq, Ord)
(..:) :: (FromJSON a) => Object -> (Text, Text) -> Parser a
(..:) obj (j, k) = obj .: j >>= (.: k)
instance FromJSON T where
parseJSON (Object v) =
ConfigFile
<$> v ..: ("server", "url")
<*> v ..: ("server", "port")
<*> v ..: ("server", "allow-origins")
<*> v ..: ("proxy", "host")
<*> v ..: ("proxy", "port")
<*> v ..: ("proxy", "key-file")
<*> v ..: ("postmark", "key")
<*> v ..: ("postmark", "sender")
<*> v ..: ("authentication", "cookie")
<*> v ..: ("authentication", "key-file")
<*> v ..: ("authentication", "email-domain")
<*> v ..: ("authentication", "title")
<*> v .:? "debug" .!= False
parseJSON _ = mzero
load :: FilePath -> IO T
load = decodeFileEither >=> either (error . show) return
| ktvoelker/auth-proxy | src/Config/File.hs | bsd-3-clause | 1,339 | 1 | 32 | 401 | 441 | 257 | 184 | 40 | 1 |
{-# LANGUAGE NoImplicitPrelude
, CPP
, GeneralizedNewtypeDeriving
, PatternGuards
#-}
-----------------------------------------------------------------------------
-- |
-- Module : Math.Combinatorics.Species.Labeled
-- Copyright : (c) Brent Yorgey 2010
-- License : BSD-style (see LICENSE)
-- Maintainer : byorgey@cis.upenn.edu
-- Stability : experimental
--
-- An interpretation of species as exponential generating functions,
-- which count labeled structures.
--
-----------------------------------------------------------------------------
module Math.Combinatorics.Species.Labeled
( labeled
, labelled
) where
-- A previous version of this module used an EGF library which
-- explicitly computed with EGFs. However, it turned out to be much
-- slower than just computing explicitly with normal power series and
-- zipping/unzipping with factorial denominators as necessary, which
-- is the current approach.
import Math.Combinatorics.Species.Types
import Math.Combinatorics.Species.Class
import Math.Combinatorics.Species.AST
import Math.Combinatorics.Species.AST.Instances
import Math.Combinatorics.Species.NewtonRaphson
import qualified MathObj.PowerSeries as PS
import qualified MathObj.FactoredRational as FQ
import NumericPrelude
#if MIN_VERSION_numeric_prelude(0,2,0)
#else
import PreludeBase hiding (cycle)
#endif
facts :: [Integer]
facts = 1 : zipWith (*) [1..] facts
instance Species EGF where
singleton = egfFromCoeffs [0,1]
set = egfFromCoeffs (map (1%) facts)
cycle = egfFromCoeffs (0 : map (1%) [1..])
o = liftEGF2 PS.compose
(><) = liftEGF2 . PS.lift2 $ \xs ys ->
zipWith3 mult xs ys (map fromIntegral facts)
where mult x y z = x * y * z
(@@) = liftEGF2 . PS.lift2 $ \fs gs ->
map (\(n,gn) -> let gn' = numerator $ gn
in (fs `safeIndex` gn') *
toRational (FQ.factorial gn' / FQ.factorial n))
(zip [0..] $ zipWith (*) (map fromIntegral facts) gs)
where safeIndex [] _ = 0
safeIndex (x:_) 0 = x
safeIndex (_:xs) n = safeIndex xs (n-1)
ofSize s p = (liftEGF . PS.lift1 $ filterCoeffs p) s
ofSizeExactly s n = (liftEGF . PS.lift1 $ selectIndex n) s
-- XXX Think about this more carefully -- is there a way to make this actually
-- return a lazy, infinite list?
rec f = case newtonRaphsonRec f 100 of
Nothing -> error $ "Unable to express " ++ show f ++ " in the form T = TX*R(T)."
Just ls -> ls
-- | Extract the coefficients of an exponential generating function as
-- a list of 'Integer's. Since 'EGF' is an instance of 'Species', the
-- idea is that 'labeled' can be applied directly to an expression
-- of the species DSL. In particular, @'labeled' s '!!' n@ is the
-- number of labeled @s@-structures on an underlying set of size @n@
-- (note that @'labeled' s@ is guaranteed to be an infinite list).
-- For example:
--
-- > > take 10 $ labeled octopi
-- > [0,1,3,14,90,744,7560,91440,1285200,20603520]
--
-- gives the number of labeled octopi on 0, 1, 2, 3, ... 9 labels.
labeled :: EGF -> [Integer]
labeled (EGF f) = (++repeat 0)
. map numerator
. zipWith (*) (map fromInteger facts)
$ PS.coeffs f
-- | A synonym for 'labeled', since both spellings are acceptable and
-- it's annoying to have to remember which is correct.
labelled :: EGF -> [Integer]
labelled = labeled
| timsears/species | Math/Combinatorics/Species/Labeled.hs | bsd-3-clause | 3,604 | 2 | 21 | 905 | 621 | 360 | 261 | 46 | 1 |
module Main(main) where
import qualified Detrospector.Main as D
main :: IO ()
main = D.main
| kmcallister/detrospector | detrospector.hs | bsd-3-clause | 94 | 0 | 6 | 17 | 34 | 21 | 13 | 4 | 1 |
{-# LANGUAGE
OverloadedStrings
, ConstraintKinds
, FlexibleContexts
, MultiParamTypeClasses
#-}
module Application.Session where
import Application.Types
import qualified Data.TimeMap as TM
import Data.UUID (UUID)
import Data.UUID.V4 (nextRandom)
import qualified Data.ByteString.UTF8 as BS
import qualified Data.Vault.Lazy as V
import Text.Read (readMaybe)
import Network.Wai.Trans
import Network.Wai.Session
import Network.Wai.Session.TimeMap
import Control.Concurrent.STM
import Control.Monad.IO.Class
import Control.Monad.Reader
-- * Impure
-- | Creates a new session id and increments the old value
newSessionId :: MonadApp m => m SessionId
newSessionId = do
sidVar <- envSessionId <$> ask
liftIO $ atomically $ do
old <- readTVar sidVar
modifyTVar' sidVar (+1)
return old
-- | Creates a new nonce and session id, and updates the cache
newSession :: MonadApp m => m (SessionId, UUID)
newSession = do
cache <- envSessionCache <$> ask
sid <- newSessionId
nonce <- liftIO nextRandom
liftIO $ TM.insert sid nonce cache
return (sid, nonce)
currentSession :: MonadApp m => Request -> m (Maybe SessionId)
currentSession req = do
vKey <- envSessionKey <$> ask
return $ V.lookup vKey (vault req)
sessionCfg :: MonadApp m => m (SessionConfig IO SessionId UUID)
sessionCfg = do
vKey <- envSessionKey <$> ask
cache <- envSessionCache <$> ask
return $ uuidSessionCfg
(BS.fromString . show . getSessionId)
(\s -> SessionId <$> (readMaybe $ BS.toString s :: Maybe Integer))
"session-key"
"session-nonce"
vKey
cache
| athanclark/nested-routes-website | src/Application/Session.hs | bsd-3-clause | 1,657 | 0 | 15 | 363 | 441 | 234 | 207 | 48 | 1 |
{-# LANGUAGE RankNTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Haskell.TH.OverloadApp
-- Copyright : (c) 2012 Michael Sloan
-- License : BSD-style (see the LICENSE file)
-- Maintainer : Michael Sloan <mgsloan@gmail.com>
-- Stability : experimental
-- Portability : GHC only
--
-- This module provides Template Haskell utilities, functions for using SYB
-- to create quasi-quoters. Also included is an example usage of this function
-- to overload function application.
--
-----------------------------------------------------------------------------
module Language.Quasi.OverloadApp where
import Data.Data ( Data )
import Data.Generics.Schemes ( everywhereM )
import Language.Haskell.TH
import Language.Haskell.TH.Quote ( QuasiQuoter(..) )
import Language.Haskell.Meta ( toExp, toPat, toType, toDecs
, parseResultToEither)
import Language.Quasi.Ast
-- | Makes quasi-quotation into an AST transformer.
{-
transformer :: (Exp -> ExpQ)
-> (Pat -> PatQ)
-> (Type -> TypeQ)
-> ([Dec] -> DecsQ)
-> QuasiQuoter
transformer qe qp qt qd = QuasiQuoter
(qe . parseExp)
(qp . parsePat)
(qt . parseType)
(qd . parseDecs)
-- | Uses SYB to transform the AST everywhere. Usually you want to have this
-- apply to a particular type
transformEverywhere :: (forall a. Data a => a -> Q a) -> QuasiQuoter
transformEverywhere f = transformer ef ef ef ef
where
ef :: Data a => a -> Q a
ef = everywhereM f
-}
-- | Translates
{-
-- | A quasiquoter that translates all instances of function application to
-- invocations of an "app" function.
--
-- > ( (1+) 5 ) becomes ( app (app (+) 1) 5 )
-- > ( (+1) 5 ) becomes ( app (app (app flip (+))))
overloadApp :: QuasiQuoter
overloadApp = overloadAppWith
(\l r -> appsE [varE $ mkName "app", return l, return r] )
-- | Takes every single instance of function application (and translates infix
-- operators appropriately), and replaces it using the passed function to
-- generate the new expression.
--
-- Things this doesn't handle:
-- * All of the de-sugarings of do-notation, comprehensions, enumeration
-- syntax, etc.
overloadAppWith :: (Exp -> Exp -> ExpQ) -> QuasiQuoter
overloadAppWith overload
= transformer ()
where
transform = everywhereM (return `extM` handlePat `extM` handleExp)
handleExp (AppE l r) = overload l r
handleExp e = return e
-- I count view patterns as function application.
handlePat (ViewP e p) = viewP lam (return p)
where lam = do n <- newName "x"
lamE [varP n] $ overload e (VarE n)
handlePat e = return e
-} | mgsloan/quasi-extras | src/Language/Quasi/OverloadApp.hs | bsd-3-clause | 2,752 | 0 | 6 | 621 | 98 | 71 | 27 | 9 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.DomainAuth.DKIM.Types where
import Data.ByteString (ByteString)
import Network.DNS
import Network.DomainAuth.Mail
----------------------------------------------------------------
-- | Canonicalized key for DKIM-Signature:.
dkimFieldKey :: CanonFieldKey
dkimFieldKey = "dkim-signature"
----------------------------------------------------------------
data DkimSigAlgo = RSA_SHA1 | RSA_SHA256 deriving (Eq,Show)
data DkimCanonAlgo = DKIM_SIMPLE | DKIM_RELAXED deriving (Eq,Show)
data DKIM = DKIM {
dkimVersion :: ByteString
, dkimSigAlgo :: DkimSigAlgo
, dkimSignature :: ByteString
, dkimBodyHash :: ByteString
, dkimHeaderCanon :: DkimCanonAlgo
, dkimBodyCanon :: DkimCanonAlgo
, dkimDomain0 :: ByteString
, dkimFields :: [CanonFieldKey]
, dkimLength :: Maybe Int
, dkimSelector0 :: ByteString
} deriving (Eq,Show)
-- | Getting of the value of the \"d\" tag in DKIM-Signature:.
dkimDomain :: DKIM -> Domain
dkimDomain = dkimDomain0
-- | Getting of the value of the \"s\" tag in DKIM-Signature:.
dkimSelector :: DKIM -> ByteString
dkimSelector = dkimSelector0
| kazu-yamamoto/domain-auth | Network/DomainAuth/DKIM/Types.hs | bsd-3-clause | 1,173 | 0 | 9 | 196 | 201 | 125 | 76 | 25 | 1 |
module MC.Protocol
( ClientPacket
, ServerPacket
, module MC.Protocol.Types
) where
import MC.Protocol.Types
import MC.Protocol.Client (ClientPacket)
import MC.Protocol.Server (ServerPacket)
| ehird/mchost | MC/Protocol.hs | bsd-3-clause | 200 | 0 | 5 | 28 | 49 | 32 | 17 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Filter where
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as LBS
import qualified Data.Text as T
import Data.Maybe (fromJust, isJust)
import Control.Lens
import Data.List
import qualified Data.Set as S
import Card
getAllCardData :: IO [Card]
getAllCardData = fromJust . decode <$> LBS.readFile "/home/adv_zxy/hearthstone-cardsearch/card-data.json"
data Filter = Filter ([Card] -> [Card])
nameFilter :: T.Text -> Filter
nameFilter n = Filter $
case n of
"" -> id
n' -> filter (\c -> T.toLower n' `T.isInfixOf` T.toLower (c ^. cardName))
descFilter :: T.Text -> Filter
descFilter n = Filter $
case n of
"" -> id
n' -> filter (\c -> T.toLower n' `T.isInfixOf` T.toLower (c ^. cardDesc))
flavorFilter :: T.Text -> Filter
flavorFilter n = Filter $
case n of
"" -> id
n' -> filter (\c -> T.toLower n' `T.isInfixOf` T.toLower (c ^. cardFlavor))
cardsetFilter :: [CardSet] -> Filter
cardsetFilter s = Filter $
if null s
then id
else filter (\c -> c ^. cardSet `elem` s)
typeFilter :: [CardType] -> Filter
typeFilter t = Filter $
if null t
then id
else filter (\c -> c ^. cardType `elem` t)
subtypeFilter :: [CardSubtype] -> Filter
subtypeFilter st = Filter $
if null st
then id
else filter (\c -> isJust (c ^. cardSubtype) &&
fromJust (c ^. cardSubtype) `elem` st)
rarityFilter :: [CardRarity] -> Filter
rarityFilter r = Filter $
if null r
then id
else filter (\c -> c ^. cardRarity `elem` r)
costFilter :: (Int, Int) -> Filter
costFilter (l, h) = Filter $
filter (\c -> let CardCost co = c ^. cardCost
in co >= l && co <= h)
atkFilter :: (Int, Int) -> Filter
atkFilter (l, h) = Filter $
filter (\c -> let CardAttack ca = c ^. cardAttack
in ca >= l && ca <= h)
hpFilter :: (Int, Int) -> Filter
hpFilter (l, h) = Filter $
filter (\c -> let CardHealth ch = c ^. cardHealth
in ch >= l && ch <= h)
abiFilter :: [Mechanic] -> Filter
abiFilter m = Filter $
filter (\c -> let cm = c ^. cardAbilities
in all (`S.member` cm) m)
tagFilter :: [Tag] -> Filter
tagFilter t = Filter $
filter (\c -> let ct = c ^. cardTags
in all (`S.member` ct) t)
classFilter :: [CardClass] -> Filter
classFilter cc = Filter $
if null cc
then id
else filter (\c -> let cla = c ^. cardClass in cla `elem` cc)
applyFilter :: Filter -> [Card] -> [Card]
applyFilter (Filter f) = f
applyAllFilter :: [Filter] -> [Card] -> [Card]
applyAllFilter fs cs = foldl' (flip applyFilter) cs fs
| Frefreak/hearthstone-cardsearch | client/src/Filter.hs | bsd-3-clause | 2,688 | 0 | 15 | 722 | 1,078 | 585 | 493 | 78 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-}
{-# LANGUAGE CPP #-}
module IfaceSyn (
module IfaceType,
IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..),
IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec,
IfaceExpr(..), IfaceAlt, IfaceLetBndr(..),
IfaceBinding(..), IfaceConAlt(..),
IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
IfaceBang(..),
IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..),
IfaceAxBranch(..),
IfaceTyConParent(..),
-- Misc
ifaceDeclImplicitBndrs, visibleIfConDecls,
ifaceConDeclFields,
ifaceDeclFingerprints,
-- Free Names
freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
-- Pretty printing
pprIfaceExpr,
pprIfaceDecl,
ShowSub(..), ShowHowMuch(..)
) where
#include "HsVersions.h"
import IfaceType
import CoreSyn( IsOrphan )
import PprCore() -- Printing DFunArgs
import Demand
import Class
import FieldLabel
import NameSet
import CoAxiom ( BranchIndex )
import Name
import CostCentre
import Literal
import ForeignCall
import Annotations( AnnPayload, AnnTarget )
import BasicTypes
import Outputable
import FastString
import Module
import SrcLoc
import Fingerprint
import Binary
import BooleanFormula ( BooleanFormula, pprBooleanFormula, isTrue )
import HsBinds
import TyCon ( Role (..), Injectivity(..) )
import StaticFlags (opt_PprStyle_Debug)
import Util( filterOut, filterByList )
import DataCon (SrcStrictness(..), SrcUnpackedness(..))
import Lexeme (isLexSym)
import Control.Monad
import System.IO.Unsafe
import Data.List (find)
import Data.Maybe (isJust)
infixl 3 &&&
{-
************************************************************************
* *
Declarations
* *
************************************************************************
-}
type IfaceTopBndr = OccName
-- It's convenient to have an OccName in the IfaceSyn, although in each
-- case the namespace is implied by the context. However, having an
-- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints
-- very convenient.
--
-- We don't serialise the namespace onto the disk though; rather we
-- drop it when serialising and add it back in when deserialising.
data IfaceDecl
= IfaceId { ifName :: IfaceTopBndr,
ifType :: IfaceType,
ifIdDetails :: IfaceIdDetails,
ifIdInfo :: IfaceIdInfo }
| IfaceData { ifName :: IfaceTopBndr, -- Type constructor
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceType, -- Result kind of type constructor
ifCType :: Maybe CType, -- C type for CAPI FFI
ifRoles :: [Role], -- Roles
ifCtxt :: IfaceContext, -- The "stupid theta"
ifCons :: IfaceConDecls, -- Includes new/data/data family info
ifRec :: RecFlag, -- Recursive or not?
ifGadtSyntax :: Bool, -- True <=> declared using
-- GADT syntax
ifParent :: IfaceTyConParent -- The axiom, for a newtype,
-- or data/newtype family instance
}
| IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor
ifRoles :: [Role], -- Roles
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceKind, -- Kind of the *result*
ifSynRhs :: IfaceType }
| IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor
ifResVar :: Maybe IfLclName, -- Result variable name, used
-- only for pretty-printing
-- with --show-iface
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceKind, -- Kind of the *tycon*
ifFamFlav :: IfaceFamTyConFlav,
ifFamInj :: Injectivity } -- injectivity information
| IfaceClass { ifCtxt :: IfaceContext, -- Superclasses
ifName :: IfaceTopBndr, -- Name of the class TyCon
ifRoles :: [Role], -- Roles
ifBinders :: [IfaceTyConBinder],
ifFDs :: [FunDep FastString], -- Functional dependencies
ifATs :: [IfaceAT], -- Associated type families
ifSigs :: [IfaceClassOp], -- Method signatures
ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition
ifRec :: RecFlag -- Is newtype/datatype associated
-- with the class recursive?
}
| IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name
ifTyCon :: IfaceTyCon, -- LHS TyCon
ifRole :: Role, -- Role of axiom
ifAxBranches :: [IfaceAxBranch] -- Branches
}
| IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym
ifPatIsInfix :: Bool,
ifPatMatcher :: (IfExtName, Bool),
ifPatBuilder :: Maybe (IfExtName, Bool),
-- Everything below is redundant,
-- but needed to implement pprIfaceDecl
ifPatUnivTvs :: [IfaceTvBndr],
ifPatExTvs :: [IfaceTvBndr],
ifPatProvCtxt :: IfaceContext,
ifPatReqCtxt :: IfaceContext,
ifPatArgs :: [IfaceType],
ifPatTy :: IfaceType,
ifFieldLabels :: [FieldLabel] }
data IfaceTyConParent
= IfNoParent
| IfDataInstance IfExtName
IfaceTyCon
IfaceTcArgs
data IfaceFamTyConFlav
= IfaceDataFamilyTyCon -- Data family
| IfaceOpenSynFamilyTyCon
| IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch]))
-- ^ Name of associated axiom and branches for pretty printing purposes,
-- or 'Nothing' for an empty closed family without an axiom
| IfaceAbstractClosedSynFamilyTyCon
| IfaceBuiltInSynFamTyCon -- for pretty printing purposes only
data IfaceClassOp
= IfaceClassOp IfaceTopBndr
IfaceType -- Class op type
(Maybe (DefMethSpec IfaceType)) -- Default method
-- The types of both the class op itself,
-- and the default method, are *not* quantifed
-- over the class variables
data IfaceAT = IfaceAT -- See Class.ClassATItem
IfaceDecl -- The associated type declaration
(Maybe IfaceType) -- Default associated type instance, if any
-- This is just like CoAxBranch
data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr]
, ifaxbCoVars :: [IfaceIdBndr]
, ifaxbLHS :: IfaceTcArgs
, ifaxbRoles :: [Role]
, ifaxbRHS :: IfaceType
, ifaxbIncomps :: [BranchIndex] }
-- See Note [Storing compatibility] in CoAxiom
data IfaceConDecls
= IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon
| IfDataTyCon [IfaceConDecl] Bool [FieldLabelString] -- Data type decls
| IfNewTyCon IfaceConDecl Bool [FieldLabelString] -- Newtype decls
-- For IfDataTyCon and IfNewTyCon we store:
-- * the data constructor(s);
-- * a boolean indicating whether DuplicateRecordFields was enabled
-- at the definition site; and
-- * a list of field labels.
data IfaceConDecl
= IfCon {
ifConOcc :: IfaceTopBndr, -- Constructor name
ifConWrapper :: Bool, -- True <=> has a wrapper
ifConInfix :: Bool, -- True <=> declared infix
-- The universal type variables are precisely those
-- of the type constructor of this data constructor
-- This is *easy* to guarantee when creating the IfCon
-- but it's not so easy for the original TyCon/DataCon
-- So this guarantee holds for IfaceConDecl, but *not* for DataCon
ifConExTvs :: [IfaceTvBndr], -- Existential tyvars
ifConEqSpec :: IfaceEqSpec, -- Equality constraints
ifConCtxt :: IfaceContext, -- Non-stupid context
ifConArgTys :: [IfaceType], -- Arg types
ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels)
ifConStricts :: [IfaceBang],
-- Empty (meaning all lazy),
-- or 1-1 corresp with arg tys
-- See Note [Bangs on imported data constructors] in MkId
ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts
type IfaceEqSpec = [(IfLclName,IfaceType)]
-- | This corresponds to an HsImplBang; that is, the final
-- implementation decision about the data constructor arg
data IfaceBang
= IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion
-- | This corresponds to HsSrcBang
data IfaceSrcBang
= IfSrcBang SrcUnpackedness SrcStrictness
data IfaceClsInst
= IfaceClsInst { ifInstCls :: IfExtName, -- See comments with
ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst
ifDFun :: IfExtName, -- The dfun
ifOFlag :: OverlapFlag, -- Overlap flag
ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv
-- There's always a separate IfaceDecl for the DFun, which gives
-- its IdInfo with its full type and version number.
-- The instance declarations taken together have a version number,
-- and we don't want that to wobble gratuitously
-- If this instance decl is *used*, we'll record a usage on the dfun;
-- and if the head does not change it won't be used if it wasn't before
-- The ifFamInstTys field of IfaceFamInst contains a list of the rough
-- match types
data IfaceFamInst
= IfaceFamInst { ifFamInstFam :: IfExtName -- Family name
, ifFamInstTys :: [Maybe IfaceTyCon] -- See above
, ifFamInstAxiom :: IfExtName -- The axiom
, ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceRule
= IfaceRule {
ifRuleName :: RuleName,
ifActivation :: Activation,
ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars
ifRuleHead :: IfExtName, -- Head of lhs
ifRuleArgs :: [IfaceExpr], -- Args of LHS
ifRuleRhs :: IfaceExpr,
ifRuleAuto :: Bool,
ifRuleOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceAnnotation
= IfaceAnnotation {
ifAnnotatedTarget :: IfaceAnnTarget,
ifAnnotatedValue :: AnnPayload
}
type IfaceAnnTarget = AnnTarget OccName
-- Here's a tricky case:
-- * Compile with -O module A, and B which imports A.f
-- * Change function f in A, and recompile without -O
-- * When we read in old A.hi we read in its IdInfo (as a thunk)
-- (In earlier GHCs we used to drop IdInfo immediately on reading,
-- but we do not do that now. Instead it's discarded when the
-- ModIface is read into the various decl pools.)
-- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *)
-- and so gives a new version.
data IfaceIdInfo
= NoInfo -- When writing interface file without -O
| HasInfo [IfaceInfoItem] -- Has info, and here it is
data IfaceInfoItem
= HsArity Arity
| HsStrictness StrictSig
| HsInline InlinePragma
| HsUnfold Bool -- True <=> isStrongLoopBreaker is true
IfaceUnfolding -- See Note [Expose recursive functions]
| HsNoCafRefs
-- NB: Specialisations and rules come in separately and are
-- only later attached to the Id. Partial reason: some are orphans.
data IfaceUnfolding
= IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
-- Possibly could eliminate the Bool here, the information
-- is also in the InlinePragma.
| IfCompulsory IfaceExpr -- Only used for default methods, in fact
| IfInlineRule Arity -- INLINE pragmas
Bool -- OK to inline even if *un*-saturated
Bool -- OK to inline even if context is boring
IfaceExpr
| IfDFunUnfold [IfaceBndr] [IfaceExpr]
-- We only serialise the IdDetails of top-level Ids, and even then
-- we only need a very limited selection. Notably, none of the
-- implicit ones are needed here, because they are not put it
-- interface files
data IfaceIdDetails
= IfVanillaId
| IfRecSelId (Either IfaceTyCon IfaceDecl) Bool
| IfDFunId
{-
Note [Versioning of instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances]
************************************************************************
* *
Functions over declarations
* *
************************************************************************
-}
visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
visibleIfConDecls (IfAbstractTyCon {}) = []
visibleIfConDecls (IfDataTyCon cs _ _) = cs
visibleIfConDecls (IfNewTyCon c _ _) = [c]
ifaceConDeclFields :: IfaceConDecls -> [FieldLbl OccName]
ifaceConDeclFields x = case x of
IfAbstractTyCon {} -> []
IfDataTyCon cons is_over labels -> map (help cons is_over) labels
IfNewTyCon con is_over labels -> map (help [con] is_over) labels
where
help (dc:_) is_over lbl = mkFieldLabelOccs lbl (ifConOcc dc) is_over
help [] _ _ = error "ifaceConDeclFields: data type has no constructors!"
ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
-- *Excludes* the 'main' name, but *includes* the implicitly-bound names
-- Deeply revolting, because it has to predict what gets bound,
-- especially the question of whether there's a wrapper for a datacon
-- See Note [Implicit TyThings] in HscTypes
-- N.B. the set of names returned here *must* match the set of
-- TyThings returned by HscTypes.implicitTyThings, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ, ifCons = cons })
= case cons of
IfAbstractTyCon {} -> []
IfNewTyCon cd _ _ -> mkNewTyCoOcc tc_occ : ifaceConDeclImplicitBndrs cd
IfDataTyCon cds _ _ -> concatMap ifaceConDeclImplicitBndrs cds
ifaceDeclImplicitBndrs (IfaceClass { ifCtxt = sc_ctxt, ifName = cls_tc_occ
, ifSigs = sigs, ifATs = ats })
= -- (possibly) newtype coercion
co_occs ++
-- data constructor (DataCon namespace)
-- data worker (Id namespace)
-- no wrapper (class dictionaries never have a wrapper)
[dc_occ, dcww_occ] ++
-- associated types
[ifName at | IfaceAT at _ <- ats ] ++
-- superclass selectors
[mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
-- operation selectors
[op | IfaceClassOp op _ _ <- sigs]
where
n_ctxt = length sc_ctxt
n_sigs = length sigs
co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
| otherwise = []
dcww_occ = mkDataConWorkerOcc dc_occ
dc_occ = mkClassDataConOcc cls_tc_occ
is_newtype = n_sigs + n_ctxt == 1 -- Sigh
ifaceDeclImplicitBndrs _ = []
ifaceConDeclImplicitBndrs :: IfaceConDecl -> [OccName]
ifaceConDeclImplicitBndrs (IfCon { ifConWrapper = has_wrapper, ifConOcc = con_occ })
= [con_occ, work_occ] ++ wrap_occs
where
work_occ = mkDataConWorkerOcc con_occ -- Id namespace
wrap_occs | has_wrapper = [mkDataConWrapperOcc con_occ] -- Id namespace
| otherwise = []
-- -----------------------------------------------------------------------------
-- The fingerprints of an IfaceDecl
-- We better give each name bound by the declaration a
-- different fingerprint! So we calculate the fingerprint of
-- each binder by combining the fingerprint of the whole
-- declaration with the name of the binder. (#5614, #7215)
ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)]
ifaceDeclFingerprints hash decl
= (ifName decl, hash) :
[ (occ, computeFingerprint' (hash,occ))
| occ <- ifaceDeclImplicitBndrs decl ]
where
computeFingerprint' =
unsafeDupablePerformIO
. computeFingerprint (panic "ifaceDeclFingerprints")
{-
************************************************************************
* *
Expressions
* *
************************************************************************
-}
data IfaceExpr
= IfaceLcl IfLclName
| IfaceExt IfExtName
| IfaceType IfaceType
| IfaceCo IfaceCoercion
| IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted
| IfaceLam IfaceLamBndr IfaceExpr
| IfaceApp IfaceExpr IfaceExpr
| IfaceCase IfaceExpr IfLclName [IfaceAlt]
| IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives]
| IfaceLet IfaceBinding IfaceExpr
| IfaceCast IfaceExpr IfaceCoercion
| IfaceLit Literal
| IfaceFCall ForeignCall IfaceType
| IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E
data IfaceTickish
= IfaceHpcTick Module Int -- from HpcTick x
| IfaceSCC CostCentre Bool Bool -- from ProfNote
| IfaceSource RealSrcSpan String -- from SourceNote
-- no breakpoints: we never export these into interface files
type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr)
-- Note: IfLclName, not IfaceBndr (and same with the case binder)
-- We reconstruct the kind/type of the thing from the context
-- thus saving bulk in interface files
data IfaceConAlt = IfaceDefault
| IfaceDataAlt IfExtName
| IfaceLitAlt Literal
data IfaceBinding
= IfaceNonRec IfaceLetBndr IfaceExpr
| IfaceRec [(IfaceLetBndr, IfaceExpr)]
-- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too
-- It's used for *non-top-level* let/rec binders
-- See Note [IdInfo on nested let-bindings]
data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo
{-
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In IfaceSyn an IfaceCase does not record the types of the alternatives,
unlike CorSyn Case. But we need this type if the alternatives are empty.
Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn.
Note [Expose recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For supercompilation we want to put *all* unfoldings in the interface
file, even for functions that are recursive (or big). So we need to
know when an unfolding belongs to a loop-breaker so that we can refrain
from inlining it (except during supercompilation).
Note [IdInfo on nested let-bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Occasionally we want to preserve IdInfo on nested let bindings. The one
that came up was a NOINLINE pragma on a let-binding inside an INLINE
function. The user (Duncan Coutts) really wanted the NOINLINE control
to cross the separate compilation boundary.
In general we retain all info that is left by CoreTidy.tidyLetBndr, since
that is what is seen by importing module with --make
************************************************************************
* *
Printing IfaceDecl
* *
************************************************************************
-}
pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc
-- The TyCon might be local (just an OccName), or this might
-- be a branch for an imported TyCon, so it would be an ExtName
-- So it's easier to take an SDoc here
pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs
, ifaxbCoVars = cvs
, ifaxbLHS = pat_tys
, ifaxbRHS = rhs
, ifaxbIncomps = incomps })
= hang ppr_binders 2 (hang pp_lhs 2 (equals <+> ppr rhs))
$+$
nest 2 maybe_incomps
where
ppr_binders
| null tvs && null cvs = empty
| null cvs = brackets (pprWithCommas pprIfaceTvBndr tvs)
| otherwise
= brackets (pprWithCommas pprIfaceTvBndr tvs <> semi <+>
pprWithCommas pprIfaceIdBndr cvs)
pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys)
maybe_incomps = ppUnless (null incomps) $ parens $
text "incompatible indices:" <+> ppr incomps
instance Outputable IfaceAnnotation where
ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value
instance HasOccName IfaceClassOp where
occName (IfaceClassOp n _ _) = n
instance HasOccName IfaceConDecl where
occName = ifConOcc
instance HasOccName IfaceDecl where
occName = ifName
instance Outputable IfaceDecl where
ppr = pprIfaceDecl showAll
{-
Note [Minimal complete definition] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The minimal complete definition should only be included if a complete
class definition is shown. Since the minimal complete definition is
anonymous we can't reuse the same mechanism that is used for the
filtering of method signatures. Instead we just check if anything at all is
filtered and hide it in that case.
-}
data ShowSub
= ShowSub
{ ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl
-- See Note [Printing IfaceDecl binders]
, ss_how_much :: ShowHowMuch }
data ShowHowMuch
= ShowHeader -- Header information only, not rhs
| ShowSome [OccName] -- [] <=> Print all sub-components
-- (n:ns) <=> print sub-component 'n' with ShowSub=ns
-- elide other sub-components to "..."
-- May 14: the list is max 1 element long at the moment
| ShowIface -- Everything including GHC-internal information (used in --show-iface)
showAll :: ShowSub
showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr }
ppShowIface :: ShowSub -> SDoc -> SDoc
ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc
ppShowIface _ _ = Outputable.empty
-- show if all sub-components or the complete interface is shown
ppShowAllSubs :: ShowSub -> SDoc -> SDoc -- Note [Minimal complete definition]
ppShowAllSubs (ShowSub { ss_how_much = ShowSome [] }) doc = doc
ppShowAllSubs (ShowSub { ss_how_much = ShowIface }) doc = doc
ppShowAllSubs _ _ = Outputable.empty
ppShowRhs :: ShowSub -> SDoc -> SDoc
ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty
ppShowRhs _ doc = doc
showSub :: HasOccName n => ShowSub -> n -> Bool
showSub (ShowSub { ss_how_much = ShowHeader }) _ = False
showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing
showSub (ShowSub { ss_how_much = _ }) _ = True
{-
Note [Printing IfaceDecl binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The binders in an IfaceDecl are just OccNames, so we don't know what module they
come from. But when we pretty-print a TyThing by converting to an IfaceDecl
(see PprTyThing), the TyThing may come from some other module so we really need
the module qualifier. We solve this by passing in a pretty-printer for the
binders.
When printing an interface file (--show-iface), we want to print
everything unqualified, so we can just print the OccName directly.
-}
ppr_trim :: [Maybe SDoc] -> [SDoc]
-- Collapse a group of Nothings to a single "..."
ppr_trim xs
= snd (foldr go (False, []) xs)
where
go (Just doc) (_, so_far) = (False, doc : so_far)
go Nothing (True, so_far) = (True, so_far)
go Nothing (False, so_far) = (True, text "..." : so_far)
isIfaceDataInstance :: IfaceTyConParent -> Bool
isIfaceDataInstance IfNoParent = False
isIfaceDataInstance _ = True
pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc
-- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi
-- See Note [Pretty-printing TyThings] in PprTyThing
pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype,
ifCtxt = context,
ifRoles = roles, ifCons = condecls,
ifParent = parent, ifRec = isrec,
ifGadtSyntax = gadt,
ifBinders = binders })
| gadt_style = vcat [ pp_roles
, pp_nd <+> pp_lhs <+> pp_where
, nest 2 (vcat pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
| otherwise = vcat [ pp_roles
, hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
where
is_data_instance = isIfaceDataInstance parent
gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons
cons = visibleIfConDecls condecls
pp_where = ppWhen (gadt_style && not (null cons)) $ text "where"
pp_cons = ppr_trim (map show_con cons) :: [SDoc]
pp_lhs = case parent of
IfNoParent -> pprIfaceDeclHead context ss tycon binders Nothing
_ -> text "instance" <+> pprIfaceTyConParent parent
pp_roles
| is_data_instance = empty
| otherwise = pprRoles (== Representational)
(pprPrefixIfDeclBndr ss tycon)
binders roles
-- Don't display roles for data family instances (yet)
-- See discussion on Trac #8672.
add_bars [] = Outputable.empty
add_bars (c:cs) = sep ((equals <+> c) : map (vbar <+>) cs)
ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc)
show_con dc
| ok_con dc = Just $ pprIfaceConDecl ss gadt_style fls tycon binders parent dc
| otherwise = Nothing
fls = ifaceConDeclFields condecls
pp_nd = case condecls of
IfAbstractTyCon d -> text "abstract" <> ppShowIface ss (parens (ppr d))
IfDataTyCon{} -> text "data"
IfNewTyCon{} -> text "newtype"
pp_extra = vcat [pprCType ctype, pprRec isrec]
pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec
, ifCtxt = context, ifName = clas
, ifRoles = roles
, ifFDs = fds, ifMinDef = minDef
, ifBinders = binders })
= vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) binders roles
, text "class" <+> pprIfaceDeclHead context ss clas binders Nothing
<+> pprFundeps fds <+> pp_where
, nest 2 (vcat [ vcat asocs, vcat dsigs, pprec
, ppShowAllSubs ss (pprMinDef minDef)])]
where
pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (text "where")
asocs = ppr_trim $ map maybeShowAssoc ats
dsigs = ppr_trim $ map maybeShowSig sigs
pprec = ppShowIface ss (pprRec isrec)
maybeShowAssoc :: IfaceAT -> Maybe SDoc
maybeShowAssoc asc@(IfaceAT d _)
| showSub ss d = Just $ pprIfaceAT ss asc
| otherwise = Nothing
maybeShowSig :: IfaceClassOp -> Maybe SDoc
maybeShowSig sg
| showSub ss sg = Just $ pprIfaceClassOp ss sg
| otherwise = Nothing
pprMinDef :: BooleanFormula IfLclName -> SDoc
pprMinDef minDef = ppUnless (isTrue minDef) $ -- hide empty definitions
text "{-# MINIMAL" <+>
pprBooleanFormula
(\_ def -> cparen (isLexSym def) (ppr def)) 0 minDef <+>
text "#-}"
pprIfaceDecl ss (IfaceSynonym { ifName = tc
, ifBinders = binders
, ifSynRhs = mono_ty
, ifResKind = res_kind})
= hang (text "type" <+> pprIfaceDeclHead [] ss tc binders Nothing <+> equals)
2 (sep [ pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau
, ppUnless (isIfaceLiftedTypeKind res_kind) (dcolon <+> ppr res_kind) ])
where
(tvs, theta, tau) = splitIfaceSigmaTy mono_ty
pprIfaceDecl ss (IfaceFamily { ifName = tycon
, ifFamFlav = rhs, ifBinders = binders
, ifResKind = res_kind
, ifResVar = res_var, ifFamInj = inj })
| IfaceDataFamilyTyCon <- rhs
= text "data family" <+> pprIfaceDeclHead [] ss tycon binders Nothing
| otherwise
= hang (text "type family" <+> pprIfaceDeclHead [] ss tycon binders (Just res_kind))
2 (pp_inj res_var inj <+> ppShowRhs ss (pp_rhs rhs))
$$
nest 2 (ppShowRhs ss (pp_branches rhs))
where
pp_inj Nothing _ = empty
pp_inj (Just res) inj
| Injective injectivity <- inj = hsep [ equals, ppr res
, pp_inj_cond res injectivity]
| otherwise = hsep [ equals, ppr res ]
pp_inj_cond res inj = case filterByList inj binders of
[] -> empty
tvs -> hsep [vbar, ppr res, text "->", interppSP (map ifTyConBinderName tvs)]
pp_rhs IfaceDataFamilyTyCon
= ppShowIface ss (text "data")
pp_rhs IfaceOpenSynFamilyTyCon
= ppShowIface ss (text "open")
pp_rhs IfaceAbstractClosedSynFamilyTyCon
= ppShowIface ss (text "closed, abstract")
pp_rhs (IfaceClosedSynFamilyTyCon {})
= empty -- see pp_branches
pp_rhs IfaceBuiltInSynFamTyCon
= ppShowIface ss (text "built-in")
pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs)))
= hang (text "where")
2 (vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs)
$$ ppShowIface ss (text "axiom" <+> ppr ax))
pp_branches _ = Outputable.empty
pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder,
ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs,
ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt,
ifPatArgs = arg_tys,
ifPatTy = pat_ty} )
= pprPatSynSig name is_bidirectional
(pprUserIfaceForAll (map tv_to_forall_bndr tvs))
(pprIfaceContextMaybe req_ctxt)
(pprIfaceContextMaybe prov_ctxt)
(pprIfaceType ty)
where
is_bidirectional = isJust builder
tvs = univ_tvs ++ ex_tvs
ty = foldr IfaceFunTy pat_ty arg_tys
pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty,
ifIdDetails = details, ifIdInfo = info })
= vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon)
2 (pprIfaceSigmaType ty)
, ppShowIface ss (ppr details)
, ppShowIface ss (ppr info) ]
pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon
, ifAxBranches = branches })
= hang (text "axiom" <+> ppr name <> dcolon)
2 (vcat $ map (pprAxBranch (ppr tycon)) branches)
pprCType :: Maybe CType -> SDoc
pprCType Nothing = Outputable.empty
pprCType (Just cType) = text "C type:" <+> ppr cType
-- if, for each role, suppress_if role is True, then suppress the role
-- output
pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTyConBinder]
-> [Role] -> SDoc
pprRoles suppress_if tyCon bndrs roles
= sdocWithDynFlags $ \dflags ->
let froles = suppressIfaceInvisibles dflags bndrs roles
in ppUnless (all suppress_if roles || null froles) $
text "type role" <+> tyCon <+> hsep (map ppr froles)
pprRec :: RecFlag -> SDoc
pprRec NonRecursive = Outputable.empty
pprRec Recursive = text "RecFlag: Recursive"
pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc
pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
= pprInfixVar (isSymOcc occ) (ppr_bndr occ)
pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
= parenSymOcc occ (ppr_bndr occ)
instance Outputable IfaceClassOp where
ppr = pprIfaceClassOp showAll
pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc
pprIfaceClassOp ss (IfaceClassOp n ty dm)
= pp_sig n ty $$ generic_dm
where
generic_dm | Just (GenericDM dm_ty) <- dm
= text "default" <+> pp_sig n dm_ty
| otherwise
= empty
pp_sig n ty = pprPrefixIfDeclBndr ss n <+> dcolon <+> pprIfaceSigmaType ty
instance Outputable IfaceAT where
ppr = pprIfaceAT showAll
pprIfaceAT :: ShowSub -> IfaceAT -> SDoc
pprIfaceAT ss (IfaceAT d mb_def)
= vcat [ pprIfaceDecl ss d
, case mb_def of
Nothing -> Outputable.empty
Just rhs -> nest 2 $
text "Default:" <+> ppr rhs ]
instance Outputable IfaceTyConParent where
ppr p = pprIfaceTyConParent p
pprIfaceTyConParent :: IfaceTyConParent -> SDoc
pprIfaceTyConParent IfNoParent
= Outputable.empty
pprIfaceTyConParent (IfDataInstance _ tc tys)
= sdocWithDynFlags $ \dflags ->
let ftys = stripInvisArgs dflags tys
in pprIfaceTypeApp tc ftys
pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName
-> [IfaceTyConBinder] -- of the tycon, for invisible-suppression
-> Maybe IfaceKind
-> SDoc
pprIfaceDeclHead context ss tc_occ bndrs m_res_kind
= sdocWithDynFlags $ \ dflags ->
sep [ pprIfaceContextArr context
, pprPrefixIfDeclBndr ss tc_occ
<+> pprIfaceTyConBinders (suppressIfaceInvisibles dflags bndrs bndrs)
, maybe empty (\res_kind -> dcolon <+> pprIfaceType res_kind) m_res_kind ]
isVanillaIfaceConDecl :: IfaceConDecl -> Bool
isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs
, ifConEqSpec = eq_spec
, ifConCtxt = ctxt })
= (null ex_tvs) && (null eq_spec) && (null ctxt)
pprIfaceConDecl :: ShowSub -> Bool
-> [FieldLbl OccName]
-> IfaceTopBndr
-> [IfaceTyConBinder]
-> IfaceTyConParent
-> IfaceConDecl -> SDoc
pprIfaceConDecl ss gadt_style fls tycon tc_binders parent
(IfCon { ifConOcc = name, ifConInfix = is_infix,
ifConExTvs = ex_tvs,
ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys,
ifConStricts = stricts, ifConFields = fields })
| gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty
| not (null fields) = pp_prefix_con <+> pp_field_args
| is_infix
, [ty1, ty2] <- pp_args = sep [ty1, pprInfixIfDeclBndr ss name, ty2]
| otherwise = pp_prefix_con <+> sep pp_args
where
tys_w_strs :: [(IfaceBang, IfaceType)]
tys_w_strs = zip stricts arg_tys
pp_prefix_con = pprPrefixIfDeclBndr ss name
(univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec
ppr_ty = pprIfaceForAllPart (map tv_to_forall_bndr (univ_tvs ++ ex_tvs))
ctxt pp_tau
-- A bit gruesome this, but we can't form the full con_tau, and ppr it,
-- because we don't have a Name for the tycon, only an OccName
pp_tau | null fields
= case pp_args ++ [pp_res_ty] of
(t:ts) -> fsep (t : map (arrow <+>) ts)
[] -> panic "pp_con_taus"
| otherwise
= sep [pp_field_args, arrow <+> pp_res_ty]
ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_'
ppr_bang IfStrict = char '!'
ppr_bang IfUnpack = text "{-# UNPACK #-}"
ppr_bang (IfUnpackCo co) = text "! {-# UNPACK #-}" <>
pprParendIfaceCoercion co
pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty
pprBangTy (bang, ty) = ppr_bang bang <> ppr ty
pp_args :: [SDoc] -- With parens, e.g (Maybe a) or !(Maybe a)
pp_args = map pprParendBangTy tys_w_strs
pp_field_args :: SDoc -- Braces form: { x :: !Maybe a, y :: Int }
pp_field_args = braces $ sep $ punctuate comma $ ppr_trim $
map maybe_show_label (zip fields tys_w_strs)
maybe_show_label (sel,bty)
| showSub ss sel = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty)
| otherwise = Nothing
where
-- IfaceConDecl contains the name of the selector function, so
-- we have to look up the field label (in case
-- DuplicateRecordFields was used for the definition)
lbl = maybe sel (mkVarOccFS . flLabel) $ find (\ fl -> flSelector fl == sel) fls
mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc)
-- See Note [Result type of a data family GADT]
mk_user_con_res_ty eq_spec
| IfDataInstance _ tc tys <- parent
= (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys)))
| otherwise
= (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst))
where
gadt_subst = mkFsEnv eq_spec
done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv)
con_univ_tvs = filterOut done_univ_tv (map ifTyConBinderTyVar tc_binders)
ppr_tc_app gadt_subst dflags
= pprPrefixIfDeclBndr ss tycon
<+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv)
| (tv,_kind)
<- map ifTyConBinderTyVar $
suppressIfaceInvisibles dflags tc_binders tc_binders ]
instance Outputable IfaceRule where
ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
= sep [hsep [pprRuleName name, ppr act,
text "forall" <+> pprIfaceBndrs bndrs],
nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args),
text "=" <+> ppr rhs])
]
instance Outputable IfaceClsInst where
ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag
, ifInstCls = cls, ifInstTys = mb_tcs})
= hang (text "instance" <+> ppr flag
<+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs))
2 (equals <+> ppr dfun_id)
instance Outputable IfaceFamInst where
ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = tycon_ax})
= hang (text "family instance" <+>
ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs)
2 (equals <+> ppr tycon_ax)
ppr_rough :: Maybe IfaceTyCon -> SDoc
ppr_rough Nothing = dot
ppr_rough (Just tc) = ppr tc
tv_to_forall_bndr :: IfaceTvBndr -> IfaceForAllBndr
tv_to_forall_bndr tv = IfaceTv tv Specified
{-
Note [Result type of a data family GADT]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data family T a
data instance T (p,q) where
T1 :: T (Int, Maybe c)
T2 :: T (Bool, q)
The IfaceDecl actually looks like
data TPr p q where
T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q
T2 :: forall p q. (p~Bool) => TPr p q
To reconstruct the result types for T1 and T2 that we
want to pretty print, we substitute the eq-spec
[p->Int, q->Maybe c] in the arg pattern (p,q) to give
T (Int, Maybe c)
Remember that in IfaceSyn, the TyCon and DataCon share the same
universal type variables.
----------------------------- Printing IfaceExpr ------------------------------------
-}
instance Outputable IfaceExpr where
ppr e = pprIfaceExpr noParens e
noParens :: SDoc -> SDoc
noParens pp = pp
pprParendIfaceExpr :: IfaceExpr -> SDoc
pprParendIfaceExpr = pprIfaceExpr parens
-- | Pretty Print an IfaceExpre
--
-- The first argument should be a function that adds parens in context that need
-- an atomic value (e.g. function args)
pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
pprIfaceExpr _ (IfaceLcl v) = ppr v
pprIfaceExpr _ (IfaceExt v) = ppr v
pprIfaceExpr _ (IfaceLit l) = ppr l
pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty
pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co
pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (pprWithCommas ppr as)
pprIfaceExpr add_par i@(IfaceLam _ _)
= add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow,
pprIfaceExpr noParens body])
where
(bndrs,body) = collect [] i
collect bs (IfaceLam b e) = collect (b:bs) e
collect bs e = (reverse bs, e)
pprIfaceExpr add_par (IfaceECase scrut ty)
= add_par (sep [ text "case" <+> pprIfaceExpr noParens scrut
, text "ret_ty" <+> pprParendIfaceType ty
, text "of {}" ])
pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)])
= add_par (sep [text "case"
<+> pprIfaceExpr noParens scrut <+> text "of"
<+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
pprIfaceExpr noParens rhs <+> char '}'])
pprIfaceExpr add_par (IfaceCase scrut bndr alts)
= add_par (sep [text "case"
<+> pprIfaceExpr noParens scrut <+> text "of"
<+> ppr bndr <+> char '{',
nest 2 (sep (map ppr_alt alts)) <+> char '}'])
pprIfaceExpr _ (IfaceCast expr co)
= sep [pprParendIfaceExpr expr,
nest 2 (text "`cast`"),
pprParendIfaceCoercion co]
pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
= add_par (sep [text "let {",
nest 2 (ppr_bind (b, rhs)),
text "} in",
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
= add_par (sep [text "letrec {",
nest 2 (sep (map ppr_bind pairs)),
text "} in",
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceTick tickish e)
= add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e)
ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc
ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs,
arrow <+> pprIfaceExpr noParens rhs]
ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc
ppr_con_bs con bs = ppr con <+> hsep (map ppr bs)
ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc
ppr_bind (IfLetBndr b ty info, rhs)
= sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info),
equals <+> pprIfaceExpr noParens rhs]
------------------
pprIfaceTickish :: IfaceTickish -> SDoc
pprIfaceTickish (IfaceHpcTick m ix)
= braces (text "tick" <+> ppr m <+> ppr ix)
pprIfaceTickish (IfaceSCC cc tick scope)
= braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope)
pprIfaceTickish (IfaceSource src _names)
= braces (pprUserRealSpan True src)
------------------
pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc
pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $
nest 2 (pprParendIfaceExpr arg) : args
pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args)
------------------
instance Outputable IfaceConAlt where
ppr IfaceDefault = text "DEFAULT"
ppr (IfaceLitAlt l) = ppr l
ppr (IfaceDataAlt d) = ppr d
------------------
instance Outputable IfaceIdDetails where
ppr IfVanillaId = Outputable.empty
ppr (IfRecSelId tc b) = text "RecSel" <+> ppr tc
<+> if b
then text "<naughty>"
else Outputable.empty
ppr IfDFunId = text "DFunId"
instance Outputable IfaceIdInfo where
ppr NoInfo = Outputable.empty
ppr (HasInfo is) = text "{-" <+> pprWithCommas ppr is
<+> text "-}"
instance Outputable IfaceInfoItem where
ppr (HsUnfold lb unf) = text "Unfolding"
<> ppWhen lb (text "(loop-breaker)")
<> colon <+> ppr unf
ppr (HsInline prag) = text "Inline:" <+> ppr prag
ppr (HsArity arity) = text "Arity:" <+> int arity
ppr (HsStrictness str) = text "Strictness:" <+> pprIfaceStrictSig str
ppr HsNoCafRefs = text "HasNoCafRefs"
instance Outputable IfaceUnfolding where
ppr (IfCompulsory e) = text "<compulsory>" <+> parens (ppr e)
ppr (IfCoreUnfold s e) = (if s
then text "<stable>"
else Outputable.empty)
<+> parens (ppr e)
ppr (IfInlineRule a uok bok e) = sep [text "InlineRule"
<+> ppr (a,uok,bok),
pprParendIfaceExpr e]
ppr (IfDFunUnfold bs es) = hang (text "DFun:" <+> sep (map ppr bs) <> dot)
2 (sep (map pprParendIfaceExpr es))
{-
************************************************************************
* *
Finding the Names in IfaceSyn
* *
************************************************************************
This is used for dependency analysis in MkIface, so that we
fingerprint a declaration before the things that depend on it. It
is specific to interface-file fingerprinting in the sense that we
don't collect *all* Names: for example, the DFun of an instance is
recorded textually rather than by its fingerprint when
fingerprinting the instance, so DFuns are not dependencies.
-}
freeNamesIfDecl :: IfaceDecl -> NameSet
freeNamesIfDecl (IfaceId _s t d i) =
freeNamesIfType t &&&
freeNamesIfIdInfo i &&&
freeNamesIfIdDetails d
freeNamesIfDecl d@IfaceData{} =
freeNamesIfTyBinders (ifBinders d) &&&
freeNamesIfType (ifResKind d) &&&
freeNamesIfaceTyConParent (ifParent d) &&&
freeNamesIfContext (ifCtxt d) &&&
freeNamesIfConDecls (ifCons d)
freeNamesIfDecl d@IfaceSynonym{} =
freeNamesIfType (ifSynRhs d) &&&
freeNamesIfTyBinders (ifBinders d) &&&
freeNamesIfKind (ifResKind d)
freeNamesIfDecl d@IfaceFamily{} =
freeNamesIfFamFlav (ifFamFlav d) &&&
freeNamesIfTyBinders (ifBinders d) &&&
freeNamesIfKind (ifResKind d)
freeNamesIfDecl d@IfaceClass{} =
freeNamesIfContext (ifCtxt d) &&&
freeNamesIfTyBinders (ifBinders d) &&&
fnList freeNamesIfAT (ifATs d) &&&
fnList freeNamesIfClsSig (ifSigs d)
freeNamesIfDecl d@IfaceAxiom{} =
freeNamesIfTc (ifTyCon d) &&&
fnList freeNamesIfAxBranch (ifAxBranches d)
freeNamesIfDecl d@IfacePatSyn{} =
unitNameSet (fst (ifPatMatcher d)) &&&
maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&&
freeNamesIfTvBndrs (ifPatUnivTvs d) &&&
freeNamesIfTvBndrs (ifPatExTvs d) &&&
freeNamesIfContext (ifPatProvCtxt d) &&&
freeNamesIfContext (ifPatReqCtxt d) &&&
fnList freeNamesIfType (ifPatArgs d) &&&
freeNamesIfType (ifPatTy d) &&&
mkNameSet (map flSelector (ifFieldLabels d))
freeNamesIfAxBranch :: IfaceAxBranch -> NameSet
freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars
, ifaxbCoVars = covars
, ifaxbLHS = lhs
, ifaxbRHS = rhs }) =
freeNamesIfTvBndrs tyvars &&&
fnList freeNamesIfIdBndr covars &&&
freeNamesIfTcArgs lhs &&&
freeNamesIfType rhs
freeNamesIfIdDetails :: IfaceIdDetails -> NameSet
freeNamesIfIdDetails (IfRecSelId tc _) =
either freeNamesIfTc freeNamesIfDecl tc
freeNamesIfIdDetails _ = emptyNameSet
-- All other changes are handled via the version info on the tycon
freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet
freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav IfaceDataFamilyTyCon = emptyNameSet
freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon (Just (ax, br)))
= unitNameSet ax &&& fnList freeNamesIfAxBranch br
freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon Nothing) = emptyNameSet
freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet
freeNamesIfContext :: IfaceContext -> NameSet
freeNamesIfContext = fnList freeNamesIfType
freeNamesIfAT :: IfaceAT -> NameSet
freeNamesIfAT (IfaceAT decl mb_def)
= freeNamesIfDecl decl &&&
case mb_def of
Nothing -> emptyNameSet
Just rhs -> freeNamesIfType rhs
freeNamesIfClsSig :: IfaceClassOp -> NameSet
freeNamesIfClsSig (IfaceClassOp _n ty dm) = freeNamesIfType ty &&& freeNamesDM dm
freeNamesDM :: Maybe (DefMethSpec IfaceType) -> NameSet
freeNamesDM (Just (GenericDM ty)) = freeNamesIfType ty
freeNamesDM _ = emptyNameSet
freeNamesIfConDecls :: IfaceConDecls -> NameSet
freeNamesIfConDecls (IfDataTyCon c _ _) = fnList freeNamesIfConDecl c
freeNamesIfConDecls (IfNewTyCon c _ _) = freeNamesIfConDecl c
freeNamesIfConDecls _ = emptyNameSet
freeNamesIfConDecl :: IfaceConDecl -> NameSet
freeNamesIfConDecl c
= freeNamesIfTvBndrs (ifConExTvs c) &&&
freeNamesIfContext (ifConCtxt c) &&&
fnList freeNamesIfType (ifConArgTys c) &&&
fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints
freeNamesIfKind :: IfaceType -> NameSet
freeNamesIfKind = freeNamesIfType
freeNamesIfTcArgs :: IfaceTcArgs -> NameSet
freeNamesIfTcArgs (ITC_Vis t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts
freeNamesIfTcArgs (ITC_Invis k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks
freeNamesIfTcArgs ITC_Nil = emptyNameSet
freeNamesIfType :: IfaceType -> NameSet
freeNamesIfType (IfaceTyVar _) = emptyNameSet
freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfTcArgs ts
freeNamesIfType (IfaceTupleTy _ _ ts) = freeNamesIfTcArgs ts
freeNamesIfType (IfaceLitTy _) = emptyNameSet
freeNamesIfType (IfaceForAllTy tv t) =
freeNamesIfForAllBndr tv &&& freeNamesIfType t
freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceCastTy t c) = freeNamesIfType t &&& freeNamesIfCoercion c
freeNamesIfType (IfaceCoercionTy c) = freeNamesIfCoercion c
freeNamesIfCoercion :: IfaceCoercion -> NameSet
freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t
freeNamesIfCoercion (IfaceFunCo _ c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceTyConAppCo _ tc cos)
= freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceAppCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceForAllCo _ kind_co co)
= freeNamesIfCoercion kind_co &&& freeNamesIfCoercion co
freeNamesIfCoercion (IfaceCoVarCo _)
= emptyNameSet
freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos)
= unitNameSet ax &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceUnivCo p _ t1 t2)
= freeNamesIfProv p &&& freeNamesIfType t1 &&& freeNamesIfType t2
freeNamesIfCoercion (IfaceSymCo c)
= freeNamesIfCoercion c
freeNamesIfCoercion (IfaceTransCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceNthCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceLRCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceInstCo co co2)
= freeNamesIfCoercion co &&& freeNamesIfCoercion co2
freeNamesIfCoercion (IfaceCoherenceCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceKindCo c)
= freeNamesIfCoercion c
freeNamesIfCoercion (IfaceSubCo co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceAxiomRuleCo _ax cos)
-- the axiom is just a string, so we don't count it as a name.
= fnList freeNamesIfCoercion cos
freeNamesIfProv :: IfaceUnivCoProv -> NameSet
freeNamesIfProv IfaceUnsafeCoerceProv = emptyNameSet
freeNamesIfProv (IfacePhantomProv co) = freeNamesIfCoercion co
freeNamesIfProv (IfaceProofIrrelProv co) = freeNamesIfCoercion co
freeNamesIfProv (IfacePluginProv _) = emptyNameSet
freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet
freeNamesIfTvBndrs = fnList freeNamesIfTvBndr
freeNamesIfForAllBndr :: IfaceForAllBndr -> NameSet
freeNamesIfForAllBndr (IfaceTv tv _) = freeNamesIfTvBndr tv
freeNamesIfTyBinder :: IfaceTyConBinder -> NameSet
freeNamesIfTyBinder (IfaceAnon _ ty) = freeNamesIfType ty
freeNamesIfTyBinder (IfaceNamed b) = freeNamesIfForAllBndr b
freeNamesIfTyBinders :: [IfaceTyConBinder] -> NameSet
freeNamesIfTyBinders = fnList freeNamesIfTyBinder
freeNamesIfBndr :: IfaceBndr -> NameSet
freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b
freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b
freeNamesIfBndrs :: [IfaceBndr] -> NameSet
freeNamesIfBndrs = fnList freeNamesIfBndr
freeNamesIfLetBndr :: IfaceLetBndr -> NameSet
-- Remember IfaceLetBndr is used only for *nested* bindings
-- The IdInfo can contain an unfolding (in the case of
-- local INLINE pragmas), so look there too
freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty
&&& freeNamesIfIdInfo info
freeNamesIfTvBndr :: IfaceTvBndr -> NameSet
freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k
-- kinds can have Names inside, because of promotion
freeNamesIfIdBndr :: IfaceIdBndr -> NameSet
freeNamesIfIdBndr (_fs,k) = freeNamesIfKind k
freeNamesIfIdInfo :: IfaceIdInfo -> NameSet
freeNamesIfIdInfo NoInfo = emptyNameSet
freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i
freeNamesItem :: IfaceInfoItem -> NameSet
freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u
freeNamesItem _ = emptyNameSet
freeNamesIfUnfold :: IfaceUnfolding -> NameSet
freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e
freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfDFunUnfold bs es) = freeNamesIfBndrs bs &&& fnList freeNamesIfExpr es
freeNamesIfExpr :: IfaceExpr -> NameSet
freeNamesIfExpr (IfaceExt v) = unitNameSet v
freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co
freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as
freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a
freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co
freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e
freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty
freeNamesIfExpr (IfaceCase s _ alts)
= freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts
where
fn_alt (_con,_bs,r) = freeNamesIfExpr r
-- Depend on the data constructors. Just one will do!
-- Note [Tracking data constructors]
fn_cons [] = emptyNameSet
fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs
fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con
fn_cons (_ : _ ) = emptyNameSet
freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body)
= freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceLet (IfaceRec as) x)
= fnList fn_pair as &&& freeNamesIfExpr x
where
fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs
freeNamesIfExpr _ = emptyNameSet
freeNamesIfTc :: IfaceTyCon -> NameSet
freeNamesIfTc tc = unitNameSet (ifaceTyConName tc)
-- ToDo: shouldn't we include IfaceIntTc & co.?
freeNamesIfRule :: IfaceRule -> NameSet
freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f
, ifRuleArgs = es, ifRuleRhs = rhs })
= unitNameSet f &&&
fnList freeNamesIfBndr bs &&&
fnList freeNamesIfExpr es &&&
freeNamesIfExpr rhs
freeNamesIfFamInst :: IfaceFamInst -> NameSet
freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName
, ifFamInstAxiom = axName })
= unitNameSet famName &&&
unitNameSet axName
freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet
freeNamesIfaceTyConParent IfNoParent = emptyNameSet
freeNamesIfaceTyConParent (IfDataInstance ax tc tys)
= unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys
-- helpers
(&&&) :: NameSet -> NameSet -> NameSet
(&&&) = unionNameSet
fnList :: (a -> NameSet) -> [a] -> NameSet
fnList f = foldr (&&&) emptyNameSet . map f
{-
Note [Tracking data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a case expression
case e of { C a -> ...; ... }
You might think that we don't need to include the datacon C
in the free names, because its type will probably show up in
the free names of 'e'. But in rare circumstances this may
not happen. Here's the one that bit me:
module DynFlags where
import {-# SOURCE #-} Packages( PackageState )
data DynFlags = DF ... PackageState ...
module Packages where
import DynFlags
data PackageState = PS ...
lookupModule (df :: DynFlags)
= case df of
DF ...p... -> case p of
PS ... -> ...
Now, lookupModule depends on DynFlags, but the transitive dependency
on the *locally-defined* type PackageState is not visible. We need
to take account of the use of the data constructor PS in the pattern match.
************************************************************************
* *
Binary instances
* *
************************************************************************
-}
instance Binary IfaceDecl where
put_ bh (IfaceId name ty details idinfo) = do
putByte bh 0
put_ bh (occNameFS name)
put_ bh ty
put_ bh details
put_ bh idinfo
put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do
putByte bh 2
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do
putByte bh 3
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh (IfaceFamily a1 a2 a3 a4 a5 a6) = do
putByte bh 4
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do
putByte bh 5
put_ bh a1
put_ bh (occNameFS a2)
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh (IfaceAxiom a1 a2 a3 a4) = do
putByte bh 6
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10 a11) = do
putByte bh 7
put_ bh (occNameFS name)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
put_ bh a11
get bh = do
h <- getByte bh
case h of
0 -> do name <- get bh
ty <- get bh
details <- get bh
idinfo <- get bh
occ <- return $! mkVarOccFS name
return (IfaceId occ ty details idinfo)
1 -> error "Binary.get(TyClDecl): ForeignType"
2 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10)
3 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceSynonym occ a2 a3 a4 a5)
4 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceFamily occ a2 a3 a4 a5 a6)
5 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
occ <- return $! mkClsOccFS a2
return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9)
6 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceAxiom occ a2 a3 a4)
7 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
a11 <- get bh
occ <- return $! mkDataOccFS a1
return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10 a11)
_ -> panic (unwords ["Unknown IfaceDecl tag:", show h])
instance Binary IfaceFamTyConFlav where
put_ bh IfaceDataFamilyTyCon = putByte bh 0
put_ bh IfaceOpenSynFamilyTyCon = putByte bh 1
put_ bh (IfaceClosedSynFamilyTyCon mb) = putByte bh 2 >> put_ bh mb
put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 3
put_ _ IfaceBuiltInSynFamTyCon
= pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty
get bh = do { h <- getByte bh
; case h of
0 -> return IfaceDataFamilyTyCon
1 -> return IfaceOpenSynFamilyTyCon
2 -> do { mb <- get bh
; return (IfaceClosedSynFamilyTyCon mb) }
3 -> return IfaceAbstractClosedSynFamilyTyCon
_ -> pprPanic "Binary.get(IfaceFamTyConFlav): Invalid tag"
(ppr (fromIntegral h :: Int)) }
instance Binary IfaceClassOp where
put_ bh (IfaceClassOp n ty def) = do
put_ bh (occNameFS n)
put_ bh ty
put_ bh def
get bh = do
n <- get bh
ty <- get bh
def <- get bh
occ <- return $! mkVarOccFS n
return (IfaceClassOp occ ty def)
instance Binary IfaceAT where
put_ bh (IfaceAT dec defs) = do
put_ bh dec
put_ bh defs
get bh = do
dec <- get bh
defs <- get bh
return (IfaceAT dec defs)
instance Binary IfaceAxBranch where
put_ bh (IfaceAxBranch a1 a2 a3 a4 a5 a6) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
return (IfaceAxBranch a1 a2 a3 a4 a5 a6)
instance Binary IfaceConDecls where
put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d
put_ bh (IfDataTyCon cs b fs) = putByte bh 1 >> put_ bh cs >> put_ bh b >> put_ bh fs
put_ bh (IfNewTyCon c b fs) = putByte bh 2 >> put_ bh c >> put_ bh b >> put_ bh fs
get bh = do
h <- getByte bh
case h of
0 -> liftM IfAbstractTyCon $ get bh
1 -> liftM3 IfDataTyCon (get bh) (get bh) (get bh)
2 -> liftM3 IfNewTyCon (get bh) (get bh) (get bh)
_ -> error "Binary(IfaceConDecls).get: Invalid IfaceConDecls"
instance Binary IfaceConDecl where
put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10)
instance Binary IfaceBang where
put_ bh IfNoBang = putByte bh 0
put_ bh IfStrict = putByte bh 1
put_ bh IfUnpack = putByte bh 2
put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co
get bh = do
h <- getByte bh
case h of
0 -> do return IfNoBang
1 -> do return IfStrict
2 -> do return IfUnpack
_ -> do { a <- get bh; return (IfUnpackCo a) }
instance Binary IfaceSrcBang where
put_ bh (IfSrcBang a1 a2) =
do put_ bh a1
put_ bh a2
get bh =
do a1 <- get bh
a2 <- get bh
return (IfSrcBang a1 a2)
instance Binary IfaceClsInst where
put_ bh (IfaceClsInst cls tys dfun flag orph) = do
put_ bh cls
put_ bh tys
put_ bh dfun
put_ bh flag
put_ bh orph
get bh = do
cls <- get bh
tys <- get bh
dfun <- get bh
flag <- get bh
orph <- get bh
return (IfaceClsInst cls tys dfun flag orph)
instance Binary IfaceFamInst where
put_ bh (IfaceFamInst fam tys name orph) = do
put_ bh fam
put_ bh tys
put_ bh name
put_ bh orph
get bh = do
fam <- get bh
tys <- get bh
name <- get bh
orph <- get bh
return (IfaceFamInst fam tys name orph)
instance Binary IfaceRule where
put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8)
instance Binary IfaceAnnotation where
put_ bh (IfaceAnnotation a1 a2) = do
put_ bh a1
put_ bh a2
get bh = do
a1 <- get bh
a2 <- get bh
return (IfaceAnnotation a1 a2)
instance Binary IfaceIdDetails where
put_ bh IfVanillaId = putByte bh 0
put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b
put_ bh IfDFunId = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> return IfVanillaId
1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) }
_ -> return IfDFunId
instance Binary IfaceIdInfo where
put_ bh NoInfo = putByte bh 0
put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut
get bh = do
h <- getByte bh
case h of
0 -> return NoInfo
_ -> liftM HasInfo $ lazyGet bh -- NB lazyGet
instance Binary IfaceInfoItem where
put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa
put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab
put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad
put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad
put_ bh HsNoCafRefs = putByte bh 4
get bh = do
h <- getByte bh
case h of
0 -> liftM HsArity $ get bh
1 -> liftM HsStrictness $ get bh
2 -> do lb <- get bh
ad <- get bh
return (HsUnfold lb ad)
3 -> liftM HsInline $ get bh
_ -> return HsNoCafRefs
instance Binary IfaceUnfolding where
put_ bh (IfCoreUnfold s e) = do
putByte bh 0
put_ bh s
put_ bh e
put_ bh (IfInlineRule a b c d) = do
putByte bh 1
put_ bh a
put_ bh b
put_ bh c
put_ bh d
put_ bh (IfDFunUnfold as bs) = do
putByte bh 2
put_ bh as
put_ bh bs
put_ bh (IfCompulsory e) = do
putByte bh 3
put_ bh e
get bh = do
h <- getByte bh
case h of
0 -> do s <- get bh
e <- get bh
return (IfCoreUnfold s e)
1 -> do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (IfInlineRule a b c d)
2 -> do as <- get bh
bs <- get bh
return (IfDFunUnfold as bs)
_ -> do e <- get bh
return (IfCompulsory e)
instance Binary IfaceExpr where
put_ bh (IfaceLcl aa) = do
putByte bh 0
put_ bh aa
put_ bh (IfaceType ab) = do
putByte bh 1
put_ bh ab
put_ bh (IfaceCo ab) = do
putByte bh 2
put_ bh ab
put_ bh (IfaceTuple ac ad) = do
putByte bh 3
put_ bh ac
put_ bh ad
put_ bh (IfaceLam (ae, os) af) = do
putByte bh 4
put_ bh ae
put_ bh os
put_ bh af
put_ bh (IfaceApp ag ah) = do
putByte bh 5
put_ bh ag
put_ bh ah
put_ bh (IfaceCase ai aj ak) = do
putByte bh 6
put_ bh ai
put_ bh aj
put_ bh ak
put_ bh (IfaceLet al am) = do
putByte bh 7
put_ bh al
put_ bh am
put_ bh (IfaceTick an ao) = do
putByte bh 8
put_ bh an
put_ bh ao
put_ bh (IfaceLit ap) = do
putByte bh 9
put_ bh ap
put_ bh (IfaceFCall as at) = do
putByte bh 10
put_ bh as
put_ bh at
put_ bh (IfaceExt aa) = do
putByte bh 11
put_ bh aa
put_ bh (IfaceCast ie ico) = do
putByte bh 12
put_ bh ie
put_ bh ico
put_ bh (IfaceECase a b) = do
putByte bh 13
put_ bh a
put_ bh b
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (IfaceLcl aa)
1 -> do ab <- get bh
return (IfaceType ab)
2 -> do ab <- get bh
return (IfaceCo ab)
3 -> do ac <- get bh
ad <- get bh
return (IfaceTuple ac ad)
4 -> do ae <- get bh
os <- get bh
af <- get bh
return (IfaceLam (ae, os) af)
5 -> do ag <- get bh
ah <- get bh
return (IfaceApp ag ah)
6 -> do ai <- get bh
aj <- get bh
ak <- get bh
return (IfaceCase ai aj ak)
7 -> do al <- get bh
am <- get bh
return (IfaceLet al am)
8 -> do an <- get bh
ao <- get bh
return (IfaceTick an ao)
9 -> do ap <- get bh
return (IfaceLit ap)
10 -> do as <- get bh
at <- get bh
return (IfaceFCall as at)
11 -> do aa <- get bh
return (IfaceExt aa)
12 -> do ie <- get bh
ico <- get bh
return (IfaceCast ie ico)
13 -> do a <- get bh
b <- get bh
return (IfaceECase a b)
_ -> panic ("get IfaceExpr " ++ show h)
instance Binary IfaceTickish where
put_ bh (IfaceHpcTick m ix) = do
putByte bh 0
put_ bh m
put_ bh ix
put_ bh (IfaceSCC cc tick push) = do
putByte bh 1
put_ bh cc
put_ bh tick
put_ bh push
put_ bh (IfaceSource src name) = do
putByte bh 2
put_ bh (srcSpanFile src)
put_ bh (srcSpanStartLine src)
put_ bh (srcSpanStartCol src)
put_ bh (srcSpanEndLine src)
put_ bh (srcSpanEndCol src)
put_ bh name
get bh = do
h <- getByte bh
case h of
0 -> do m <- get bh
ix <- get bh
return (IfaceHpcTick m ix)
1 -> do cc <- get bh
tick <- get bh
push <- get bh
return (IfaceSCC cc tick push)
2 -> do file <- get bh
sl <- get bh
sc <- get bh
el <- get bh
ec <- get bh
let start = mkRealSrcLoc file sl sc
end = mkRealSrcLoc file el ec
name <- get bh
return (IfaceSource (mkRealSrcSpan start end) name)
_ -> panic ("get IfaceTickish " ++ show h)
instance Binary IfaceConAlt where
put_ bh IfaceDefault = putByte bh 0
put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa
put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> return IfaceDefault
1 -> liftM IfaceDataAlt $ get bh
_ -> liftM IfaceLitAlt $ get bh
instance Binary IfaceBinding where
put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab
put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) }
_ -> do { ac <- get bh; return (IfaceRec ac) }
instance Binary IfaceLetBndr where
put_ bh (IfLetBndr 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 (IfLetBndr a b c)
instance Binary IfaceTyConParent where
put_ bh IfNoParent = putByte bh 0
put_ bh (IfDataInstance ax pr ty) = do
putByte bh 1
put_ bh ax
put_ bh pr
put_ bh ty
get bh = do
h <- getByte bh
case h of
0 -> return IfNoParent
_ -> do
ax <- get bh
pr <- get bh
ty <- get bh
return $ IfDataInstance ax pr ty
| oldmanmike/ghc | compiler/iface/IfaceSyn.hs | bsd-3-clause | 76,590 | 77 | 29 | 25,263 | 18,716 | 9,314 | 9,402 | 1,467 | 12 |
module Numerical.HBLAS.Lapack.FFI where
import Foreign.Ptr
import Foreign()
import Foreign.C.Types
import Data.Complex
import Data.Int
{-?ges
-}
{-
stylenote: we will not use the LAPACKE_* operations, only the
LAPACKE_*_work variants that require an explicitly provided work buffer.
This is to ensure that solver routine allocation behavior is transparent
-}
{-
void LAPACK_dgesvx( char* fact, char* trans, lapack_int* n, lapack_int* nrhs,
double* a, lapack_int* lda, double* af, lapack_int* ldaf,
lapack_int* ipiv, char* equed, double* r, double* c,
double* b, lapack_int* ldb, double* x, lapack_int* ldx,
double* rcond, double* ferr, double* berr, double* work,
lapack_int* iwork, lapack_int *info );
-}
{-
fortran FFI conventions!
-}
--type Stride_C =
newtype JobTy = JBT CChar
newtype UploTy = UPLT CChar
newtype Info = Info Int32
newtype Fact_C = Fact_C CChar
newtype Trans_C = Trans_C CChar
newtype Stride_C = Stride_C Int32
newtype Equilib_C = Equilib_C CChar
type Fun_FFI_GESVX el = Ptr Fact_C {- fact -}-> Ptr Trans_C {- trans -}
-> Ptr Int32 {-n -}-> Ptr Int32 {- NRHS -}->
Ptr el {- a -} -> Ptr Stride_C {- lda -} -> Ptr Double {- af -} -> Ptr Stride_C {- ldf-}->
Ptr Int32 -> Ptr Equilib_C {- equed -} -> Ptr el {- r -} -> Ptr el ->
Ptr el {- b -} -> Ptr Stride_C {- ld b -} -> Ptr el {- x -} -> Ptr Stride_C {- ldx -}->
Ptr el {-rcond -}-> Ptr el {- ferr-} -> Ptr el {-berr-} -> Ptr el {-work-}->
Ptr Int32 {-iwork -}-> Ptr Info {-info -} -> IO ()
{-
the prefixes mean s=single,d=double,c=complex float,d=complex double
fact will be a 1 character C string
either
"F", then the inputs af and ipiv already contain the permuted LU factorization
(act as input rather than result params)
"E", Matrix input A will be equilibriated if needed, then copied to AF and Factored
"N", matrix input A will be copied to AF
-}
{-
im assuming for now that any real use of *gesvx routines, or any other
n^3 complexity algs from LAPACK, are on inputs typically n>=15, which means > 1000 flops,
which is > 1µs, and thus ok to always use the Safe FFI convention
-}
--need to get around to wrapping these, but thats for another day
foreign import ccall "sgesvx_" sgesvx :: Fun_FFI_GESVX Float
foreign import ccall "dgesvx_" dgesvx :: Fun_FFI_GESVX Double
foreign import ccall "cgesvx_" cgesvx :: Fun_FFI_GESVX (Complex Float)
foreign import ccall "zgesvx_" zgesvx :: Fun_FFI_GESVX (Complex Double)
--lapack_int ?syev_( char *jobz, char *uplo, lapack_int *n, ?* a, lapack_int * lda, ?* w );
-- ? is Double or Float
--basic symmetric eigen value solvers
type SYEV_FUN_FFI elem = Ptr JobTy -> Ptr UploTy -> Ptr Int32 -> Ptr elem -> Ptr Int32 -> Ptr elem -> Ptr Info-> IO ()
foreign import ccall "ssyev_" ssyev_ffi :: SYEV_FUN_FFI Float
foreign import ccall "dsyev_" dsyev_ffi :: SYEV_FUN_FFI Double
{-unsafe versions of lapack routines are meant to ONLY be used for workspace queries-}
foreign import ccall unsafe "ssyev_" ssyev_ffi_unsafe :: SYEV_FUN_FFI Float
foreign import ccall unsafe "dsyev_" dsyev_ffi_unsafe :: SYEV_FUN_FFI Double
--lapack_int LAPACKE_<?>gesv( int matrix_order, lapack_int n, lapack_int nrhs, <datatype>* a, lapack_int lda, lapack_int* ipiv, <datatype>* b, lapack_int ldb );
--call sgesv( n, nrhs, a, lda, ipiv, b, ldb, info )
type GESV_FUN_FFI elem = Ptr Int32 {- n -} -> Ptr Int32 {- nrhs -} -> Ptr elem {- a -}
-> Ptr Int32 {- lda -} -> Ptr Int32 {- permutation vector -}
-> Ptr elem {- b -} -> Ptr Int32 {- ldb -} -> Ptr Info -> IO ()
-- | basic Linear system solvers. they act inplace
foreign import ccall "sgesv_" sgesv_ffi ::GESV_FUN_FFI Float
foreign import ccall "dgesv_" dgesv_ffi :: GESV_FUN_FFI Double
foreign import ccall "cgesv_" cgesv_ffi :: GESV_FUN_FFI (Complex Float)
foreign import ccall "zgesv_" zgesv_ffi :: GESV_FUN_FFI (Complex Double)
-- / not sure if linear solvers ever are run in < 1 microsecond size instances in practice
foreign import ccall unsafe "sgesv_" sgesv_ffi_unsafe ::GESV_FUN_FFI Float
foreign import ccall unsafe "dgesv_" dgesv_ffi_unsafe :: GESV_FUN_FFI Double
foreign import ccall unsafe "cgesv_" cgesv_ffi_unsafe :: GESV_FUN_FFI (Complex Float)
foreign import ccall unsafe "zgesv_" zgesv_ffi_unsafe :: GESV_FUN_FFI (Complex Double)
{- only provide -}
| wellposed/hblas | src/Numerical/HBLAS/Lapack/FFI.hs | bsd-3-clause | 4,460 | 0 | 28 | 942 | 718 | 386 | 332 | 40 | 0 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
--
-- Module : Venue
-- Copyright : Copyright © 2014, Quixoftic, LLC <src@quixoftic.com>
-- License : BSD3 (see LICENSE file)
-- Maintainer : dhess-src@quixoftic.com
-- Stability : experimental
-- Portability : GHC
--
-- SXSW music venue representation.
--
module Venue (Venue(..)) where
import Data.Maybe
import Data.Data (Data, Typeable)
import qualified Data.Text.Lazy as T
import GHC.Generics
import Data.Aeson
data Venue = Venue { name :: T.Text
, address :: Maybe T.Text
} deriving (Show, Data, Typeable, Generic)
instance ToJSON Venue
instance FromJSON Venue
| quixoftic/Sxcrape | src/Venue.hs | bsd-3-clause | 675 | 0 | 10 | 146 | 122 | 76 | 46 | 12 | 0 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DuplicateRecordFields #-}
module GameState where
import GHC.Generics
import Data.Aeson
import Data.Aeson.Types
import Data.Graph.Inductive.Graph as G
import Data.Graph.Inductive.PatriciaTree
import Protocol
import NormTypes
data GameState = GameState
{ gs_punter :: Int
, gs_punters :: Int
, gs_mines :: [Node]
, gs_map :: Gr SiteLabel RiverLabel
, gs_submaps :: [Gr SiteLabel RiverLabel]
} deriving (Generic, Show)
type SiteLabel = ()
type RiverLabel = ()
initGameState :: Setup -> GameState
initGameState (Setup spunter spunters smap _setting) = GameState
{ gs_punter = spunter
, gs_punters = spunters
, gs_mines = mineList smap
, gs_map = inigraph smap
, gs_submaps = Prelude.replicate spunters G.empty
}
inigraph :: Map -> Gr SiteLabel RiverLabel
inigraph (Map ss rs _) = mkGraph (Prelude.map (lnode . deSite) ss) (Prelude.map (ledge () . deNRiver . toNRiver) rs)
mineList :: Map -> [Node]
mineList (Map _ _ ms) = ms
deSite :: Site -> SiteId
deSite (Site i) = i
lnode :: SiteId -> LNode SiteLabel
lnode i = (i,())
ledge :: RiverLabel -> (SiteId, SiteId) -> LEdge RiverLabel
ledge lb (s,t) = (s,t,lb)
instance ToJSON GameState where
toJSON = genericToJSON (defaultOptions { fieldLabelModifier = Prelude.drop 3 })
instance FromJSON GameState where
parseJSON = genericParseJSON (defaultOptions { fieldLabelModifier = ("gs_" ++) })
instance (ToJSON a, ToJSON b) => ToJSON (Gr a b) where
toJSON g = object ["nodes" .= nodes g, "edges" .= edges g]
instance (FromJSON a, FromJSON b) => FromJSON (Gr a b) where
parseJSON (Object v) = mkGraph <$> v .: "nodes" <*> v .: "edges"
parseJSON _ = return G.empty
| nobsun/icfpc2017 | hs/src/GameState.hs | bsd-3-clause | 1,778 | 0 | 12 | 326 | 611 | 337 | 274 | 47 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
module Hint.Compat
where
#if __GLASGOW_HASKELL__ < 702
import Control.Monad.Trans (liftIO)
#endif
#if __GLASGOW_HASKELL__ >= 704
import Control.Monad (foldM, liftM)
#endif
import qualified Hint.GHC as GHC
-- Kinds became a synonym for Type in GHC 6.8. We define this wrapper
-- to be able to define a FromGhcRep instance for both versions
newtype Kind = Kind GHC.Kind
#if __GLASGOW_HASKELL__ >= 700
-- supportedLanguages :: [String]
supportedExtensions = map f GHC.xFlags
where
#if (__GLASGOW_HASKELL__ >= 710)
f = GHC.flagSpecName
#elif (__GLASGOW_HASKELL__ < 702) || (__GLASGOW_HASKELL__ >= 704)
f (e,_,_) = e
#else
f (e,_,_,_) = e
#endif
#if __GLASGOW_HASKELL__ < 702
-- setContext :: GHC.GhcMonad m => [GHC.Module] -> [GHC.Module] -> m ()
setContext xs = GHC.setContext xs . map (\y -> (y,Nothing))
getContext :: GHC.GhcMonad m => m ([GHC.Module], [GHC.Module])
getContext = fmap (\(as,bs) -> (as,map fst bs)) GHC.getContext
#elif __GLASGOW_HASKELL__ < 704
-- Keep setContext/getContext unmodified for use where the results of getContext
-- are simply restored by setContext, in which case we don't really care about the
-- particular type of b.
-- setContext :: GHC.GhcMonad m => [GHC.Module] -> [b] -> m ()
setContext = GHC.setContext
-- getContext :: GHC.GhcMonad m => m ([GHC.Module], [b])
getContext = GHC.getContext
#else
setContext :: GHC.GhcMonad m => [GHC.Module] -> [GHC.ImportDecl GHC.RdrName] -> m ()
setContext ms ds =
let ms' = map modToIIMod ms
ds' = map GHC.IIDecl ds
is = ms' ++ ds'
in GHC.setContext is
getContext :: GHC.GhcMonad m => m ([GHC.Module], [GHC.ImportDecl GHC.RdrName])
getContext = GHC.getContext >>= foldM f ([], [])
where
f :: (GHC.GhcMonad m) =>
([GHC.Module], [GHC.ImportDecl GHC.RdrName]) ->
GHC.InteractiveImport ->
m ([GHC.Module], [GHC.ImportDecl GHC.RdrName])
f (ns, ds) i = case i of
(GHC.IIDecl d) -> return (ns, (d:ds))
m@(GHC.IIModule _) -> do n <- iiModToMod m; return ((n:ns), ds)
modToIIMod :: GHC.Module -> GHC.InteractiveImport
iiModToMod :: GHC.GhcMonad m => GHC.InteractiveImport -> m GHC.Module
#if __GLASGOW_HASKELL__ < 706
modToIIMod = GHC.IIModule
iiModToMod (GHC.IIModule m) = return m
#else
modToIIMod = GHC.IIModule . GHC.moduleName
iiModToMod (GHC.IIModule m) = GHC.findModule m Nothing
#endif
iiModToMod _ = error "iiModToMod!"
#endif
mkPState = GHC.mkPState
#else
-- supportedExtensions :: [String]
supportedExtensions = GHC.supportedLanguages
-- setContext :: GHC.GhcMonad m => [GHC.Module] -> [GHC.Module] -> m ()
-- i don't want to check the signature on every ghc version....
setContext = GHC.setContext
getContext = GHC.getContext
mkPState df buf loc = GHC.mkPState buf loc df
#endif
-- Explicitly-typed variants of getContext/setContext, for use where we modify
-- or override the context.
#if __GLASGOW_HASKELL__ < 702
setContextModules :: GHC.GhcMonad m => [GHC.Module] -> [GHC.Module] -> m ()
setContextModules = setContext
getContextNames :: GHC.GhcMonad m => m([String], [String])
getContextNames = fmap (\(as,bs) -> (map name as, map name bs)) getContext
where name = GHC.moduleNameString . GHC.moduleName
#else
setContextModules :: GHC.GhcMonad m => [GHC.Module] -> [GHC.Module] -> m ()
setContextModules as = setContext as . map (GHC.simpleImportDecl . GHC.moduleName)
getContextNames :: GHC.GhcMonad m => m([String], [String])
getContextNames = fmap (\(as,bs) -> (map name as, map decl bs)) getContext
where name = GHC.moduleNameString . GHC.moduleName
decl = GHC.moduleNameString . GHC.unLoc . GHC.ideclName
#endif
#if __GLASGOW_HASKELL__ < 702
mkSrcLoc = GHC.mkSrcLoc
stringToStringBuffer = liftIO . GHC.stringToStringBuffer
#else
mkSrcLoc = GHC.mkRealSrcLoc
stringToStringBuffer = return . GHC.stringToStringBuffer
#endif
#if __GLASGOW_HASKELL__ >= 610
configureDynFlags :: GHC.DynFlags -> GHC.DynFlags
configureDynFlags dflags = dflags{GHC.ghcMode = GHC.CompManager,
GHC.hscTarget = GHC.HscInterpreted,
GHC.ghcLink = GHC.LinkInMemory,
GHC.verbosity = 0}
parseDynamicFlags :: GHC.GhcMonad m
=> GHC.DynFlags -> [String] -> m (GHC.DynFlags, [String])
parseDynamicFlags d = fmap firstTwo . GHC.parseDynamicFlags d . map GHC.noLoc
where firstTwo (a,b,_) = (a, map GHC.unLoc b)
fileTarget :: FilePath -> GHC.Target
fileTarget f = GHC.Target (GHC.TargetFile f $ Just next_phase) True Nothing
where next_phase = GHC.Cpp GHC.HsSrcFile
targetId :: GHC.Target -> GHC.TargetId
targetId = GHC.targetId
guessTarget :: GHC.GhcMonad m => String -> Maybe GHC.Phase -> m GHC.Target
guessTarget = GHC.guessTarget
-- add a bogus Maybe, in order to use it with mayFail
compileExpr :: GHC.GhcMonad m => String -> m (Maybe GHC.HValue)
compileExpr = fmap Just . GHC.compileExpr
-- add a bogus Maybe, in order to use it with mayFail
exprType :: GHC.GhcMonad m => String -> m (Maybe GHC.Type)
exprType = fmap Just . GHC.exprType
-- add a bogus Maybe, in order to use it with mayFail
#if __GLASGOW_HASKELL__ < 704
typeKind :: GHC.GhcMonad m => String -> m (Maybe GHC.Kind)
typeKind = fmap Just . GHC.typeKind
#else
typeKind :: GHC.GhcMonad m => String -> m (Maybe GHC.Kind)
typeKind = fmap Just . (liftM snd) . (GHC.typeKind True)
#endif
#else
-- add a bogus session parameter, in order to use it with runGhc2
parseDynamicFlags :: GHC.Session
-> GHC.DynFlags
-> [String] -> IO (GHC.DynFlags, [String])
parseDynamicFlags = const GHC.parseDynamicFlags
fileTarget :: FilePath -> GHC.Target
fileTarget f = GHC.Target (GHC.TargetFile f $ Just next_phase) Nothing
where next_phase = GHC.Cpp GHC.HsSrcFile
targetId :: GHC.Target -> GHC.TargetId
targetId (GHC.Target _id _) = _id
-- add a bogus session parameter, in order to use it with runGhc2
guessTarget :: GHC.Session -> String -> Maybe GHC.Phase -> IO GHC.Target
guessTarget = const GHC.guessTarget
compileExpr :: GHC.Session -> String -> IO (Maybe GHC.HValue)
compileExpr = GHC.compileExpr
exprType :: GHC.Session -> String -> IO (Maybe GHC.Type)
exprType = GHC.exprType
typeKind :: GHC.Session -> String -> IO (Maybe GHC.Kind)
typeKind = GHC.typeKind
#endif
#if __GLASGOW_HASKELL__ >= 608
#if __GLASGOW_HASKELL__ < 610
-- 6.08 only
newSession :: FilePath -> IO GHC.Session
newSession ghc_root = GHC.newSession (Just ghc_root)
configureDynFlags :: GHC.DynFlags -> GHC.DynFlags
configureDynFlags dflags = dflags{GHC.ghcMode = GHC.CompManager,
GHC.hscTarget = GHC.HscInterpreted,
GHC.ghcLink = GHC.LinkInMemory}
#endif
#if __GLASGOW_HASKELL__ < 701
-- 6.08 - 7.0.4
pprType :: GHC.Type -> (GHC.PprStyle -> GHC.Doc)
pprType = GHC.pprTypeForUser False -- False means drop explicit foralls
pprKind :: GHC.Kind -> (GHC.PprStyle -> GHC.Doc)
pprKind = pprType
#else
-- 7.2.1 and above
pprType :: GHC.Type -> GHC.SDoc
#if __GLASGOW_HASKELL__ < 708
pprType = GHC.pprTypeForUser False -- False means drop explicit foralls
#else
pprType = GHC.pprTypeForUser
#endif
pprKind :: GHC.Kind -> GHC.SDoc
pprKind = pprType
#endif
#elif __GLASGOW_HASKELL__ >= 606
-- 6.6 only
newSession :: FilePath -> IO GHC.Session
newSession ghc_root = GHC.newSession GHC.Interactive (Just ghc_root)
configureDynFlags :: GHC.DynFlags -> GHC.DynFlags
configureDynFlags dflags = dflags{GHC.hscTarget = GHC.HscInterpreted}
pprType :: GHC.Type -> (GHC.PprStyle -> GHC.Doc)
pprType = GHC.ppr . GHC.dropForAlls
pprKind :: GHC.Kind -> (GHC.PprStyle -> GHC.Doc)
pprKind = GHC.ppr
#endif
#if __GLASGOW_HASKELL__ >= 706
showSDoc = GHC.showSDoc
showSDocForUser = GHC.showSDocForUser
showSDocUnqual = GHC.showSDocUnqual
#else
-- starting from ghc 7.6, they started to receive a DynFlags argument (sigh)
showSDoc _ = GHC.showSDoc
showSDocForUser _ = GHC.showSDocForUser
showSDocUnqual _ = GHC.showSDocUnqual
#endif
#if __GLASGOW_HASKELL__ >= 706
mkLocMessage = GHC.mkLocMessage GHC.SevError
#else
mkLocMessage = GHC.mkLocMessage
#endif
| hakaru-dev/hint-exts | src/Hint/Compat.hs | bsd-3-clause | 8,226 | 0 | 12 | 1,531 | 995 | 556 | 439 | 38 | 1 |
{-# LANGUAGE CPP, TypeFamilies, ViewPatterns, OverloadedStrings #-}
-- -----------------------------------------------------------------------------
-- | This is the top-level module in the LLVM code generator.
--
module LlvmCodeGen ( LlvmVersion, llvmVersionList, llvmCodeGen, llvmFixupAsm ) where
#include "HsVersions.h"
import GhcPrelude
import Llvm
import LlvmCodeGen.Base
import LlvmCodeGen.CodeGen
import LlvmCodeGen.Data
import LlvmCodeGen.Ppr
import LlvmCodeGen.Regs
import LlvmMangler
import GHC.StgToCmm.CgUtils ( fixStgRegisters )
import GHC.Cmm
import GHC.Cmm.Dataflow.Collections
import GHC.Cmm.Ppr
import BufWrite
import DynFlags
import GHC.Platform ( platformArch, Arch(..) )
import ErrUtils
import FastString
import Outputable
import SysTools ( figureLlvmVersion )
import qualified Stream
import Control.Monad ( when, forM_ )
import Data.Maybe ( fromMaybe, catMaybes )
import System.IO
-- -----------------------------------------------------------------------------
-- | Top-level of the LLVM Code generator
--
llvmCodeGen :: DynFlags -> Handle
-> Stream.Stream IO RawCmmGroup a
-> IO a
llvmCodeGen dflags h cmm_stream
= withTiming dflags (text "LLVM CodeGen") (const ()) $ do
bufh <- newBufHandle h
-- Pass header
showPass dflags "LLVM CodeGen"
-- get llvm version, cache for later use
mb_ver <- figureLlvmVersion dflags
-- warn if unsupported
forM_ mb_ver $ \ver -> do
debugTraceMsg dflags 2
(text "Using LLVM version:" <+> text (llvmVersionStr ver))
let doWarn = wopt Opt_WarnUnsupportedLlvmVersion dflags
when (not (llvmVersionSupported ver) && doWarn) $ putMsg dflags $
"You are using an unsupported version of LLVM!" $$
"Currently only " <> text (llvmVersionStr supportedLlvmVersion) <> " is supported." <+>
"System LLVM version: " <> text (llvmVersionStr ver) $$
"We will try though..."
let isS390X = platformArch (targetPlatform dflags) == ArchS390X
let major_ver = head . llvmVersionList $ ver
when (isS390X && major_ver < 10 && doWarn) $ putMsg dflags $
"Warning: For s390x the GHC calling convention is only supported since LLVM version 10." <+>
"You are using LLVM version: " <> text (llvmVersionStr ver)
-- run code generation
a <- runLlvm dflags (fromMaybe supportedLlvmVersion mb_ver) bufh $
llvmCodeGen' (liftStream cmm_stream)
bFlush bufh
return a
llvmCodeGen' :: Stream.Stream LlvmM RawCmmGroup a -> LlvmM a
llvmCodeGen' cmm_stream
= do -- Preamble
renderLlvm header
ghcInternalFunctions
cmmMetaLlvmPrelude
-- Procedures
a <- Stream.consume cmm_stream llvmGroupLlvmGens
-- Declare aliases for forward references
renderLlvm . pprLlvmData =<< generateExternDecls
-- Postamble
cmmUsedLlvmGens
return a
where
header :: SDoc
header = sdocWithDynFlags $ \dflags ->
let target = platformMisc_llvmTarget $ platformMisc dflags
in text ("target datalayout = \"" ++ getDataLayout dflags target ++ "\"")
$+$ text ("target triple = \"" ++ target ++ "\"")
getDataLayout :: DynFlags -> String -> String
getDataLayout dflags target =
case lookup target (llvmTargets $ llvmConfig dflags) of
Just (LlvmTarget {lDataLayout=dl}) -> dl
Nothing -> pprPanic "Failed to lookup LLVM data layout" $
text "Target:" <+> text target $$
hang (text "Available targets:") 4
(vcat $ map (text . fst) $ llvmTargets $ llvmConfig dflags)
llvmGroupLlvmGens :: RawCmmGroup -> LlvmM ()
llvmGroupLlvmGens cmm = do
-- Insert functions into map, collect data
let split (CmmData s d' ) = return $ Just (s, d')
split (CmmProc h l live g) = do
-- Set function type
let l' = case mapLookup (g_entry g) h of
Nothing -> l
Just (RawCmmStatics info_lbl _) -> info_lbl
lml <- strCLabel_llvm l'
funInsert lml =<< llvmFunTy live
return Nothing
cdata <- fmap catMaybes $ mapM split cmm
{-# SCC "llvm_datas_gen" #-}
cmmDataLlvmGens cdata
{-# SCC "llvm_procs_gen" #-}
mapM_ cmmLlvmGen cmm
-- -----------------------------------------------------------------------------
-- | Do LLVM code generation on all these Cmms data sections.
--
cmmDataLlvmGens :: [(Section,RawCmmStatics)] -> LlvmM ()
cmmDataLlvmGens statics
= do lmdatas <- mapM genLlvmData statics
let (concat -> gs, tss) = unzip lmdatas
let regGlobal (LMGlobal (LMGlobalVar l ty _ _ _ _) _)
= funInsert l ty
regGlobal _ = pure ()
mapM_ regGlobal gs
gss' <- mapM aliasify $ gs
renderLlvm $ pprLlvmData (concat gss', concat tss)
-- | Complete LLVM code generation phase for a single top-level chunk of Cmm.
cmmLlvmGen ::RawCmmDecl -> LlvmM ()
cmmLlvmGen cmm@CmmProc{} = do
-- rewrite assignments to global regs
dflags <- getDynFlag id
let fixed_cmm = {-# SCC "llvm_fix_regs" #-} fixStgRegisters dflags cmm
dumpIfSetLlvm Opt_D_dump_opt_cmm "Optimised Cmm"
FormatCMM (pprCmmGroup [fixed_cmm])
-- generate llvm code from cmm
llvmBC <- withClearVars $ genLlvmProc fixed_cmm
-- pretty print
(docs, ivars) <- fmap unzip $ mapM pprLlvmCmmDecl llvmBC
-- Output, note down used variables
renderLlvm (vcat docs)
mapM_ markUsedVar $ concat ivars
cmmLlvmGen _ = return ()
-- -----------------------------------------------------------------------------
-- | Generate meta data nodes
--
cmmMetaLlvmPrelude :: LlvmM ()
cmmMetaLlvmPrelude = do
metas <- flip mapM stgTBAA $ \(uniq, name, parent) -> do
-- Generate / lookup meta data IDs
tbaaId <- getMetaUniqueId
setUniqMeta uniq tbaaId
parentId <- maybe (return Nothing) getUniqMeta parent
-- Build definition
return $ MetaUnnamed tbaaId $ MetaStruct $
case parentId of
Just p -> [ MetaStr name, MetaNode p ]
-- As of LLVM 4.0, a node without parents should be rendered as
-- just a name on its own. Previously `null` was accepted as the
-- name.
Nothing -> [ MetaStr name ]
renderLlvm $ ppLlvmMetas metas
-- -----------------------------------------------------------------------------
-- | Marks variables as used where necessary
--
cmmUsedLlvmGens :: LlvmM ()
cmmUsedLlvmGens = do
-- LLVM would discard variables that are internal and not obviously
-- used if we didn't provide these hints. This will generate a
-- definition of the form
--
-- @llvm.used = appending global [42 x i8*] [i8* bitcast <var> to i8*, ...]
--
-- Which is the LLVM way of protecting them against getting removed.
ivars <- getUsedVars
let cast x = LMBitc (LMStaticPointer (pVarLift x)) i8Ptr
ty = (LMArray (length ivars) i8Ptr)
usedArray = LMStaticArray (map cast ivars) ty
sectName = Just $ fsLit "llvm.metadata"
lmUsedVar = LMGlobalVar (fsLit "llvm.used") ty Appending sectName Nothing Constant
lmUsed = LMGlobal lmUsedVar (Just usedArray)
if null ivars
then return ()
else renderLlvm $ pprLlvmData ([lmUsed], [])
| sdiehl/ghc | compiler/llvmGen/LlvmCodeGen.hs | bsd-3-clause | 7,484 | 0 | 25 | 1,956 | 1,668 | 832 | 836 | 133 | 3 |
--------------------------------------------------------------------------------
-- | This module provides a Heist frontend for the digestive-functors library.
--
-- Disclaimer: this documentation requires very basic familiarity with
-- digestive-functors. You might want to take a quick look at this tutorial
-- first:
--
-- <https://github.com/jaspervdj/digestive-functors/blob/master/examples/tutorial.lhs>
--
-- This module exports the functions 'digestiveSplices' and
-- 'bindDigestiveSplices', and most users will not require anything else.
--
-- These splices are used to create HTML for different form elements. This way,
-- the developer doesn't have to care about setting e.g. the previous values in
-- a text field when something goes wrong.
--
-- For documentation on the different splices, see the different functions
-- exported by this module. All splices have the same name as given in
-- 'digestiveSplices'.
--
-- You can give arbitrary attributes to most of the elements (i.e. where it
-- makes sense). This means you can do e.g.:
--
-- > <dfInputTextArea ref="description" cols="20" rows="3" />
{-# LANGUAGE OverloadedStrings #-}
module Text.Digestive.Heist
( -- * Core methods
digestiveSplices
, bindDigestiveSplices
-- * Main splices
, dfInput
, dfInputList
, dfInputText
, dfInputTextArea
, dfInputPassword
, dfInputHidden
, dfInputSelect
, dfInputSelectGroup
, dfInputRadio
, dfInputCheckbox
, dfInputFile
, dfInputSubmit
, dfLabel
, dfForm
, dfErrorList
, dfChildErrorList
, dfSubView
-- * Utility splices
, dfIfChildErrors
) where
--------------------------------------------------------------------------------
import Control.Monad (liftM, mplus)
import Control.Monad.Trans
import Data.Function (on)
import Data.List (unionBy)
import Data.Maybe (fromMaybe)
import Data.Monoid (mappend)
import Data.Text (Text)
import qualified Data.Text as T
import Heist
import Heist.Interpreted
import qualified Text.XmlHtml as X
--------------------------------------------------------------------------------
import Text.Digestive.Form.List
import Text.Digestive.View
--------------------------------------------------------------------------------
bindDigestiveSplices :: MonadIO m => View Text -> HeistState m -> HeistState m
bindDigestiveSplices = bindSplices . digestiveSplices
--------------------------------------------------------------------------------
digestiveSplices :: MonadIO m => View Text -> Splices (Splice m)
digestiveSplices view = do
"dfInput" ## dfInput view
"dfInputList" ## dfInputList view
"dfInputText" ## dfInputText view
"dfInputTextArea" ## dfInputTextArea view
"dfInputPassword" ## dfInputPassword view
"dfInputHidden" ## dfInputHidden view
"dfInputSelect" ## dfInputSelect view
"dfInputSelectGroup" ## dfInputSelectGroup view
"dfInputRadio" ## dfInputRadio view
"dfInputCheckbox" ## dfInputCheckbox view
"dfInputFile" ## dfInputFile view
"dfInputSubmit" ## dfInputSubmit view
"dfLabel" ## dfLabel view
"dfForm" ## dfForm view
"dfErrorList" ## dfErrorList view
"dfChildErrorList" ## dfChildErrorList view
"dfSubView" ## dfSubView view
"dfIfChildErrors" ## dfIfChildErrors view
--------------------------------------------------------------------------------
attr :: Bool -> (Text, Text) -> [(Text, Text)] -> [(Text, Text)]
attr False _ = id
attr True a = (a :)
--------------------------------------------------------------------------------
makeElement :: Text -> [X.Node] -> [(Text, Text)] -> [X.Node]
makeElement name nodes = return . flip (X.Element name) nodes
--------------------------------------------------------------------------------
getRefAttributes :: Monad m
=> Maybe Text -- ^ Optional default ref
-> HeistT m m (Text, [(Text, Text)]) -- ^ (Ref, other attrs)
getRefAttributes defaultRef = do
node <- getParamNode
return $ case node of
X.Element _ as _ ->
let ref = fromMaybe (error $ show node ++ ": missing ref") $
lookup "ref" as `mplus` defaultRef
in (ref, filter ((/= "ref") . fst) as)
_ -> (error "Wrong type of node!", [])
--------------------------------------------------------------------------------
getContent :: Monad m => HeistT m m [X.Node]
getContent = liftM X.childNodes getParamNode
--------------------------------------------------------------------------------
-- | Does not override existing attributes
addAttrs :: [(Text, Text)] -- ^ Original attributes
-> [(Text, Text)] -- ^ Attributes to add
-> [(Text, Text)] -- ^ Resulting attributes
addAttrs = unionBy (on (==) fst)
--------------------------------------------------------------------------------
-- |
setDisabled :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
setDisabled ref view = if viewDisabled ref view then (("disabled",""):) else id
--------------------------------------------------------------------------------
-- | Generate an input field with a supplied type. Example:
--
-- > <dfInput type="date" ref="date" />
dfInput :: Monad m => View v -> Splice m
dfInput view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a text input field. Example:
--
-- > <dfInputText ref="user.name" />
dfInputText :: Monad m => View v -> Splice m
dfInputText view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "text"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a text area. Example:
--
-- > <dfInputTextArea ref="user.about" />
dfInputTextArea :: Monad m => View v -> Splice m
dfInputTextArea view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "textarea" [X.TextNode value] $ addAttrs attrs $
setDisabled ref view [("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a password field. Example:
--
-- > <dfInputPassword ref="user.password" />
dfInputPassword :: Monad m => View v -> Splice m
dfInputPassword view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "password"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a hidden input field. Example:
--
-- > <dfInputHidden ref="user.forgery" />
dfInputHidden :: Monad m => View v -> Splice m
dfInputHidden view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputText ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "hidden"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a select button (also known as a combo box). Example:
--
-- > <dfInputSelect ref="user.sex" />
dfInputSelect :: Monad m => View Text -> Splice m
dfInputSelect view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = map makeOption choices
value i = ref' `mappend` "." `mappend` i
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", value i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a select button (also known as a combo box). Example:
--
-- > <dfInputSelectGroup ref="user.sex" />
dfInputSelectGroup :: Monad m => View Text -> Splice m
dfInputSelectGroup view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoiceGroup ref view
kids = map makeGroup choices
value i = ref' `mappend` "." `mappend` i
makeGroup (name, options) = X.Element "optgroup"
[("label", name)] $ map makeOption options
makeOption (i, c, sel) = X.Element "option"
(attr sel ("selected", "selected") [("value", value i)])
[X.TextNode c]
return $ makeElement "select" kids $ addAttrs attrs $ setDisabled ref view
[("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a number of radio buttons. Example:
--
-- > <dfInputRadio ref="user.sex" />
dfInputRadio :: Monad m => View Text -> Splice m
dfInputRadio view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
choices = fieldInputChoice ref view
kids = concatMap makeOption choices
value i = ref' `mappend` "." `mappend` i
makeOption (i, c, sel) =
[ X.Element "label" [("for", value i)]
[ X.Element "input"
(attr sel ("checked", "checked") $ addAttrs attrs
[ ("type", "radio"), ("value", value i)
, ("id", value i), ("name", ref')
]) []
, X.TextNode c]
]
return kids
--------------------------------------------------------------------------------
-- | Generate a checkbox. Example:
--
-- > <dfInputCheckbox ref="user.married" />
dfInputCheckbox :: Monad m => View Text -> Splice m
dfInputCheckbox view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = fieldInputBool ref view
return $ makeElement "input" [] $ addAttrs attrs $
attr value ("checked", "checked") $ setDisabled ref view
[("type", "checkbox"), ("id", ref'), ("name", ref')]
--------------------------------------------------------------------------------
-- | Generate a file upload element. Example:
--
-- > <dfInputFile ref="user.avatar" />
dfInputFile :: Monad m => View Text -> Splice m
dfInputFile view = do
(ref, attrs) <- getRefAttributes Nothing
let ref' = absoluteRef ref view
value = maybe "" T.pack $ fieldInputFile ref view
return $ makeElement "input" [] $ addAttrs attrs $ setDisabled ref view
[("type", "file"), ("id", ref'), ("name", ref'), ("value", value)]
--------------------------------------------------------------------------------
-- | Generate a submit button. Example:
--
-- > <dfInputSubmit />
dfInputSubmit :: Monad m => View v -> Splice m
dfInputSubmit _ = do
(_, attrs) <- getRefAttributes Nothing
return $ makeElement "input" [] $ addAttrs attrs [("type", "submit")]
--------------------------------------------------------------------------------
-- | Generate a label for a field. Example:
--
-- > <dfLabel ref="user.married">Married: </dfLabel>
-- > <dfInputCheckbox ref="user.married" />
dfLabel :: Monad m => View v -> Splice m
dfLabel view = do
(ref, attrs) <- getRefAttributes Nothing
content <- getContent
let ref' = absoluteRef ref view
return $ makeElement "label" content $ addAttrs attrs [("for", ref')]
--------------------------------------------------------------------------------
-- | Generate a form tag with the @method@ attribute set to @POST@ and
-- the @enctype@ set to the right value (depending on the form).
-- Custom @method@ or @enctype@ attributes would override this
-- behavior. Example:
--
-- > <dfForm action="/users/new">
-- > <dfInputText ... />
-- > ...
-- > <dfInputSubmit />
-- > </dfForm>
dfForm :: Monad m => View v -> Splice m
dfForm view = do
(_, attrs) <- getRefAttributes Nothing
content <- getContent
return $ makeElement "form" content $ addAttrs attrs
[ ("method", "POST")
, ("enctype", T.pack (show $ viewEncType view))
]
--------------------------------------------------------------------------------
errorList :: [Text] -> [(Text, Text)] -> [X.Node]
errorList [] _ = []
errorList errs attrs = [X.Element "ul" attrs $ map makeError errs]
where
makeError e = X.Element "li" [] [X.TextNode e]
--------------------------------------------------------------------------------
-- | Display the list of errors for a certain field. Example:
--
-- > <dfErrorList ref="user.name" />
-- > <dfInputText ref="user.name" />
dfErrorList :: Monad m => View Text -> Splice m
dfErrorList view = do
(ref, attrs) <- getRefAttributes Nothing
return $ errorList (errors ref view) attrs
--------------------------------------------------------------------------------
-- | Display the list of errors for a certain form and all forms below it. E.g.,
-- if there is a subform called @\"user\"@:
--
-- > <dfChildErrorList ref="user" />
--
-- Or display /all/ errors for the form:
--
-- > <dfChildErrorList ref="" />
--
-- Which is more conveniently written as:
--
-- > <dfChildErrorList />
dfChildErrorList :: Monad m => View Text -> Splice m
dfChildErrorList view = do
(ref, attrs) <- getRefAttributes $ Just ""
return $ errorList (childErrors ref view) attrs
--------------------------------------------------------------------------------
-- | This splice allows reuse of templates by selecting some child of a form
-- tree. While this may sound complicated, it's pretty straightforward and
-- practical. Suppose we have:
--
-- > <dfInputText ref="user.name" />
-- > <dfInputText ref="user.password" />
-- >
-- > <dfInputTextArea ref="comment.body" />
--
-- You may want to abstract the @\"user\"@ parts in some other template so you
-- Don't Repeat Yourself (TM). If you create a template called @\"user-form\"@
-- with the following contents:
--
-- > <dfInputText ref="name" />
-- > <dfInputText ref="password" />
--
-- You will be able to use:
--
-- > <dfSubView ref="user">
-- > <apply template="user-form" />
-- > </dfSubView>
-- >
-- > <dfInputTextArea ref="comment.body" />
dfSubView :: MonadIO m => View Text -> Splice m
dfSubView view = do
(ref, _) <- getRefAttributes Nothing
let view' = subView ref view
nodes <- localHS (bindDigestiveSplices view') runChildren
return nodes
disableOnclick :: Text -> View v -> [(Text, Text)] -> [(Text, Text)]
disableOnclick ref view =
if viewDisabled ref view then const [("disabled","")] else id
--------------------------------------------------------------------------------
-- | This splice allows variable length lists. It binds several attribute
-- splices providing functionality for dynamically manipulating the list. The
-- following descriptions will use the example of a form named \"foo\" with a
-- list subform named \"items\".
--
-- Splices:
-- dfListItem - This tag must surround the markup for a single list item.
-- It surrounds all of its children with a div with id \"foo.items\" and
-- class \"inputList\".
--
-- Attribute Splices:
-- itemAttrs - Attribute you should use on div, span, etc that surrounds all
-- the markup for a single list item. This splice expands to an id of
-- \"foo.items.ix\" (where ix is the index of the current item) and a
-- class of \"inputListItem\".
-- addControl - Use this attribute on the tag you use to define a control
-- for adding elements to the list (usually a button or anchor). It adds
-- an onclick attribute that calls a javascript function addInputListItem.
-- removeControl - Use this attribute on the control for removing individual
-- items. It adds an onclick attribute that calls removeInputListItem.
dfInputList :: MonadIO m => View Text -> Splice m
dfInputList view = do
(ref, _) <- getRefAttributes Nothing
let listRef = absoluteRef ref view
listAttrs =
[ ("id", listRef)
, ("class", "inputList")
]
addControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "addInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
removeControl _ = return $ disableOnclick ref view
[ ("onclick", T.concat [ "removeInputListItem(this, '"
, listRef
, "'); return false;"] ) ]
itemAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "0" : viewContext v])
, ("class", T.append listRef ".inputListItem")
]
templateAttrs v _ = return
[ ("id", T.concat [listRef, ".", last $ "-1" : viewContext v])
, ("class", T.append listRef ".inputListTemplate")
, ("style", "display: none;")
]
items = listSubViews ref view
f attrs v = localHS (bindAttributeSplices ("itemAttrs" ## attrs v) .
bindDigestiveSplices v) runChildren
dfListItem = do
template <- f templateAttrs (makeListSubView ref (-1) view)
res <- mapSplices (f itemAttrs) items
return $ template ++ res
attrSplices = do
"addControl" ## addControl
"removeControl" ## removeControl
nodes <- localHS (bindSplices ("dfListItem" ## dfListItem) .
bindAttributeSplices attrSplices) runChildren
let indices = [X.Element "input"
[ ("type", "hidden")
, ("name", T.intercalate "." [listRef, indicesRef])
, ("value", T.intercalate "," $ map
(last . ("0":) . viewContext) items)
] []
]
return [X.Element "div" listAttrs (indices ++ nodes)]
--------------------------------------------------------------------------------
-- | Render some content only if there are any errors. This is useful for markup
-- purposes.
--
-- > <dfIfChildErrors ref="user">
-- > Content to be rendered if there are any errors...
-- > </dfIfChildErrors>
--
-- The @ref@ attribute can be omitted if you want to check the entire form.
dfIfChildErrors :: Monad m => View v -> Splice m
dfIfChildErrors view = do
(ref, _) <- getRefAttributes $ Just ""
if null (childErrors ref view)
then return []
else runChildren
| f-me/digestive-functors-heist | src/Text/Digestive/Heist.hs | bsd-3-clause | 19,350 | 0 | 21 | 4,490 | 4,052 | 2,173 | 1,879 | 259 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DataKinds #-}
module TestInstances where
import Control.Applicative
import Control.Monad (replicateM)
import Test.QuickCheck hiding (property)-- (Arbitrary, arbitrary, (==>))
import Data.AEq
import Data.Proxy
import GHC.TypeLits
import TestUtil
import Numeric.Units.Dimensional.Prelude
import Numeric.Units.Dimensional.Cyclic (plusMinusPi, zeroTwoPi, (==~), (~==~))
import Numeric.Units.Dimensional.Coercion
import Numeric.Units.Dimensional (Dimensional (..))
import Numeric.Units.Dimensional.LinearAlgebra
import Numeric.Units.Dimensional.LinearAlgebra.Vector (Vec (ListVec))
import Numeric.Units.Dimensional.LinearAlgebra.PosVel (Sph (..))
import qualified Prelude
import Astro.Coords
import Astro.Coords.PosVel
import Astro.Place
import Astro.Place.ReferenceEllipsoid
import Astro.Orbit.Types
import Astro.Orbit.DeltaV
import Astro.Orbit.MEOE as M -- (MEOE (MEOE), meoe2vec)
import qualified Astro.Orbit.COE as C -- (COE (COE), coe2vec)
import Astro.Orbit.Conversion (meoe2coe)
import Astro.Orbit.Maneuver
import Astro.Time hiding (coerce)
import Astro.Time.At
-- ----------------------------------------------------------
-- Special generators and Arbitrary instances.
-- These could be defined in terms of the newtypes, e,g, getNonZeroD <$> arbitrary
nonZeroArbitrary :: (Arbitrary a, Eq a, Num a) => Gen (Quantity d a)
nonZeroArbitrary = suchThat arbitrary (/= _0)
positiveArbitrary :: (Arbitrary a, Ord a, Num a) => Gen (Quantity d a)
positiveArbitrary = suchThat arbitrary (> _0)
nonNegativeArbitrary :: (Arbitrary a, Ord a, Num a) => Gen (Quantity d a)
nonNegativeArbitrary = suchThat arbitrary (>= _0)
zeroOneArbitrary :: (Arbitrary a, RealFrac a) => Gen (Dimensionless a)
zeroOneArbitrary = (*~one) . snd . properFraction <$> arbitrary
-- | @NonZeroD x@ has an Arbitrary instance that guarantees that @x \/= 0@.
newtype NonZeroD d a = NonZeroD { getNonZeroD :: Quantity d a }
instance (Arbitrary a, Eq a, Num a) => Arbitrary (NonZeroD d a) where
arbitrary = NonZeroD <$> suchThat arbitrary (/= _0)
deriving instance (KnownDimension d, Real a, Show a) => Show (NonZeroD d a)
-- | @PositiveD x@ has an Arbitrary instance that guarantees that @x \> 0@.
newtype PositiveD d a = PositiveD { getPositiveD :: Quantity d a }
instance (Arbitrary a, Ord a, Num a) => Arbitrary (PositiveD d a) where
arbitrary = PositiveD <$> suchThat arbitrary (> _0)
deriving instance (KnownDimension d, Real a, Show a) => Show (PositiveD d a)
-- | @NonNegativeD x@ has an Arbitrary instance that guarantees that @x \>= 0@.
newtype NonNegativeD d a = NonNegativeD { getNonNegativeD :: Quantity d a }
instance (Arbitrary a, Ord a, Num a) => Arbitrary (NonNegativeD d a) where
arbitrary = NonNegativeD <$> suchThat arbitrary (>= _0)
deriving instance (KnownDimension d, Real a, Show a) => Show (NonNegativeD d a)
-- | @ZeroOneD x@ has an Arbitrary instance that guarantees that @0 <= x < 1@.
newtype ZeroOneD a = ZeroOneD { getZeroOneD :: Dimensionless a } deriving (Show)
instance (Arbitrary a, RealFrac a) => Arbitrary (ZeroOneD a) where
arbitrary = ZeroOneD . (*~one) . snd . properFraction <$> arbitrary
-- ----------------------------------------------------------
-- Arbitrary instances
-- -------------------
instance (Arbitrary a) => Arbitrary (Quantity d a) where
arbitrary = coerceQ <$> arbitrary
where coerceQ = coerce :: a -> Quantity d a
instance (KnownNat n, Arbitrary a) => Arbitrary (Vec d n a) where
arbitrary = fromListErr <$> vectorOf n arbitrary
where
n = fromInteger $ natVal (Proxy :: Proxy n)
instance Arbitrary a => Arbitrary (Coord s a) where
arbitrary = C <$> arbitrary
instance Arbitrary a => Arbitrary (ImpulsiveDV s a) where
arbitrary = DV <$> arbitrary
-- | Guarantees the vector (or @Coord@) is non-null.
newtype NonNull v = NonNull v deriving (Show)
instance Functor NonNull where fmap f (NonNull v) = NonNull (f v)
instance (KnownNat n, Num a, Eq a, Arbitrary a) => Arbitrary (NonNull (Vec d n a)) where
arbitrary = NonNull <$> suchThat arbitrary (/= nullVector)
instance (Num a, Eq a, Arbitrary a) => Arbitrary (NonNull (Coord s a)) where
arbitrary = fmap C <$> arbitrary
instance (Num a, Eq a, Arbitrary a) => Arbitrary (NonNull (ImpulsiveDV s a)) where
arbitrary = fmap DV <$> arbitrary
instance (Num a, Eq a, Arbitrary a) => Arbitrary (NonNull (Maneuver a)) where
arbitrary = fmap toManeuver <$> arbitrary
instance Arbitrary a => Arbitrary (GeodeticLatitude a) where
arbitrary = GeodeticLatitude <$> arbitrary
instance Arbitrary a => Arbitrary (GeoLongitude a) where
arbitrary = GeoLongitude <$> arbitrary
instance (Fractional a, Ord a, Arbitrary a) => Arbitrary (GeodeticPlace a) where
arbitrary = GeodeticPlace <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance (Num a, Ord a, Arbitrary a) => Arbitrary (ReferenceEllipsoid a) where
arbitrary = do
x <- positiveArbitrary
y <- positiveArbitrary
return $ ReferenceEllipsoid (max x y) (min x y)
instance (Arbitrary a, Fractional a) => Arbitrary (E t a) where
arbitrary = mjd' <$> arbitrary
instance (Arbitrary a, Fractional a, AEq a) => Arbitrary (PosVel s a) where
arbitrary = do
let pv = C' <$> arbitrary <*> arbitrary
suchThat pv (not . degeneratePosVel)
deriving instance Arbitrary a => Arbitrary (SemiMajorAxis a)
deriving instance Arbitrary a => Arbitrary (SemiLatusRectum a)
deriving instance Arbitrary a => Arbitrary (Anomaly t a)
deriving instance Arbitrary a => Arbitrary (Longitude t a)
-- Arbitrary instance always returns values >= 0.
instance (Num a, Ord a, Arbitrary a) => Arbitrary (Eccentricity a) where
arbitrary = Ecc <$> nonNegativeArbitrary
instance Arbitrary a => Arbitrary (Maneuver a) where
arbitrary = ImpulsiveRTN <$> arbitrary <*> arbitrary <*> arbitrary
-- This instance will not generate orbits with very large eccentricities.
instance (RealFrac a, Ord a, Arbitrary a) => Arbitrary (M.MEOE t a) where
arbitrary = do
let m = M.MEOE <$> positiveArbitrary
<*> positiveArbitrary
<*> zeroOneArbitrary <*> zeroOneArbitrary
<*> zeroOneArbitrary <*> zeroOneArbitrary
<*> arbitrary
suchThat m (\m -> semiMajorAxis m > SMA _0)
instance (RealFloat a, Arbitrary a) => Arbitrary (C.COE t a) where
arbitrary = meoe2coe <$> arbitrary
instance (Fractional a, Arbitrary a, Arbitrary x) => Arbitrary (At t a x) where
arbitrary = At <$> arbitrary <*> arbitrary
-- ----------------------------------------------------------
-- AEq instances.
-- Approximate equality
-- --------------------
instance (RealFloat a, AEq a) => AEq (E t a) where
E t1 ~== E t2 = t1 ~== t2
deriving instance AEq a => AEq (SemiMajorAxis a)
deriving instance AEq a => AEq (SemiLatusRectum a)
deriving instance AEq a => AEq (Eccentricity a)
instance (RealFloat a, Eq a) => Eq (Anomaly t a) where
Anom x == Anom y = x ==~ y -- TODO Cyclic may be good, but also approximate for Eq??
instance (RealFloat a, AEq a) => AEq (Anomaly t a) where
Anom x ~== Anom y = x ~==~ y
instance (RealFloat a, Eq a) => Eq (Longitude l a) where
Long x == Long y = x ==~ y -- TODO Cyclic may be good, but also approximate for Eq??
instance (RealFloat a, AEq a) => AEq (Longitude l a) where
Long x ~== Long y = x ~==~ y
deriving instance (RealFloat a, Eq a) => Eq (M.MEOE l a)
deriving instance (RealFloat a, Eq a) => Eq (C.COE t a)
instance (RealFloat a, AEq a) => AEq (M.MEOE t a) where
--m0 ~== m1 = meoe2vec m0 ~== meoe2vec m1
m0 ~== m1 = M.mu m0 ~== M.mu m1
&& M.p m0 ~== M.p m1
&& M.f m0 ~== M.f m1
&& M.g m0 ~== M.g m1
&& M.h m0 ~== M.h m1
&& M.k m0 ~== M.k m1
&& long (M.longitude m0) ~==~ long (M.longitude m1)
instance (RealFloat a, AEq a) => AEq (C.COE t a) where
--c0 ~== c1 = C.coe2vec c0 ~== C.coe2vec c1
c0 ~== c1 = C.mu c0 ~== C.mu c1
&& C.slr c0 ~== C.slr c1
&& C.ecc c0 ~== C.ecc c1
&& C.inc c0 ~== C.inc c1
&& C.aop c0 ~==~ C.aop c1
&& C.raan c0 ~==~ C.raan c1
&& anom (C.anomaly c0) ~==~ anom (C.anomaly c1)
instance (RealFloat a, AEq a, AEq x) => AEq (At t a x) where
(x0 `At` t0) ~== (x1 `At` t1) = x0 ~== x1 && t0 ~== t1
| bjornbm/astro | test/TestInstances.hs | bsd-3-clause | 8,581 | 0 | 20 | 1,680 | 2,860 | 1,506 | 1,354 | 150 | 1 |
import qualified System.Exit
import System.IO
main = do
-- don't buffer input and output
System.IO.hSetBuffering stdin NoBuffering
System.IO.hSetBuffering stdout NoBuffering
putStr "Are you sure? [Y/n] "
answer <- getChar
if positive answer
then System.Exit.exitSuccess
else System.Exit.exitFailure
where
positive answer = answer == 'Y' || answer == 'y'
| shiroyasha/ask | ask.hs | bsd-3-clause | 402 | 0 | 9 | 95 | 95 | 48 | 47 | 11 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Data.TileMap where
import Data.Grid
import Data.Points
import Data.Surrounding
import Data.TileSet
import Error
import Util
import Control.Applicative
import qualified Data.Traversable as T
newtype TileMap c = TileMap
{ tileMap :: Grid c TileIndex
} deriving (Eq,Show)
-- Building {{{
tmFromGrid :: Grid c TileIndex -> TileMap c
tmFromGrid = TileMap
emptyTileMap :: TileMap c
emptyTileMap = tmFromGrid emptyGrid
mkRepeatTileMap :: (DiscreteCoord c) => Size c -> TileMap c
mkRepeatTileMap sz = tmFromGrid $ mkRepeatGrid sz 0
mkIotaTileMapExcept :: (CoordType c)
=> Size c -> [(Int,Int)] -> TileMap c
mkIotaTileMapExcept sz es = tmFromList $ flip zip [0..]
$ concat
$ deleteGridIndices es
$ coordGrid sz
mkIotaTileMap :: (DiscreteCoord c) => Size c -> TileMap c
mkIotaTileMap = tmFromGrid . mkIotaGrid
tmFromList :: (CoordType c) => [(Coord c,TileIndex)] -> TileMap c
tmFromList = tmFromGrid . gridFromList
csGenerateTileMap :: (CoordType c) => (Coord c -> TileIndex)
-> Coords c -> TileMap c
csGenerateTileMap f = tmFromGrid . gridMapKeysTo f
csGenerateTileMapA :: (Applicative m, CoordType c)
=> (Coord c -> m TileIndex) -> Coords c -> m (TileMap c)
csGenerateTileMapA f = fmap tmFromGrid . gridTraverseKeys f
tmInsert :: (CoordType c) => Coord c -> TileIndex -> TileMap c -> TileMap c
tmInsert c = tmOnGrid . gridInsert c
tmUnion :: (CoordType c) => TileMap c -> TileMap c -> TileMap c
tmUnion m1 = tmFromGrid . gridUnion (tileMap m1) . tileMap
tmUnions :: (CoordType c) => [TileMap c] -> TileMap c
tmUnions = tmFromGrid . gridUnions . map tileMap
-- }}}
-- Reducing {{{
tmFilter :: (TileIndex -> Bool) -> TileMap c -> TileMap c
tmFilter = tmOnGrid . gridFilter
tmDifference :: (CoordType c) => TileMap c -> TileMap c -> TileMap c
tmDifference = tmOnGrid . gridDifference . tileMap
newtype SubMap c = SubMap
{ subMap :: TileMap c
} deriving (Eq,Show)
tmSubMap :: (CoordType c) => Coords c -> TileMap c -> SubMap c
tmSubMap cs = SubMap . tmOnGrid (gridSubMap cs)
tmSubMapByIndex :: (CoordType c) => TileIndex -> TileMap c -> SubMap c
tmSubMapByIndex ti = SubMap . tmOnGrid (gridSubMapByValue ti)
tmSubMapsByIndex :: (CoordType c) => TileMap c -> [SubMap c]
tmSubMapsByIndex tm = map (`tmSubMapByIndex` tm) $ tmValues tm
tmSubMapSetByIndex :: (CoordType c) => TileMap c -> TileSet (SubMap c)
tmSubMapSetByIndex tm = tsFromList [ (i,tmSubMapByIndex i tm) | i <- is ]
where
is = tmValues tm
-- }}}
-- Mapping / Traversing {{{
tmOnGrid :: (Grid c TileIndex -> Grid c TileIndex) -> TileMap c -> TileMap c
tmOnGrid f tm = tm { tileMap = f $ tileMap tm }
tmOnGridA :: (Applicative f) => (Grid c TileIndex -> f (Grid c TileIndex))
-> TileMap c -> f (TileMap c)
tmOnGridA f tm = TileMap <$> f (tileMap tm)
tmOnGridM :: (Monad m) => (Grid c TileIndex -> m (Grid c TileIndex))
-> TileMap c -> m (TileMap c)
tmOnGridM f tm = do
g <- f (tileMap tm)
return $ tm { tileMap = g }
tmUpdate :: (TileIndex -> TileIndex) -> TileMap c -> TileMap c
tmUpdate = tmOnGrid . fmap
tmUpdateAt :: (CoordType c) => [Coord c] -> (TileIndex -> TileIndex) -> TileMap c -> TileMap c
tmUpdateAt cs = tmOnGrid . gridUpdateAt cs
tmUpdateWithKeyAt :: (CoordType c) => [Coord c] -> (Coord c -> TileIndex -> TileIndex)
-> TileMap c -> TileMap c
tmUpdateWithKeyAt cs = tmOnGrid . gridUpdateWithKeyAt cs
tmUpdateAtM :: (Functor m, Monad m, CoordType c) => [Coord c]
-> (TileIndex -> m TileIndex) -> TileMap c -> m (TileMap c)
tmUpdateAtM cs = tmOnGridM . gridUpdateAtM cs
tmTraverseWithKey :: (Applicative m, CoordType c)
=> (Coord c -> TileIndex -> m TileIndex) -> TileMap c -> m (TileMap c)
tmTraverseWithKey = tmOnGridA . gridTraverseWithKey
tmUpdateWithKeyAtM :: (Functor m, Monad m, CoordType c) => [Coord c]
-> (Coord c -> TileIndex -> m TileIndex) -> TileMap c -> m (TileMap c)
tmUpdateWithKeyAtM cs = tmOnGridM . gridUpdateWithKeyAtM cs
tmTraverse :: (Applicative f, CoordType c) => (TileIndex -> f TileIndex)
-> TileMap c -> f (TileMap c)
tmTraverse = tmOnGridA . T.traverse
tmTraverseKeys :: (Applicative f, CoordType c) => (Coord c -> f TileIndex)
-> TileMap c -> f (TileMap c)
tmTraverseKeys = tmOnGridA . gridTraverseKeys
tmFoldrWithKey :: (Coord c -> TileIndex -> a -> a) -> a -> TileMap c -> a
tmFoldrWithKey f a = gridFoldrWithKey f a . tileMap
tmFoldrKeys :: (Coord c -> a -> a) -> a -> TileMap c -> a
tmFoldrKeys f a = gridFoldrKeys f a . tileMap
-- }}}
-- Accessing {{{
tmRows :: CoordType c => TileMap c -> c
tmRows = gridRows . tileMap
tmCols :: CoordType c => TileMap c -> c
tmCols = gridCols . tileMap
tmCoords :: CoordType c => TileMap c -> [Coord c]
tmCoords = gridKeys . tileMap
tmValues :: CoordType c => TileMap c -> [TileIndex]
tmValues = gridValues . tileMap
tmAssocs :: TileMap c -> [(Coord c,TileIndex)]
tmAssocs = gridContents . tileMap
tmIndex :: (CoordType c) => TileMap c -> Coord c -> TileIndex
tmIndex tm = gridIndex (tileMap tm)
tmLookup :: (CoordType c) => TileMap c -> Coord c -> Error TileIndex
tmLookup tm c = reportNothing err $ gridLookup (tileMap tm) c
where
err = "Couldn't find coord " ++ ppCoord c ++ "in TileMap:\n" ++ ppTileMap tm
tmMinimum, tmMaximum :: (CoordType c) => TileMap c -> Error (Coord c, TileIndex)
tmMinimum tm = reportNothing "tmMinimum: empty TileMap" $ gridMinimum $ tileMap tm
tmMaximum tm = reportNothing "tmMaximum: empty TileMap" $ gridMaximum $ tileMap tm
tmSize :: (CoordType c) => TileMap c -> Size c
tmSize = gridSize . tileMap
-- }}}
-- Surrounding {{{
tmSurrounding :: (CoordType c) => TileMap c -> Coord c -> Surrounding TileIndex
tmSurrounding = gridSurrounding . tileMap
-- }}}
-- Pretty Printing {{{
printTileMap :: (CoordType c, Show c) => TileMap c -> IO ()
printTileMap = putStrLn . ppTileMap
ppTileMap :: (CoordType c, Show c) => TileMap c -> String
ppTileMap = ppGrid . tileMap
-- }}}
| kylcarte/wangtiles | src/Data/TileMap.hs | bsd-3-clause | 5,881 | 0 | 11 | 1,106 | 2,305 | 1,168 | 1,137 | 119 | 1 |
import Graphics.UI.GLUT.Turtle
import Graphics.UI.GLUT hiding (position, initialize, clear)
main :: IO ()
main = do
_args <- initialize
f <- openField "test" 640 480
c <- openConsole "console" 640 480
consolePrompt c "> "
setConsole f c
t <- newTurtle f
onclick f $ \_bn x y -> goto t x y >> return True
oncommand f (processInput f c t)
-- speed t "slowest"
-- fillcolor t ((255, 255, 255) :: (Int, Int, Int))
-- pencolor t ((255, 255, 255) :: (Int, Int, Int))
-- threadDelay 1000000
-- left t 45
-- forward t 100
mainLoop
processInput :: Field -> Console -> Turtle -> String -> IO Bool
processInput _ _ t "forward" = forward t 100 >> return True
processInput _ _ t "left" = left t 90 >> return True
processInput _ _ t "right" = right t 90 >> return True
processInput _ _ t "begin" = beginfill t >> return True
processInput _ _ t "end" = endfill t >> return True
processInput _ _ t "turtle" = shape t "turtle" >> return True
processInput _ _ t "stamp" = stamp t >> return True
processInput _ _ t "bold" = pensize t 7 >> return True
processInput _ _ t "verybold" = pensize t 10 >> return True
processInput _ _ t "big" = shapesize t 3 3 >> return True
processInput _ _ t "blue" = pencolor t ((0, 0, 255) :: (Int, Int, Int)) >> return True
processInput _ _ t "fblue" = fillcolor t ((0, 0, 255) :: (Int, Int, Int)) >> return True
processInput _ _ t "yellow" = pencolor t ((255, 255, 0) :: (Int, Int, Int)) >> return True
processInput _ _ t "normal" = pensize t 1 >> return True
processInput _ _ _ "exit" = return False
processInput _ c t "position" = position t >>= consoleOutput c . show >> return True
processInput _ _ t "penup" = penup t >> return True
processInput _ _ t "pendown" = pendown t >> return True
processInput _ _ t "message" = write t "KochiGothic" 100 "Hello, world!" >> return True
processInput _ _ _ "0very1very2very3very4very5very6very7very8very9very0very-long-line"
= putStrLn "very long line" >> return True
processInput _ _ t "hide" = hideturtle t >> return True
processInput _ _ t "bred" = bgcolor t ((255, 0, 0) :: (Int, Int, Int)) >> return True
processInput _ _ t "bgreen" = bgcolor t ((0, 255, 0) :: (Int, Int, Int)) >> return True
-- processInput _ _ t "home" = goto t 0 0 >> return True
processInput _ _ t "undo" = undo t >> return True
processInput f _ _ "size" = setFieldSize f 100 200 >> return True
processInput f _ _ "topleft" = topleft f >> return True
processInput f _ _ "center" = center f >> return True
processInput _ _ t "goto100" = goto t 100 100 >> return True
processInput _ _ t "clear" = clear t >> return True
processInput _ _ t "svg" = getSVG t >>= print >> return True
processInput _ _ t "home" = home t >> return True
processInput _ _ _ _ = return True
| YoshikuniJujo/gluturtle | tests/testGLUT.hs | bsd-3-clause | 2,710 | 2 | 10 | 542 | 1,120 | 548 | 572 | 47 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TupleSections #-}
module Generalization where
import Control.Exception.Base
import Data.List hiding (group, groupBy)
import qualified Data.Map as Map
import Embed
import qualified Subst
import Syntax
import Text.Printf (printf)
import Util.Miscellaneous (map1in3)
import qualified FreshNames as FN
import qualified Environment as Env
import Control.Monad.State
type Generalizer = Subst.Subst
class Generalization a g | g -> a where
generalize :: Generalizer -> Generalizer -> g -> g -> State (FN.PolyFreshNames a) (g, Generalizer, Generalizer)
instance Generalization S (G S) where
generalize gen1 gen2 (Invoke f as) (Invoke g bs) | f == g =
map1in3 (Invoke f) <$> generalize gen1 gen2 as bs
generalize _ _ x y =
error (printf "Failed to generalize calls.\nAttempting to generalize\n%s\n%s\n" (show x) (show y))
instance Generalization S (Term S) where
generalize gen1 s2 (C m ms) (C n ns) | m == n =
map1in3 (C m) <$> generalize gen1 s2 ms ns
generalize gen1 s2 (V x) (V y) | x == y =
return (V x, gen1, s2)
generalize gen1 s2 t1 t2 = do
names <- get
let (v, vs) = FN.getFreshName names
put vs
return (V v, Subst.insert v t1 gen1, Subst.insert v t2 s2)
instance Generalization S (f S) => Generalization S [f S] where
generalize gen1 gen2 ns ms | length ns == length ms =
map1in3 reverse <$>
foldM (\(gs, gen1, gen2) (t1, t2) ->
map1in3 (:gs) <$> generalize gen1 gen2 t1 t2
)
([], gen1, gen2)
(zip ns ms)
generalizeGoals :: FN.FreshNames -> [G S] -> [G S] -> ([G S], Generalizer, Generalizer, FN.FreshNames)
generalizeGoals s as bs | as `isRenaming` bs =
let (Just subst) = inst as bs Map.empty in
(bs, Subst.Subst subst, Subst.empty, s)
generalizeGoals s as bs | length as == length bs =
let ((g, gen1, gen2), d) = runState (generalize Subst.empty Subst.empty as bs) s in
refine (g, gen1, gen2, d)
generalizeGoals _ as bs = error $ printf "Cannot generalize: different lengths of\nas: %s\nbs: %s\n" (show as) (show bs)
generalizeSplit :: FN.FreshNames -> [G S] -> [G S] -> ([G S], [G S], Generalizer, Generalizer, FN.FreshNames)
generalizeSplit s gs hs =
let (ok, notOk) = go gs hs in
let (res, gen1, gen2, d) = generalizeGoals s gs ok in
(res, notOk, gen1, gen2, d)
where
go gs hs | length gs == length hs = (hs, [])
go (g : gs) (h : hs) | g `embed` h =
let (ok, notOk) = go gs hs in
(h : ok, notOk)
go (g : gs) (h : hs) =
let (ok, notOk) = go (g : gs) hs in
(ok, h : notOk)
go [] hs = ([], hs)
refine :: ([G S], Generalizer, Generalizer, FN.FreshNames) -> ([G S], Generalizer, Generalizer, FN.FreshNames)
refine msg@(g, Subst.Subst s1, Subst.Subst s2, d) =
let similar1 = filter ((>1) . length) $ groupBy group (Map.toList s1) [] in
let similar2 = filter ((>1) . length) $ groupBy group (Map.toList s2) [] in
let sim1 = map (map fst) similar1 in
let sim2 = map (map fst) similar2 in
let toSwap = concatMap (\(x:xs) -> map (, V x) xs) (sim1 `intersect` sim2) in
let newGoal = Subst.substitute (Subst.Subst $ Map.fromList toSwap) g in
let s2' = filter (\(x,_) -> x `notElem` map fst toSwap) (Map.toList s2) in
let s1' = filter (\(x,_) -> x `notElem` map fst toSwap) (Map.toList s1) in
(newGoal, Subst.Subst $ Map.fromList s1', Subst.Subst $ Map.fromList s2', d)
where
groupBy _ [] acc = acc
groupBy p xs acc =
let (similar, rest) = partition (p (head xs)) xs in
assert (similar /= []) $ groupBy p rest (similar : acc)
group x y = snd x == snd y
generalizeAllVarsToFree :: [G S] -> Env.Env -> ([G S], Generalizer, Env.Env)
generalizeAllVarsToFree goals env =
let (gs, gens, d') = foldl go ([], [], Env.getFreshNames env) goals in
(reverse gs, Subst.Subst $ Map.fromList $ concat $ reverse gens, Env.updateNames env d')
where
go (acc, gens, vars) (Invoke n args) =
let (vs, newVars) = FN.getNames (length args) vars in
let gen = zip vs args in
(Invoke n (map V vs) : acc, gen : gens, newVars)
| kajigor/uKanren_transformations | src/Generalization.hs | bsd-3-clause | 4,323 | 0 | 27 | 1,109 | 1,983 | 1,028 | 955 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ExistentialQuantification #-}
module Graphics.Rendering.Ipe.Attributes where
import Data.Char(toLower)
import Data.Maybe
import Data.Semigroup
import Data.Text(Text)
import Data.Text.Format
import Text.XML(Name)
import Diagrams.Attributes
import Diagrams.Backend.Ipe.Attributes
import Diagrams.Backend.Ipe.Types
import Diagrams.Core.Style(getAttr, AttributeClass, Style, addAttr )
import Graphics.Rendering.Ipe.IpeWriteable
import qualified Data.Map as M
import qualified Data.Text as T
--------------------------------------------------------------------------------
-- | Generic functions and types to deal with attributes
type AttrMap = M.Map Name Text
-- | A class expressing how to construct a name and text value, that we use in the XML
-- representation.
--
-- Minimal implementation: either toAttr or both atName and atVal.
class ToAttribute v where
atName :: v -> Name
atName = fst . toAttr
atVal :: v -> Text
atVal = snd . toAttr
toAttr :: v -> (Name,Text)
toAttr v = (atName v, atVal v)
-- | Existential data type wrapping around all things that can be convert to an attribute.
data Attribute = forall a. (ToAttribute a) => Attr a
-- | given a list of attributes, produce an attribute map that we use in the XML elements
attributes :: [Maybe Attribute] -> AttrMap
attributes = M.fromList . map f . catMaybes
where
f (Attr a') = toAttr a'
attr :: forall a. ToAttribute a => Maybe a -> Maybe Attribute
attr = fmap Attr
showT :: Show a => a -> Text
showT = T.pack . show
--------------------------------------------------------------------------------
-- | Info Attributes
instance ToAttribute Title where
atName = const "title"
atVal = getLast . title'
instance ToAttribute Subject where
atName = const "subject"
atVal = getLast . subject'
instance ToAttribute Author where
atName = const "author"
atVal = getLast . author'
instance ToAttribute PageMode where
atName = const "pagemode"
atVal = showT . getLast . pageMode'
instance ToAttribute NumberPages where
atName = const "numberpages"
atVal v = case getLast . numberPages' $ v of
True -> "yes"
False -> "no"
instance ToAttribute Created where
atName = const "created"
atVal = showT . getLast . created'
instance ToAttribute Modified where
atName = const "modified"
atVal = showT . getLast . modified'
--------------------------------------------------------------------------------
-- | Common Attributes (for IpeObjects)
-- | The attributes valid in *all* ipeObjects
commonAttributes :: Style v -> AttrMap
commonAttributes s = attributes [ attr (a :: Maybe Layer)
, attr (a :: Maybe Pin)
, attr (a :: Maybe Transformations)
]
where
a :: forall a. AttributeClass a => Maybe a
a = getAttr s
instance ToAttribute Layer where
atName = const "layer"
atVal = getLast . layer'
instance ToAttribute Pin where
atName = const "pin"
atVal v = case getLast . pin' $ v of
Pinned -> "yes"
Horizontal -> "h"
Vertical -> "v"
instance ToAttribute Transformations where
atName = const "transformations"
atVal = T.toLower . showT . getLast . transformations'
----------------------------------------
-- | Attributes not valid in all, but several types of ipeObjects
instance ToAttribute LineColor where
atName = const "stroke"
atVal = colorVal . getLineColor
instance ToAttribute FillColor where
atName = const "fill"
atVal = colorVal . getFillColor
instance ToAttribute LineWidth where
atName = const "pen"
atVal = showT . getLineWidth
--------------------------------------------------------------------------------
-- | Path Attributes
instance ToAttribute Opacity where
atName = const "opacity"
atVal = opacityVal . getOpacity
instance ToAttribute DashingA where
atName = const "dash"
atVal v = case getDashing v of
Dashing _ _ -> "TODO"
-- -- dash
-- -- (optional) Either a symbolic name defined in a style sheet, or a dash pattern in PDF format, such as "[3 1] 0" for "three pixels on, one off, starting with the first pixel". If the attribute is missing, a solid line is drawn.
-- -- cap
-- -- (optional) The line cap setting of PDF as an integer. If the argument is missing, the setting from the style sheet is used.
-- -- join
-- -- (optional) The line join setting of PDF as an integer. If the argument is missing, the setting from the style sheet is used.
-- -- fillrule
-- -- (optional) Possible values are wind and eofill, selecting one of two algorithms for determining whether a point lies inside a filled object. If the argument is missing, the setting from the style sheet is used.
-- -- arrow
-- -- (optional) The value consists of a symbolic name, say "triangle" for an arrow type (a symbol with name "arrow/triangle(spx)"), followed by a slash and the size of the arrow. The size is either a symbolic name (of type "arrowsize") defined in a style sheet, or a real number. If the attribute is missing, no arrow is drawn.
-- -- rarrow
-- -- (optional) Same for an arrow in the reverse direction (at the beginning of the first subpath).
-- -- opacity
-- -- (optional) Opacity of the element. This must be a symbolic name. The default is 1.0, meaning fully opaque.
-- -- tiling
-- -- (optional) A tiling pattern to be used to fill the element. The default is not to tile the element. If the element is not filled, then the tiling pattern is ignored.
-- -- gradient
-- -- (optional) A gradient pattern to be used to fill the element. If the element is not filled, then the gradient pattern is ignored. (The fill color is only used for rendering where gradients are not available, for instance currently in Postscript.) If gradient is set, then tiling is ignored.
--------------------------------------------------------------------------------
-- | Use Attributes
instance ToAttribute MarkName where
atName = const "name"
atVal v = case getLast . markName' $ v of
Mark n ops -> toStrictT $ format "mark/{}({})" (n,map toT ops)
where
toT :: MarkOption -> Char
toT = toLower . head . show
instance ToAttribute SymbolSize where
atName = const "size"
atVal = showT . getLast . symbolSize'
--------------------------------------------------------------------------------
-- | Text Attributes
-- type
-- (required) Possible values are label and minipage.
-- stroke
-- (optional) The stroke color. If the attribute is missing, black will be used.
-- size
-- (optional) The font size—either a symbolic name defined in a style sheet, or a real number. The default is "normal".
-- pos
-- (required) Two real numbers separated by white space, defining the position of the text on the paper.
-- width
-- (required for minipage objects, optional for label objects) The width of the object in points.
-- height
-- (optional) The total height of the object in points.
-- depth
-- (optional) The depth of the object in points.
-- valign
-- (optional) Possible values are top (default for a minipage object), bottom (default for a label object), center, and baseline.
-- halign
-- (optional, label only) Possible values are left, right, and center. left is the default. This determines the position of the reference point with respect to the text box.
-- style
-- (optional, minipage only) Selects a LaTeX "style" to be used for formatting the text, and must be a symbolic name defined in a style sheet. The standard style sheet defines the styles "normal", "center", "itemize", and "item". If the attribute is not present, the "normal" style is applied.
-- opacity
-- (optional) Opacity of the element. This must be a symbolic name. The default is 1.0, meaning fully opaque.
--------------------------------------------------------------------------------
-- | Image/Bitmap Attributes
bitmapAttrs = undefined
rect :: IsIpeNum a => Rect a -> M.Map Name Text
rect = M.singleton "rect" . toStrictText
--------------------------------------------------------------------------------
-- | Stuff with colors
colorVal :: forall c. Color c => c -> Text
colorVal = colorToRgbString
colorToRgbString :: forall c . Color c => c -> Text
colorToRgbString (colorToSRGBA -> (r,g,b,_)) = T.intercalate " " . map showT $ [r,g,b]
opacityVal :: Double -> Text
opacityVal = const "1.0" -- TODO: this must be a symbolic name in Ipe
colorToOpacity :: forall c . Color c => c -> Double
colorToOpacity (colorToSRGBA -> (_,_,_,a)) = a
| noinia/diagrams-ipe | src/Graphics/Rendering/Ipe/Attributes.hs | bsd-3-clause | 8,900 | 0 | 12 | 1,959 | 1,308 | 727 | 581 | 110 | 1 |
{-# LANGUAGE RankNTypes, MultiParamTypeClasses,FlexibleInstances, FlexibleContexts #-}
import Criterion.Types
import qualified Data.Discrimination as D
import Data.Ix
import Data.List
import Test.BigOh
import qualified Test.BigOh.Fit.R as R
import Control.Monad
import Prelude hiding (abs)
main
= rVoodoo
$ do header "free:"
go (== 2) (== R.Quadratic) (lengthTrace . slowRunRevEcho)
header "codensity:"
go (== 1) (== R.Linear) (lengthTrace . fastRunRevEcho)
where
go i o f
= do x <- genRunWhnf (defaultsForListInput :: Settings [Char])
{ generator = return . genInputSized
, benchConf = defaultBenchmarkConfig { timeLimit = 2 }
, sampleRange = (10,2000)
, numSamples = 10
}
f
graphPoints $ getPoints x
header "Naive:"
naive i x
header "R:"
rlm o x
data Free f a = Return a | Wrap (f (Free f a))
instance Functor f => Functor (Free f) where
fmap f x = x >>= return . f
instance Functor f => Applicative (Free f) where
pure = Return
(<*>) = ap
instance Functor f => Monad (Free f) where
return = Return
Return a >>= k = k a
Wrap t >>= k = Wrap (fmap (>>= k) t)
newtype C m a = C (forall b. (a -> m b) -> m b)
rep :: Monad m => m a -> C m a
rep m = C (m >>=)
abs :: Monad m => C m a -> m a
abs (C p) = p return
instance Functor (C m) where
fmap f x = x >>= return . f
instance Applicative (C m) where
pure = return
(<*>) = ap
instance Monad (C m) where
return a = C ($ a)
C r >>= k = C (\h -> r (\a -> case k a of C q -> q h))
class (Functor f, Monad m) => FreeLike f m where
wrap :: f (m a) -> m a
instance Functor f => FreeLike f (Free f) where
wrap = Wrap
instance FreeLike f m => FreeLike f (C m) where
wrap t = C (\h -> wrap (fmap (\(C r) -> r h) t))
improve :: Functor f => (forall m. FreeLike f m => m a) -> Free f a
improve m = abs m
data FakeIO n = GetChar (Char -> n)
| PutChar Char n
instance Functor FakeIO where
fmap f (GetChar c) = GetChar (fmap f c)
fmap f (PutChar c n) = PutChar c (f n)
getChar' :: FreeLike FakeIO m => m Char
getChar' = wrap (GetChar return)
putChar' :: FreeLike FakeIO m => Char -> m ()
putChar' c = wrap (PutChar c (return ()))
revEcho :: FreeLike FakeIO m => m ()
revEcho = do
c <- getChar'
when (c /= ' ') $ do
revEcho
putChar' c
lengthTrace :: Trace a -> Int
lengthTrace (Read t) = lengthTrace t
lengthTrace (Print _ t) = 1 + lengthTrace t
lengthTrace _ = 0
data Trace a = Read (Trace a) | Print Char (Trace a) | Finish a deriving (Show)
run :: Free FakeIO a -> [Char] -> Trace a
run (Return a) cs = Finish a
run (Wrap (GetChar f)) (c:cs) = Read (run (f c) cs)
run (Wrap (PutChar c f)) cs = Print c (run f cs)
slowRunRevEcho :: [Char] -> Trace ()
slowRunRevEcho = run (revEcho :: Free FakeIO ())
fastRunRevEcho :: [Char] -> Trace ()
fastRunRevEcho = run (improve revEcho)
genInputSized :: Int -> [Char]
genInputSized n = take n (cycle "abcdefgh") ++ " "
| tranma/big-oh | example/codensity.hs | bsd-3-clause | 3,195 | 0 | 15 | 977 | 1,436 | 730 | 706 | 88 | 1 |
-- | Extended utilities for 'Bool' type.
module Extended.Data.Bool
( (==>)
) where
import Universum
-- | Logical implication.
(==>) :: Bool -> Bool -> Bool
False ==> _ = True
True ==> x = x
infixr 4 ==>
| serokell/importify | src/Extended/Data/Bool.hs | mit | 231 | 0 | 6 | 67 | 61 | 36 | 25 | 7 | 1 |
-- https://www.codewars.com/kata/fruit-machine
module Haskell.SylarDoom.FruitMachine where
import Data.List (group, sort, sortOn)
fruit :: [[String]] -> [Int] -> Int
fruit = (score .) . extract
extract :: [[String]] -> [Int] -> [String]
extract = zipWith (!!) . map cycle
score :: [String] -> Int
score items =
case xitem of
[x] -> threeOfTheSame x
["Wild", x] -> twoOfTheSamePlusOneWild x
[_, x] -> twoOfTheSame x
_ -> 0
where
xitem = map head . sortOn length . group . sort $ items
threeOfTheSame :: String -> Int
threeOfTheSame = (* 10) . twoOfTheSame
twoOfTheSamePlusOneWild :: String -> Int
twoOfTheSamePlusOneWild = (* 2) . twoOfTheSame
twoOfTheSame :: String -> Int
twoOfTheSame "Wild" = 10
twoOfTheSame "Star" = 9
twoOfTheSame "Bell" = 8
twoOfTheSame "Shell" = 7
twoOfTheSame "Seven" = 6
twoOfTheSame "Cherry" = 5
twoOfTheSame "Bar" = 4
twoOfTheSame "King" = 3
twoOfTheSame "Queen" = 2
twoOfTheSame "Jack" = 1
twoOfTheSame _ = undefined
| airtial/Codegames | codewars/fruit-machine.hs | gpl-2.0 | 977 | 0 | 11 | 182 | 343 | 188 | 155 | 30 | 4 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.ElasticTranscoder.CancelJob
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | The CancelJob operation cancels an unfinished job.
--
-- You can only cancel a job that has a status of 'Submitted'. To prevent a
-- pipeline from starting to process a job while you're getting the job
-- identifier, use 'UpdatePipelineStatus' to temporarily pause the pipeline.
--
-- <http://docs.aws.amazon.com/elastictranscoder/latest/developerguide/CancelJob.html>
module Network.AWS.ElasticTranscoder.CancelJob
(
-- * Request
CancelJob
-- ** Request constructor
, cancelJob
-- ** Request lenses
, cjId
-- * Response
, CancelJobResponse
-- ** Response constructor
, cancelJobResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.RestJSON
import Network.AWS.ElasticTranscoder.Types
import qualified GHC.Exts
newtype CancelJob = CancelJob
{ _cjId :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'CancelJob' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cjId' @::@ 'Text'
--
cancelJob :: Text -- ^ 'cjId'
-> CancelJob
cancelJob p1 = CancelJob
{ _cjId = p1
}
-- | The identifier of the job that you want to cancel.
--
-- To get a list of the jobs (including their 'jobId') that have a status of 'Submitted', use the 'ListJobsByStatus' API action.
cjId :: Lens' CancelJob Text
cjId = lens _cjId (\s a -> s { _cjId = a })
data CancelJobResponse = CancelJobResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'CancelJobResponse' constructor.
cancelJobResponse :: CancelJobResponse
cancelJobResponse = CancelJobResponse
instance ToPath CancelJob where
toPath CancelJob{..} = mconcat
[ "/2012-09-25/jobs/"
, toText _cjId
]
instance ToQuery CancelJob where
toQuery = const mempty
instance ToHeaders CancelJob
instance ToJSON CancelJob where
toJSON = const (toJSON Empty)
instance AWSRequest CancelJob where
type Sv CancelJob = ElasticTranscoder
type Rs CancelJob = CancelJobResponse
request = delete
response = nullResponse CancelJobResponse
| kim/amazonka | amazonka-elastictranscoder/gen/Network/AWS/ElasticTranscoder/CancelJob.hs | mpl-2.0 | 3,133 | 0 | 9 | 708 | 367 | 226 | 141 | 49 | 1 |
{-# OPTIONS_GHC -fglasgow-exts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Comonad.Stream
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Control.Comonad.Stream
( Stream
) where
import Control.Comonad.Cofree
import Control.Monad.Identity
type Stream = Cofree Identity
-- class ComonadStream w where fby :: a -> (w a -> a)
-- next :: w a -> w a
-- run :: (ComonadStream w, ComonadContext Int c) => (c a -> b) -> w a -> w b
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Comonad/Stream.hs | apache-2.0 | 739 | 4 | 5 | 125 | 52 | 38 | 14 | 6 | 0 |
import Paraiso
import Integrator
import System.Environment
import Debug.Trace
main = do
args <- getArgs
let arch = if "--cuda" `elem` args then
CUDA 128 128
else
X86
putStrLn $ compile arch code
where
code = do
parallel 16384 $ do
x <- allocate
y <- allocate
z <- allocate
x =$ Rand 10 (20.0::Double)
y =$ Rand 10 20
z =$ Rand 10 20
cuda $ do
p <- allocate
r <- allocate
b <- allocate
p =$ 10
r =$ 28
b =$ 8/3
integrate4 0.01 (10 * 655.36) $ [
d_dt x $ - p*x + p*y ,
d_dt y $ - x*z + r*x - y ,
d_dt z $ x*y - b*z ]
output [x,y,z]
| nushio3/Paraiso | attic/paraiso-2008-ODEsolver/MainLorenz.hs | bsd-3-clause | 842 | 0 | 22 | 431 | 310 | 149 | 161 | 30 | 2 |
{- |
Module : $Header$
Copyright : (c) Christian Maeder, Uni Bremen 2004-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : luecke@informatik.uni-bremen.de
Stability : provisional
Portability : portable
static analysis of modal logic parts
-}
module Modal.StatAna (basicModalAnalysis, minExpForm) where
import Modal.AS_Modal
import Modal.Print_AS ()
import Modal.ModalSign
import CASL.Sign
import CASL.MixfixParser
import CASL.StaticAna
import CASL.AS_Basic_CASL
import CASL.ShowMixfix
import CASL.Overload
import CASL.Quantification
import Common.AS_Annotation
import Common.GlobalAnnotations
import Common.Keywords
import Common.Lib.State
import Common.Id
import Common.Result
import Common.ExtSign
import qualified Common.Lib.MapSet as MapSet
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.List as List
import Data.Function
instance TermExtension M_FORMULA where
freeVarsOfExt sign (BoxOrDiamond _ _ f _) = freeVars sign f
basicModalAnalysis
:: (BASIC_SPEC M_BASIC_ITEM M_SIG_ITEM M_FORMULA,
Sign M_FORMULA ModalSign, GlobalAnnos)
-> Result (BASIC_SPEC M_BASIC_ITEM M_SIG_ITEM M_FORMULA,
ExtSign (Sign M_FORMULA ModalSign) Symbol,
[Named (FORMULA M_FORMULA)])
basicModalAnalysis =
basicAnalysis minExpForm ana_M_BASIC_ITEM ana_M_SIG_ITEM ana_Mix
ana_Mix :: Mix M_BASIC_ITEM M_SIG_ITEM M_FORMULA ModalSign
ana_Mix = emptyMix
{ getSigIds = ids_M_SIG_ITEM
, putParen = mapM_FORMULA
, mixResolve = resolveM_FORMULA
}
-- rigid ops will also be part of the CASL signature
ids_M_SIG_ITEM :: M_SIG_ITEM -> IdSets
ids_M_SIG_ITEM si = let e = Set.empty in case si of
Rigid_op_items _ al _ ->
(unite2 $ map (ids_OP_ITEM . item) al, e)
Rigid_pred_items _ al _ ->
((e, e), Set.unions $ map (ids_PRED_ITEM . item) al)
mapMODALITY :: MODALITY -> MODALITY
mapMODALITY m = case m of
Term_mod t -> Term_mod $ mapTerm mapM_FORMULA t
_ -> m
mapM_FORMULA :: M_FORMULA -> M_FORMULA
mapM_FORMULA (BoxOrDiamond b m f ps) =
BoxOrDiamond b (mapMODALITY m) (mapFormula mapM_FORMULA f) ps
resolveMODALITY :: MixResolve MODALITY
resolveMODALITY ga ids m = case m of
Term_mod t -> fmap Term_mod $ resolveMixTrm mapM_FORMULA
resolveM_FORMULA ga ids t
_ -> return m
resolveM_FORMULA :: MixResolve M_FORMULA
resolveM_FORMULA ga ids cf = case cf of
BoxOrDiamond b m f ps -> do
nm <- resolveMODALITY ga ids m
nf <- resolveMixFrm mapM_FORMULA resolveM_FORMULA ga ids f
return $ BoxOrDiamond b nm nf ps
minExpForm :: Min M_FORMULA ModalSign
minExpForm s form =
let minMod md ps = case md of
Simple_mod i -> minMod (Term_mod (Mixfix_token i)) ps
Term_mod t -> let
r = do
t2 <- oneExpTerm minExpForm s t
let srt = sortOfTerm t2
trm = Term_mod t2
supers = supersortsOf srt s
if Set.null $ Set.intersection
(Set.insert srt supers)
$ Map.keysSet $ termModies $ extendedInfo s
then Result [mkDiag Error
("unknown term modality sort '"
++ showId srt "' for term") t ]
$ Just trm
else return trm
in case t of
Mixfix_token tm ->
if Map.member tm (modies $ extendedInfo s)
|| tokStr tm == emptyS
then return $ Simple_mod tm
else Result
[mkDiag Error "unknown modality" tm]
$ Just $ Simple_mod tm
Application (Op_name (Id [tm] [] _)) [] _ ->
if Map.member tm (modies $ extendedInfo s)
then return $ Simple_mod tm
else r
_ -> r
in case form of
BoxOrDiamond b m f ps ->
do nm <- minMod m ps
f2 <- minExpFORMULA minExpForm s f
return $ BoxOrDiamond b nm f2 ps
ana_M_SIG_ITEM :: Ana M_SIG_ITEM M_BASIC_ITEM M_SIG_ITEM M_FORMULA ModalSign
ana_M_SIG_ITEM mix mi =
case mi of
Rigid_op_items r al ps ->
do ul <- mapM (ana_OP_ITEM minExpForm mix) al
case r of
Flexible -> mapM_ (\ aoi -> case item aoi of
Op_decl ops ty _ _ ->
mapM_ (updateExtInfo . addFlexOp (toOpType ty)) ops
Op_defn i par _ _ -> maybe (return ())
(\ ty -> updateExtInfo $ addFlexOp (toOpType ty) i)
$ headToType par) ul
Rigid -> return ()
return $ Rigid_op_items r ul ps
Rigid_pred_items r al ps ->
do ul <- mapM (ana_PRED_ITEM minExpForm mix) al
case r of
Flexible -> mapM_ (\ aoi -> case item aoi of
Pred_decl ops ty _ ->
mapM_ (updateExtInfo . addFlexPred (toPredType ty)) ops
Pred_defn i (Pred_head args _) _ _ ->
updateExtInfo $ addFlexPred
(PredType $ sortsOfArgs args) i ) ul
Rigid -> return ()
return $ Rigid_pred_items r ul ps
addFlexOp :: OpType -> Id -> ModalSign -> Result ModalSign
addFlexOp ty i m = return
m { flexOps = addOpTo i ty $ flexOps m }
addFlexPred :: PredType -> Id -> ModalSign -> Result ModalSign
addFlexPred ty i m = return
m { flexPreds = MapSet.insert i ty $ flexPreds m }
ana_M_BASIC_ITEM
:: Ana M_BASIC_ITEM M_BASIC_ITEM M_SIG_ITEM M_FORMULA ModalSign
ana_M_BASIC_ITEM mix bi = case bi of
Simple_mod_decl al fs ps -> do
mapM_ ((updateExtInfo . preAddModId) . item) al
newFs <- mapAnM (ana_FORMULA mix) fs
resFs <- mapAnM (return . fst) newFs
anaFs <- mapAnM (return . snd) newFs
mapM_ ((updateExtInfo . addModId anaFs) . item) al
return $ Simple_mod_decl al resFs ps
Term_mod_decl al fs ps -> do
e <- get
mapM_ ((updateExtInfo . preAddModSort e) . item) al
newFs <- mapAnM (ana_FORMULA mix) fs
resFs <- mapAnM (return . fst) newFs
anaFs <- mapAnM (return . snd) newFs
mapM_ ((updateExtInfo . addModSort anaFs) . item) al
return $ Term_mod_decl al resFs ps
preAddModId :: SIMPLE_ID -> ModalSign -> Result ModalSign
preAddModId i m =
let ms = modies m in
if Map.member i ms then
Result [mkDiag Hint "repeated modality" i] $ Just m
else return m { modies = Map.insert i [] ms }
addModId :: [AnModFORM] -> SIMPLE_ID -> ModalSign -> Result ModalSign
addModId frms i m = return m
{ modies = Map.insertWith List.union i frms $ modies m }
preAddModSort :: Sign M_FORMULA ModalSign -> SORT -> ModalSign
-> Result ModalSign
preAddModSort e i m =
let ms = termModies m
ds = hasSort e i
in if Map.member i ms || not (null ds) then
Result (mkDiag Hint "repeated term modality" i : ds) $ Just m
else return m { termModies = Map.insert i [] ms }
addModSort :: [AnModFORM] -> SORT -> ModalSign -> Result ModalSign
addModSort frms i m = return m
{ termModies = Map.insertWith List.union i frms $ termModies m }
ana_FORMULA :: Mix M_BASIC_ITEM M_SIG_ITEM M_FORMULA ModalSign
-> FORMULA M_FORMULA -> State (Sign M_FORMULA ModalSign)
(FORMULA M_FORMULA, FORMULA M_FORMULA)
ana_FORMULA mix f = do
let ps = map simpleIdToId $ Set.toList $ getFormPredToks f
pm <- gets predMap
mapM_ (addPred (emptyAnno ()) $ PredType []) ps
newGa <- gets globAnnos
let Result es m = resolveFormula mapM_FORMULA
resolveM_FORMULA newGa (mixRules mix) f
addDiags es
e <- get
phi <- case m of
Nothing -> return (f, f)
Just r -> do
n <- resultToState (minExpFORMULA minExpForm e) r
return (r, n)
e2 <- get
put e2 {predMap = pm}
return phi
getFormPredToks :: FORMULA M_FORMULA -> Set.Set Token
getFormPredToks frm = case frm of
Quantification _ _ f _ -> getFormPredToks f
Junction _ fs _ -> Set.unions $ map getFormPredToks fs
Relation f1 _ f2 _ -> on Set.union getFormPredToks f1 f2
Negation f _ -> getFormPredToks f
Mixfix_formula (Mixfix_token t) -> Set.singleton t
Mixfix_formula t -> getTermPredToks t
ExtFORMULA (BoxOrDiamond _ _ f _) -> getFormPredToks f
Predication _ ts _ -> Set.unions $ map getTermPredToks ts
Definedness t _ -> getTermPredToks t
Equation t1 _ t2 _ -> on Set.union getTermPredToks t1 t2
Membership t _ _ -> getTermPredToks t
_ -> Set.empty
getTermPredToks :: TERM M_FORMULA -> Set.Set Token
getTermPredToks trm = case trm of
Application _ ts _ -> Set.unions $ map getTermPredToks ts
Sorted_term t _ _ -> getTermPredToks t
Cast t _ _ -> getTermPredToks t
Conditional t1 f t2 _ -> Set.union (getTermPredToks t1) $
Set.union (getFormPredToks f) $ getTermPredToks t2
Mixfix_term ts -> Set.unions $ map getTermPredToks ts
Mixfix_parenthesized ts _ -> Set.unions $ map getTermPredToks ts
Mixfix_bracketed ts _ -> Set.unions $ map getTermPredToks ts
Mixfix_braced ts _ -> Set.unions $ map getTermPredToks ts
_ -> Set.empty
| mariefarrell/Hets | Modal/StatAna.hs | gpl-2.0 | 9,719 | 1 | 28 | 3,215 | 3,002 | 1,450 | 1,552 | 213 | 12 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.