Search is not available for this dataset
repo_name
string | path
string | license
string | full_code
string | full_size
int64 | uncommented_code
string | uncommented_size
int64 | function_only_code
string | function_only_size
int64 | is_commented
bool | is_signatured
bool | n_ast_errors
int64 | ast_max_depth
int64 | n_whitespaces
int64 | n_ast_nodes
int64 | n_ast_terminals
int64 | n_ast_nonterminals
int64 | loc
int64 | cycloplexity
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Enzo-Liu/cis194
|
src/Adt03.hs
|
bsd-3-clause
|
desugar (Incr var) = DAssign var (Op (Var var) Plus (Val 1))
| 60
|
desugar (Incr var) = DAssign var (Op (Var var) Plus (Val 1))
| 60
|
desugar (Incr var) = DAssign var (Op (Var var) Plus (Val 1))
| 60
| false
| false
| 0
| 9
| 11
| 42
| 20
| 22
| null | null |
romanb/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/Types.hs
|
mpl-2.0
|
-- | The ID of the network interface attachment.
niaAttachmentId :: Lens' NetworkInterfaceAttachment (Maybe Text)
niaAttachmentId = lens _niaAttachmentId (\s a -> s { _niaAttachmentId = a })
| 190
|
niaAttachmentId :: Lens' NetworkInterfaceAttachment (Maybe Text)
niaAttachmentId = lens _niaAttachmentId (\s a -> s { _niaAttachmentId = a })
| 141
|
niaAttachmentId = lens _niaAttachmentId (\s a -> s { _niaAttachmentId = a })
| 76
| true
| true
| 1
| 9
| 27
| 51
| 25
| 26
| null | null |
fmapfmapfmap/amazonka
|
amazonka-s3/gen/Network/AWS/S3/HeadBucket.hs
|
mpl-2.0
|
-- | Creates a value of 'HeadBucket' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'hbBucket'
headBucket
:: BucketName -- ^ 'hbBucket'
-> HeadBucket
headBucket pBucket_ =
HeadBucket'
{ _hbBucket = pBucket_
}
| 314
|
headBucket
:: BucketName -- ^ 'hbBucket'
-> HeadBucket
headBucket pBucket_ =
HeadBucket'
{ _hbBucket = pBucket_
}
| 133
|
headBucket pBucket_ =
HeadBucket'
{ _hbBucket = pBucket_
}
| 70
| true
| true
| 0
| 6
| 70
| 32
| 20
| 12
| null | null |
randen/cabal
|
cabal-install/Distribution/Client/Tar.hs
|
bsd-3-clause
|
toTarPath :: Bool -- ^ Is the path for a directory? This is needed because for
-- directories a 'TarPath' must always use a trailing @\/@.
-> FilePath -> Either String TarPath
toTarPath isDir = splitLongPath
. addTrailingSep
. FilePath.Posix.joinPath
. FilePath.Native.splitDirectories
where
addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator
| otherwise = id
-- | Take a sanitized path, split on directory separators and try to pack it
-- into the 155 + 100 tar file name format.
--
-- The strategy is this: take the name-directory components in reverse order
-- and try to fit as many components into the 100 long name area as possible.
-- If all the remaining components fit in the 155 name area then we win.
--
| 834
|
toTarPath :: Bool -- ^ Is the path for a directory? This is needed because for
-- directories a 'TarPath' must always use a trailing @\/@.
-> FilePath -> Either String TarPath
toTarPath isDir = splitLongPath
. addTrailingSep
. FilePath.Posix.joinPath
. FilePath.Native.splitDirectories
where
addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator
| otherwise = id
-- | Take a sanitized path, split on directory separators and try to pack it
-- into the 155 + 100 tar file name format.
--
-- The strategy is this: take the name-directory components in reverse order
-- and try to fit as many components into the 100 long name area as possible.
-- If all the remaining components fit in the 155 name area then we win.
--
| 834
|
toTarPath isDir = splitLongPath
. addTrailingSep
. FilePath.Posix.joinPath
. FilePath.Native.splitDirectories
where
addTrailingSep | isDir = FilePath.Posix.addTrailingPathSeparator
| otherwise = id
-- | Take a sanitized path, split on directory separators and try to pack it
-- into the 155 + 100 tar file name format.
--
-- The strategy is this: take the name-directory components in reverse order
-- and try to fit as many components into the 100 long name area as possible.
-- If all the remaining components fit in the 155 name area then we win.
--
| 630
| false
| true
| 0
| 7
| 227
| 80
| 44
| 36
| null | null |
headprogrammingczar/cabal
|
Cabal/Distribution/Version.hs
|
bsd-3-clause
|
isWildcardRange :: Version -> Version -> Bool
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
| 998
|
isWildcardRange :: Version -> Version -> Bool
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
| 998
|
isWildcardRange (Version branch1 _) (Version branch2 _) = check branch1 branch2
where check (n:[]) (m:[]) | n+1 == m = True
check (n:ns) (m:ms) | n == m = check ns ms
check _ _ = False
------------------
-- Intervals view
--
-- | A complementary representation of a 'VersionRange'. Instead of a boolean
-- version predicate it uses an increasing sequence of non-overlapping,
-- non-empty intervals.
--
-- The key point is that this representation gives a canonical representation
-- for the semantics of 'VersionRange's. This makes it easier to check things
-- like whether a version range is empty, covers all versions, or requires a
-- certain minimum or maximum version. It also makes it easy to check equality
-- or containment. It also makes it easier to identify \'simple\' version
-- predicates for translation into foreign packaging systems that do not
-- support complex version range expressions.
--
| 952
| false
| true
| 1
| 9
| 200
| 153
| 83
| 70
| null | null |
OpenXT/network
|
nws/NetworkUtils.hs
|
gpl-2.0
|
enableBridgeNetfilter = do
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-arptables"
logAndExecuteIptables $ printf "-t nat -I POSTROUTING -m physdev --physdev-is-bridge -j ACCEPT"
| 342
|
enableBridgeNetfilter = do
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-arptables"
logAndExecuteIptables $ printf "-t nat -I POSTROUTING -m physdev --physdev-is-bridge -j ACCEPT"
| 342
|
enableBridgeNetfilter = do
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-ip6tables"
spawnShell "echo 1 > /proc/sys/net/bridge/bridge-nf-call-arptables"
logAndExecuteIptables $ printf "-t nat -I POSTROUTING -m physdev --physdev-is-bridge -j ACCEPT"
| 342
| false
| false
| 0
| 8
| 46
| 34
| 13
| 21
| null | null |
afiodorov/pamTree
|
Pam.hs
|
mit
|
initial :: BinTree Double
initial = treeFromList $ 1 : repeat 0
| 63
|
initial :: BinTree Double
initial = treeFromList $ 1 : repeat 0
| 63
|
initial = treeFromList $ 1 : repeat 0
| 37
| false
| true
| 0
| 6
| 11
| 25
| 12
| 13
| null | null |
peletomi/icanhasren
|
Tests.hs
|
gpl-3.0
|
isUpperFirst [] = False
| 27
|
isUpperFirst [] = False
| 27
|
isUpperFirst [] = False
| 27
| false
| false
| 1
| 5
| 7
| 15
| 5
| 10
| null | null |
keera-studios/hsQt
|
Qtc/ClassTypes/Gui.hs
|
bsd-2-clause
|
qCast_QUndoView :: Object a -> IO (QUndoView ())
qCast_QUndoView _qobj
= return (objectCast _qobj)
| 100
|
qCast_QUndoView :: Object a -> IO (QUndoView ())
qCast_QUndoView _qobj
= return (objectCast _qobj)
| 100
|
qCast_QUndoView _qobj
= return (objectCast _qobj)
| 51
| false
| true
| 0
| 9
| 15
| 41
| 19
| 22
| null | null |
SKA-ScienceDataProcessor/RC
|
MS4/lib/DNA/Interpreter/Run.hs
|
apache-2.0
|
----------------------------------------------------------------
-- Functions for starting actors
----------------------------------------------------------------
-- | Start execution of standard actor
runActor :: Actor a b -> Process ()
runActor (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
-- Send data destination back
sendChan (actorSendBack p)
( RcvSimple (wrapMessage chSendParam)
, [sendPortId chSendParam]
)
-- Now we can start execution and send back data
a <- receiveChan chRecvParam
!b <- runDnaParam p (action a)
sendResult p b
{-
-- | Run actor for group of processes which allow more than 1 task per
-- actor.
runActorManyRanks :: Actor a b -> Process ()
runActorManyRanks (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendDst, chRecvDst ) <- newChan
(chSendRnk, chRecvRnk ) <- newChan
-- Send shell process back
sendChan (actorSendBack p)
(RcvSimple (wrapMessage chSendParam))
-- let shell = ( RecvVal chSendParam
-- , SendVal chSendDst )
-- send (actorParent p) (chSendRnk,shell)
-- -- Start actor execution
-- a <- receiveChan chRecvParam
-- let loop dst = do
-- send (actorParent p) (me,chSendRnk)
-- mrnk <- receiveChan chRecvRnk
-- case mrnk of
-- Nothing -> return ()
-- Just rnk -> do
-- !b <- runDnaParam p{actorRank = rnk} (action a)
-- dst' <- drainChannel0 chRecvDst dst
-- sendToDest dst' b
-- send (actorParent p) (me,DoneTask)
-- loop dst'
-- loop =<< drainChannel chRecvDst
-}
-- | Start execution of collector actor
| 1,962
|
runActor :: Actor a b -> Process ()
runActor (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
-- Send data destination back
sendChan (actorSendBack p)
( RcvSimple (wrapMessage chSendParam)
, [sendPortId chSendParam]
)
-- Now we can start execution and send back data
a <- receiveChan chRecvParam
!b <- runDnaParam p (action a)
sendResult p b
{-
-- | Run actor for group of processes which allow more than 1 task per
-- actor.
runActorManyRanks :: Actor a b -> Process ()
runActorManyRanks (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendDst, chRecvDst ) <- newChan
(chSendRnk, chRecvRnk ) <- newChan
-- Send shell process back
sendChan (actorSendBack p)
(RcvSimple (wrapMessage chSendParam))
-- let shell = ( RecvVal chSendParam
-- , SendVal chSendDst )
-- send (actorParent p) (chSendRnk,shell)
-- -- Start actor execution
-- a <- receiveChan chRecvParam
-- let loop dst = do
-- send (actorParent p) (me,chSendRnk)
-- mrnk <- receiveChan chRecvRnk
-- case mrnk of
-- Nothing -> return ()
-- Just rnk -> do
-- !b <- runDnaParam p{actorRank = rnk} (action a)
-- dst' <- drainChannel0 chRecvDst dst
-- sendToDest dst' b
-- send (actorParent p) (me,DoneTask)
-- loop dst'
-- loop =<< drainChannel chRecvDst
-}
-- | Start execution of collector actor
| 1,759
|
runActor (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
-- Send data destination back
sendChan (actorSendBack p)
( RcvSimple (wrapMessage chSendParam)
, [sendPortId chSendParam]
)
-- Now we can start execution and send back data
a <- receiveChan chRecvParam
!b <- runDnaParam p (action a)
sendResult p b
{-
-- | Run actor for group of processes which allow more than 1 task per
-- actor.
runActorManyRanks :: Actor a b -> Process ()
runActorManyRanks (Actor action) = do
-- Obtain parameters
p <- expect
-- Create channels for communication
(chSendParam,chRecvParam) <- newChan
(chSendDst, chRecvDst ) <- newChan
(chSendRnk, chRecvRnk ) <- newChan
-- Send shell process back
sendChan (actorSendBack p)
(RcvSimple (wrapMessage chSendParam))
-- let shell = ( RecvVal chSendParam
-- , SendVal chSendDst )
-- send (actorParent p) (chSendRnk,shell)
-- -- Start actor execution
-- a <- receiveChan chRecvParam
-- let loop dst = do
-- send (actorParent p) (me,chSendRnk)
-- mrnk <- receiveChan chRecvRnk
-- case mrnk of
-- Nothing -> return ()
-- Just rnk -> do
-- !b <- runDnaParam p{actorRank = rnk} (action a)
-- dst' <- drainChannel0 chRecvDst dst
-- sendToDest dst' b
-- send (actorParent p) (me,DoneTask)
-- loop dst'
-- loop =<< drainChannel chRecvDst
-}
-- | Start execution of collector actor
| 1,723
| true
| true
| 0
| 11
| 592
| 136
| 68
| 68
| null | null |
brendanhay/gogol
|
gogol-healthcare/gen/Network/Google/Healthcare/Types/Product.hs
|
mpl-2.0
|
-- | The returned Messages. Won\'t be more Messages than the value of
-- page_size in the request. See view for populated fields.
lmrHl7V2Messages :: Lens' ListMessagesResponse [Message]
lmrHl7V2Messages
= lens _lmrHl7V2Messages
(\ s a -> s{_lmrHl7V2Messages = a})
. _Default
. _Coerce
| 305
|
lmrHl7V2Messages :: Lens' ListMessagesResponse [Message]
lmrHl7V2Messages
= lens _lmrHl7V2Messages
(\ s a -> s{_lmrHl7V2Messages = a})
. _Default
. _Coerce
| 175
|
lmrHl7V2Messages
= lens _lmrHl7V2Messages
(\ s a -> s{_lmrHl7V2Messages = a})
. _Default
. _Coerce
| 118
| true
| true
| 3
| 8
| 62
| 60
| 29
| 31
| null | null |
RossMeikleham/GPC
|
tests/GPC/ParserTests.hs
|
bsd-2-clause
|
assignCheck :: [(ProgramPos, Either String ProgramPos)]
assignCheck = [asInt, asChr, asBool, asDouble, asStr, asId]
where
-- |Check integer literal assignment
asInt = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "x") (ExpLit (Number srcPos (Left 20))))],
parseSource "int x = 20;")
-- |Check char literal assignment
asChr = (Program [TLAssign (Assign (NormalType srcPos False "char") (identPos "y") (ExpLit (Ch srcPos 'c')))],
parseSource "char y = 'c';")
-- |Check bool literal assignment
asBool = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b") (ExpLit (Bl srcPos False)))],
parseSource "bool b = false;")
-- |Check float literal assignment
asDouble = (Program [TLAssign (Assign (NormalType srcPos False "double") (identPos "d") (ExpLit (Number srcPos (Right 20.4))))],
parseSource "double d = 20.4;")
-- |Check string literal assignment
asStr = (Program [TLAssign (Assign (NormalType srcPos False "string") (identPos "s") (ExpLit (Str srcPos "hi")))],
parseSource "string s = \"hi\";")
-- |Check identifier assignment
asId = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")))],
parseSource "int i = x;")
-- | List of ProgramPoss which should fail assignment by the parser
assignFailCheck :: [Either String ProgramPos]
assignFailCheck = [noSemi, noAssign]
where
-- | No semicolon at end of statement
noSemi = parseSource "int x ="
-- | No equals, variables are single assignment
noAssign = parseSource "float y;"
-- | Check binary operators are individually parsed
binOpCheck :: [(ProgramPos, Either String ProgramPos)]
binOpCheck = [ asMul, asEq, asShift, asPrece, asPrece2
, asPrece3, asPrece4, asPrece5, asPrece6
, asPrece7, asPrece8, parensCheck]
where
-- Check multiplication assignment of 2 identities
asMul = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "x")) (ExpIdent (identPos "y"))))]
,parseSource "/* Check comment ignored */ int i = x * y;")
-- Check equality assignment of a literal and identity
asEq = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b")
(ExpBinOp (Equals srcPos) (ExpLit (Bl srcPos True)) (ExpIdent (identPos "b"))))]
,parseSource "bool b = true == b;")
-- Check shift assignment of 3 values
asShift = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (ShiftL srcPos) ( ExpBinOp (ShiftL srcPos) (ExpLit (Number srcPos (Left 4))) (ExpLit (Number srcPos (Left 3))))
(ExpLit (Number srcPos (Left 2)))))]
,parseSource "int i = 4 << 3 << 2;")
-- Check operator precedence works
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Mul srcPos) (
ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int j = a + b * c;")
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (Add srcPos) (ExpBinOp (Mul srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a * b + c;")
asPrece3 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Equals srcPos) (ExpBinOp (Div srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a / b == c;")
asPrece4 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (ShiftL srcPos) (ExpBinOp (Mod srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a % b << c;")
asPrece5 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Less srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b < c;")
asPrece6 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (BOr srcPos)
(ExpBinOp (BXor srcPos)
(ExpBinOp (BAnd srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpIdent (identPos "c"))
)
(ExpIdent (identPos "d"))
))]
,parseSource "int k = a & b ^ c | d;")
asPrece7 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Or srcPos)
(ExpBinOp (And srcPos)
(ExpBinOp (LessEq srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpBinOp (Greater srcPos) (ExpIdent (identPos "c")) (ExpIdent (identPos "d")))
)
(ExpBinOp (GreaterEq srcPos) (ExpIdent (identPos "e")) (ExpIdent (identPos "f")))
)
)]
,parseSource "bool k = a <= b && c > d || e >= f;")
asPrece8 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (NEquals srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b != c;")
-- Check precedence with parens
parensCheck = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "l")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Add srcPos)
(ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int l = a * ( b + c);")
-- | Check unary operators are individually parsed
unOpCheck :: [(ProgramPos, Either String ProgramPos)]
unOpCheck = [asNot, asPrece, asPrece2, asParens]
where
-- Check assignment of not identity
asNot = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "i")
(ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x"))))]
,parseSource "bool i = !x;")
-- Check precedence with binary operators
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "b")))))]
,parseSource "int j = a + ~b;")
-- Check precedence with binary operators
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "a"))) (ExpIdent (identPos "b"))))]
,parseSource "int j = ~ a + b;")
-- Check precedence with parenthesis
asParens = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpUnaryOp (Neg srcPos) (ExpBinOp (Sub srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))))]
,parseSource "int k = -(a - b);")
-- | Check function calls made within functions are correctly parsed
funCallCheck :: [(ProgramPos, Either String ProgramPos)]
funCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone]
where
-- Check function with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpFunCall $ FunCall (identPos "test") []))]]
,parseSource $ funStr ++ "int i = test();" ++ "}")
-- Check function with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpFunCall $ FunCall (identPos "func") [ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = func(a);" ++ "}")
-- Check function with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpFunCall $ FunCall (identPos "destroyAllHumans") [ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = destroyAllHumans(a, b);" ++ "}")
-- Check function with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpFunCall $ FunCall (identPos "call") [ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")),
ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))]]
,parseSource $ funStr ++ "int a = call(a * b, -c);" ++ "}")
-- Check function call statement
standAlone = (Program [fun [FunCallStmt $ FunCall (identPos "call") []]]
,parseSource $ funStr ++ "call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check method calls made within functions are correctly parsed
methodCallCheck :: [(ProgramPos, Either String ProgramPos)]
methodCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone, standAloneIndexed]
where
-- Check method with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "test") []))]]
,parseSource $ funStr ++ "int i = a.test();" ++ "}")
-- Check method with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "func")
[ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = a.func(a);" ++ "}")
-- Check method with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "destroyAllHumans")
[ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = a.destroyAllHumans(a, b);" ++ "}")
-- Check method with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "call")
[ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b"))
,ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))
]]
,parseSource $ funStr ++ "int a = a.call(a * b, -c);" ++ "}")
-- Check method call statement
standAlone = (Program [fun [MethodStmt $ MethodCall (VarIdent $ identPos "a") (identPos "call") []]]
,parseSource $ funStr ++ "a.call();" ++ "}")
--
standAloneIndexed =
(Program [fun [MethodStmt $ MethodCall (VarArrayElem (identPos "a") (ExpLit (Number srcPos $ Left 2)))
(identPos "call") []]]
,parseSource $ funStr ++ "a[2].call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check sequential/parallel blocks are correctly parsed
seqParBlockCheck :: [(ProgramPos, Either String ProgramPos)]
seqParBlockCheck = [seqB, parB, seqMultiB]
where
seqB = (Program [fun [(Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "seq {int i = x;}" ++ "}")
parB = (Program [fun [(BStmt $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "par {int i = x;}" ++ "}")
seqMultiB = (Program [fun [ (Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")),
AssignStmt $ Assign (NormalType srcPos False "int") (identPos "j") (ExpIdent (identPos "y"))])]],
parseSource $ funStr ++ "seq {int i = x; int j = y;}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check If-Else statements are correctly parsed
ifElseCheck :: [(ProgramPos, Either String ProgramPos)]
ifElseCheck = [ifCheck, elseCheck]
where
-- Check If by itself
ifCheck = (Program [fun [
(If (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x")))
(BStmt $ BlockStmt [Return $ ExpIdent (identPos "y")])
)]],
parseSource $ funStr ++ "if (!x) {return y;}" ++ "}")
-- Check If with Else
elseCheck = (Program [fun [
(IfElse (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "z")))
(Return $ ExpIdent (identPos "y"))
(Return $ ExpIdent (identPos "a"))
)]],
parseSource $ funStr ++ "if (!z) return y; else return a;" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check For loop statements are correctly parsed
forLoopCheck :: [(ProgramPos, Either String ProgramPos)]
forLoopCheck = [forCheck]
where
forCheck = (Program [fun [
(ForLoop (identPos "a") (ExpUnaryOp (Neg srcPos) (ExpLit $ Number srcPos $ Left 17))
(ExpBinOp (LessEq srcPos) (ExpIdent $ identPos "a") (ExpLit $ Number srcPos $ Left 16)) (ExpLit $ Number srcPos $ Left 1) (BlockStmt []))]]
, parseSource $ funStr ++ "for (int a = -17; a <= 16; a+=1) {}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check Pointer
pointersCheck :: [(ProgramPos, Either String ProgramPos)]
pointersCheck = [singlePtr, mulPtr]
where
singlePtr = (Program [Func intType (identPos "test") [(PointerType intType, a)]
$ BlockStmt [AssignStmt
$ Assign (PointerType intType) b (ExpIdent a)]]
,parseSource "int test(int *a) {int *b = a;}")
mulPtr = (Program [Func intType (identPos "test") [(triplePtr intType, a)]
$ BlockStmt [AssignStmt
$ Assign (triplePtr intType) b (ExpIdent a)]]
,parseSource "int test(int ***a) {int ***b = a;}")
intType = NormalType srcPos False "int"
triplePtr = PointerType . PointerType . PointerType
a = identPos "a"
b = identPos "b"
validTest :: String -> (ProgramPos, Either String ProgramPos) -> TFA.Test
validTest label (e, a) = testCase label (
case a of
Left err -> assertFailure err
Right p -> assertEqual "" e p)
validTests :: String -> [(ProgramPos, Either String ProgramPos)] -> [TFA.Test]
validTests s ps = map (uncurry validTest) $ zip labels ps
where labels = makeLabels s ps
validObjectsTests :: [TFA.Test]
validObjectsTests = validTests "validObjectDecl" objectsCheck
validObjectConsTests :: [TFA.Test]
validObjectConsTests = validTests "validObjectCons" constructObjsCheck
-- | Test valid assignments
validAssignTests :: [TFA.Test]
validAssignTests = validTests "validAssignTest" assignCheck
-- | Test valid assignments with binary operators
validOpTests :: [TFA.Test]
validOpTests = validTests "validOpTest" binOpCheck
-- | Test valid assignments with unary operators
validUnOpTests :: [TFA.Test]
validUnOpTests = validTests "validUnOpTest" unOpCheck
-- | Test valid function call expressions/statements
validFunCallTests :: [TFA.Test]
validFunCallTests = validTests "validFunCallTest" funCallCheck
-- | Test valid method call expressions/statements
validMethodCallTests :: [TFA.Test]
validMethodCallTests = validTests "validMethodCallTest" methodCallCheck
-- | Test valid sequential/parallel blocks
validSeqParTests :: [TFA.Test]
validSeqParTests = validTests "seqParTest" seqParBlockCheck
-- | Test valid if/else statements
validIfElseTests :: [TFA.Test]
validIfElseTests = validTests "ifElseTest" ifElseCheck
-- | Test valid for loops
validForLoopTests :: [TFA.Test]
validForLoopTests = validTests "forLoopTest" forLoopCheck
-- | Test Pointer Parsing
validPointerTests :: [TFA.Test]
validPointerTests = validTests "pointerTest" pointersCheck
-- | Test invalid statement
invalidTest :: String -> Either String ProgramPos -> TFA.Test
invalidTest label a = testCase label (
unless (isLeft a) $
assertFailure $ "ProgramPos should have caused a parse error" ++ show a)
where isLeft = null . rights . return
invalidAssignTests :: [TFA.Test]
invalidAssignTests = map (uncurry invalidTest) $ zip labels assignFailCheck
where labels = makeLabels "invalidAssignTest" assignFailCheck
invalidObjectsTests :: [TFA.Test]
invalidObjectsTests = map (uncurry invalidTest) $ zip labels invalidObjsCheck
where labels = makeLabels "invalidObjDeclTest" invalidObjsCheck
parserTests = TFA.testGroup "Parser Tests" $ concat
[validAssignTests, invalidAssignTests
,validOpTests, validUnOpTests
,validFunCallTests, validSeqParTests
,validIfElseTests, validForLoopTests, validObjectsTests
,validObjectConsTests, validMethodCallTests
,invalidObjectsTests, validPointerTests
]
| 17,909
|
assignCheck :: [(ProgramPos, Either String ProgramPos)]
assignCheck = [asInt, asChr, asBool, asDouble, asStr, asId]
where
-- |Check integer literal assignment
asInt = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "x") (ExpLit (Number srcPos (Left 20))))],
parseSource "int x = 20;")
-- |Check char literal assignment
asChr = (Program [TLAssign (Assign (NormalType srcPos False "char") (identPos "y") (ExpLit (Ch srcPos 'c')))],
parseSource "char y = 'c';")
-- |Check bool literal assignment
asBool = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b") (ExpLit (Bl srcPos False)))],
parseSource "bool b = false;")
-- |Check float literal assignment
asDouble = (Program [TLAssign (Assign (NormalType srcPos False "double") (identPos "d") (ExpLit (Number srcPos (Right 20.4))))],
parseSource "double d = 20.4;")
-- |Check string literal assignment
asStr = (Program [TLAssign (Assign (NormalType srcPos False "string") (identPos "s") (ExpLit (Str srcPos "hi")))],
parseSource "string s = \"hi\";")
-- |Check identifier assignment
asId = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")))],
parseSource "int i = x;")
-- | List of ProgramPoss which should fail assignment by the parser
assignFailCheck :: [Either String ProgramPos]
assignFailCheck = [noSemi, noAssign]
where
-- | No semicolon at end of statement
noSemi = parseSource "int x ="
-- | No equals, variables are single assignment
noAssign = parseSource "float y;"
-- | Check binary operators are individually parsed
binOpCheck :: [(ProgramPos, Either String ProgramPos)]
binOpCheck = [ asMul, asEq, asShift, asPrece, asPrece2
, asPrece3, asPrece4, asPrece5, asPrece6
, asPrece7, asPrece8, parensCheck]
where
-- Check multiplication assignment of 2 identities
asMul = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "x")) (ExpIdent (identPos "y"))))]
,parseSource "/* Check comment ignored */ int i = x * y;")
-- Check equality assignment of a literal and identity
asEq = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b")
(ExpBinOp (Equals srcPos) (ExpLit (Bl srcPos True)) (ExpIdent (identPos "b"))))]
,parseSource "bool b = true == b;")
-- Check shift assignment of 3 values
asShift = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (ShiftL srcPos) ( ExpBinOp (ShiftL srcPos) (ExpLit (Number srcPos (Left 4))) (ExpLit (Number srcPos (Left 3))))
(ExpLit (Number srcPos (Left 2)))))]
,parseSource "int i = 4 << 3 << 2;")
-- Check operator precedence works
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Mul srcPos) (
ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int j = a + b * c;")
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (Add srcPos) (ExpBinOp (Mul srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a * b + c;")
asPrece3 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Equals srcPos) (ExpBinOp (Div srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a / b == c;")
asPrece4 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (ShiftL srcPos) (ExpBinOp (Mod srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a % b << c;")
asPrece5 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Less srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b < c;")
asPrece6 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (BOr srcPos)
(ExpBinOp (BXor srcPos)
(ExpBinOp (BAnd srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpIdent (identPos "c"))
)
(ExpIdent (identPos "d"))
))]
,parseSource "int k = a & b ^ c | d;")
asPrece7 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Or srcPos)
(ExpBinOp (And srcPos)
(ExpBinOp (LessEq srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpBinOp (Greater srcPos) (ExpIdent (identPos "c")) (ExpIdent (identPos "d")))
)
(ExpBinOp (GreaterEq srcPos) (ExpIdent (identPos "e")) (ExpIdent (identPos "f")))
)
)]
,parseSource "bool k = a <= b && c > d || e >= f;")
asPrece8 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (NEquals srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b != c;")
-- Check precedence with parens
parensCheck = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "l")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Add srcPos)
(ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int l = a * ( b + c);")
-- | Check unary operators are individually parsed
unOpCheck :: [(ProgramPos, Either String ProgramPos)]
unOpCheck = [asNot, asPrece, asPrece2, asParens]
where
-- Check assignment of not identity
asNot = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "i")
(ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x"))))]
,parseSource "bool i = !x;")
-- Check precedence with binary operators
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "b")))))]
,parseSource "int j = a + ~b;")
-- Check precedence with binary operators
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "a"))) (ExpIdent (identPos "b"))))]
,parseSource "int j = ~ a + b;")
-- Check precedence with parenthesis
asParens = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpUnaryOp (Neg srcPos) (ExpBinOp (Sub srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))))]
,parseSource "int k = -(a - b);")
-- | Check function calls made within functions are correctly parsed
funCallCheck :: [(ProgramPos, Either String ProgramPos)]
funCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone]
where
-- Check function with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpFunCall $ FunCall (identPos "test") []))]]
,parseSource $ funStr ++ "int i = test();" ++ "}")
-- Check function with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpFunCall $ FunCall (identPos "func") [ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = func(a);" ++ "}")
-- Check function with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpFunCall $ FunCall (identPos "destroyAllHumans") [ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = destroyAllHumans(a, b);" ++ "}")
-- Check function with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpFunCall $ FunCall (identPos "call") [ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")),
ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))]]
,parseSource $ funStr ++ "int a = call(a * b, -c);" ++ "}")
-- Check function call statement
standAlone = (Program [fun [FunCallStmt $ FunCall (identPos "call") []]]
,parseSource $ funStr ++ "call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check method calls made within functions are correctly parsed
methodCallCheck :: [(ProgramPos, Either String ProgramPos)]
methodCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone, standAloneIndexed]
where
-- Check method with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "test") []))]]
,parseSource $ funStr ++ "int i = a.test();" ++ "}")
-- Check method with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "func")
[ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = a.func(a);" ++ "}")
-- Check method with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "destroyAllHumans")
[ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = a.destroyAllHumans(a, b);" ++ "}")
-- Check method with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "call")
[ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b"))
,ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))
]]
,parseSource $ funStr ++ "int a = a.call(a * b, -c);" ++ "}")
-- Check method call statement
standAlone = (Program [fun [MethodStmt $ MethodCall (VarIdent $ identPos "a") (identPos "call") []]]
,parseSource $ funStr ++ "a.call();" ++ "}")
--
standAloneIndexed =
(Program [fun [MethodStmt $ MethodCall (VarArrayElem (identPos "a") (ExpLit (Number srcPos $ Left 2)))
(identPos "call") []]]
,parseSource $ funStr ++ "a[2].call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check sequential/parallel blocks are correctly parsed
seqParBlockCheck :: [(ProgramPos, Either String ProgramPos)]
seqParBlockCheck = [seqB, parB, seqMultiB]
where
seqB = (Program [fun [(Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "seq {int i = x;}" ++ "}")
parB = (Program [fun [(BStmt $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "par {int i = x;}" ++ "}")
seqMultiB = (Program [fun [ (Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")),
AssignStmt $ Assign (NormalType srcPos False "int") (identPos "j") (ExpIdent (identPos "y"))])]],
parseSource $ funStr ++ "seq {int i = x; int j = y;}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check If-Else statements are correctly parsed
ifElseCheck :: [(ProgramPos, Either String ProgramPos)]
ifElseCheck = [ifCheck, elseCheck]
where
-- Check If by itself
ifCheck = (Program [fun [
(If (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x")))
(BStmt $ BlockStmt [Return $ ExpIdent (identPos "y")])
)]],
parseSource $ funStr ++ "if (!x) {return y;}" ++ "}")
-- Check If with Else
elseCheck = (Program [fun [
(IfElse (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "z")))
(Return $ ExpIdent (identPos "y"))
(Return $ ExpIdent (identPos "a"))
)]],
parseSource $ funStr ++ "if (!z) return y; else return a;" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check For loop statements are correctly parsed
forLoopCheck :: [(ProgramPos, Either String ProgramPos)]
forLoopCheck = [forCheck]
where
forCheck = (Program [fun [
(ForLoop (identPos "a") (ExpUnaryOp (Neg srcPos) (ExpLit $ Number srcPos $ Left 17))
(ExpBinOp (LessEq srcPos) (ExpIdent $ identPos "a") (ExpLit $ Number srcPos $ Left 16)) (ExpLit $ Number srcPos $ Left 1) (BlockStmt []))]]
, parseSource $ funStr ++ "for (int a = -17; a <= 16; a+=1) {}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check Pointer
pointersCheck :: [(ProgramPos, Either String ProgramPos)]
pointersCheck = [singlePtr, mulPtr]
where
singlePtr = (Program [Func intType (identPos "test") [(PointerType intType, a)]
$ BlockStmt [AssignStmt
$ Assign (PointerType intType) b (ExpIdent a)]]
,parseSource "int test(int *a) {int *b = a;}")
mulPtr = (Program [Func intType (identPos "test") [(triplePtr intType, a)]
$ BlockStmt [AssignStmt
$ Assign (triplePtr intType) b (ExpIdent a)]]
,parseSource "int test(int ***a) {int ***b = a;}")
intType = NormalType srcPos False "int"
triplePtr = PointerType . PointerType . PointerType
a = identPos "a"
b = identPos "b"
validTest :: String -> (ProgramPos, Either String ProgramPos) -> TFA.Test
validTest label (e, a) = testCase label (
case a of
Left err -> assertFailure err
Right p -> assertEqual "" e p)
validTests :: String -> [(ProgramPos, Either String ProgramPos)] -> [TFA.Test]
validTests s ps = map (uncurry validTest) $ zip labels ps
where labels = makeLabels s ps
validObjectsTests :: [TFA.Test]
validObjectsTests = validTests "validObjectDecl" objectsCheck
validObjectConsTests :: [TFA.Test]
validObjectConsTests = validTests "validObjectCons" constructObjsCheck
-- | Test valid assignments
validAssignTests :: [TFA.Test]
validAssignTests = validTests "validAssignTest" assignCheck
-- | Test valid assignments with binary operators
validOpTests :: [TFA.Test]
validOpTests = validTests "validOpTest" binOpCheck
-- | Test valid assignments with unary operators
validUnOpTests :: [TFA.Test]
validUnOpTests = validTests "validUnOpTest" unOpCheck
-- | Test valid function call expressions/statements
validFunCallTests :: [TFA.Test]
validFunCallTests = validTests "validFunCallTest" funCallCheck
-- | Test valid method call expressions/statements
validMethodCallTests :: [TFA.Test]
validMethodCallTests = validTests "validMethodCallTest" methodCallCheck
-- | Test valid sequential/parallel blocks
validSeqParTests :: [TFA.Test]
validSeqParTests = validTests "seqParTest" seqParBlockCheck
-- | Test valid if/else statements
validIfElseTests :: [TFA.Test]
validIfElseTests = validTests "ifElseTest" ifElseCheck
-- | Test valid for loops
validForLoopTests :: [TFA.Test]
validForLoopTests = validTests "forLoopTest" forLoopCheck
-- | Test Pointer Parsing
validPointerTests :: [TFA.Test]
validPointerTests = validTests "pointerTest" pointersCheck
-- | Test invalid statement
invalidTest :: String -> Either String ProgramPos -> TFA.Test
invalidTest label a = testCase label (
unless (isLeft a) $
assertFailure $ "ProgramPos should have caused a parse error" ++ show a)
where isLeft = null . rights . return
invalidAssignTests :: [TFA.Test]
invalidAssignTests = map (uncurry invalidTest) $ zip labels assignFailCheck
where labels = makeLabels "invalidAssignTest" assignFailCheck
invalidObjectsTests :: [TFA.Test]
invalidObjectsTests = map (uncurry invalidTest) $ zip labels invalidObjsCheck
where labels = makeLabels "invalidObjDeclTest" invalidObjsCheck
parserTests = TFA.testGroup "Parser Tests" $ concat
[validAssignTests, invalidAssignTests
,validOpTests, validUnOpTests
,validFunCallTests, validSeqParTests
,validIfElseTests, validForLoopTests, validObjectsTests
,validObjectConsTests, validMethodCallTests
,invalidObjectsTests, validPointerTests
]
| 17,909
|
assignCheck = [asInt, asChr, asBool, asDouble, asStr, asId]
where
-- |Check integer literal assignment
asInt = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "x") (ExpLit (Number srcPos (Left 20))))],
parseSource "int x = 20;")
-- |Check char literal assignment
asChr = (Program [TLAssign (Assign (NormalType srcPos False "char") (identPos "y") (ExpLit (Ch srcPos 'c')))],
parseSource "char y = 'c';")
-- |Check bool literal assignment
asBool = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b") (ExpLit (Bl srcPos False)))],
parseSource "bool b = false;")
-- |Check float literal assignment
asDouble = (Program [TLAssign (Assign (NormalType srcPos False "double") (identPos "d") (ExpLit (Number srcPos (Right 20.4))))],
parseSource "double d = 20.4;")
-- |Check string literal assignment
asStr = (Program [TLAssign (Assign (NormalType srcPos False "string") (identPos "s") (ExpLit (Str srcPos "hi")))],
parseSource "string s = \"hi\";")
-- |Check identifier assignment
asId = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")))],
parseSource "int i = x;")
-- | List of ProgramPoss which should fail assignment by the parser
assignFailCheck :: [Either String ProgramPos]
assignFailCheck = [noSemi, noAssign]
where
-- | No semicolon at end of statement
noSemi = parseSource "int x ="
-- | No equals, variables are single assignment
noAssign = parseSource "float y;"
-- | Check binary operators are individually parsed
binOpCheck :: [(ProgramPos, Either String ProgramPos)]
binOpCheck = [ asMul, asEq, asShift, asPrece, asPrece2
, asPrece3, asPrece4, asPrece5, asPrece6
, asPrece7, asPrece8, parensCheck]
where
-- Check multiplication assignment of 2 identities
asMul = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "x")) (ExpIdent (identPos "y"))))]
,parseSource "/* Check comment ignored */ int i = x * y;")
-- Check equality assignment of a literal and identity
asEq = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "b")
(ExpBinOp (Equals srcPos) (ExpLit (Bl srcPos True)) (ExpIdent (identPos "b"))))]
,parseSource "bool b = true == b;")
-- Check shift assignment of 3 values
asShift = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "i")
(ExpBinOp (ShiftL srcPos) ( ExpBinOp (ShiftL srcPos) (ExpLit (Number srcPos (Left 4))) (ExpLit (Number srcPos (Left 3))))
(ExpLit (Number srcPos (Left 2)))))]
,parseSource "int i = 4 << 3 << 2;")
-- Check operator precedence works
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Mul srcPos) (
ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int j = a + b * c;")
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (Add srcPos) (ExpBinOp (Mul srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a * b + c;")
asPrece3 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Equals srcPos) (ExpBinOp (Div srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a / b == c;")
asPrece4 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (ShiftL srcPos) (ExpBinOp (Mod srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "int k = a % b << c;")
asPrece5 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Less srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b < c;")
asPrece6 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpBinOp (BOr srcPos)
(ExpBinOp (BXor srcPos)
(ExpBinOp (BAnd srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpIdent (identPos "c"))
)
(ExpIdent (identPos "d"))
))]
,parseSource "int k = a & b ^ c | d;")
asPrece7 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (Or srcPos)
(ExpBinOp (And srcPos)
(ExpBinOp (LessEq srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))
(ExpBinOp (Greater srcPos) (ExpIdent (identPos "c")) (ExpIdent (identPos "d")))
)
(ExpBinOp (GreaterEq srcPos) (ExpIdent (identPos "e")) (ExpIdent (identPos "f")))
)
)]
,parseSource "bool k = a <= b && c > d || e >= f;")
asPrece8 = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "k")
(ExpBinOp (NEquals srcPos) (ExpBinOp (ShiftR srcPos)
(ExpIdent (identPos "a")) (ExpIdent (identPos "b"))) (ExpIdent (identPos "c"))))]
,parseSource "bool k = a >> b != c;")
-- Check precedence with parens
parensCheck = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "l")
(ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpBinOp (Add srcPos)
(ExpIdent (identPos "b")) (ExpIdent (identPos "c")))))]
,parseSource "int l = a * ( b + c);")
-- | Check unary operators are individually parsed
unOpCheck :: [(ProgramPos, Either String ProgramPos)]
unOpCheck = [asNot, asPrece, asPrece2, asParens]
where
-- Check assignment of not identity
asNot = (Program [TLAssign (Assign (NormalType srcPos False "bool") (identPos "i")
(ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x"))))]
,parseSource "bool i = !x;")
-- Check precedence with binary operators
asPrece = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpIdent (identPos "a")) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "b")))))]
,parseSource "int j = a + ~b;")
-- Check precedence with binary operators
asPrece2 = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "j")
(ExpBinOp (Add srcPos) (ExpUnaryOp (BNot srcPos) (ExpIdent (identPos "a"))) (ExpIdent (identPos "b"))))]
,parseSource "int j = ~ a + b;")
-- Check precedence with parenthesis
asParens = (Program [TLAssign (Assign (NormalType srcPos False "int") (identPos "k")
(ExpUnaryOp (Neg srcPos) (ExpBinOp (Sub srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")))))]
,parseSource "int k = -(a - b);")
-- | Check function calls made within functions are correctly parsed
funCallCheck :: [(ProgramPos, Either String ProgramPos)]
funCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone]
where
-- Check function with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpFunCall $ FunCall (identPos "test") []))]]
,parseSource $ funStr ++ "int i = test();" ++ "}")
-- Check function with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpFunCall $ FunCall (identPos "func") [ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = func(a);" ++ "}")
-- Check function with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpFunCall $ FunCall (identPos "destroyAllHumans") [ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = destroyAllHumans(a, b);" ++ "}")
-- Check function with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpFunCall $ FunCall (identPos "call") [ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b")),
ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))]]
,parseSource $ funStr ++ "int a = call(a * b, -c);" ++ "}")
-- Check function call statement
standAlone = (Program [fun [FunCallStmt $ FunCall (identPos "call") []]]
,parseSource $ funStr ++ "call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check method calls made within functions are correctly parsed
methodCallCheck :: [(ProgramPos, Either String ProgramPos)]
methodCallCheck = [noArgs, singleArgs, multiArgs, multiComplexArgs, standAlone, standAloneIndexed]
where
-- Check method with no arguments
noArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "i")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "test") []))]]
,parseSource $ funStr ++ "int i = a.test();" ++ "}")
-- Check method with one argument
singleArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "test") (identPos "j")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "func")
[ExpIdent (identPos "a")]))]]
,parseSource $ funStr ++ "test j = a.func(a);" ++ "}")
-- Check method with multiple arguments
multiArgs = (Program [fun $ [AssignStmt $ (Assign (NormalType srcPos False "blarg") (identPos "m")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "destroyAllHumans")
[ExpIdent (identPos "a"), ExpIdent (identPos "b")]))]]
,parseSource$ funStr ++ "blarg m = a.destroyAllHumans(a, b);" ++ "}")
-- Check method with multiple arguments with expressions
multiComplexArgs = (Program [ fun $ [AssignStmt $ (Assign (NormalType srcPos False "int") (identPos "a")
(ExpMethodCall $ MethodCall (VarIdent $ identPos "a") (identPos "call")
[ExpBinOp (Mul srcPos) (ExpIdent (identPos "a")) (ExpIdent (identPos "b"))
,ExpUnaryOp (Neg srcPos) (ExpIdent (identPos "c"))]))
]]
,parseSource $ funStr ++ "int a = a.call(a * b, -c);" ++ "}")
-- Check method call statement
standAlone = (Program [fun [MethodStmt $ MethodCall (VarIdent $ identPos "a") (identPos "call") []]]
,parseSource $ funStr ++ "a.call();" ++ "}")
--
standAloneIndexed =
(Program [fun [MethodStmt $ MethodCall (VarArrayElem (identPos "a") (ExpLit (Number srcPos $ Left 2)))
(identPos "call") []]]
,parseSource $ funStr ++ "a[2].call();" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check sequential/parallel blocks are correctly parsed
seqParBlockCheck :: [(ProgramPos, Either String ProgramPos)]
seqParBlockCheck = [seqB, parB, seqMultiB]
where
seqB = (Program [fun [(Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "seq {int i = x;}" ++ "}")
parB = (Program [fun [(BStmt $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x"))])]],
parseSource $ funStr ++ "par {int i = x;}" ++ "}")
seqMultiB = (Program [fun [ (Seq $ BlockStmt [AssignStmt $ Assign
(NormalType srcPos False "int") (identPos "i") (ExpIdent (identPos "x")),
AssignStmt $ Assign (NormalType srcPos False "int") (identPos "j") (ExpIdent (identPos "y"))])]],
parseSource $ funStr ++ "seq {int i = x; int j = y;}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check If-Else statements are correctly parsed
ifElseCheck :: [(ProgramPos, Either String ProgramPos)]
ifElseCheck = [ifCheck, elseCheck]
where
-- Check If by itself
ifCheck = (Program [fun [
(If (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "x")))
(BStmt $ BlockStmt [Return $ ExpIdent (identPos "y")])
)]],
parseSource $ funStr ++ "if (!x) {return y;}" ++ "}")
-- Check If with Else
elseCheck = (Program [fun [
(IfElse (ExpUnaryOp (Not srcPos) (ExpIdent (identPos "z")))
(Return $ ExpIdent (identPos "y"))
(Return $ ExpIdent (identPos "a"))
)]],
parseSource $ funStr ++ "if (!z) return y; else return a;" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check For loop statements are correctly parsed
forLoopCheck :: [(ProgramPos, Either String ProgramPos)]
forLoopCheck = [forCheck]
where
forCheck = (Program [fun [
(ForLoop (identPos "a") (ExpUnaryOp (Neg srcPos) (ExpLit $ Number srcPos $ Left 17))
(ExpBinOp (LessEq srcPos) (ExpIdent $ identPos "a") (ExpLit $ Number srcPos $ Left 16)) (ExpLit $ Number srcPos $ Left 1) (BlockStmt []))]]
, parseSource $ funStr ++ "for (int a = -17; a <= 16; a+=1) {}" ++ "}")
fun xs = Func (NormalType srcPos False "tes") (identPos "test") [] (BlockStmt xs)
funStr = "tes test() {"
-- | Check Pointer
pointersCheck :: [(ProgramPos, Either String ProgramPos)]
pointersCheck = [singlePtr, mulPtr]
where
singlePtr = (Program [Func intType (identPos "test") [(PointerType intType, a)]
$ BlockStmt [AssignStmt
$ Assign (PointerType intType) b (ExpIdent a)]]
,parseSource "int test(int *a) {int *b = a;}")
mulPtr = (Program [Func intType (identPos "test") [(triplePtr intType, a)]
$ BlockStmt [AssignStmt
$ Assign (triplePtr intType) b (ExpIdent a)]]
,parseSource "int test(int ***a) {int ***b = a;}")
intType = NormalType srcPos False "int"
triplePtr = PointerType . PointerType . PointerType
a = identPos "a"
b = identPos "b"
validTest :: String -> (ProgramPos, Either String ProgramPos) -> TFA.Test
validTest label (e, a) = testCase label (
case a of
Left err -> assertFailure err
Right p -> assertEqual "" e p)
validTests :: String -> [(ProgramPos, Either String ProgramPos)] -> [TFA.Test]
validTests s ps = map (uncurry validTest) $ zip labels ps
where labels = makeLabels s ps
validObjectsTests :: [TFA.Test]
validObjectsTests = validTests "validObjectDecl" objectsCheck
validObjectConsTests :: [TFA.Test]
validObjectConsTests = validTests "validObjectCons" constructObjsCheck
-- | Test valid assignments
validAssignTests :: [TFA.Test]
validAssignTests = validTests "validAssignTest" assignCheck
-- | Test valid assignments with binary operators
validOpTests :: [TFA.Test]
validOpTests = validTests "validOpTest" binOpCheck
-- | Test valid assignments with unary operators
validUnOpTests :: [TFA.Test]
validUnOpTests = validTests "validUnOpTest" unOpCheck
-- | Test valid function call expressions/statements
validFunCallTests :: [TFA.Test]
validFunCallTests = validTests "validFunCallTest" funCallCheck
-- | Test valid method call expressions/statements
validMethodCallTests :: [TFA.Test]
validMethodCallTests = validTests "validMethodCallTest" methodCallCheck
-- | Test valid sequential/parallel blocks
validSeqParTests :: [TFA.Test]
validSeqParTests = validTests "seqParTest" seqParBlockCheck
-- | Test valid if/else statements
validIfElseTests :: [TFA.Test]
validIfElseTests = validTests "ifElseTest" ifElseCheck
-- | Test valid for loops
validForLoopTests :: [TFA.Test]
validForLoopTests = validTests "forLoopTest" forLoopCheck
-- | Test Pointer Parsing
validPointerTests :: [TFA.Test]
validPointerTests = validTests "pointerTest" pointersCheck
-- | Test invalid statement
invalidTest :: String -> Either String ProgramPos -> TFA.Test
invalidTest label a = testCase label (
unless (isLeft a) $
assertFailure $ "ProgramPos should have caused a parse error" ++ show a)
where isLeft = null . rights . return
invalidAssignTests :: [TFA.Test]
invalidAssignTests = map (uncurry invalidTest) $ zip labels assignFailCheck
where labels = makeLabels "invalidAssignTest" assignFailCheck
invalidObjectsTests :: [TFA.Test]
invalidObjectsTests = map (uncurry invalidTest) $ zip labels invalidObjsCheck
where labels = makeLabels "invalidObjDeclTest" invalidObjsCheck
parserTests = TFA.testGroup "Parser Tests" $ concat
[validAssignTests, invalidAssignTests
,validOpTests, validUnOpTests
,validFunCallTests, validSeqParTests
,validIfElseTests, validForLoopTests, validObjectsTests
,validObjectConsTests, validMethodCallTests
,invalidObjectsTests, validPointerTests
]
| 17,853
| false
| true
| 79
| 21
| 4,527
| 5,870
| 2,898
| 2,972
| null | null |
jfeltz/dash-haskell
|
src/Pipe/Conf.hs
|
lgpl-3.0
|
ghcVersionRange :: CV.VersionRange
ghcVersionRange =
CV.intersectVersionRanges
(CV.orLaterVersion (CV.Version [7,10] []))
(CV.earlierVersion (CV.Version [7,10,2] []))
| 175
|
ghcVersionRange :: CV.VersionRange
ghcVersionRange =
CV.intersectVersionRanges
(CV.orLaterVersion (CV.Version [7,10] []))
(CV.earlierVersion (CV.Version [7,10,2] []))
| 175
|
ghcVersionRange =
CV.intersectVersionRanges
(CV.orLaterVersion (CV.Version [7,10] []))
(CV.earlierVersion (CV.Version [7,10,2] []))
| 140
| false
| true
| 0
| 10
| 22
| 75
| 40
| 35
| null | null |
Gonzih/HNApi
|
Parser.hs
|
mit
|
zerifyComments s = s
| 28
|
zerifyComments s = s
| 28
|
zerifyComments s = s
| 28
| false
| false
| 0
| 5
| 11
| 9
| 4
| 5
| null | null |
yxm4109/pandoc
|
src/Text/Pandoc/Readers/HTML.hs
|
gpl-2.0
|
unsanitaryURI :: String -> Bool
unsanitaryURI u =
let safeURISchemes = [ "", "http:", "https:", "ftp:", "mailto:", "file:",
"telnet:", "gopher:", "aaa:", "aaas:", "acap:", "cap:", "cid:",
"crid:", "dav:", "dict:", "dns:", "fax:", "go:", "h323:", "im:",
"imap:", "ldap:", "mid:", "news:", "nfs:", "nntp:", "pop:",
"pres:", "sip:", "sips:", "snmp:", "tel:", "urn:", "wais:",
"xmpp:", "z39.50r:", "z39.50s:", "aim:", "callto:", "cvs:",
"ed2k:", "feed:", "fish:", "gg:", "irc:", "ircs:", "lastfm:",
"ldaps:", "magnet:", "mms:", "msnim:", "notes:", "rsync:",
"secondlife:", "skype:", "ssh:", "sftp:", "smb:", "sms:",
"snews:", "webcal:", "ymsgr:"]
in case parseURIReference u of
Just p -> (map toLower $ uriScheme p) `notElem` safeURISchemes
Nothing -> True
-- | Read blocks until end tag.
| 930
|
unsanitaryURI :: String -> Bool
unsanitaryURI u =
let safeURISchemes = [ "", "http:", "https:", "ftp:", "mailto:", "file:",
"telnet:", "gopher:", "aaa:", "aaas:", "acap:", "cap:", "cid:",
"crid:", "dav:", "dict:", "dns:", "fax:", "go:", "h323:", "im:",
"imap:", "ldap:", "mid:", "news:", "nfs:", "nntp:", "pop:",
"pres:", "sip:", "sips:", "snmp:", "tel:", "urn:", "wais:",
"xmpp:", "z39.50r:", "z39.50s:", "aim:", "callto:", "cvs:",
"ed2k:", "feed:", "fish:", "gg:", "irc:", "ircs:", "lastfm:",
"ldaps:", "magnet:", "mms:", "msnim:", "notes:", "rsync:",
"secondlife:", "skype:", "ssh:", "sftp:", "smb:", "sms:",
"snews:", "webcal:", "ymsgr:"]
in case parseURIReference u of
Just p -> (map toLower $ uriScheme p) `notElem` safeURISchemes
Nothing -> True
-- | Read blocks until end tag.
| 930
|
unsanitaryURI u =
let safeURISchemes = [ "", "http:", "https:", "ftp:", "mailto:", "file:",
"telnet:", "gopher:", "aaa:", "aaas:", "acap:", "cap:", "cid:",
"crid:", "dav:", "dict:", "dns:", "fax:", "go:", "h323:", "im:",
"imap:", "ldap:", "mid:", "news:", "nfs:", "nntp:", "pop:",
"pres:", "sip:", "sips:", "snmp:", "tel:", "urn:", "wais:",
"xmpp:", "z39.50r:", "z39.50s:", "aim:", "callto:", "cvs:",
"ed2k:", "feed:", "fish:", "gg:", "irc:", "ircs:", "lastfm:",
"ldaps:", "magnet:", "mms:", "msnim:", "notes:", "rsync:",
"secondlife:", "skype:", "ssh:", "sftp:", "smb:", "sms:",
"snews:", "webcal:", "ymsgr:"]
in case parseURIReference u of
Just p -> (map toLower $ uriScheme p) `notElem` safeURISchemes
Nothing -> True
-- | Read blocks until end tag.
| 898
| false
| true
| 0
| 13
| 245
| 260
| 161
| 99
| null | null |
beni55/texmath
|
src/Text/TeXMath/Readers/TeX.hs
|
gpl-2.0
|
boxed :: TP Exp
boxed = EBoxed <$> (ctrlseq "boxed" *> texToken)
| 64
|
boxed :: TP Exp
boxed = EBoxed <$> (ctrlseq "boxed" *> texToken)
| 64
|
boxed = EBoxed <$> (ctrlseq "boxed" *> texToken)
| 48
| false
| true
| 2
| 8
| 11
| 35
| 15
| 20
| null | null |
GaloisInc/halvm-ghc
|
compiler/ghci/ByteCodeGen.hs
|
bsd-3-clause
|
isVoidArg :: ArgRep -> Bool
isVoidArg V = True
| 46
|
isVoidArg :: ArgRep -> Bool
isVoidArg V = True
| 46
|
isVoidArg V = True
| 18
| false
| true
| 0
| 5
| 8
| 18
| 9
| 9
| null | null |
netrium/Netrium
|
src/Valuation.hs
|
mit
|
-- |Lift functions for binary operations
lift2PrAll :: (a -> a -> a) -> PR a -> PR a -> PR a
lift2PrAll f (PR a) (PR b) = PR $ zipWithAll (zipWith f) a b
| 153
|
lift2PrAll :: (a -> a -> a) -> PR a -> PR a -> PR a
lift2PrAll f (PR a) (PR b) = PR $ zipWithAll (zipWith f) a b
| 112
|
lift2PrAll f (PR a) (PR b) = PR $ zipWithAll (zipWith f) a b
| 60
| true
| true
| 0
| 8
| 35
| 86
| 40
| 46
| null | null |
LouisJenkinsCS/Minimal-JVM
|
MateVMRuntime/BlockAllocation.hs
|
bsd-3-clause
|
generation0 :: GcState -> GenState
generation0 s = generations s !0
| 67
|
generation0 :: GcState -> GenState
generation0 s = generations s !0
| 67
|
generation0 s = generations s !0
| 32
| false
| true
| 0
| 7
| 10
| 31
| 13
| 18
| null | null |
vladimir-ipatov/ganeti
|
src/Ganeti/Constants.hs
|
gpl-2.0
|
ssHvparamsXenHvm :: String
ssHvparamsXenHvm = ssHvparamsPref ++ htXenHvm
| 72
|
ssHvparamsXenHvm :: String
ssHvparamsXenHvm = ssHvparamsPref ++ htXenHvm
| 72
|
ssHvparamsXenHvm = ssHvparamsPref ++ htXenHvm
| 45
| false
| true
| 2
| 6
| 7
| 23
| 9
| 14
| null | null |
beni55/github
|
samples/Teams/Memberships/DeleteTeamMembershipFor.hs
|
bsd-3-clause
|
main = do
args <- getArgs
result <- case args of
[token, team_id, username] ->
Github.deleteTeamMembershipFor' (Github.GithubOAuth token) (read team_id) username
_ ->
error "usage: DeleteTeamMembershipFor <token> <team_id> <username>"
case result of
Left err -> putStrLn $ "Error: " ++ show err
Right team -> putStrLn $ show team
| 430
|
main = do
args <- getArgs
result <- case args of
[token, team_id, username] ->
Github.deleteTeamMembershipFor' (Github.GithubOAuth token) (read team_id) username
_ ->
error "usage: DeleteTeamMembershipFor <token> <team_id> <username>"
case result of
Left err -> putStrLn $ "Error: " ++ show err
Right team -> putStrLn $ show team
| 430
|
main = do
args <- getArgs
result <- case args of
[token, team_id, username] ->
Github.deleteTeamMembershipFor' (Github.GithubOAuth token) (read team_id) username
_ ->
error "usage: DeleteTeamMembershipFor <token> <team_id> <username>"
case result of
Left err -> putStrLn $ "Error: " ++ show err
Right team -> putStrLn $ show team
| 430
| false
| false
| 1
| 15
| 149
| 118
| 54
| 64
| null | null |
mwotton/ctkl
|
src/Text/CTK/Pretty.hs
|
bsd-3-clause
|
(<^>) :: Doc -> Doc -> Doc
(<^>) = (<>)
| 40
|
(<^>) :: Doc -> Doc -> Doc
(<^>) = (<>)
| 40
|
(<^>) = (<>)
| 13
| false
| true
| 0
| 8
| 10
| 32
| 17
| 15
| null | null |
tlunter/PushBullet
|
src/Web/PushBullet/Push.hs
|
mit
|
readResponse :: Result (JSObject JSValue) -> Response
readResponse (Ok x) = Response { responseIden = iden, responseCreated = created }
where iden = readString "iden" x
created = readInt "created" x
| 215
|
readResponse :: Result (JSObject JSValue) -> Response
readResponse (Ok x) = Response { responseIden = iden, responseCreated = created }
where iden = readString "iden" x
created = readInt "created" x
| 215
|
readResponse (Ok x) = Response { responseIden = iden, responseCreated = created }
where iden = readString "iden" x
created = readInt "created" x
| 161
| false
| true
| 1
| 8
| 47
| 70
| 36
| 34
| null | null |
GRACeFUL-project/haskelzinc
|
src/Interfaces/MZPrinter.hs
|
bsd-3-clause
|
printParensExpr _ e = printExpr e
| 34
|
printParensExpr _ e = printExpr e
| 34
|
printParensExpr _ e = printExpr e
| 34
| false
| false
| 0
| 5
| 6
| 14
| 6
| 8
| null | null |
mdsteele/fallback
|
src/Fallback/Resource.hs
|
gpl-3.0
|
readFromFile :: (Read a) => FilePath -> IO (Maybe a)
readFromFile filepath = parseFromFile filepath parseRead
| 109
|
readFromFile :: (Read a) => FilePath -> IO (Maybe a)
readFromFile filepath = parseFromFile filepath parseRead
| 109
|
readFromFile filepath = parseFromFile filepath parseRead
| 56
| false
| true
| 0
| 10
| 15
| 47
| 21
| 26
| null | null |
mikusp/accelerate-cuda
|
Data/Array/Accelerate/CUDA/CodeGen/Base.hs
|
bsd-3-clause
|
umul24 :: DeviceProperties -> C.Exp -> C.Exp -> C.Exp
umul24 dev x y
| computeCapability dev < Compute 2 0 = [cexp| __umul24($exp:x, $exp:y) |]
| otherwise = [cexp| $exp:x * $exp:y |]
| 213
|
umul24 :: DeviceProperties -> C.Exp -> C.Exp -> C.Exp
umul24 dev x y
| computeCapability dev < Compute 2 0 = [cexp| __umul24($exp:x, $exp:y) |]
| otherwise = [cexp| $exp:x * $exp:y |]
| 213
|
umul24 dev x y
| computeCapability dev < Compute 2 0 = [cexp| __umul24($exp:x, $exp:y) |]
| otherwise = [cexp| $exp:x * $exp:y |]
| 159
| false
| true
| 1
| 10
| 62
| 75
| 38
| 37
| null | null |
TravisWhitaker/BroScore-backend
|
BroScore/WebHandlers.hs
|
mit
|
mkContextHandler :: BroAction
mkContextHandler bs = do
cn <- param "context"
ds <- param "description"
liftIO (mkContext bs cn ds) >>= \case Just s -> status s
Nothing -> return ()
| 234
|
mkContextHandler :: BroAction
mkContextHandler bs = do
cn <- param "context"
ds <- param "description"
liftIO (mkContext bs cn ds) >>= \case Just s -> status s
Nothing -> return ()
| 234
|
mkContextHandler bs = do
cn <- param "context"
ds <- param "description"
liftIO (mkContext bs cn ds) >>= \case Just s -> status s
Nothing -> return ()
| 204
| false
| true
| 0
| 13
| 84
| 85
| 36
| 49
| null | null |
vinnymac/glot-www
|
Model/Language.hs
|
mit
|
languageDefaultContent Idris = [multiline|module Main
main : IO ()
main = putStrLn "Hello World!"|]
| 100
|
languageDefaultContent Idris = [multiline|module Main
main : IO ()
main = putStrLn "Hello World!"|]
| 100
|
languageDefaultContent Idris = [multiline|module Main
main : IO ()
main = putStrLn "Hello World!"|]
| 100
| false
| false
| 0
| 5
| 14
| 13
| 8
| 5
| null | null |
itsbruce/hackerrank
|
alg/bits/lonelyInt.hs
|
unlicense
|
single :: [Int] -> Int
single = head . M.keys . M.filter (== 1) . foldr (\i m -> M.insertWith (+) i 1 m) M.empty
| 112
|
single :: [Int] -> Int
single = head . M.keys . M.filter (== 1) . foldr (\i m -> M.insertWith (+) i 1 m) M.empty
| 112
|
single = head . M.keys . M.filter (== 1) . foldr (\i m -> M.insertWith (+) i 1 m) M.empty
| 89
| false
| true
| 0
| 10
| 24
| 71
| 38
| 33
| null | null |
byorgey/Idris-dev
|
src/Idris/REPL.hs
|
bsd-3-clause
|
parseArgs ("--include":ns) = ShowIncs : (parseArgs ns)
| 60
|
parseArgs ("--include":ns) = ShowIncs : (parseArgs ns)
| 60
|
parseArgs ("--include":ns) = ShowIncs : (parseArgs ns)
| 60
| false
| false
| 0
| 7
| 12
| 27
| 13
| 14
| null | null |
omefire/lens
|
src/Control/Lens/Traversal.hs
|
bsd-3-clause
|
-- | Generalizes 'Data.Traversable.mapAccumR' to an arbitrary 'IndexedTraversal' with access to the index.
--
-- 'imapAccumROf' accumulates state from right to left.
--
-- @
-- 'Control.Lens.Traversal.mapAccumROf' l ≡ 'imapAccumROf' l '.' 'const'
-- @
--
-- @
-- 'imapAccumROf' :: 'IndexedLens' i s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)
-- 'imapAccumROf' :: 'IndexedTraversal' i s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)
-- @
imapAccumROf :: Over (Indexed i) (Backwards (State acc)) s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)
imapAccumROf = imapAccumLOf . backwards
| 634
|
imapAccumROf :: Over (Indexed i) (Backwards (State acc)) s t a b -> (i -> acc -> a -> (acc, b)) -> acc -> s -> (acc, t)
imapAccumROf = imapAccumLOf . backwards
| 159
|
imapAccumROf = imapAccumLOf . backwards
| 39
| true
| true
| 0
| 11
| 127
| 101
| 59
| 42
| null | null |
snoyberg/hackage-proxy
|
HackageProxy.hs
|
mit
|
runHackageProxy :: HackageProxySettings -> IO ()
runHackageProxy HackageProxySettings {..} = do
baseReq <- parseUrl $ T.unpack hpsSource
run hpsPort $ app baseReq
{ checkStatus = \_ _ _ -> Nothing
-- Sometimes Hackage can be slow at responding.
, responseTimeout = Just 30000000
}
where
tcs = TweakCabalSettings hpsNoBounds
-- Keep-alive connections with the main Hackage server do not seem to work,
-- so for now we're just creating a new manager for each connection. Note
-- that we're /not/ using withManager: we want to reuse the original
-- ResourceT of the WAI app so that we can keep resources open from the
-- request to response.
app baseReq waiReq =
bracket (newManager conduitManagerSettings) closeManager $ \man -> do
responseSourceBracket (responseOpen req man) responseClose $ \res -> do
let src = bodyReaderSource $ responseBody res
resStatus = responseStatus res
resHeaders = (filter ((`HashSet.member` safeResponseHeaders) . fst) (responseHeaders res))
src' <- if isTarball res
then do
lbs <- L.fromChunks <$> lazyConsume (src $= ungzip)
entries <- mapEntries tweakEntry $ Tar.read lbs
return $ yield $ Chunk $ fromLazyByteString $ compress $ Tar.write entries
else return $ mapOutput (Chunk . fromByteString) src
return (resStatus, resHeaders, src')
where
isTarball res =
".tar.gz" `S.isSuffixOf` rawPathInfo waiReq
&& responseStatus res == status200
req = baseReq { path = path baseReq `combine` rawPathInfo' }
rawPathInfo' =
case pathInfo waiReq of
["package", T.stripSuffix ".tar.gz" -> Just packver] | Just package <- mpackage ->
encodeUtf8 $ intercalate "/" [package, version, packver ++ ".tar.gz"]
where
(T.stripSuffix "-" -> mpackage, version) = breakOnEnd "-" packver
_ -> rawPathInfo waiReq
combine a b
| "/" `S.isSuffixOf` a || "/" `S.isPrefixOf` b = a ++ b
| otherwise = mconcat [a, "/", b]
tweakEntry e@(Tar.entryContent -> Tar.NormalFile lbs _)
| takeExtension (Tar.entryPath e) == ".cabal" = e
{ Tar.entryContent = Tar.NormalFile lbs' $ L.length lbs'
}
where
lbs' = tweakCabal tcs lbs
tweakEntry e = e
mapEntries f (Tar.Next entry rest) = (f entry:) <$> mapEntries f rest
mapEntries _ Tar.Done = return []
mapEntries _ (Tar.Fail e) = throwIO e
| 2,637
|
runHackageProxy :: HackageProxySettings -> IO ()
runHackageProxy HackageProxySettings {..} = do
baseReq <- parseUrl $ T.unpack hpsSource
run hpsPort $ app baseReq
{ checkStatus = \_ _ _ -> Nothing
-- Sometimes Hackage can be slow at responding.
, responseTimeout = Just 30000000
}
where
tcs = TweakCabalSettings hpsNoBounds
-- Keep-alive connections with the main Hackage server do not seem to work,
-- so for now we're just creating a new manager for each connection. Note
-- that we're /not/ using withManager: we want to reuse the original
-- ResourceT of the WAI app so that we can keep resources open from the
-- request to response.
app baseReq waiReq =
bracket (newManager conduitManagerSettings) closeManager $ \man -> do
responseSourceBracket (responseOpen req man) responseClose $ \res -> do
let src = bodyReaderSource $ responseBody res
resStatus = responseStatus res
resHeaders = (filter ((`HashSet.member` safeResponseHeaders) . fst) (responseHeaders res))
src' <- if isTarball res
then do
lbs <- L.fromChunks <$> lazyConsume (src $= ungzip)
entries <- mapEntries tweakEntry $ Tar.read lbs
return $ yield $ Chunk $ fromLazyByteString $ compress $ Tar.write entries
else return $ mapOutput (Chunk . fromByteString) src
return (resStatus, resHeaders, src')
where
isTarball res =
".tar.gz" `S.isSuffixOf` rawPathInfo waiReq
&& responseStatus res == status200
req = baseReq { path = path baseReq `combine` rawPathInfo' }
rawPathInfo' =
case pathInfo waiReq of
["package", T.stripSuffix ".tar.gz" -> Just packver] | Just package <- mpackage ->
encodeUtf8 $ intercalate "/" [package, version, packver ++ ".tar.gz"]
where
(T.stripSuffix "-" -> mpackage, version) = breakOnEnd "-" packver
_ -> rawPathInfo waiReq
combine a b
| "/" `S.isSuffixOf` a || "/" `S.isPrefixOf` b = a ++ b
| otherwise = mconcat [a, "/", b]
tweakEntry e@(Tar.entryContent -> Tar.NormalFile lbs _)
| takeExtension (Tar.entryPath e) == ".cabal" = e
{ Tar.entryContent = Tar.NormalFile lbs' $ L.length lbs'
}
where
lbs' = tweakCabal tcs lbs
tweakEntry e = e
mapEntries f (Tar.Next entry rest) = (f entry:) <$> mapEntries f rest
mapEntries _ Tar.Done = return []
mapEntries _ (Tar.Fail e) = throwIO e
| 2,637
|
runHackageProxy HackageProxySettings {..} = do
baseReq <- parseUrl $ T.unpack hpsSource
run hpsPort $ app baseReq
{ checkStatus = \_ _ _ -> Nothing
-- Sometimes Hackage can be slow at responding.
, responseTimeout = Just 30000000
}
where
tcs = TweakCabalSettings hpsNoBounds
-- Keep-alive connections with the main Hackage server do not seem to work,
-- so for now we're just creating a new manager for each connection. Note
-- that we're /not/ using withManager: we want to reuse the original
-- ResourceT of the WAI app so that we can keep resources open from the
-- request to response.
app baseReq waiReq =
bracket (newManager conduitManagerSettings) closeManager $ \man -> do
responseSourceBracket (responseOpen req man) responseClose $ \res -> do
let src = bodyReaderSource $ responseBody res
resStatus = responseStatus res
resHeaders = (filter ((`HashSet.member` safeResponseHeaders) . fst) (responseHeaders res))
src' <- if isTarball res
then do
lbs <- L.fromChunks <$> lazyConsume (src $= ungzip)
entries <- mapEntries tweakEntry $ Tar.read lbs
return $ yield $ Chunk $ fromLazyByteString $ compress $ Tar.write entries
else return $ mapOutput (Chunk . fromByteString) src
return (resStatus, resHeaders, src')
where
isTarball res =
".tar.gz" `S.isSuffixOf` rawPathInfo waiReq
&& responseStatus res == status200
req = baseReq { path = path baseReq `combine` rawPathInfo' }
rawPathInfo' =
case pathInfo waiReq of
["package", T.stripSuffix ".tar.gz" -> Just packver] | Just package <- mpackage ->
encodeUtf8 $ intercalate "/" [package, version, packver ++ ".tar.gz"]
where
(T.stripSuffix "-" -> mpackage, version) = breakOnEnd "-" packver
_ -> rawPathInfo waiReq
combine a b
| "/" `S.isSuffixOf` a || "/" `S.isPrefixOf` b = a ++ b
| otherwise = mconcat [a, "/", b]
tweakEntry e@(Tar.entryContent -> Tar.NormalFile lbs _)
| takeExtension (Tar.entryPath e) == ".cabal" = e
{ Tar.entryContent = Tar.NormalFile lbs' $ L.length lbs'
}
where
lbs' = tweakCabal tcs lbs
tweakEntry e = e
mapEntries f (Tar.Next entry rest) = (f entry:) <$> mapEntries f rest
mapEntries _ Tar.Done = return []
mapEntries _ (Tar.Fail e) = throwIO e
| 2,588
| false
| true
| 23
| 21
| 800
| 763
| 369
| 394
| null | null |
dysinger/amazonka
|
amazonka-swf/gen/Network/AWS/SWF/PollForActivityTask.hs
|
mpl-2.0
|
-- | 'PollForActivityTask' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pfatDomain' @::@ 'Text'
--
-- * 'pfatIdentity' @::@ 'Maybe' 'Text'
--
-- * 'pfatTaskList' @::@ 'TaskList'
--
pollForActivityTask :: Text -- ^ 'pfatDomain'
-> TaskList -- ^ 'pfatTaskList'
-> PollForActivityTask
pollForActivityTask p1 p2 = PollForActivityTask
{ _pfatDomain = p1
, _pfatTaskList = p2
, _pfatIdentity = Nothing
}
| 494
|
pollForActivityTask :: Text -- ^ 'pfatDomain'
-> TaskList -- ^ 'pfatTaskList'
-> PollForActivityTask
pollForActivityTask p1 p2 = PollForActivityTask
{ _pfatDomain = p1
, _pfatTaskList = p2
, _pfatIdentity = Nothing
}
| 274
|
pollForActivityTask p1 p2 = PollForActivityTask
{ _pfatDomain = p1
, _pfatTaskList = p2
, _pfatIdentity = Nothing
}
| 133
| true
| true
| 0
| 7
| 121
| 60
| 38
| 22
| null | null |
rueshyna/gogol
|
gogol-admin-directory/gen/Network/Google/Directory/Types.hs
|
mpl-2.0
|
-- | View user schemas on your domain
adminDirectoryUserschemaReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/admin.directory.userschema.readonly"]
adminDirectoryUserschemaReadOnlyScope = Proxy
| 203
|
adminDirectoryUserschemaReadOnlyScope :: Proxy '["https://www.googleapis.com/auth/admin.directory.userschema.readonly"]
adminDirectoryUserschemaReadOnlyScope = Proxy
| 165
|
adminDirectoryUserschemaReadOnlyScope = Proxy
| 45
| true
| true
| 0
| 8
| 14
| 26
| 12
| 14
| null | null |
marcelosousa/poet
|
src/Test/Examples/ExSeven.hs
|
gpl-2.0
|
check _ _ = False
| 17
|
check _ _ = False
| 17
|
check _ _ = False
| 17
| false
| false
| 1
| 5
| 4
| 12
| 5
| 7
| null | null |
TimRichter/Idris-dev
|
src/Idris/Completion.hs
|
bsd-3-clause
|
tacticArgs :: [(String, Maybe TacticArg)]
tacticArgs = [ (name, args) | (names, args, _) <- Idris.ParseExpr.tactics
, name <- names ]
| 161
|
tacticArgs :: [(String, Maybe TacticArg)]
tacticArgs = [ (name, args) | (names, args, _) <- Idris.ParseExpr.tactics
, name <- names ]
| 161
|
tacticArgs = [ (name, args) | (names, args, _) <- Idris.ParseExpr.tactics
, name <- names ]
| 119
| false
| true
| 0
| 8
| 48
| 60
| 35
| 25
| null | null |
konn/Yablog
|
Handler/User.hs
|
bsd-2-clause
|
postBanSettingsR :: Handler RepHtml
postBanSettingsR = do
isAdm <- isAdmin . entityVal =<< requireAuth
unless isAdm $ permissionDenied "!!! YOU ARE NOT ALLOWED TO CHANGE BAN !!!"
((result, _), _) <- runFormPost banForm
liftIO $ print result
case result of
FormSuccess bans -> do
runDB $ mapM_ (delete . entityKey) bans
redirect UserSettingsR
_ -> permissionDenied "!!!!YOU ARE NOT ALLOWED TO CHANGE!!!!"
| 450
|
postBanSettingsR :: Handler RepHtml
postBanSettingsR = do
isAdm <- isAdmin . entityVal =<< requireAuth
unless isAdm $ permissionDenied "!!! YOU ARE NOT ALLOWED TO CHANGE BAN !!!"
((result, _), _) <- runFormPost banForm
liftIO $ print result
case result of
FormSuccess bans -> do
runDB $ mapM_ (delete . entityKey) bans
redirect UserSettingsR
_ -> permissionDenied "!!!!YOU ARE NOT ALLOWED TO CHANGE!!!!"
| 450
|
postBanSettingsR = do
isAdm <- isAdmin . entityVal =<< requireAuth
unless isAdm $ permissionDenied "!!! YOU ARE NOT ALLOWED TO CHANGE BAN !!!"
((result, _), _) <- runFormPost banForm
liftIO $ print result
case result of
FormSuccess bans -> do
runDB $ mapM_ (delete . entityKey) bans
redirect UserSettingsR
_ -> permissionDenied "!!!!YOU ARE NOT ALLOWED TO CHANGE!!!!"
| 414
| false
| true
| 0
| 15
| 108
| 124
| 57
| 67
| null | null |
themoritz/cabal
|
Cabal/Distribution/Simple/LHC.hs
|
bsd-3-clause
|
-- -----------------------------------------------------------------------------
-- Installing
-- |Install executables for GHC.
installExe :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi binDir buildPref (progprefix, progsuffix) _pkg exe = do
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = unUnqualComponentName (exeName exe) <.> exeExtension
fixedExeBaseName = progprefix ++ unUnqualComponentName (exeName exe) ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> unUnqualComponentName (exeName exe) </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
| 1,025
|
installExe :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^Where to copy the files to
-> FilePath -- ^Build location
-> (FilePath, FilePath) -- ^Executable (prefix,suffix)
-> PackageDescription
-> Executable
-> IO ()
installExe verbosity lbi binDir buildPref (progprefix, progsuffix) _pkg exe = do
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = unUnqualComponentName (exeName exe) <.> exeExtension
fixedExeBaseName = progprefix ++ unUnqualComponentName (exeName exe) ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> unUnqualComponentName (exeName exe) </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
| 896
|
installExe verbosity lbi binDir buildPref (progprefix, progsuffix) _pkg exe = do
createDirectoryIfMissingVerbose verbosity True binDir
let exeFileName = unUnqualComponentName (exeName exe) <.> exeExtension
fixedExeBaseName = progprefix ++ unUnqualComponentName (exeName exe) ++ progsuffix
installBinary dest = do
installExecutableFile verbosity
(buildPref </> unUnqualComponentName (exeName exe) </> exeFileName)
(dest <.> exeExtension)
stripExe verbosity lbi exeFileName (dest <.> exeExtension)
installBinary (binDir </> fixedExeBaseName)
| 601
| true
| true
| 0
| 18
| 241
| 208
| 105
| 103
| null | null |
dylanmc/cryptol
|
sbv/Data/SBV/BitVectors/Model.hs
|
bsd-3-clause
|
isConcreteOnes (SBV _ (Left (CW KUnbounded (CWInteger n)))) = n == -1
| 69
|
isConcreteOnes (SBV _ (Left (CW KUnbounded (CWInteger n)))) = n == -1
| 69
|
isConcreteOnes (SBV _ (Left (CW KUnbounded (CWInteger n)))) = n == -1
| 69
| false
| false
| 0
| 12
| 11
| 44
| 21
| 23
| null | null |
pparkkin/eta
|
compiler/ETA/Prelude/PrelNames.hs
|
bsd-3-clause
|
intTyConKey = mkPreludeTyConUnique 15
| 65
|
intTyConKey = mkPreludeTyConUnique 15
| 65
|
intTyConKey = mkPreludeTyConUnique 15
| 65
| false
| false
| 0
| 5
| 31
| 9
| 4
| 5
| null | null |
x-y-z/cabal
|
Cabal/Distribution/Simple/GHC.hs
|
bsd-3-clause
|
-- | Given something like /usr/local/bin/ghc-6.6.1(.exe) we try and find a
-- corresponding hsc2hs, we try looking for both a versioned and unversioned
-- hsc2hs in the same dir, that is:
--
-- > /usr/local/bin/hsc2hs-ghc-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs-6.6.1(.exe)
-- > /usr/local/bin/hsc2hs(.exe)
--
guessHsc2hsFromGhcPath :: ConfiguredProgram
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram
| 492
|
guessHsc2hsFromGhcPath :: ConfiguredProgram
-> Verbosity -> ProgramSearchPath -> IO (Maybe FilePath)
guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram
| 183
|
guessHsc2hsFromGhcPath = guessToolFromGhcPath hsc2hsProgram
| 59
| true
| true
| 0
| 10
| 79
| 43
| 25
| 18
| null | null |
yiannist/ganeti
|
src/Ganeti/HTools/Program/Harep.hs
|
bsd-2-clause
|
updateTag :: AutoRepairData -> AutoRepairData
updateTag arData =
let ini = [autoRepairTypeToRaw $ arType arData,
arUuid arData,
clockTimeToString $ arTime arData]
end = [intercalate "+" . map (show . fromJobId) $ arJobs arData]
(pfx, middle) =
case arResult arData of
Nothing -> (Tags.autoRepairTagPending, [])
Just rs -> (Tags.autoRepairTagResult, [autoRepairResultToRaw rs])
in
arData { arTag = pfx ++ intercalate ":" (ini ++ middle ++ end) }
| 518
|
updateTag :: AutoRepairData -> AutoRepairData
updateTag arData =
let ini = [autoRepairTypeToRaw $ arType arData,
arUuid arData,
clockTimeToString $ arTime arData]
end = [intercalate "+" . map (show . fromJobId) $ arJobs arData]
(pfx, middle) =
case arResult arData of
Nothing -> (Tags.autoRepairTagPending, [])
Just rs -> (Tags.autoRepairTagResult, [autoRepairResultToRaw rs])
in
arData { arTag = pfx ++ intercalate ":" (ini ++ middle ++ end) }
| 518
|
updateTag arData =
let ini = [autoRepairTypeToRaw $ arType arData,
arUuid arData,
clockTimeToString $ arTime arData]
end = [intercalate "+" . map (show . fromJobId) $ arJobs arData]
(pfx, middle) =
case arResult arData of
Nothing -> (Tags.autoRepairTagPending, [])
Just rs -> (Tags.autoRepairTagResult, [autoRepairResultToRaw rs])
in
arData { arTag = pfx ++ intercalate ":" (ini ++ middle ++ end) }
| 472
| false
| true
| 0
| 14
| 138
| 173
| 89
| 84
| null | null |
MetaMemoryT/Idris-dev
|
src/Idris/AbsSyntaxTree.hs
|
bsd-3-clause
|
highestFC (PUnifyLog tm) = highestFC tm
| 39
|
highestFC (PUnifyLog tm) = highestFC tm
| 39
|
highestFC (PUnifyLog tm) = highestFC tm
| 39
| false
| false
| 0
| 7
| 5
| 18
| 8
| 10
| null | null |
ghc-android/ghc
|
distrib/compare/Tar.hs
|
bsd-3-clause
|
readTarLines :: FilePath -> IO [TarLine]
readTarLines fp
= do (ec, out, err) <- readProcessWithExitCode "tar" ["-jtvf", fp] ""
case (ec, err) of
(ExitSuccess, []) ->
case parseTarLines fp out of
Left errs -> die errs
Right tls -> return tls
_ ->
die ["Failed running tar -jtvf " ++ show fp,
"Exit code: " ++ show ec,
"Stderr: " ++ show err]
| 475
|
readTarLines :: FilePath -> IO [TarLine]
readTarLines fp
= do (ec, out, err) <- readProcessWithExitCode "tar" ["-jtvf", fp] ""
case (ec, err) of
(ExitSuccess, []) ->
case parseTarLines fp out of
Left errs -> die errs
Right tls -> return tls
_ ->
die ["Failed running tar -jtvf " ++ show fp,
"Exit code: " ++ show ec,
"Stderr: " ++ show err]
| 475
|
readTarLines fp
= do (ec, out, err) <- readProcessWithExitCode "tar" ["-jtvf", fp] ""
case (ec, err) of
(ExitSuccess, []) ->
case parseTarLines fp out of
Left errs -> die errs
Right tls -> return tls
_ ->
die ["Failed running tar -jtvf " ++ show fp,
"Exit code: " ++ show ec,
"Stderr: " ++ show err]
| 434
| false
| true
| 0
| 13
| 197
| 152
| 76
| 76
| null | null |
dreamcodez/moddit-yesod
|
AppState.hs
|
bsd-2-clause
|
readHits :: Query Database Int
readHits = hits <$> ask
| 54
|
readHits :: Query Database Int
readHits = hits <$> ask
| 54
|
readHits = hits <$> ask
| 23
| false
| true
| 0
| 5
| 9
| 20
| 10
| 10
| null | null |
beni55/LambdaHack
|
Game/LambdaHack/Client/AI/Preferences.hs
|
bsd-3-clause
|
-- | How much AI benefits from applying the effect. Multipllied by item p.
-- Negative means harm to the enemy when thrown at him. Effects with zero
-- benefit won't ever be used, neither actively nor passively.
effectToBenefit :: Kind.COps -> Actor -> [ItemFull] -> Faction
-> IK.Effect -> Int
effectToBenefit cops b activeItems fact eff =
let dungeonDweller = not $ fcanEscape $ gplayer fact
in case eff of
IK.NoEffect _ -> 0
IK.Hurt d -> -(min 150 $ 10 * Dice.meanDice d)
IK.Burn d -> -(min 200 $ 15 * Dice.meanDice d)
-- often splash damage, etc.
IK.Explode _ -> 0 -- depends on explosion
IK.RefillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
-- TODO: when picking up, always deem valuable; when drinking, only if
-- HP not maxxed.
then 10 * min p (max 0 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.OverfillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
then 11 * min p (max 1 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.RefillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 0 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.OverfillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 1 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.Dominate -> -200
IK.Impress -> -10
IK.CallFriend d -> 100 * Dice.meanDice d
IK.Summon _ d | dungeonDweller ->
-- Probably summons friends or crazies.
-- TODO: should be Negative, to use Calm of enemy, but also positive
-- to use with own Calm, if needed.
50 * Dice.meanDice d
IK.Summon{} -> 0 -- probably generates enemies
IK.Ascend{} -> 1 -- low, to only change levels sensibly, in teams
-- TODO: use if low HP and enemies at hand
IK.Escape{} -> 10000 -- AI wants to win; spawners to guard
IK.Paralyze d -> -20 * Dice.meanDice d
IK.InsertMove d -> 50 * Dice.meanDice d
IK.Teleport d ->
let p = Dice.meanDice d
in if p <= 8 -- blink to shoot at foe
&& dungeonDweller -- non-dwellers have to explore and escape ASAP
then 1
else -p -- get rid of the foe
IK.CreateItem COrgan grp _ -> -- TODO: use the timeout
let (total, count) = organBenefit grp cops b activeItems fact
in total `divUp` count -- average over all matching grp; rarities ignored
IK.CreateItem{} -> 30 -- TODO
IK.DropItem COrgan grp True -> -- calculated for future use, general pickup
let (total, _) = organBenefit grp cops b activeItems fact
in - total -- sum over all matching grp; simplification: rarities ignored
IK.DropItem _ _ False -> -15
IK.DropItem _ _ True -> -30
IK.PolyItem -> 0 -- AI can't estimate item desirability vs average
IK.Identify -> 0 -- AI doesn't know how to use
IK.SendFlying _ -> -10 -- but useful on self sometimes, too
IK.PushActor _ -> -10 -- but useful on self sometimes, too
IK.PullActor _ -> -10
IK.DropBestWeapon -> -50
IK.ActivateInv ' ' -> -100
IK.ActivateInv _ -> -50
IK.ApplyPerfume -> 0 -- depends on the smell sense of friends and foes
IK.OneOf _ -> 1 -- usually a mixed blessing, but slightly beneficial
IK.OnSmash _ -> 0 -- TOOD: can be beneficial or not; analyze explosions
IK.Recharging e ->
-- Used, e.g., in @periodicBens@, which takes timeout into account, too.
effectToBenefit cops b activeItems fact e
IK.Temporary _ -> 0
-- TODO: calculating this for "temporary conditions" takes forever
| 3,997
|
effectToBenefit :: Kind.COps -> Actor -> [ItemFull] -> Faction
-> IK.Effect -> Int
effectToBenefit cops b activeItems fact eff =
let dungeonDweller = not $ fcanEscape $ gplayer fact
in case eff of
IK.NoEffect _ -> 0
IK.Hurt d -> -(min 150 $ 10 * Dice.meanDice d)
IK.Burn d -> -(min 200 $ 15 * Dice.meanDice d)
-- often splash damage, etc.
IK.Explode _ -> 0 -- depends on explosion
IK.RefillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
-- TODO: when picking up, always deem valuable; when drinking, only if
-- HP not maxxed.
then 10 * min p (max 0 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.OverfillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
then 11 * min p (max 1 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.RefillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 0 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.OverfillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 1 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.Dominate -> -200
IK.Impress -> -10
IK.CallFriend d -> 100 * Dice.meanDice d
IK.Summon _ d | dungeonDweller ->
-- Probably summons friends or crazies.
-- TODO: should be Negative, to use Calm of enemy, but also positive
-- to use with own Calm, if needed.
50 * Dice.meanDice d
IK.Summon{} -> 0 -- probably generates enemies
IK.Ascend{} -> 1 -- low, to only change levels sensibly, in teams
-- TODO: use if low HP and enemies at hand
IK.Escape{} -> 10000 -- AI wants to win; spawners to guard
IK.Paralyze d -> -20 * Dice.meanDice d
IK.InsertMove d -> 50 * Dice.meanDice d
IK.Teleport d ->
let p = Dice.meanDice d
in if p <= 8 -- blink to shoot at foe
&& dungeonDweller -- non-dwellers have to explore and escape ASAP
then 1
else -p -- get rid of the foe
IK.CreateItem COrgan grp _ -> -- TODO: use the timeout
let (total, count) = organBenefit grp cops b activeItems fact
in total `divUp` count -- average over all matching grp; rarities ignored
IK.CreateItem{} -> 30 -- TODO
IK.DropItem COrgan grp True -> -- calculated for future use, general pickup
let (total, _) = organBenefit grp cops b activeItems fact
in - total -- sum over all matching grp; simplification: rarities ignored
IK.DropItem _ _ False -> -15
IK.DropItem _ _ True -> -30
IK.PolyItem -> 0 -- AI can't estimate item desirability vs average
IK.Identify -> 0 -- AI doesn't know how to use
IK.SendFlying _ -> -10 -- but useful on self sometimes, too
IK.PushActor _ -> -10 -- but useful on self sometimes, too
IK.PullActor _ -> -10
IK.DropBestWeapon -> -50
IK.ActivateInv ' ' -> -100
IK.ActivateInv _ -> -50
IK.ApplyPerfume -> 0 -- depends on the smell sense of friends and foes
IK.OneOf _ -> 1 -- usually a mixed blessing, but slightly beneficial
IK.OnSmash _ -> 0 -- TOOD: can be beneficial or not; analyze explosions
IK.Recharging e ->
-- Used, e.g., in @periodicBens@, which takes timeout into account, too.
effectToBenefit cops b activeItems fact e
IK.Temporary _ -> 0
-- TODO: calculating this for "temporary conditions" takes forever
| 3,785
|
effectToBenefit cops b activeItems fact eff =
let dungeonDweller = not $ fcanEscape $ gplayer fact
in case eff of
IK.NoEffect _ -> 0
IK.Hurt d -> -(min 150 $ 10 * Dice.meanDice d)
IK.Burn d -> -(min 200 $ 15 * Dice.meanDice d)
-- often splash damage, etc.
IK.Explode _ -> 0 -- depends on explosion
IK.RefillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
-- TODO: when picking up, always deem valuable; when drinking, only if
-- HP not maxxed.
then 10 * min p (max 0 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.OverfillHP p ->
let hpMax = sumSlotNoFilter IK.EqpSlotAddMaxHP activeItems
in if p > 0
then 11 * min p (max 1 $ fromIntegral
$ (xM hpMax - bhp b) `divUp` oneM)
else max (-99) (11 * p)
IK.RefillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 0 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.OverfillCalm p ->
let calmMax = sumSlotNoFilter IK.EqpSlotAddMaxCalm activeItems
in if p > 0
then min p (max 1 $ fromIntegral
$ (xM calmMax - bcalm b) `divUp` oneM)
else max (-20) p
IK.Dominate -> -200
IK.Impress -> -10
IK.CallFriend d -> 100 * Dice.meanDice d
IK.Summon _ d | dungeonDweller ->
-- Probably summons friends or crazies.
-- TODO: should be Negative, to use Calm of enemy, but also positive
-- to use with own Calm, if needed.
50 * Dice.meanDice d
IK.Summon{} -> 0 -- probably generates enemies
IK.Ascend{} -> 1 -- low, to only change levels sensibly, in teams
-- TODO: use if low HP and enemies at hand
IK.Escape{} -> 10000 -- AI wants to win; spawners to guard
IK.Paralyze d -> -20 * Dice.meanDice d
IK.InsertMove d -> 50 * Dice.meanDice d
IK.Teleport d ->
let p = Dice.meanDice d
in if p <= 8 -- blink to shoot at foe
&& dungeonDweller -- non-dwellers have to explore and escape ASAP
then 1
else -p -- get rid of the foe
IK.CreateItem COrgan grp _ -> -- TODO: use the timeout
let (total, count) = organBenefit grp cops b activeItems fact
in total `divUp` count -- average over all matching grp; rarities ignored
IK.CreateItem{} -> 30 -- TODO
IK.DropItem COrgan grp True -> -- calculated for future use, general pickup
let (total, _) = organBenefit grp cops b activeItems fact
in - total -- sum over all matching grp; simplification: rarities ignored
IK.DropItem _ _ False -> -15
IK.DropItem _ _ True -> -30
IK.PolyItem -> 0 -- AI can't estimate item desirability vs average
IK.Identify -> 0 -- AI doesn't know how to use
IK.SendFlying _ -> -10 -- but useful on self sometimes, too
IK.PushActor _ -> -10 -- but useful on self sometimes, too
IK.PullActor _ -> -10
IK.DropBestWeapon -> -50
IK.ActivateInv ' ' -> -100
IK.ActivateInv _ -> -50
IK.ApplyPerfume -> 0 -- depends on the smell sense of friends and foes
IK.OneOf _ -> 1 -- usually a mixed blessing, but slightly beneficial
IK.OnSmash _ -> 0 -- TOOD: can be beneficial or not; analyze explosions
IK.Recharging e ->
-- Used, e.g., in @periodicBens@, which takes timeout into account, too.
effectToBenefit cops b activeItems fact e
IK.Temporary _ -> 0
-- TODO: calculating this for "temporary conditions" takes forever
| 3,686
| true
| true
| 0
| 20
| 1,190
| 1,057
| 527
| 530
| null | null |
agarwalayush/Firewall-authentication-IIT-Kanpur
|
src/Main.hs
|
bsd-3-clause
|
tryToLog :: (String,String) -> Response ByteString -> IO ()
tryToLog (username,password) res = do
infoM "Firewall.login" $ "Hello " ++ username ++ "\nNow trying to login"
let authLocation = lookup "Location" (read (show $ responseHeaders res) :: [(String,String)])
authRes <- getResponse (fromJust authLocation) -- Connecting to authentication Location
let (magicString:_) = fromJust.getMagicString.unpack $ responseBody authRes
request <- parseUrl (fromJust authLocation)
resp <- withManager.httpLbs $ urlEncodedBody (map (pack *** pack) [("username",username),("password",password),("magic",magicString),("4Tredir","/")]) request
let body = responseBody resp
let (logout:_) = (fromJust.getLogout.unpack $ body)
infoM "Firewall.login" $ "Logout url is " ++ logout
let keepAliveMatch = getKeepAlive $ unpack body
case keepAliveMatch of
Nothing -> emergencyM "Firewall.login" "Check Username or password" >> exitFailure
Just (str:_) -> do
infoM "Firewall.login" $ "Keep Alive URL is " ++ str
keepAlive str logout
| 1,053
|
tryToLog :: (String,String) -> Response ByteString -> IO ()
tryToLog (username,password) res = do
infoM "Firewall.login" $ "Hello " ++ username ++ "\nNow trying to login"
let authLocation = lookup "Location" (read (show $ responseHeaders res) :: [(String,String)])
authRes <- getResponse (fromJust authLocation) -- Connecting to authentication Location
let (magicString:_) = fromJust.getMagicString.unpack $ responseBody authRes
request <- parseUrl (fromJust authLocation)
resp <- withManager.httpLbs $ urlEncodedBody (map (pack *** pack) [("username",username),("password",password),("magic",magicString),("4Tredir","/")]) request
let body = responseBody resp
let (logout:_) = (fromJust.getLogout.unpack $ body)
infoM "Firewall.login" $ "Logout url is " ++ logout
let keepAliveMatch = getKeepAlive $ unpack body
case keepAliveMatch of
Nothing -> emergencyM "Firewall.login" "Check Username or password" >> exitFailure
Just (str:_) -> do
infoM "Firewall.login" $ "Keep Alive URL is " ++ str
keepAlive str logout
| 1,053
|
tryToLog (username,password) res = do
infoM "Firewall.login" $ "Hello " ++ username ++ "\nNow trying to login"
let authLocation = lookup "Location" (read (show $ responseHeaders res) :: [(String,String)])
authRes <- getResponse (fromJust authLocation) -- Connecting to authentication Location
let (magicString:_) = fromJust.getMagicString.unpack $ responseBody authRes
request <- parseUrl (fromJust authLocation)
resp <- withManager.httpLbs $ urlEncodedBody (map (pack *** pack) [("username",username),("password",password),("magic",magicString),("4Tredir","/")]) request
let body = responseBody resp
let (logout:_) = (fromJust.getLogout.unpack $ body)
infoM "Firewall.login" $ "Logout url is " ++ logout
let keepAliveMatch = getKeepAlive $ unpack body
case keepAliveMatch of
Nothing -> emergencyM "Firewall.login" "Check Username or password" >> exitFailure
Just (str:_) -> do
infoM "Firewall.login" $ "Keep Alive URL is " ++ str
keepAlive str logout
| 993
| false
| true
| 13
| 13
| 169
| 348
| 180
| 168
| null | null |
meiersi/bytestring-builder
|
tests/FusionProperties.hs
|
bsd-3-clause
|
prop_downfilter_list = eq3
(\f g -> P.filter f . P.scanr g (0::W))
((\f g -> filter f . scanr g (0::W)) :: (W -> Bool) -> (W -> W -> W) -> [W] -> [W])
| 165
|
prop_downfilter_list = eq3
(\f g -> P.filter f . P.scanr g (0::W))
((\f g -> filter f . scanr g (0::W)) :: (W -> Bool) -> (W -> W -> W) -> [W] -> [W])
| 165
|
prop_downfilter_list = eq3
(\f g -> P.filter f . P.scanr g (0::W))
((\f g -> filter f . scanr g (0::W)) :: (W -> Bool) -> (W -> W -> W) -> [W] -> [W])
| 165
| false
| false
| 0
| 11
| 49
| 113
| 61
| 52
| null | null |
snapframework/io-streams
|
test/System/IO/Streams/Tests/Concurrent.hs
|
bsd-3-clause
|
testInputOutput :: Test
testInputOutput = testCase "concurrent/input-output" $ do
is <- Streams.fromList [1..10::Int]
chan <- newChan
is' <- Streams.chanToInput chan
Streams.inputToChan is chan
Streams.toList is' >>= assertEqual "input-output" [1..10]
| 274
|
testInputOutput :: Test
testInputOutput = testCase "concurrent/input-output" $ do
is <- Streams.fromList [1..10::Int]
chan <- newChan
is' <- Streams.chanToInput chan
Streams.inputToChan is chan
Streams.toList is' >>= assertEqual "input-output" [1..10]
| 274
|
testInputOutput = testCase "concurrent/input-output" $ do
is <- Streams.fromList [1..10::Int]
chan <- newChan
is' <- Streams.chanToInput chan
Streams.inputToChan is chan
Streams.toList is' >>= assertEqual "input-output" [1..10]
| 250
| false
| true
| 0
| 11
| 51
| 96
| 42
| 54
| null | null |
zaxtax/hakaru
|
haskell/Tests/Expect.hs
|
bsd-3-clause
|
test6 :: TrivialABT Term '[] ('HMeasure (HPair 'HReal 'HReal))
test6 = constantPropagation . normalize $
normal zero one >>= \a ->
normal a (prob_ 2) >>= \b ->
dirac (pair b a)
| 188
|
test6 :: TrivialABT Term '[] ('HMeasure (HPair 'HReal 'HReal))
test6 = constantPropagation . normalize $
normal zero one >>= \a ->
normal a (prob_ 2) >>= \b ->
dirac (pair b a)
| 188
|
test6 = constantPropagation . normalize $
normal zero one >>= \a ->
normal a (prob_ 2) >>= \b ->
dirac (pair b a)
| 125
| false
| true
| 0
| 11
| 43
| 95
| 47
| 48
| null | null |
dmgolubovsky/9ph
|
src/Data/NineP.hs
|
bsd-3-clause
|
getVarMsg TRopen = Ropen <$> get <*> get
| 40
|
getVarMsg TRopen = Ropen <$> get <*> get
| 40
|
getVarMsg TRopen = Ropen <$> get <*> get
| 40
| false
| false
| 1
| 6
| 7
| 21
| 8
| 13
| null | null |
amtal/soyuz
|
DCPU16/Instructions.hs
|
mit
|
toOpCode 0x7=SHL
| 16
|
toOpCode 0x7=SHL
| 16
|
toOpCode 0x7=SHL
| 16
| false
| false
| 0
| 5
| 1
| 9
| 4
| 5
| null | null |
cdodev/scintilla
|
src/Scintilla/Query/Types.hs
|
bsd-3-clause
|
runMonadQuery
:: ( MonadIO m, MonadMask m
, QueryOnly ps, ps' ~ DropPerm ['Transact, 'Insert, 'Update, 'Delete] ps
)
=> Conn ps -> DBMonad ps' m a -> m a
runMonadQuery conn dbm = withReadOnlyTransaction Serializable conn (runReaderT (unQ dbm))
| 258
|
runMonadQuery
:: ( MonadIO m, MonadMask m
, QueryOnly ps, ps' ~ DropPerm ['Transact, 'Insert, 'Update, 'Delete] ps
)
=> Conn ps -> DBMonad ps' m a -> m a
runMonadQuery conn dbm = withReadOnlyTransaction Serializable conn (runReaderT (unQ dbm))
| 258
|
runMonadQuery conn dbm = withReadOnlyTransaction Serializable conn (runReaderT (unQ dbm))
| 89
| false
| true
| 0
| 10
| 54
| 113
| 56
| 57
| null | null |
yan-ac/bbq.yan.ac
|
BBQ/Route.hs
|
mit
|
routeBasedOnUserStat :: Sitemap -> RouteT Sitemap App Response
routeBasedOnUserStat url = do
authURL <- showURL Authentication
dashboardURL <- showURL Dashboard
loginStat <- lift $ askUserStat
case loginStat of
Nothing -> seeOther authURL $ toResponse "会话已过期,请登录"
Just (aid, bbqStat) -> do
case url of
Dashboard ->
case bbqStat of
BBQNotStarted -> BBQ.Dashboard.notStartPage
BBQInProgress -> BBQ.Dashboard.inProgressPage
BBQFinished -> BBQ.Dashboard.finishedPage
IgniteFire -> forbidden $ toResponse "比赛已经结束"
Upload pid ->
case bbqStat of
BBQInProgress -> BBQ.Upload.upload aid pid
_ -> seeOther dashboardURL $ toResponse "不在比赛中"
ViewSheets pid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewSheets aid pid
ViewASheet pid sid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewASheet aid pid sid
| 1,111
|
routeBasedOnUserStat :: Sitemap -> RouteT Sitemap App Response
routeBasedOnUserStat url = do
authURL <- showURL Authentication
dashboardURL <- showURL Dashboard
loginStat <- lift $ askUserStat
case loginStat of
Nothing -> seeOther authURL $ toResponse "会话已过期,请登录"
Just (aid, bbqStat) -> do
case url of
Dashboard ->
case bbqStat of
BBQNotStarted -> BBQ.Dashboard.notStartPage
BBQInProgress -> BBQ.Dashboard.inProgressPage
BBQFinished -> BBQ.Dashboard.finishedPage
IgniteFire -> forbidden $ toResponse "比赛已经结束"
Upload pid ->
case bbqStat of
BBQInProgress -> BBQ.Upload.upload aid pid
_ -> seeOther dashboardURL $ toResponse "不在比赛中"
ViewSheets pid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewSheets aid pid
ViewASheet pid sid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewASheet aid pid sid
| 1,111
|
routeBasedOnUserStat url = do
authURL <- showURL Authentication
dashboardURL <- showURL Dashboard
loginStat <- lift $ askUserStat
case loginStat of
Nothing -> seeOther authURL $ toResponse "会话已过期,请登录"
Just (aid, bbqStat) -> do
case url of
Dashboard ->
case bbqStat of
BBQNotStarted -> BBQ.Dashboard.notStartPage
BBQInProgress -> BBQ.Dashboard.inProgressPage
BBQFinished -> BBQ.Dashboard.finishedPage
IgniteFire -> forbidden $ toResponse "比赛已经结束"
Upload pid ->
case bbqStat of
BBQInProgress -> BBQ.Upload.upload aid pid
_ -> seeOther dashboardURL $ toResponse "不在比赛中"
ViewSheets pid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewSheets aid pid
ViewASheet pid sid ->
case bbqStat of
BBQNotStarted -> seeOther dashboardURL $ toResponse "尚未参赛"
_ -> BBQ.Upload.viewASheet aid pid sid
| 1,048
| false
| true
| 0
| 22
| 336
| 285
| 134
| 151
| null | null |
dschalk/JS-monads-stable
|
Main.hs
|
mit
|
changeS :: Text -> Int -> Int -> Client -> Client
changeS x y z (a, b, c, d, e) | x == a = (a, y, z, d, e)
| otherwise = (a, b, c, d, e)
| 164
|
changeS :: Text -> Int -> Int -> Client -> Client
changeS x y z (a, b, c, d, e) | x == a = (a, y, z, d, e)
| otherwise = (a, b, c, d, e)
| 164
|
changeS x y z (a, b, c, d, e) | x == a = (a, y, z, d, e)
| otherwise = (a, b, c, d, e)
| 114
| false
| true
| 0
| 8
| 65
| 100
| 56
| 44
| null | null |
pzel/praxis
|
Happy.hs
|
unlicense
|
happyUpto :: Integer -> [Integer]
happyUpto n = filter isHappy [1..n]
| 69
|
happyUpto :: Integer -> [Integer]
happyUpto n = filter isHappy [1..n]
| 69
|
happyUpto n = filter isHappy [1..n]
| 35
| false
| true
| 0
| 6
| 10
| 31
| 16
| 15
| null | null |
brendanhay/gogol
|
gogol-securitycenter/gen/Network/Google/SecurityCenter/Types/Product.hs
|
mpl-2.0
|
-- | Associates a list of \`members\` to a \`role\`. Optionally, may specify
-- a \`condition\` that determines how and when the \`bindings\` are
-- applied. Each of the \`bindings\` must contain at least one member.
pBindings :: Lens' Policy [Binding]
pBindings
= lens _pBindings (\ s a -> s{_pBindings = a}) .
_Default
. _Coerce
| 344
|
pBindings :: Lens' Policy [Binding]
pBindings
= lens _pBindings (\ s a -> s{_pBindings = a}) .
_Default
. _Coerce
| 127
|
pBindings
= lens _pBindings (\ s a -> s{_pBindings = a}) .
_Default
. _Coerce
| 91
| true
| true
| 0
| 11
| 69
| 55
| 30
| 25
| null | null |
manpages/AAA
|
src/AAA/Session.hs
|
mit
|
tick _ e r g =
tick'Do r g (sex r) (tokenMatches r) (pc e r) (contToken r) (justSessTime r)
| 93
|
tick _ e r g =
tick'Do r g (sex r) (tokenMatches r) (pc e r) (contToken r) (justSessTime r)
| 93
|
tick _ e r g =
tick'Do r g (sex r) (tokenMatches r) (pc e r) (contToken r) (justSessTime r)
| 93
| false
| false
| 1
| 7
| 21
| 58
| 28
| 30
| null | null |
sol/hpack
|
src/Hpack/Render.hs
|
mit
|
renderCxxOptions :: [CxxOption] -> Element
renderCxxOptions = Field "cxx-options" . WordList
| 92
|
renderCxxOptions :: [CxxOption] -> Element
renderCxxOptions = Field "cxx-options" . WordList
| 92
|
renderCxxOptions = Field "cxx-options" . WordList
| 49
| false
| true
| 0
| 6
| 10
| 25
| 13
| 12
| null | null |
sordina/scotty
|
Web/Scotty.hs
|
bsd-3-clause
|
-- | Get list of uploaded files.
files :: ActionM [File]
files = Trans.files
| 76
|
files :: ActionM [File]
files = Trans.files
| 43
|
files = Trans.files
| 19
| true
| true
| 0
| 7
| 13
| 26
| 12
| 14
| null | null |
fpco/cabal
|
Cabal/Distribution/Simple/Configure.hs
|
bsd-3-clause
|
configCompilerEx :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> Verbosity
-> IO (Compiler, Platform, ProgramConfiguration)
configCompilerEx Nothing _ _ _ _ = die "Unknown compiler"
| 254
|
configCompilerEx :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
-> ProgramConfiguration -> Verbosity
-> IO (Compiler, Platform, ProgramConfiguration)
configCompilerEx Nothing _ _ _ _ = die "Unknown compiler"
| 254
|
configCompilerEx Nothing _ _ _ _ = die "Unknown compiler"
| 57
| false
| true
| 0
| 11
| 62
| 66
| 32
| 34
| null | null |
mydaum/cabal
|
cabal-install/Distribution/Solver/Types/PackageConstraint.hs
|
bsd-3-clause
|
dispConstraintScope (ScopeAnySetupQualifier pn) = Disp.text "setup." <<>> disp pn
| 81
|
dispConstraintScope (ScopeAnySetupQualifier pn) = Disp.text "setup." <<>> disp pn
| 81
|
dispConstraintScope (ScopeAnySetupQualifier pn) = Disp.text "setup." <<>> disp pn
| 81
| false
| false
| 0
| 7
| 8
| 27
| 12
| 15
| null | null |
2ion/yst
|
yst.hs
|
gpl-2.0
|
createSite :: FilePath -> IO ()
createSite path = do
existsd <- doesDirectoryExist path
existsf <- doesFileExist path
when (existsd || existsf) $ do
hPutStrLn stderr $ "Aborting! " ++ path ++ " already exists."
exitWith $ ExitFailure 5
demoDir <- getDataFileName "demo"
contents <- liftM (filter (/=".") . map (makeRelative demoDir)) $ getDirectoryContentsRecursive demoDir
forM_ contents $ \file -> do
let dest = path </> file
createDirectoryIfMissing True $ takeDirectory dest
copyFile (demoDir </> file) dest
readme <- getDataFileName "README.markdown"
copyFile readme (path </> "README")
hPutStrLn stderr $ "Created starter site in " ++ path
| 685
|
createSite :: FilePath -> IO ()
createSite path = do
existsd <- doesDirectoryExist path
existsf <- doesFileExist path
when (existsd || existsf) $ do
hPutStrLn stderr $ "Aborting! " ++ path ++ " already exists."
exitWith $ ExitFailure 5
demoDir <- getDataFileName "demo"
contents <- liftM (filter (/=".") . map (makeRelative demoDir)) $ getDirectoryContentsRecursive demoDir
forM_ contents $ \file -> do
let dest = path </> file
createDirectoryIfMissing True $ takeDirectory dest
copyFile (demoDir </> file) dest
readme <- getDataFileName "README.markdown"
copyFile readme (path </> "README")
hPutStrLn stderr $ "Created starter site in " ++ path
| 685
|
createSite path = do
existsd <- doesDirectoryExist path
existsf <- doesFileExist path
when (existsd || existsf) $ do
hPutStrLn stderr $ "Aborting! " ++ path ++ " already exists."
exitWith $ ExitFailure 5
demoDir <- getDataFileName "demo"
contents <- liftM (filter (/=".") . map (makeRelative demoDir)) $ getDirectoryContentsRecursive demoDir
forM_ contents $ \file -> do
let dest = path </> file
createDirectoryIfMissing True $ takeDirectory dest
copyFile (demoDir </> file) dest
readme <- getDataFileName "README.markdown"
copyFile readme (path </> "README")
hPutStrLn stderr $ "Created starter site in " ++ path
| 653
| false
| true
| 0
| 14
| 135
| 233
| 104
| 129
| null | null |
brendanhay/gogol
|
gogol-datastore/gen/Network/Google/Resource/Datastore/Projects/ReserveIds.hs
|
mpl-2.0
|
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
priUploadProtocol :: Lens' ProjectsReserveIds (Maybe Text)
priUploadProtocol
= lens _priUploadProtocol
(\ s a -> s{_priUploadProtocol = a})
| 209
|
priUploadProtocol :: Lens' ProjectsReserveIds (Maybe Text)
priUploadProtocol
= lens _priUploadProtocol
(\ s a -> s{_priUploadProtocol = a})
| 147
|
priUploadProtocol
= lens _priUploadProtocol
(\ s a -> s{_priUploadProtocol = a})
| 88
| true
| true
| 0
| 9
| 33
| 48
| 25
| 23
| null | null |
MathiasVP/syntax-checker-checker
|
buggyunparse.hs
|
mit
|
unparseExpr (Let bindings e) = do
sbindings <- mapM unparse bindings
incr
se <- handle [return "", definition] (unparseExpr e)
return $ "(let (" ++ unwords sbindings ++ ") " ++ se ++ ")"
where unparse = handle [definition, time, if_, and_, or_,
cond, case_, let_, letstar, letrec, begin,
unless_, quote, abstraction] . unparseLetbinding
| 398
|
unparseExpr (Let bindings e) = do
sbindings <- mapM unparse bindings
incr
se <- handle [return "", definition] (unparseExpr e)
return $ "(let (" ++ unwords sbindings ++ ") " ++ se ++ ")"
where unparse = handle [definition, time, if_, and_, or_,
cond, case_, let_, letstar, letrec, begin,
unless_, quote, abstraction] . unparseLetbinding
| 398
|
unparseExpr (Let bindings e) = do
sbindings <- mapM unparse bindings
incr
se <- handle [return "", definition] (unparseExpr e)
return $ "(let (" ++ unwords sbindings ++ ") " ++ se ++ ")"
where unparse = handle [definition, time, if_, and_, or_,
cond, case_, let_, letstar, letrec, begin,
unless_, quote, abstraction] . unparseLetbinding
| 398
| false
| false
| 1
| 11
| 115
| 146
| 74
| 72
| null | null |
oldmanmike/ghc
|
compiler/hsSyn/HsExpr.hs
|
bsd-3-clause
|
hsExprNeedsParens (ExplicitTuple {}) = False
| 45
|
hsExprNeedsParens (ExplicitTuple {}) = False
| 45
|
hsExprNeedsParens (ExplicitTuple {}) = False
| 45
| false
| false
| 0
| 7
| 5
| 16
| 8
| 8
| null | null |
nfjinjing/luka
|
src/Language/ObjectiveC/Luka/RunTime.hs
|
bsd-3-clause
|
objc_allocateClassPair :: ID -> String -> IO ID
objc_allocateClassPair super name = callFFI funPtr_objc_allocateClassPair retId [argPtr super, argString name, argCSize 0]
| 170
|
objc_allocateClassPair :: ID -> String -> IO ID
objc_allocateClassPair super name = callFFI funPtr_objc_allocateClassPair retId [argPtr super, argString name, argCSize 0]
| 170
|
objc_allocateClassPair super name = callFFI funPtr_objc_allocateClassPair retId [argPtr super, argString name, argCSize 0]
| 122
| false
| true
| 0
| 7
| 20
| 52
| 25
| 27
| null | null |
shangaslammi/prose-doc
|
src/Text/ProseDoc/Tree.hs
|
mit
|
breakTree :: (l -> Bool) -> Tree l n -> (Tree l n, Maybe (Tree l n), Tree l n)
breakTree test = go where
go t = case t of
Empty -> (Empty, Nothing, Empty)
Label l t'
| test l -> (Empty, Just (Label l t'), Empty)
| otherwise -> (Label l a, sep, b')
where
(a, sep, b) = go t'
b' = case sep of
Nothing -> Empty
_ -> Label l b
Leaf n -> (Leaf n, Nothing, Empty)
Branch bs -> case sep of
Nothing -> (Branch bs, Nothing, Empty)
_ -> (mconcat a, sep, mconcat b)
where (a, sep, b) = gob bs
gob [] = ([], Nothing, [])
gob (b:bs) = case sep of
Nothing -> (l:b', sep', bs')
_ -> (l:[], sep, r:bs)
where
(l, sep, r) = go b
(b', sep', bs') = gob bs
{-%
Version of `breakTree` which splits the tree into a list of tree sections.
-}
| 979
|
breakTree :: (l -> Bool) -> Tree l n -> (Tree l n, Maybe (Tree l n), Tree l n)
breakTree test = go where
go t = case t of
Empty -> (Empty, Nothing, Empty)
Label l t'
| test l -> (Empty, Just (Label l t'), Empty)
| otherwise -> (Label l a, sep, b')
where
(a, sep, b) = go t'
b' = case sep of
Nothing -> Empty
_ -> Label l b
Leaf n -> (Leaf n, Nothing, Empty)
Branch bs -> case sep of
Nothing -> (Branch bs, Nothing, Empty)
_ -> (mconcat a, sep, mconcat b)
where (a, sep, b) = gob bs
gob [] = ([], Nothing, [])
gob (b:bs) = case sep of
Nothing -> (l:b', sep', bs')
_ -> (l:[], sep, r:bs)
where
(l, sep, r) = go b
(b', sep', bs') = gob bs
{-%
Version of `breakTree` which splits the tree into a list of tree sections.
-}
| 979
|
breakTree test = go where
go t = case t of
Empty -> (Empty, Nothing, Empty)
Label l t'
| test l -> (Empty, Just (Label l t'), Empty)
| otherwise -> (Label l a, sep, b')
where
(a, sep, b) = go t'
b' = case sep of
Nothing -> Empty
_ -> Label l b
Leaf n -> (Leaf n, Nothing, Empty)
Branch bs -> case sep of
Nothing -> (Branch bs, Nothing, Empty)
_ -> (mconcat a, sep, mconcat b)
where (a, sep, b) = gob bs
gob [] = ([], Nothing, [])
gob (b:bs) = case sep of
Nothing -> (l:b', sep', bs')
_ -> (l:[], sep, r:bs)
where
(l, sep, r) = go b
(b', sep', bs') = gob bs
{-%
Version of `breakTree` which splits the tree into a list of tree sections.
-}
| 900
| false
| true
| 2
| 13
| 421
| 434
| 223
| 211
| null | null |
tomberek/rulestesting
|
src/Control/Category/Rules.hs
|
bsd-3-clause
|
category_ruleset' :: [RuleE]
category_ruleset' = [category_id,category_id_comp,category_leftAssoc]
| 98
|
category_ruleset' :: [RuleE]
category_ruleset' = [category_id,category_id_comp,category_leftAssoc]
| 98
|
category_ruleset' = [category_id,category_id_comp,category_leftAssoc]
| 69
| false
| true
| 0
| 5
| 5
| 23
| 14
| 9
| null | null |
asr/apia
|
src/Apia/Defaults.hs
|
mit
|
piaFileName ∷ FilePath
apiaFileName = ".apia"
| 46
|
apiaFileName ∷ FilePath
apiaFileName = ".apia"
| 46
|
apiaFileName = ".apia"
| 22
| false
| true
| 0
| 6
| 6
| 17
| 7
| 10
| null | null |
mrakgr/futhark
|
src/Futhark/Representation/SOACS/SOAC.hs
|
bsd-3-clause
|
substNamesInExtDimSize subs (Free o) = Free $ substNamesInSubExp subs o
| 71
|
substNamesInExtDimSize subs (Free o) = Free $ substNamesInSubExp subs o
| 71
|
substNamesInExtDimSize subs (Free o) = Free $ substNamesInSubExp subs o
| 71
| false
| false
| 0
| 7
| 9
| 26
| 12
| 14
| null | null |
Mathnerd314/lamdu
|
src/Lamdu/Data/Expression/Lens.hs
|
gpl-3.0
|
bodyGetVariable ::
Lens.Prism (Body defa expr) (Body defb expr)
(VariableRef defa) (VariableRef defb)
bodyGetVariable = _BodyLeaf . _GetVariable
| 148
|
bodyGetVariable ::
Lens.Prism (Body defa expr) (Body defb expr)
(VariableRef defa) (VariableRef defb)
bodyGetVariable = _BodyLeaf . _GetVariable
| 148
|
bodyGetVariable = _BodyLeaf . _GetVariable
| 42
| false
| true
| 0
| 7
| 21
| 56
| 27
| 29
| null | null |
brendanhay/gogol
|
gogol-tpu/gen/Network/Google/TPU/Types/Product.hs
|
mpl-2.0
|
-- | Creates a value of 'StopNodeRequest' with the minimum fields required to make a request.
--
stopNodeRequest
:: StopNodeRequest
stopNodeRequest = StopNodeRequest'
| 170
|
stopNodeRequest
:: StopNodeRequest
stopNodeRequest = StopNodeRequest'
| 73
|
stopNodeRequest = StopNodeRequest'
| 34
| true
| true
| 0
| 6
| 26
| 20
| 9
| 11
| null | null |
Trundle/idris-go
|
src/IRTS/CodegenGo.hs
|
mit
|
primToGo var (LSLt (ATInt ITChar)) [left, right] =
let code = T.concat [ "MkIntFromBool(*(*rune)("
, lVarToGo left
, ") < *(*rune)("
, lVarToGo right
, "))"
]
in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code)
| 350
|
primToGo var (LSLt (ATInt ITChar)) [left, right] =
let code = T.concat [ "MkIntFromBool(*(*rune)("
, lVarToGo left
, ") < *(*rune)("
, lVarToGo right
, "))"
]
in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code)
| 350
|
primToGo var (LSLt (ATInt ITChar)) [left, right] =
let code = T.concat [ "MkIntFromBool(*(*rune)("
, lVarToGo left
, ") < *(*rune)("
, lVarToGo right
, "))"
]
in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code)
| 350
| false
| false
| 0
| 11
| 158
| 101
| 51
| 50
| null | null |
nikita-volkov/postgresql-binary
|
tasty/Main/TextEncoder.hs
|
mit
|
int2_word16 :: Encoder Word16
int2_word16 =
word16Dec
| 55
|
int2_word16 :: Encoder Word16
int2_word16 =
word16Dec
| 55
|
int2_word16 =
word16Dec
| 25
| false
| true
| 0
| 5
| 8
| 14
| 7
| 7
| null | null |
romanb/amazonka
|
amazonka-elasticache/gen/Network/AWS/ElastiCache/CreateCacheSecurityGroup.hs
|
mpl-2.0
|
-- | A name for the cache security group. This value is stored as a lowercase
-- string.
--
-- Constraints: Must contain no more than 255 alphanumeric characters. Cannot
-- be the word "Default".
--
-- Example: 'mysecuritygroup'
ccsgCacheSecurityGroupName :: Lens' CreateCacheSecurityGroup Text
ccsgCacheSecurityGroupName =
lens _ccsgCacheSecurityGroupName
(\s a -> s { _ccsgCacheSecurityGroupName = a })
| 416
|
ccsgCacheSecurityGroupName :: Lens' CreateCacheSecurityGroup Text
ccsgCacheSecurityGroupName =
lens _ccsgCacheSecurityGroupName
(\s a -> s { _ccsgCacheSecurityGroupName = a })
| 187
|
ccsgCacheSecurityGroupName =
lens _ccsgCacheSecurityGroupName
(\s a -> s { _ccsgCacheSecurityGroupName = a })
| 121
| true
| true
| 0
| 8
| 68
| 47
| 28
| 19
| null | null |
foreverbell/unlimited-plt-toys
|
extra/re/src/VM.hs
|
bsd-3-clause
|
isInsMatch _ = False
| 20
|
isInsMatch _ = False
| 20
|
isInsMatch _ = False
| 20
| false
| false
| 0
| 5
| 3
| 9
| 4
| 5
| null | null |
bhamrick/HSS
|
HSS/Color.hs
|
mit
|
saddleBrown = RGB 0x8B 0x45 0x13
| 44
|
saddleBrown = RGB 0x8B 0x45 0x13
| 44
|
saddleBrown = RGB 0x8B 0x45 0x13
| 44
| false
| false
| 0
| 5
| 17
| 13
| 6
| 7
| null | null |
tjakway/ghcjvm
|
compiler/rename/RnSplice.hs
|
bsd-3-clause
|
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
rnTopSpliceDecls e = failTH e "Template Haskell top splice"
| 133
|
rnTopSpliceDecls :: HsSplice RdrName -> RnM ([LHsDecl RdrName], FreeVars)
rnTopSpliceDecls e = failTH e "Template Haskell top splice"
| 133
|
rnTopSpliceDecls e = failTH e "Template Haskell top splice"
| 59
| false
| true
| 0
| 10
| 17
| 45
| 21
| 24
| null | null |
divipp/lensref
|
src/LensRef.hs
|
bsd-3-clause
|
ocChildren :: Lens' (OnChange c a m) (c (TriggerList m))
ocChildren tr ~OnChange{..} = tr _ocChildren <&> \_ocChildren -> OnChange{..}
| 134
|
ocChildren :: Lens' (OnChange c a m) (c (TriggerList m))
ocChildren tr ~OnChange{..} = tr _ocChildren <&> \_ocChildren -> OnChange{..}
| 134
|
ocChildren tr ~OnChange{..} = tr _ocChildren <&> \_ocChildren -> OnChange{..}
| 77
| false
| true
| 0
| 9
| 19
| 67
| 33
| 34
| null | null |
michalt/cvector
|
Data/CVector/Unboxed.hs
|
bsd-3-clause
|
update_ :: Unbox a => CVector a -> CVector Int -> CVector a -> CVector a
update_ = G.update_
| 92
|
update_ :: Unbox a => CVector a -> CVector Int -> CVector a -> CVector a
update_ = G.update_
| 92
|
update_ = G.update_
| 19
| false
| true
| 0
| 9
| 18
| 44
| 20
| 24
| null | null |
jgoerzen/missingpy
|
testsrc/Interpretertest.hs
|
gpl-2.0
|
tests = TestList [TestLabel "base" (TestList test_base),
TestLabel "args" (TestList test_args),
TestLabel "callByName" (TestList test_callbyname)]
| 182
|
tests = TestList [TestLabel "base" (TestList test_base),
TestLabel "args" (TestList test_args),
TestLabel "callByName" (TestList test_callbyname)]
| 182
|
tests = TestList [TestLabel "base" (TestList test_base),
TestLabel "args" (TestList test_args),
TestLabel "callByName" (TestList test_callbyname)]
| 182
| false
| false
| 0
| 9
| 50
| 51
| 25
| 26
| null | null |
exercism/xhaskell
|
exercises/practice/food-chain/test/Tests.hs
|
mit
|
lineAssertions = zipWith checkLine [1 :: Int ..] $ zipMaybe (lines song) (lines lyrics)
| 87
|
lineAssertions = zipWith checkLine [1 :: Int ..] $ zipMaybe (lines song) (lines lyrics)
| 87
|
lineAssertions = zipWith checkLine [1 :: Int ..] $ zipMaybe (lines song) (lines lyrics)
| 87
| false
| false
| 0
| 8
| 13
| 39
| 20
| 19
| null | null |
thomie/cabal
|
cabal-install/Distribution/Client/ProjectConfig/Legacy.hs
|
bsd-3-clause
|
parseAllowNewer :: ReadP r AllowNewer
parseAllowNewer =
((const AllowNewerNone <$> (Parse.string "none" +++ Parse.string "None"))
+++ (const AllowNewerAll <$> (Parse.string "all" +++ Parse.string "All")))
<++ ( AllowNewerSome <$> parseOptCommaList parse)
| 270
|
parseAllowNewer :: ReadP r AllowNewer
parseAllowNewer =
((const AllowNewerNone <$> (Parse.string "none" +++ Parse.string "None"))
+++ (const AllowNewerAll <$> (Parse.string "all" +++ Parse.string "All")))
<++ ( AllowNewerSome <$> parseOptCommaList parse)
| 270
|
parseAllowNewer =
((const AllowNewerNone <$> (Parse.string "none" +++ Parse.string "None"))
+++ (const AllowNewerAll <$> (Parse.string "all" +++ Parse.string "All")))
<++ ( AllowNewerSome <$> parseOptCommaList parse)
| 232
| false
| true
| 2
| 12
| 45
| 93
| 45
| 48
| null | null |
Daniel-Diaz/processing
|
Graphics/Web/Processing/Core/TH.hs
|
bsd-3-clause
|
-- | Pretty instance of ProcArg.
procAssignPrettyInst :: Dec -> Dec
procAssignPrettyInst procAssign =
let DataD _ _ _ cs _ = procAssign
defs = fmap (\(NormalC n _) ->
let t = VarE $ mkName "t"
x = VarE $ mkName "x"
e1 <+> e2 = InfixE (Just e1) (VarE $ mkName "<+>") (Just e2)
fromText = AppE $ VarE (mkName "fromText")
e = fromText t <+> fromText (LitE $ StringL "=") <+> AppE (VarE $ mkName "ppr") x
in Clause [ConP n [VarP $ mkName "t", VarP $ mkName "x"]] (NormalB e) []
) cs
inst = FunD (mkName "ppr") defs
in InstanceD [] (AppT (ConT $ mkName "Pretty") (ConT $ mkName "ProcAssign")) [inst]
| 748
|
procAssignPrettyInst :: Dec -> Dec
procAssignPrettyInst procAssign =
let DataD _ _ _ cs _ = procAssign
defs = fmap (\(NormalC n _) ->
let t = VarE $ mkName "t"
x = VarE $ mkName "x"
e1 <+> e2 = InfixE (Just e1) (VarE $ mkName "<+>") (Just e2)
fromText = AppE $ VarE (mkName "fromText")
e = fromText t <+> fromText (LitE $ StringL "=") <+> AppE (VarE $ mkName "ppr") x
in Clause [ConP n [VarP $ mkName "t", VarP $ mkName "x"]] (NormalB e) []
) cs
inst = FunD (mkName "ppr") defs
in InstanceD [] (AppT (ConT $ mkName "Pretty") (ConT $ mkName "ProcAssign")) [inst]
| 715
|
procAssignPrettyInst procAssign =
let DataD _ _ _ cs _ = procAssign
defs = fmap (\(NormalC n _) ->
let t = VarE $ mkName "t"
x = VarE $ mkName "x"
e1 <+> e2 = InfixE (Just e1) (VarE $ mkName "<+>") (Just e2)
fromText = AppE $ VarE (mkName "fromText")
e = fromText t <+> fromText (LitE $ StringL "=") <+> AppE (VarE $ mkName "ppr") x
in Clause [ConP n [VarP $ mkName "t", VarP $ mkName "x"]] (NormalB e) []
) cs
inst = FunD (mkName "ppr") defs
in InstanceD [] (AppT (ConT $ mkName "Pretty") (ConT $ mkName "ProcAssign")) [inst]
| 680
| true
| true
| 0
| 21
| 269
| 304
| 147
| 157
| null | null |
martine/gat
|
FileMode_test.hs
|
gpl-2.0
|
testRoundTrip :: String -> String -> Int -> Test
testRoundTrip msg exp inp = test $
assertEqual ("round-trip " ++ msg) exp (modeToString (modeFromInt inp))
| 157
|
testRoundTrip :: String -> String -> Int -> Test
testRoundTrip msg exp inp = test $
assertEqual ("round-trip " ++ msg) exp (modeToString (modeFromInt inp))
| 157
|
testRoundTrip msg exp inp = test $
assertEqual ("round-trip " ++ msg) exp (modeToString (modeFromInt inp))
| 108
| false
| true
| 0
| 10
| 26
| 60
| 30
| 30
| null | null |
maximilianhuber/univOpWrap
|
src/System/HsTColors.hs
|
bsd-3-clause
|
cyanShow = colorShow ANSICyan
| 29
|
cyanShow = colorShow ANSICyan
| 29
|
cyanShow = colorShow ANSICyan
| 29
| false
| false
| 1
| 5
| 3
| 13
| 4
| 9
| null | null |
NorfairKing/the-notes
|
src/Macro/Numbers/Macro.hs
|
gpl-2.0
|
realsn :: Note
realsn = reals ^: "n"
| 36
|
realsn :: Note
realsn = reals ^: "n"
| 36
|
realsn = reals ^: "n"
| 21
| false
| true
| 2
| 6
| 7
| 23
| 9
| 14
| null | null |
daleooo/barrelfish
|
tools/flounder/THCBackend.hs
|
mit
|
ooo_rpc_seq_name = "ooo_rpc_seq"
| 32
|
ooo_rpc_seq_name = "ooo_rpc_seq"
| 32
|
ooo_rpc_seq_name = "ooo_rpc_seq"
| 32
| false
| false
| 1
| 5
| 2
| 10
| 3
| 7
| null | null |
matterhorn-chat/matterhorn
|
src/Matterhorn/Config.hs
|
bsd-3-clause
|
findConfig :: Maybe FilePath -> IO (Either String ([String], Config))
findConfig Nothing = runExceptT $ do
cfg <- lift $ locateConfig configFileName
(warns, config) <-
case cfg of
Nothing -> return ([], defaultConfig)
Just path -> getConfig path
config' <- fixupPaths config
return (warns, config')
| 336
|
findConfig :: Maybe FilePath -> IO (Either String ([String], Config))
findConfig Nothing = runExceptT $ do
cfg <- lift $ locateConfig configFileName
(warns, config) <-
case cfg of
Nothing -> return ([], defaultConfig)
Just path -> getConfig path
config' <- fixupPaths config
return (warns, config')
| 336
|
findConfig Nothing = runExceptT $ do
cfg <- lift $ locateConfig configFileName
(warns, config) <-
case cfg of
Nothing -> return ([], defaultConfig)
Just path -> getConfig path
config' <- fixupPaths config
return (warns, config')
| 266
| false
| true
| 0
| 14
| 82
| 127
| 62
| 65
| null | null |
Peaker/keyvaluehash
|
src/Database/GrowingFile.hs
|
bsd-3-clause
|
msync :: GrowingFile -> IO ()
msync gfile = do
header <- readHeader gfile
fptr <- readIORef (gfPtr gfile)
withForeignPtr fptr $ \ptr ->
MMapSync.msync ptr (fromIntegral (hUsed header)) (Just MMapSync.Async) MMapSync.NoInvalidate
| 238
|
msync :: GrowingFile -> IO ()
msync gfile = do
header <- readHeader gfile
fptr <- readIORef (gfPtr gfile)
withForeignPtr fptr $ \ptr ->
MMapSync.msync ptr (fromIntegral (hUsed header)) (Just MMapSync.Async) MMapSync.NoInvalidate
| 238
|
msync gfile = do
header <- readHeader gfile
fptr <- readIORef (gfPtr gfile)
withForeignPtr fptr $ \ptr ->
MMapSync.msync ptr (fromIntegral (hUsed header)) (Just MMapSync.Async) MMapSync.NoInvalidate
| 208
| false
| true
| 0
| 13
| 41
| 97
| 45
| 52
| null | null |
gcampax/ghc
|
compiler/basicTypes/BasicTypes.hs
|
bsd-3-clause
|
pprSafeOverlap :: Bool -> SDoc
pprSafeOverlap True = ptext $ sLit "[safe]"
| 75
|
pprSafeOverlap :: Bool -> SDoc
pprSafeOverlap True = ptext $ sLit "[safe]"
| 75
|
pprSafeOverlap True = ptext $ sLit "[safe]"
| 44
| false
| true
| 0
| 7
| 12
| 30
| 13
| 17
| null | null |
kmate/raw-feldspar-mcs
|
src/Zeldspar/Multicore/Compile.hs
|
bsd-3-clause
|
count :: CoreIdTree -> Int
count (One _) = 1
| 46
|
count :: CoreIdTree -> Int
count (One _) = 1
| 46
|
count (One _) = 1
| 19
| false
| true
| 0
| 7
| 11
| 24
| 12
| 12
| null | null |
julianalucena/mancala
|
Rules.hs
|
lgpl-3.0
|
hasMove :: Player -> Board -> Bool
hasMove p b = any (/=0) holes
where holes = removeMancalaHole (getPlayerHoles p b)
-- Verifies if a capture can be done
| 157
|
hasMove :: Player -> Board -> Bool
hasMove p b = any (/=0) holes
where holes = removeMancalaHole (getPlayerHoles p b)
-- Verifies if a capture can be done
| 157
|
hasMove p b = any (/=0) holes
where holes = removeMancalaHole (getPlayerHoles p b)
-- Verifies if a capture can be done
| 122
| false
| true
| 1
| 8
| 31
| 62
| 28
| 34
| null | null |
pparkkin/eta
|
compiler/ETA/Prelude/PrelNames.hs
|
bsd-3-clause
|
neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey
| 96
|
neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey
| 96
|
neqIntegerPrimName = varQual gHC_INTEGER_TYPE (fsLit "neqInteger#") neqIntegerPrimIdKey
| 96
| false
| false
| 0
| 7
| 15
| 19
| 9
| 10
| null | null |
danr/hipspec
|
src/HipSpec/ATP/Invoke.hs
|
gpl-3.0
|
promiseProof :: forall eq .
InvokeEnv -> Obligation eq LinTheory -> Double -> Prover
-> HS (Promise [Obligation eq Result])
promiseProof env@InvokeEnv{store} ob@Obligation{..} timelimit prover@Prover{..} = do
tmp <- fmap (</> "hipspec") (liftIO getTemporaryDirectory)
theory_str <- liftIO (lin prover_input_format)
let sha = showDigest (sha256 (pack theory_str))
cache_dir = tmp </> show prover </> take 2 sha
cache_file = cache_dir </> drop 2 sha
cache_exists <- liftIO (doesFileExist cache_file)
cached cache_exists cache_dir cache_file theory_str
where
LinTheory lin = ob_content
ret res = An [fmap (const (prover_name,res)) ob]
cached True _cache_dir cache_file _theory_str = do
content <- liftIO (readFile cache_file)
let mk_promise s = do
-- liftIO $ putStrLn $ cache_file ++ ": Cache exists with content: " ++ content
return Promise
{ spawn = return ()
, cancel = return ()
, result = return s
}
length content `seq` case content of
'1':_ -> mk_promise (ret (Success Nothing))
_ -> mk_promise Cancelled
cached False cache_dir cache_file theory_str = do
let writeCache r = do
ex <- doesFileExist cache_file
createDirectoryIfMissing True cache_dir
content <- if ex then liftIO (readFile cache_file) else return ""
when (not ex || content /= "1") $ do
let v = if r then "1" else "0"
-- putStrLn $ cache_file ++ ": Writing cache: " ++ v
writeFile cache_file v
`E.catch` \ (_ :: SomeException) -> return ()
filepath <- liftIO $ case store of
Nothing -> return Nothing
Just dir -> do
let (path,file) = filename env ob
d = dir </> path
f = d </> file <.> extension prover_input_format
createDirectoryIfMissing True d
writeFile f theory_str
return (Just f)
when (prover_cannot_stdin && isNothing filepath) $ liftIO $
putStrLn $
"*** " ++ show prover_name ++
" must read its input from a file, run with --output ***"
let filepath' | prover_cannot_stdin = case filepath of
Just k -> k
Nothing -> error "Run with --output"
| otherwise = error $
"Prover " ++ show prover_name ++
" should not open a file, but it did!"
inputStr | prover_cannot_stdin = ""
| otherwise = theory_str
w <- getWriteMsgFun
let callback r = do
w . ProverResult (prop_name ob_prop) ob_info . stdout $ r
writeCache $ case interpretResult prover r of
Just Success{} -> True
_ -> False
promise <- length inputStr `seq` (liftIO $
processPromiseCallback
callback
prover_cmd
(prover_args filepath' timelimit) inputStr)
let update :: PromiseResult ProcessResult -> PromiseResult [Obligation eq Result]
update Cancelled = Cancelled
update Unfinished = Unfinished
update (An r) = case interpretResult prover r of
Just res -> ret res
Nothing -> Cancelled
return Promise
{ spawn = do
w $ Spawning (prop_name ob_prop) ob_info
w $ SpawningWithTheory (prop_name ob_prop) ob_info theory_str
spawn promise
, cancel = do
w $ Cancelling (prop_name ob_prop) ob_info
cancel promise
-- writeCache False
, result = update <$> result promise
}
-- TODO: make this in the HS monad and send messages
| 4,102
|
promiseProof :: forall eq .
InvokeEnv -> Obligation eq LinTheory -> Double -> Prover
-> HS (Promise [Obligation eq Result])
promiseProof env@InvokeEnv{store} ob@Obligation{..} timelimit prover@Prover{..} = do
tmp <- fmap (</> "hipspec") (liftIO getTemporaryDirectory)
theory_str <- liftIO (lin prover_input_format)
let sha = showDigest (sha256 (pack theory_str))
cache_dir = tmp </> show prover </> take 2 sha
cache_file = cache_dir </> drop 2 sha
cache_exists <- liftIO (doesFileExist cache_file)
cached cache_exists cache_dir cache_file theory_str
where
LinTheory lin = ob_content
ret res = An [fmap (const (prover_name,res)) ob]
cached True _cache_dir cache_file _theory_str = do
content <- liftIO (readFile cache_file)
let mk_promise s = do
-- liftIO $ putStrLn $ cache_file ++ ": Cache exists with content: " ++ content
return Promise
{ spawn = return ()
, cancel = return ()
, result = return s
}
length content `seq` case content of
'1':_ -> mk_promise (ret (Success Nothing))
_ -> mk_promise Cancelled
cached False cache_dir cache_file theory_str = do
let writeCache r = do
ex <- doesFileExist cache_file
createDirectoryIfMissing True cache_dir
content <- if ex then liftIO (readFile cache_file) else return ""
when (not ex || content /= "1") $ do
let v = if r then "1" else "0"
-- putStrLn $ cache_file ++ ": Writing cache: " ++ v
writeFile cache_file v
`E.catch` \ (_ :: SomeException) -> return ()
filepath <- liftIO $ case store of
Nothing -> return Nothing
Just dir -> do
let (path,file) = filename env ob
d = dir </> path
f = d </> file <.> extension prover_input_format
createDirectoryIfMissing True d
writeFile f theory_str
return (Just f)
when (prover_cannot_stdin && isNothing filepath) $ liftIO $
putStrLn $
"*** " ++ show prover_name ++
" must read its input from a file, run with --output ***"
let filepath' | prover_cannot_stdin = case filepath of
Just k -> k
Nothing -> error "Run with --output"
| otherwise = error $
"Prover " ++ show prover_name ++
" should not open a file, but it did!"
inputStr | prover_cannot_stdin = ""
| otherwise = theory_str
w <- getWriteMsgFun
let callback r = do
w . ProverResult (prop_name ob_prop) ob_info . stdout $ r
writeCache $ case interpretResult prover r of
Just Success{} -> True
_ -> False
promise <- length inputStr `seq` (liftIO $
processPromiseCallback
callback
prover_cmd
(prover_args filepath' timelimit) inputStr)
let update :: PromiseResult ProcessResult -> PromiseResult [Obligation eq Result]
update Cancelled = Cancelled
update Unfinished = Unfinished
update (An r) = case interpretResult prover r of
Just res -> ret res
Nothing -> Cancelled
return Promise
{ spawn = do
w $ Spawning (prop_name ob_prop) ob_info
w $ SpawningWithTheory (prop_name ob_prop) ob_info theory_str
spawn promise
, cancel = do
w $ Cancelling (prop_name ob_prop) ob_info
cancel promise
-- writeCache False
, result = update <$> result promise
}
-- TODO: make this in the HS monad and send messages
| 4,102
|
promiseProof env@InvokeEnv{store} ob@Obligation{..} timelimit prover@Prover{..} = do
tmp <- fmap (</> "hipspec") (liftIO getTemporaryDirectory)
theory_str <- liftIO (lin prover_input_format)
let sha = showDigest (sha256 (pack theory_str))
cache_dir = tmp </> show prover </> take 2 sha
cache_file = cache_dir </> drop 2 sha
cache_exists <- liftIO (doesFileExist cache_file)
cached cache_exists cache_dir cache_file theory_str
where
LinTheory lin = ob_content
ret res = An [fmap (const (prover_name,res)) ob]
cached True _cache_dir cache_file _theory_str = do
content <- liftIO (readFile cache_file)
let mk_promise s = do
-- liftIO $ putStrLn $ cache_file ++ ": Cache exists with content: " ++ content
return Promise
{ spawn = return ()
, cancel = return ()
, result = return s
}
length content `seq` case content of
'1':_ -> mk_promise (ret (Success Nothing))
_ -> mk_promise Cancelled
cached False cache_dir cache_file theory_str = do
let writeCache r = do
ex <- doesFileExist cache_file
createDirectoryIfMissing True cache_dir
content <- if ex then liftIO (readFile cache_file) else return ""
when (not ex || content /= "1") $ do
let v = if r then "1" else "0"
-- putStrLn $ cache_file ++ ": Writing cache: " ++ v
writeFile cache_file v
`E.catch` \ (_ :: SomeException) -> return ()
filepath <- liftIO $ case store of
Nothing -> return Nothing
Just dir -> do
let (path,file) = filename env ob
d = dir </> path
f = d </> file <.> extension prover_input_format
createDirectoryIfMissing True d
writeFile f theory_str
return (Just f)
when (prover_cannot_stdin && isNothing filepath) $ liftIO $
putStrLn $
"*** " ++ show prover_name ++
" must read its input from a file, run with --output ***"
let filepath' | prover_cannot_stdin = case filepath of
Just k -> k
Nothing -> error "Run with --output"
| otherwise = error $
"Prover " ++ show prover_name ++
" should not open a file, but it did!"
inputStr | prover_cannot_stdin = ""
| otherwise = theory_str
w <- getWriteMsgFun
let callback r = do
w . ProverResult (prop_name ob_prop) ob_info . stdout $ r
writeCache $ case interpretResult prover r of
Just Success{} -> True
_ -> False
promise <- length inputStr `seq` (liftIO $
processPromiseCallback
callback
prover_cmd
(prover_args filepath' timelimit) inputStr)
let update :: PromiseResult ProcessResult -> PromiseResult [Obligation eq Result]
update Cancelled = Cancelled
update Unfinished = Unfinished
update (An r) = case interpretResult prover r of
Just res -> ret res
Nothing -> Cancelled
return Promise
{ spawn = do
w $ Spawning (prop_name ob_prop) ob_info
w $ SpawningWithTheory (prop_name ob_prop) ob_info theory_str
spawn promise
, cancel = do
w $ Cancelling (prop_name ob_prop) ob_info
cancel promise
-- writeCache False
, result = update <$> result promise
}
-- TODO: make this in the HS monad and send messages
| 3,949
| false
| true
| 0
| 18
| 1,635
| 1,070
| 506
| 564
| null | null |
lpeterse/koka
|
src/Type/Type.hs
|
apache-2.0
|
-- | Is a type variable a 'Skolem' (eq. not unifiable)
isSkolem :: TypeVar -> Bool
isSkolem tv = typevarFlavour tv == Skolem
| 124
|
isSkolem :: TypeVar -> Bool
isSkolem tv = typevarFlavour tv == Skolem
| 69
|
isSkolem tv = typevarFlavour tv == Skolem
| 41
| true
| true
| 0
| 6
| 22
| 26
| 13
| 13
| null | null |
adamschoenemann/simple-frp
|
test/FRP/TestFunctions.hs
|
mit
|
prog_swap_const_nats = Program [] [mainfn, frp_unfold, frp_const, frp_nats, frp_swap]
where
mainfn = frp_main mainbd (tystream tynat)
mainbd =
"us" -->
"swap" <| "us" <| 10 <|
("nats" <| "us" <| 0) <| ("const" <| "us" <| 42)
| 252
|
prog_swap_const_nats = Program [] [mainfn, frp_unfold, frp_const, frp_nats, frp_swap]
where
mainfn = frp_main mainbd (tystream tynat)
mainbd =
"us" -->
"swap" <| "us" <| 10 <|
("nats" <| "us" <| 0) <| ("const" <| "us" <| 42)
| 252
|
prog_swap_const_nats = Program [] [mainfn, frp_unfold, frp_const, frp_nats, frp_swap]
where
mainfn = frp_main mainbd (tystream tynat)
mainbd =
"us" -->
"swap" <| "us" <| 10 <|
("nats" <| "us" <| 0) <| ("const" <| "us" <| 42)
| 252
| false
| false
| 0
| 9
| 64
| 94
| 50
| 44
| null | null |
jxv/gridland
|
demo/Main.hs
|
mit
|
updateSfx :: GridLand App ()
updateSfx = do
app <- getData
inputs <- getInputs
when (elem (Key (Char 'a') Pressed) inputs) (playSfx (oops app))
when (elem (Key (Char 'f') Pressed) inputs) (playSfx (laser app))
| 225
|
updateSfx :: GridLand App ()
updateSfx = do
app <- getData
inputs <- getInputs
when (elem (Key (Char 'a') Pressed) inputs) (playSfx (oops app))
when (elem (Key (Char 'f') Pressed) inputs) (playSfx (laser app))
| 225
|
updateSfx = do
app <- getData
inputs <- getInputs
when (elem (Key (Char 'a') Pressed) inputs) (playSfx (oops app))
when (elem (Key (Char 'f') Pressed) inputs) (playSfx (laser app))
| 196
| false
| true
| 0
| 13
| 49
| 116
| 55
| 61
| null | null |
rahulmutt/ghcvm
|
compiler/Eta/Prelude/PrimOp.hs
|
bsd-3-clause
|
tagOf_PrimOp IndexOffAddrOp_Addr = _ILIT(276)
| 45
|
tagOf_PrimOp IndexOffAddrOp_Addr = _ILIT(276)
| 45
|
tagOf_PrimOp IndexOffAddrOp_Addr = _ILIT(276)
| 45
| false
| false
| 0
| 6
| 3
| 15
| 7
| 8
| null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.