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
GaloisInc/halvm-ghc
compiler/hsSyn/HsPat.hs
bsd-3-clause
pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, pat_binds = binds, pat_args = details }) = sdocWithDynFlags $ \dflags -> -- Tiresome; in TcBinds.tcRhs we print out a -- typechecked Pat in an error message, -- and we want to make sure it prints nicely if gopt Opt_PrintTypecheckerElaboration dflags then ppr con <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts)) , ppr binds]) <+> pprConArgs details else pprUserCon (unLoc con) details
562
pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, pat_binds = binds, pat_args = details }) = sdocWithDynFlags $ \dflags -> -- Tiresome; in TcBinds.tcRhs we print out a -- typechecked Pat in an error message, -- and we want to make sure it prints nicely if gopt Opt_PrintTypecheckerElaboration dflags then ppr con <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts)) , ppr binds]) <+> pprConArgs details else pprUserCon (unLoc con) details
562
pprPat (ConPatOut { pat_con = con, pat_tvs = tvs, pat_dicts = dicts, pat_binds = binds, pat_args = details }) = sdocWithDynFlags $ \dflags -> -- Tiresome; in TcBinds.tcRhs we print out a -- typechecked Pat in an error message, -- and we want to make sure it prints nicely if gopt Opt_PrintTypecheckerElaboration dflags then ppr con <> braces (sep [ hsep (map pprPatBndr (tvs ++ dicts)) , ppr binds]) <+> pprConArgs details else pprUserCon (unLoc con) details
562
false
false
0
18
180
132
71
61
null
null
mpickering/pandoc-lit
src/Text/Pandoc/Lit.hs
bsd-3-clause
readFileUTF8 :: FilePath -> IO String readFileUTF8 name = do handle <- openFile name ReadMode hSetEncoding handle utf8 hSetNewlineMode handle universalNewlineMode hGetContents handle
190
readFileUTF8 :: FilePath -> IO String readFileUTF8 name = do handle <- openFile name ReadMode hSetEncoding handle utf8 hSetNewlineMode handle universalNewlineMode hGetContents handle
190
readFileUTF8 name = do handle <- openFile name ReadMode hSetEncoding handle utf8 hSetNewlineMode handle universalNewlineMode hGetContents handle
152
false
true
0
8
30
55
23
32
null
null
christiaanb/ghc
testsuite/tests/typecheck/should_fail/T10351.hs
bsd-3-clause
f x = op [x]
12
f x = op [x]
12
f x = op [x]
12
false
false
1
6
4
18
7
11
null
null
BartAdv/Idris-dev
src/Idris/Primitives.hs
bsd-3-clause
toInt (ITFixed IT32) x = B32 (fromIntegral x)
49
toInt (ITFixed IT32) x = B32 (fromIntegral x)
49
toInt (ITFixed IT32) x = B32 (fromIntegral x)
49
false
false
1
7
11
31
12
19
null
null
snoyberg/ghc
compiler/hsSyn/HsExpr.hs
bsd-3-clause
pprGRHS :: (OutputableBndrId idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body
154
pprGRHS :: (OutputableBndrId idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body
154
pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body
48
false
true
0
8
33
67
31
36
null
null
vikraman/ghc
compiler/prelude/THNames.hs
bsd-3-clause
decTyConName = thTc (fsLit "Dec") decTyConKey
61
decTyConName = thTc (fsLit "Dec") decTyConKey
61
decTyConName = thTc (fsLit "Dec") decTyConKey
61
false
false
0
7
21
17
8
9
null
null
spinda/liquidhaskell
src/Language/Haskell/Liquid/Pipeline/Annotate.hs
bsd-3-clause
cinfoErr e = case pos e of RealSrcSpan l -> Just (srcSpanStartLoc l, srcSpanEndLoc l, showpp e) _ -> Nothing -- cinfoErr (Ci (RealSrcSpan l) e) = -- cinfoErr _ = Nothing -- mkAnnMapTyp :: (RefTypable a c tv r, RefTypable a c tv (), PPrint tv, PPrint a) =>Config-> AnnInfo (RType a c tv r) -> M.HashMap Loc (String, String)
388
cinfoErr e = case pos e of RealSrcSpan l -> Just (srcSpanStartLoc l, srcSpanEndLoc l, showpp e) _ -> Nothing -- cinfoErr (Ci (RealSrcSpan l) e) = -- cinfoErr _ = Nothing -- mkAnnMapTyp :: (RefTypable a c tv r, RefTypable a c tv (), PPrint tv, PPrint a) =>Config-> AnnInfo (RType a c tv r) -> M.HashMap Loc (String, String)
388
cinfoErr e = case pos e of RealSrcSpan l -> Just (srcSpanStartLoc l, srcSpanEndLoc l, showpp e) _ -> Nothing -- cinfoErr (Ci (RealSrcSpan l) e) = -- cinfoErr _ = Nothing -- mkAnnMapTyp :: (RefTypable a c tv r, RefTypable a c tv (), PPrint tv, PPrint a) =>Config-> AnnInfo (RType a c tv r) -> M.HashMap Loc (String, String)
388
false
false
0
10
126
55
27
28
null
null
travitch/dalvik
src/Dalvik/SSA/Internal/BasicBlocks.hs
bsd-3-clause
-- | Get the block number for an instruction instructionBlockNumber :: BasicBlocks -> Int -> Maybe BlockNumber instructionBlockNumber bbs ix = case IM.containing (bbFromInstruction bbs) ix of [(_, bnum)] -> Just bnum _ -> Nothing -- | Get the basic block ID for the instruction at the given index.
308
instructionBlockNumber :: BasicBlocks -> Int -> Maybe BlockNumber instructionBlockNumber bbs ix = case IM.containing (bbFromInstruction bbs) ix of [(_, bnum)] -> Just bnum _ -> Nothing -- | Get the basic block ID for the instruction at the given index.
263
instructionBlockNumber bbs ix = case IM.containing (bbFromInstruction bbs) ix of [(_, bnum)] -> Just bnum _ -> Nothing -- | Get the basic block ID for the instruction at the given index.
197
true
true
2
8
59
63
35
28
null
null
facebookincubator/duckling
Duckling/Email/Corpus.hs
bsd-3-clause
negativeCorpus :: NegativeCorpus negativeCorpus = (testContext, testOptions, examples) where examples = [ "hey@6" , "hey@you" ]
151
negativeCorpus :: NegativeCorpus negativeCorpus = (testContext, testOptions, examples) where examples = [ "hey@6" , "hey@you" ]
151
negativeCorpus = (testContext, testOptions, examples) where examples = [ "hey@6" , "hey@you" ]
118
false
true
0
5
39
34
20
14
null
null
formrre/yi
yi-core/src/Yi/Buffer/Implementation.hs
gpl-2.0
focusAst :: M.Map WindowRef Region -> BufferImpl syntax -> BufferImpl syntax focusAst r b@FBufferData {hlCache = HLState s@(SynHL {hlFocus = foc}) cache} = b {hlCache = HLState s (foc r cache)}
194
focusAst :: M.Map WindowRef Region -> BufferImpl syntax -> BufferImpl syntax focusAst r b@FBufferData {hlCache = HLState s@(SynHL {hlFocus = foc}) cache} = b {hlCache = HLState s (foc r cache)}
194
focusAst r b@FBufferData {hlCache = HLState s@(SynHL {hlFocus = foc}) cache} = b {hlCache = HLState s (foc r cache)}
116
false
true
7
10
31
94
46
48
null
null
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionOperations/Get.hs
mpl-2.0
-- | Name of the Operations resource to return. rogOperation :: Lens' RegionOperationsGet Text rogOperation = lens _rogOperation (\ s a -> s{_rogOperation = a})
162
rogOperation :: Lens' RegionOperationsGet Text rogOperation = lens _rogOperation (\ s a -> s{_rogOperation = a})
114
rogOperation = lens _rogOperation (\ s a -> s{_rogOperation = a})
67
true
true
0
9
26
42
22
20
null
null
adinapoli/memento
src/Memento/HipChat.hs
mit
-- | Simple HipChat notifier module for Memento. -------------------------------------------------------------------------------- apiToken_ :: Memento T.Text apiToken_ = requireEnv "memento.hipchat.apiToken"
208
apiToken_ :: Memento T.Text apiToken_ = requireEnv "memento.hipchat.apiToken"
77
apiToken_ = requireEnv "memento.hipchat.apiToken"
49
true
true
0
6
17
21
11
10
null
null
elieux/ghc
compiler/hsSyn/HsPat.hs
bsd-3-clause
hsPatNeedsParens (SigPatOut {}) = True
43
hsPatNeedsParens (SigPatOut {}) = True
43
hsPatNeedsParens (SigPatOut {}) = True
43
false
false
0
7
9
16
8
8
null
null
ierton/yteratee
src/Data/Yteratee/IO.hs
bsd-3-clause
enumFile :: (MonadCatchIO m, ReadableChunk s el) => Int -> FilePath -> YEnumerator s m a enumFile = FD.enumFile
128
enumFile :: (MonadCatchIO m, ReadableChunk s el) => Int -> FilePath -> YEnumerator s m a enumFile = FD.enumFile
128
enumFile = FD.enumFile
22
false
true
0
8
35
49
24
25
null
null
unclechu/haskell-qm-interpolated-string
src/Text/InterpolatedString/QM/Internal/Parsers.hs
unlicense
-- With interpolation blocks (line breaks are kept, indentation is ignored) qmb :: String -> TH.ExpQ qmb = makeExpr . parseQMB "" . clearFirstQXXLineBreak . clearIndentAtStart
187
qmb :: String -> TH.ExpQ qmb = makeExpr . parseQMB "" . clearFirstQXXLineBreak . clearIndentAtStart
111
qmb = makeExpr . parseQMB "" . clearFirstQXXLineBreak . clearIndentAtStart
86
true
true
3
8
37
43
18
25
null
null
ambiata/highlighting-kate
Text/Highlighting/Kate/Syntax/Vhdl.hs
gpl-2.0
parseRules ("VHDL","packagefunction") = (((pRegExpr regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'5cb >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("VHDL","packagefunction")) >> pDefault >>= withAttribute NormalTok))
362
parseRules ("VHDL","packagefunction") = (((pRegExpr regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'5cb >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("VHDL","packagefunction")) >> pDefault >>= withAttribute NormalTok))
362
parseRules ("VHDL","packagefunction") = (((pRegExpr regex_'28'5cb'29'5cb'28'3f'21'28'3f'3aprocess'7cconstant'7csignal'7cvariable'29'29'28'5bA'2dZa'2dz'5f'5d'5bA'2dZa'2dz0'2d9'5f'5d'2a'29'5cb'5cb >>= withAttribute KeywordTok) >>~ (popContext)) <|> (currentContext >>= \x -> guard (x == ("VHDL","packagefunction")) >> pDefault >>= withAttribute NormalTok))
362
false
false
0
15
31
85
45
40
null
null
573/leksah
src/IDE/Command/VCS/SVN.hs
gpl-2.0
--HELPERS createSVNActionFromContext :: (Either GUISvn.Handler (Maybe Text) -> Wrapper.Ctx()) -> Types.VCSAction () createSVNActionFromContext action = do (mergeInfo, mbPw) <- Types.readIDE' vcsData ide <- Types.askIDERef case mbPw of Nothing -> Helper.createActionFromContext $ action $ Left $ passwordHandler ide mergeInfo Just mb -> Helper.createActionFromContext $ action $ Right mb where -- passwordHandler :: IORef IDE-> Maybe MergeId -> ((Maybe (Bool, Maybe Text)) -> Wrapper.Ctx ()) passwordHandler ide mbMergeInfo result = liftIO $ case result of Just (True, pw) -> modifyIDE_' ide (\ide -> ide {vcsData = (mbMergeInfo, Just pw) }) _ -> return () modifyIDE_' ide f = liftIO (atomicModifyIORef ide f') where f' a = (f a,())
966
createSVNActionFromContext :: (Either GUISvn.Handler (Maybe Text) -> Wrapper.Ctx()) -> Types.VCSAction () createSVNActionFromContext action = do (mergeInfo, mbPw) <- Types.readIDE' vcsData ide <- Types.askIDERef case mbPw of Nothing -> Helper.createActionFromContext $ action $ Left $ passwordHandler ide mergeInfo Just mb -> Helper.createActionFromContext $ action $ Right mb where -- passwordHandler :: IORef IDE-> Maybe MergeId -> ((Maybe (Bool, Maybe Text)) -> Wrapper.Ctx ()) passwordHandler ide mbMergeInfo result = liftIO $ case result of Just (True, pw) -> modifyIDE_' ide (\ide -> ide {vcsData = (mbMergeInfo, Just pw) }) _ -> return () modifyIDE_' ide f = liftIO (atomicModifyIORef ide f') where f' a = (f a,())
955
createSVNActionFromContext action = do (mergeInfo, mbPw) <- Types.readIDE' vcsData ide <- Types.askIDERef case mbPw of Nothing -> Helper.createActionFromContext $ action $ Left $ passwordHandler ide mergeInfo Just mb -> Helper.createActionFromContext $ action $ Right mb where -- passwordHandler :: IORef IDE-> Maybe MergeId -> ((Maybe (Bool, Maybe Text)) -> Wrapper.Ctx ()) passwordHandler ide mbMergeInfo result = liftIO $ case result of Just (True, pw) -> modifyIDE_' ide (\ide -> ide {vcsData = (mbMergeInfo, Just pw) }) _ -> return () modifyIDE_' ide f = liftIO (atomicModifyIORef ide f') where f' a = (f a,())
790
true
true
1
16
340
250
124
126
null
null
achirkin/fgeom
src/Geometry/Space/Approximate.hs
bsd-3-clause
-- | Get tolerance of the approximation getEps :: Approximately eps eps getEps = Approximately id
97
getEps :: Approximately eps eps getEps = Approximately id
57
getEps = Approximately id
25
true
true
0
5
15
20
10
10
null
null
pscollins/cmsc-22311-lab-2
Suck.hs
gpl-2.0
extractBody :: String -> String extractBody = filter isAscii . innerText . flattenTree . searchTree (treeHasAttribute ("id", "body")) . tagTree . parseTags
169
extractBody :: String -> String extractBody = filter isAscii . innerText . flattenTree . searchTree (treeHasAttribute ("id", "body")) . tagTree . parseTags
169
extractBody = filter isAscii . innerText . flattenTree . searchTree (treeHasAttribute ("id", "body")) . tagTree . parseTags
137
false
true
0
11
35
53
27
26
null
null
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/Routers/List.hs
mpl-2.0
-- | Specifies a page token to use. Set pageToken to the nextPageToken -- returned by a previous list request to get the next page of results. rlPageToken :: Lens' RoutersList (Maybe Text) rlPageToken = lens _rlPageToken (\ s a -> s{_rlPageToken = a})
253
rlPageToken :: Lens' RoutersList (Maybe Text) rlPageToken = lens _rlPageToken (\ s a -> s{_rlPageToken = a})
110
rlPageToken = lens _rlPageToken (\ s a -> s{_rlPageToken = a})
64
true
true
1
9
45
51
26
25
null
null
pradyuman/haskell
recursion.hs
mit
filter' p (x:xs) | p x = x : filter' p xs | otherwise = filter' p xs
78
filter' p (x:xs) | p x = x : filter' p xs | otherwise = filter' p xs
78
filter' p (x:xs) | p x = x : filter' p xs | otherwise = filter' p xs
78
false
false
1
8
27
48
22
26
null
null
UBMLtonGroup/timberc
src/Desugar2.hs
bsd-3-clause
dsDecls (d@(DKSig _ _) : ds) = liftM (d :) (dsDecls ds)
58
dsDecls (d@(DKSig _ _) : ds) = liftM (d :) (dsDecls ds)
58
dsDecls (d@(DKSig _ _) : ds) = liftM (d :) (dsDecls ds)
58
false
false
0
10
14
42
22
20
null
null
Proclivis/wxHaskell
wxcore/src/haskell/Graphics/UI/WXCore/WxcDefs.hs
lgpl-2.1
wxLANGUAGE_ASSAMESE :: Int wxLANGUAGE_ASSAMESE = 26
51
wxLANGUAGE_ASSAMESE :: Int wxLANGUAGE_ASSAMESE = 26
51
wxLANGUAGE_ASSAMESE = 26
24
false
true
0
4
5
11
6
5
null
null
ku-fpg/kansas-amber
System/Hardware/Haskino/Protocol.hs
bsd-3-clause
parseQueryResult (SerialReadList _) (SerialReadListReply ws) = Just ws
70
parseQueryResult (SerialReadList _) (SerialReadListReply ws) = Just ws
70
parseQueryResult (SerialReadList _) (SerialReadListReply ws) = Just ws
70
false
false
0
7
7
26
12
14
null
null
glguy/irc-core
src/Client/State/Window.hs
isc
unpackUTCTime :: PackedTime -> UTCTime unpackUTCTime = zonedTimeToUTC . unpackZonedTime
87
unpackUTCTime :: PackedTime -> UTCTime unpackUTCTime = zonedTimeToUTC . unpackZonedTime
87
unpackUTCTime = zonedTimeToUTC . unpackZonedTime
48
false
true
0
7
9
26
11
15
null
null
brendanhay/gogol
gogol-proximitybeacon/gen/Network/Google/Resource/ProximityBeacon/Beacons/Get.hs
mpl-2.0
-- | Upload protocol for media (e.g. \"raw\", \"multipart\"). bgUploadProtocol :: Lens' BeaconsGet (Maybe Text) bgUploadProtocol = lens _bgUploadProtocol (\ s a -> s{_bgUploadProtocol = a})
197
bgUploadProtocol :: Lens' BeaconsGet (Maybe Text) bgUploadProtocol = lens _bgUploadProtocol (\ s a -> s{_bgUploadProtocol = a})
135
bgUploadProtocol = lens _bgUploadProtocol (\ s a -> s{_bgUploadProtocol = a})
85
true
true
1
9
33
52
25
27
null
null
kazu-yamamoto/concurrent-dns-cache
Network/DNS/Cache.hs
bsd-3-clause
---------------------------------------------------------------- -- | A basic function to create DNS cache. -- Domains should be resolved in the function of the second argument. withDNSCache :: (MonadBaseControl IO m, MonadIO m) => DNSCacheConf -> (DNSCache -> m a) -> m a withDNSCache conf func = do seeds <- mapM (liftIO . makeResolvSeed) (resolvConfs conf) let n = length seeds cacheref <- liftIO newCacheRef activeref <- liftIO S.newActiveRef lvar <- liftIO S.newConcVar let cache = DNSCache seeds n cacheref activeref lvar maxcon minttl maxttl negttl bracket (fork $ liftIO $ prune cacheref) killThread (const $ func cache) where maxcon = maxConcurrency conf minttl = minTTL conf maxttl = maxTTL conf negttl = negativeTTL conf ----------------------------------------------------------------
859
withDNSCache :: (MonadBaseControl IO m, MonadIO m) => DNSCacheConf -> (DNSCache -> m a) -> m a withDNSCache conf func = do seeds <- mapM (liftIO . makeResolvSeed) (resolvConfs conf) let n = length seeds cacheref <- liftIO newCacheRef activeref <- liftIO S.newActiveRef lvar <- liftIO S.newConcVar let cache = DNSCache seeds n cacheref activeref lvar maxcon minttl maxttl negttl bracket (fork $ liftIO $ prune cacheref) killThread (const $ func cache) where maxcon = maxConcurrency conf minttl = minTTL conf maxttl = maxTTL conf negttl = negativeTTL conf ----------------------------------------------------------------
678
withDNSCache conf func = do seeds <- mapM (liftIO . makeResolvSeed) (resolvConfs conf) let n = length seeds cacheref <- liftIO newCacheRef activeref <- liftIO S.newActiveRef lvar <- liftIO S.newConcVar let cache = DNSCache seeds n cacheref activeref lvar maxcon minttl maxttl negttl bracket (fork $ liftIO $ prune cacheref) killThread (const $ func cache) where maxcon = maxConcurrency conf minttl = minTTL conf maxttl = maxTTL conf negttl = negativeTTL conf ----------------------------------------------------------------
570
true
true
0
10
174
226
108
118
null
null
markus-git/co-feldspar
src/Feldspar/Hardware/Optimize.hs
bsd-3-clause
freeVar :: Name -> Opt () freeVar v = tell (Set.singleton v, mempty)
68
freeVar :: Name -> Opt () freeVar v = tell (Set.singleton v, mempty)
68
freeVar v = tell (Set.singleton v, mempty)
42
false
true
0
8
12
37
18
19
null
null
kkspeed/SICP-Practise
Interpreter/code/Eval.hs
lgpl-3.0
defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value
558
defineVar :: Env -> String -> LispVal -> IOThrowsError LispVal defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value
558
defineVar envRef var value = do alreadyDefined <- liftIO $ isBound envRef var if alreadyDefined then setVar envRef var value >> return value else liftIO $ do valueRef <- newIORef value env <- readIORef envRef writeIORef envRef ((var, valueRef) : env) return value
495
false
true
0
14
284
125
58
67
null
null
markwright/antlrc-examples
src/tapl/fulluntyped/Semantic.hs
bsd-3-clause
termSubstTop :: Term Info -> Term Info -> Term Info termSubstTop s t = termShift (-1) (termSubst 0 (termShift 1 s) t)
117
termSubstTop :: Term Info -> Term Info -> Term Info termSubstTop s t = termShift (-1) (termSubst 0 (termShift 1 s) t)
117
termSubstTop s t = termShift (-1) (termSubst 0 (termShift 1 s) t)
65
false
true
0
9
21
61
29
32
null
null
thoughtpolice/binary-serialise-cbor
bench/Real/Load.hs
bsd-3-clause
readPkgIndex :: BS.ByteString -> Either String [GenericPackageDescription] readPkgIndex = fmap extractCabalFiles . readTarIndex where extractCabalFiles entries = [ pkgDesc | Tar.Entry { Tar.entryContent = Tar.NormalFile cabalFile _ } <- entries , let ParseOk _ pkgDesc = parsePackageDescription . fromUTF8 . BS.unpack $ cabalFile ] readTarIndex :: BS.ByteString -> Either String [Tar.Entry] readTarIndex indexFileContent = collect [] entries where entries = Tar.read indexFileContent collect es' Tar.Done = Right es' collect es' (Tar.Next e es) = case entry e of Just e' -> collect (e':es') es Nothing -> collect es' es collect _ (Tar.Fail err) = Left (show err) entry e | [_pkgname,versionStr,_] <- splitDirectories (normalise (Tar.entryPath e)) , Just (Version _ []) <- simpleParse versionStr = Just e entry _ = Nothing
1,043
readPkgIndex :: BS.ByteString -> Either String [GenericPackageDescription] readPkgIndex = fmap extractCabalFiles . readTarIndex where extractCabalFiles entries = [ pkgDesc | Tar.Entry { Tar.entryContent = Tar.NormalFile cabalFile _ } <- entries , let ParseOk _ pkgDesc = parsePackageDescription . fromUTF8 . BS.unpack $ cabalFile ] readTarIndex :: BS.ByteString -> Either String [Tar.Entry] readTarIndex indexFileContent = collect [] entries where entries = Tar.read indexFileContent collect es' Tar.Done = Right es' collect es' (Tar.Next e es) = case entry e of Just e' -> collect (e':es') es Nothing -> collect es' es collect _ (Tar.Fail err) = Left (show err) entry e | [_pkgname,versionStr,_] <- splitDirectories (normalise (Tar.entryPath e)) , Just (Version _ []) <- simpleParse versionStr = Just e entry _ = Nothing
1,043
readPkgIndex = fmap extractCabalFiles . readTarIndex where extractCabalFiles entries = [ pkgDesc | Tar.Entry { Tar.entryContent = Tar.NormalFile cabalFile _ } <- entries , let ParseOk _ pkgDesc = parsePackageDescription . fromUTF8 . BS.unpack $ cabalFile ] readTarIndex :: BS.ByteString -> Either String [Tar.Entry] readTarIndex indexFileContent = collect [] entries where entries = Tar.read indexFileContent collect es' Tar.Done = Right es' collect es' (Tar.Next e es) = case entry e of Just e' -> collect (e':es') es Nothing -> collect es' es collect _ (Tar.Fail err) = Left (show err) entry e | [_pkgname,versionStr,_] <- splitDirectories (normalise (Tar.entryPath e)) , Just (Version _ []) <- simpleParse versionStr = Just e entry _ = Nothing
968
false
true
15
13
342
316
161
155
null
null
RossMeikleham/GB-Assembler
BinGen.hs
mit
genLd16 :: Ld16Stmt -> B.ByteString genLd16 (LdCombinedRegIm reg16 w16) = B.pack $ [ins] ++ (splitW16 w16) where ins = case reg16 of BC -> 0x01 DE -> 0x11 HL -> 0x21 SP -> 0x31
210
genLd16 :: Ld16Stmt -> B.ByteString genLd16 (LdCombinedRegIm reg16 w16) = B.pack $ [ins] ++ (splitW16 w16) where ins = case reg16 of BC -> 0x01 DE -> 0x11 HL -> 0x21 SP -> 0x31
210
genLd16 (LdCombinedRegIm reg16 w16) = B.pack $ [ins] ++ (splitW16 w16) where ins = case reg16 of BC -> 0x01 DE -> 0x11 HL -> 0x21 SP -> 0x31
174
false
true
0
7
67
83
42
41
null
null
vikraman/ghc
compiler/cmm/CLabel.hs
bsd-3-clause
labelType (PlainModuleInitLabel _) = CodeLabel
59
labelType (PlainModuleInitLabel _) = CodeLabel
59
labelType (PlainModuleInitLabel _) = CodeLabel
59
false
false
0
6
17
16
7
9
null
null
ndmitchell/nsis
src/Development/NSIS/Plugins/WinMessages.hs
bsd-3-clause
-- Window Messages -- wm_ACTIVATE = 0x0006
62
wm_ACTIVATE = 0x0006
40
wm_ACTIVATE = 0x0006
40
true
false
0
4
26
7
4
3
null
null
sethfowler/pygmalion
src/Pygmalion/Database/IO.hs
bsd-3-clause
getLastMTime :: DBHandle -> SourceFileHash -> IO (Maybe Time) getLastMTime h sfHash = do v <- execSingleRowQuery h getLastMTimeStmt (Only sfHash) case v of Just (Only t) -> return $ Just t Nothing -> return Nothing
232
getLastMTime :: DBHandle -> SourceFileHash -> IO (Maybe Time) getLastMTime h sfHash = do v <- execSingleRowQuery h getLastMTimeStmt (Only sfHash) case v of Just (Only t) -> return $ Just t Nothing -> return Nothing
232
getLastMTime h sfHash = do v <- execSingleRowQuery h getLastMTimeStmt (Only sfHash) case v of Just (Only t) -> return $ Just t Nothing -> return Nothing
170
false
true
0
12
53
91
42
49
null
null
lisphacker/codewars
FindingAnAppointment.hs
bsd-2-clause
timeMax = 599
13
timeMax = 599
13
timeMax = 599
13
false
false
1
5
2
10
3
7
null
null
maffh92/AFP-ANT
src/Abstractions.hs
bsd-3-clause
-------------------------------------------------------------------------------- -- Other combinators -- | Try to move, if fail do something else move_ :: (MonadFix m, Label l) => AntT m l () -- ^ Failure -> AntT m l () move_ = move (return ())
259
move_ :: (MonadFix m, Label l) => AntT m l () -- ^ Failure -> AntT m l () move_ = move (return ())
110
move_ = move (return ())
24
true
true
0
8
52
63
33
30
null
null
themoritz/cabal
Cabal/Distribution/Types/BuildInfo.hs
bsd-3-clause
-- | The 'Extension's that are used somewhere by this component -- allExtensions :: BuildInfo -> [Extension] allExtensions bi = usedExtensions bi ++ otherExtensions bi
183
allExtensions :: BuildInfo -> [Extension] allExtensions bi = usedExtensions bi ++ otherExtensions bi
116
allExtensions bi = usedExtensions bi ++ otherExtensions bi
74
true
true
0
6
40
33
17
16
null
null
f1u77y/xmonad-contrib
XMonad/Layout/BinarySpacePartition.hs
bsd-3-clause
removeNth :: BinarySpacePartition a -> BinarySpacePartition a removeNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP
119
removeNth :: BinarySpacePartition a -> BinarySpacePartition a removeNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP
119
removeNth (BinarySpacePartition _ _ _ Nothing) = emptyBSP
57
false
true
0
7
14
36
17
19
null
null
zhiyuanshi/include
Include.hs
mit
-- | A LaTeX preprocessor. latexP :: Processor latexP = emit . parse . lines
76
latexP :: Processor latexP = emit . parse . lines
49
latexP = emit . parse . lines
29
true
true
2
6
14
29
12
17
null
null
pjones/xmonad-test
vendor/xmonad-contrib/XMonad/Layout/MosaicAlt.hs
bsd-2-clause
makeTree :: [Window] -> Params -> Tree makeTree wins params = case wins of [] -> None [x] -> Leaf x _ -> Node (aArea, makeTree aWins params) (bArea, makeTree bWins params) where ((aWins, aArea), (bWins, bArea)) = areaSplit params wins -- Split a list of windows in half by area.
299
makeTree :: [Window] -> Params -> Tree makeTree wins params = case wins of [] -> None [x] -> Leaf x _ -> Node (aArea, makeTree aWins params) (bArea, makeTree bWins params) where ((aWins, aArea), (bWins, bArea)) = areaSplit params wins -- Split a list of windows in half by area.
299
makeTree wins params = case wins of [] -> None [x] -> Leaf x _ -> Node (aArea, makeTree aWins params) (bArea, makeTree bWins params) where ((aWins, aArea), (bWins, bArea)) = areaSplit params wins -- Split a list of windows in half by area.
260
false
true
2
7
71
105
60
45
null
null
mettekou/ghc
compiler/deSugar/DsArrows.hs
bsd-3-clause
dsCmd ids local_vars stack_ty res_ty (HsCmdDo (L _ stmts) _) env_ids = do (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids let env_ty = mkBigCoreVarTupTy env_ids core_fst <- mkFstExpr env_ty stack_ty return (do_premap ids (mkCorePairTy env_ty stack_ty) env_ty res_ty core_fst core_stmts, env_ids') -- D |- e :: forall e. a1 (e,stk1) t1 -> ... an (e,stkn) tn -> a (e,stk) t -- D; xs |-a ci :: stki --> ti -- ----------------------------------- -- D; xs |-a (|e c1 ... cn|) :: stk --> t ---> e [t_xs] c1 ... cn
640
dsCmd ids local_vars stack_ty res_ty (HsCmdDo (L _ stmts) _) env_ids = do (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids let env_ty = mkBigCoreVarTupTy env_ids core_fst <- mkFstExpr env_ty stack_ty return (do_premap ids (mkCorePairTy env_ty stack_ty) env_ty res_ty core_fst core_stmts, env_ids') -- D |- e :: forall e. a1 (e,stk1) t1 -> ... an (e,stkn) tn -> a (e,stk) t -- D; xs |-a ci :: stki --> ti -- ----------------------------------- -- D; xs |-a (|e c1 ... cn|) :: stk --> t ---> e [t_xs] c1 ... cn
640
dsCmd ids local_vars stack_ty res_ty (HsCmdDo (L _ stmts) _) env_ids = do (core_stmts, env_ids') <- dsCmdDo ids local_vars res_ty stmts env_ids let env_ty = mkBigCoreVarTupTy env_ids core_fst <- mkFstExpr env_ty stack_ty return (do_premap ids (mkCorePairTy env_ty stack_ty) env_ty res_ty core_fst core_stmts, env_ids') -- D |- e :: forall e. a1 (e,stk1) t1 -> ... an (e,stkn) tn -> a (e,stk) t -- D; xs |-a ci :: stki --> ti -- ----------------------------------- -- D; xs |-a (|e c1 ... cn|) :: stk --> t ---> e [t_xs] c1 ... cn
640
false
false
0
11
201
120
59
61
null
null
Alex-Diez/haskell-tdd-kata
old-katas/test/SubListKata/Day4Spec.hs
bsd-3-clause
spec :: Spec spec = do it "empty equals empty" $ do sublist "" "" `shouldBe` Equal it "empty is sublinst of anything" $ do sublist "" "anything" `shouldBe` Sublist it "anything is superlist of empty" $ do sublist "anything" "" `shouldBe` Superlist it "1 does not equal 2" $ do sublist "1" "2" `shouldBe` Unequal it "100 equals to 100" $ do sublist "100" "100" `shouldBe` Equal it "11 is sublist of 44311234" $ do sublist "11" "44311234" `shouldBe` Sublist it "6545590 is superlist of 55" $ do sublist "6545590" "55" `shouldBe` Superlist
686
spec :: Spec spec = do it "empty equals empty" $ do sublist "" "" `shouldBe` Equal it "empty is sublinst of anything" $ do sublist "" "anything" `shouldBe` Sublist it "anything is superlist of empty" $ do sublist "anything" "" `shouldBe` Superlist it "1 does not equal 2" $ do sublist "1" "2" `shouldBe` Unequal it "100 equals to 100" $ do sublist "100" "100" `shouldBe` Equal it "11 is sublist of 44311234" $ do sublist "11" "44311234" `shouldBe` Sublist it "6545590 is superlist of 55" $ do sublist "6545590" "55" `shouldBe` Superlist
682
spec = do it "empty equals empty" $ do sublist "" "" `shouldBe` Equal it "empty is sublinst of anything" $ do sublist "" "anything" `shouldBe` Sublist it "anything is superlist of empty" $ do sublist "anything" "" `shouldBe` Superlist it "1 does not equal 2" $ do sublist "1" "2" `shouldBe` Unequal it "100 equals to 100" $ do sublist "100" "100" `shouldBe` Equal it "11 is sublist of 44311234" $ do sublist "11" "44311234" `shouldBe` Sublist it "6545590 is superlist of 55" $ do sublist "6545590" "55" `shouldBe` Superlist
669
false
true
0
11
243
186
84
102
null
null
kyoungrok0517/linguist
samples/Haskell/Sudoku.hs
mit
solve :: Sudoku -> Maybe Sudoku solve sudoku | isSolved sudoku = Just sudoku | otherwise = do index <- elemIndex 0 sudoku let sudokus = [nextTest sudoku index i | i <- [1..9], checkRow (nextTest sudoku index i) index, checkColumn (nextTest sudoku index i) index, checkBox (nextTest sudoku index i) index] listToMaybe $ mapMaybe solve sudokus where nextTest sudoku index i = take index sudoku ++ [i] ++ drop (index+1) sudoku checkRow sudoku index = (length $ getRow sudoku index) == (length $ nub $ getRow sudoku index) checkColumn sudoku index = (length $ getColumn sudoku index) == (length $ nub $ getColumn sudoku index) checkBox sudoku index = (length $ getBox sudoku index) == (length $ nub $ getBox sudoku index) getRow sudoku index = filter (/=0) $ (chunksOf 9 sudoku) !! (quot index 9) getColumn sudoku index = filter (/=0) $ (transpose $ chunksOf 9 sudoku) !! (mod index 9) getBox sudoku index = filter (/=0) $ (map concat $ concatMap transpose $ chunksOf 3 $ map (chunksOf 3) $ chunksOf 9 sudoku) !! (3 * (quot index 27) + (quot (mod index 9) 3))
1,303
solve :: Sudoku -> Maybe Sudoku solve sudoku | isSolved sudoku = Just sudoku | otherwise = do index <- elemIndex 0 sudoku let sudokus = [nextTest sudoku index i | i <- [1..9], checkRow (nextTest sudoku index i) index, checkColumn (nextTest sudoku index i) index, checkBox (nextTest sudoku index i) index] listToMaybe $ mapMaybe solve sudokus where nextTest sudoku index i = take index sudoku ++ [i] ++ drop (index+1) sudoku checkRow sudoku index = (length $ getRow sudoku index) == (length $ nub $ getRow sudoku index) checkColumn sudoku index = (length $ getColumn sudoku index) == (length $ nub $ getColumn sudoku index) checkBox sudoku index = (length $ getBox sudoku index) == (length $ nub $ getBox sudoku index) getRow sudoku index = filter (/=0) $ (chunksOf 9 sudoku) !! (quot index 9) getColumn sudoku index = filter (/=0) $ (transpose $ chunksOf 9 sudoku) !! (mod index 9) getBox sudoku index = filter (/=0) $ (map concat $ concatMap transpose $ chunksOf 3 $ map (chunksOf 3) $ chunksOf 9 sudoku) !! (3 * (quot index 27) + (quot (mod index 9) 3))
1,303
solve sudoku | isSolved sudoku = Just sudoku | otherwise = do index <- elemIndex 0 sudoku let sudokus = [nextTest sudoku index i | i <- [1..9], checkRow (nextTest sudoku index i) index, checkColumn (nextTest sudoku index i) index, checkBox (nextTest sudoku index i) index] listToMaybe $ mapMaybe solve sudokus where nextTest sudoku index i = take index sudoku ++ [i] ++ drop (index+1) sudoku checkRow sudoku index = (length $ getRow sudoku index) == (length $ nub $ getRow sudoku index) checkColumn sudoku index = (length $ getColumn sudoku index) == (length $ nub $ getColumn sudoku index) checkBox sudoku index = (length $ getBox sudoku index) == (length $ nub $ getBox sudoku index) getRow sudoku index = filter (/=0) $ (chunksOf 9 sudoku) !! (quot index 9) getColumn sudoku index = filter (/=0) $ (transpose $ chunksOf 9 sudoku) !! (mod index 9) getBox sudoku index = filter (/=0) $ (map concat $ concatMap transpose $ chunksOf 3 $ map (chunksOf 3) $ chunksOf 9 sudoku) !! (3 * (quot index 27) + (quot (mod index 9) 3))
1,271
false
true
1
14
435
515
250
265
null
null
shouya/thinking-dumps
wys48h/code/Parser.hs
mit
parseQuoted :: Parser LispVal parseQuoted = do char '\'' x <- parseExpr return $ List [Identifier "quote", x]
127
parseQuoted :: Parser LispVal parseQuoted = do char '\'' x <- parseExpr return $ List [Identifier "quote", x]
127
parseQuoted = do char '\'' x <- parseExpr return $ List [Identifier "quote", x]
97
false
true
0
11
35
52
22
30
null
null
josefs/sbv
Data/SBV/Core/Model.hs
bsd-3-clause
mkSymOpSC :: (SW -> SW -> Maybe SW) -> Op -> State -> Kind -> SW -> SW -> IO SW mkSymOpSC shortCut op st k a b = maybe (newExpr st k (SBVApp op [a, b])) return (shortCut a b)
174
mkSymOpSC :: (SW -> SW -> Maybe SW) -> Op -> State -> Kind -> SW -> SW -> IO SW mkSymOpSC shortCut op st k a b = maybe (newExpr st k (SBVApp op [a, b])) return (shortCut a b)
174
mkSymOpSC shortCut op st k a b = maybe (newExpr st k (SBVApp op [a, b])) return (shortCut a b)
94
false
true
0
11
40
104
52
52
null
null
stepcut/plugins
src/System/Eval/Haskell.hs
lgpl-2.1
unsafeEval :: String -> [Import] -> IO (Maybe a) unsafeEval src mods = do pwd <- getCurrentDirectory tmpf <- mkUniqueWith wrap src mods status <- make tmpf [] m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- load obj [pwd] [] symbol case m_v of LoadFailure _ -> return Nothing LoadSuccess _ rsrc -> return $ Just rsrc MakeFailure err -> mapM_ putStrLn err >> return Nothing makeCleaner tmpf return m_rsrc -- -- | 'unsafeEval_' is a form of 'unsafeEval' with all internal hooks -- exposed. This is useful for application wishing to return error -- messages to users, to specify particular libraries to link against -- and so on. --
734
unsafeEval :: String -> [Import] -> IO (Maybe a) unsafeEval src mods = do pwd <- getCurrentDirectory tmpf <- mkUniqueWith wrap src mods status <- make tmpf [] m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- load obj [pwd] [] symbol case m_v of LoadFailure _ -> return Nothing LoadSuccess _ rsrc -> return $ Just rsrc MakeFailure err -> mapM_ putStrLn err >> return Nothing makeCleaner tmpf return m_rsrc -- -- | 'unsafeEval_' is a form of 'unsafeEval' with all internal hooks -- exposed. This is useful for application wishing to return error -- messages to users, to specify particular libraries to link against -- and so on. --
734
unsafeEval src mods = do pwd <- getCurrentDirectory tmpf <- mkUniqueWith wrap src mods status <- make tmpf [] m_rsrc <- case status of MakeSuccess _ obj -> do m_v <- load obj [pwd] [] symbol case m_v of LoadFailure _ -> return Nothing LoadSuccess _ rsrc -> return $ Just rsrc MakeFailure err -> mapM_ putStrLn err >> return Nothing makeCleaner tmpf return m_rsrc -- -- | 'unsafeEval_' is a form of 'unsafeEval' with all internal hooks -- exposed. This is useful for application wishing to return error -- messages to users, to specify particular libraries to link against -- and so on. --
685
false
true
0
18
210
195
89
106
null
null
edsko/cabal
Cabal/src/Distribution/Simple.hs
bsd-3-clause
configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo configureAction hooks flags args = do distPref <- findDistPrefOrDefault (configDistPref flags) let flags' = flags { configDistPref = toFlag distPref } pbi <- preConf hooks args flags' (mb_pd_file, pkg_descr0) <- confPkgDescr --get_pkg_descr (configVerbosity flags') --let pkg_descr = updatePackageDescription pbi pkg_descr0 let epkg_descr = (pkg_descr0, pbi) --(warns, ers) <- sanityCheckPackage pkg_descr --errorOut (configVerbosity flags') warns ers localbuildinfo0 <- confHook hooks epkg_descr flags' -- remember the .cabal filename if we know it -- and all the extra command line args let localbuildinfo = localbuildinfo0 { pkgDescrFile = mb_pd_file, extraConfigArgs = args } writePersistBuildConfig distPref localbuildinfo let pkg_descr = localPkgDescr localbuildinfo postConf hooks args flags' pkg_descr localbuildinfo return localbuildinfo where verbosity = fromFlag (configVerbosity flags) confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription) confPkgDescr = do mdescr <- readDesc hooks case mdescr of Just descr -> return (Nothing, descr) Nothing -> do pdfile <- defaultPackageDesc verbosity descr <- readPackageDescription verbosity pdfile return (Just pdfile, descr)
1,505
configureAction :: UserHooks -> ConfigFlags -> Args -> IO LocalBuildInfo configureAction hooks flags args = do distPref <- findDistPrefOrDefault (configDistPref flags) let flags' = flags { configDistPref = toFlag distPref } pbi <- preConf hooks args flags' (mb_pd_file, pkg_descr0) <- confPkgDescr --get_pkg_descr (configVerbosity flags') --let pkg_descr = updatePackageDescription pbi pkg_descr0 let epkg_descr = (pkg_descr0, pbi) --(warns, ers) <- sanityCheckPackage pkg_descr --errorOut (configVerbosity flags') warns ers localbuildinfo0 <- confHook hooks epkg_descr flags' -- remember the .cabal filename if we know it -- and all the extra command line args let localbuildinfo = localbuildinfo0 { pkgDescrFile = mb_pd_file, extraConfigArgs = args } writePersistBuildConfig distPref localbuildinfo let pkg_descr = localPkgDescr localbuildinfo postConf hooks args flags' pkg_descr localbuildinfo return localbuildinfo where verbosity = fromFlag (configVerbosity flags) confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription) confPkgDescr = do mdescr <- readDesc hooks case mdescr of Just descr -> return (Nothing, descr) Nothing -> do pdfile <- defaultPackageDesc verbosity descr <- readPackageDescription verbosity pdfile return (Just pdfile, descr)
1,505
configureAction hooks flags args = do distPref <- findDistPrefOrDefault (configDistPref flags) let flags' = flags { configDistPref = toFlag distPref } pbi <- preConf hooks args flags' (mb_pd_file, pkg_descr0) <- confPkgDescr --get_pkg_descr (configVerbosity flags') --let pkg_descr = updatePackageDescription pbi pkg_descr0 let epkg_descr = (pkg_descr0, pbi) --(warns, ers) <- sanityCheckPackage pkg_descr --errorOut (configVerbosity flags') warns ers localbuildinfo0 <- confHook hooks epkg_descr flags' -- remember the .cabal filename if we know it -- and all the extra command line args let localbuildinfo = localbuildinfo0 { pkgDescrFile = mb_pd_file, extraConfigArgs = args } writePersistBuildConfig distPref localbuildinfo let pkg_descr = localPkgDescr localbuildinfo postConf hooks args flags' pkg_descr localbuildinfo return localbuildinfo where verbosity = fromFlag (configVerbosity flags) confPkgDescr :: IO (Maybe FilePath, GenericPackageDescription) confPkgDescr = do mdescr <- readDesc hooks case mdescr of Just descr -> return (Nothing, descr) Nothing -> do pdfile <- defaultPackageDesc verbosity descr <- readPackageDescription verbosity pdfile return (Just pdfile, descr)
1,432
false
true
0
14
405
311
150
161
null
null
wouwouwou/2017_module_8
src/haskell/PP-project-2017/Checker.hs
apache-2.0
checker2 (ASTVar str _) check = ASTVar str check
52
checker2 (ASTVar str _) check = ASTVar str check
52
checker2 (ASTVar str _) check = ASTVar str check
52
false
false
1
7
12
30
11
19
null
null
HJvT/hdirect
src/Parser.hs
bsd-3-clause
action_2 (19#) = happyGoto action_12
36
action_2 (19#) = happyGoto action_12
36
action_2 (19#) = happyGoto action_12
36
false
false
0
6
4
15
7
8
null
null
yairchu/ad
src/Numeric/AD/Internal/Combinators.hs
bsd-3-clause
-- | Zip a @'Foldable' f@ with a @'Traversable' g@ assuming @f@, using a default value after @f@ is exhausted. zipWithDefaultT :: (Foldable f, Traversable g) => a -> (a -> b -> c) -> f a -> g b -> g c zipWithDefaultT z f as = zipWithT f (toList as ++ repeat z)
260
zipWithDefaultT :: (Foldable f, Traversable g) => a -> (a -> b -> c) -> f a -> g b -> g c zipWithDefaultT z f as = zipWithT f (toList as ++ repeat z)
149
zipWithDefaultT z f as = zipWithT f (toList as ++ repeat z)
59
true
true
0
10
54
88
43
45
null
null
ssaavedra/liquidhaskell
benchmarks/icfp15/pos/DataBase.hs
bsd-3-clause
filter f (x:xs) | f x = x : filter f xs | otherwise = filter f xs
75
filter f (x:xs) | f x = x : filter f xs | otherwise = filter f xs
75
filter f (x:xs) | f x = x : filter f xs | otherwise = filter f xs
75
false
false
1
8
27
49
22
27
null
null
jtojnar/haste-compiler
libraries/ghc-7.10/ghc-prim/GHC/PrimopWrappers.hs
bsd-3-clause
readWord32Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #) readWord32Array# a1 a2 a3 = (GHC.Prim.readWord32Array#) a1 a2 a3
148
readWord32Array# :: MutableByteArray# s -> Int# -> State# s -> (# State# s,Word# #) readWord32Array# a1 a2 a3 = (GHC.Prim.readWord32Array#) a1 a2 a3
148
readWord32Array# a1 a2 a3 = (GHC.Prim.readWord32Array#) a1 a2 a3
64
false
true
0
9
22
57
28
29
null
null
mbrock/HBEAM
src/Language/Erlang/BEAM/Opcodes.hs
gpl-3.0
opcodeInfo 37 = ("int_bsr", 4)
30
opcodeInfo 37 = ("int_bsr", 4)
30
opcodeInfo 37 = ("int_bsr", 4)
30
false
false
0
5
4
15
8
7
null
null
andrey013/pluginstest
Plugins/Gallery/Gallery/Manual48.hs
mit
example = no <> image "static/phone.png" 1.5 1.5
48
example = no <> image "static/phone.png" 1.5 1.5
48
example = no <> image "static/phone.png" 1.5 1.5
48
false
false
0
6
7
17
8
9
null
null
Kheldar/hw-koans
solution/Koan/Simple.hs
bsd-3-clause
takeWhile _ _ = []
23
takeWhile _ _ = []
23
takeWhile _ _ = []
23
false
false
1
6
9
14
6
8
null
null
AndreasPK/stack
src/Stack/Types/Config.hs
bsd-3-clause
configMonoidConnectionCountName :: Text configMonoidConnectionCountName = "connection-count"
92
configMonoidConnectionCountName :: Text configMonoidConnectionCountName = "connection-count"
92
configMonoidConnectionCountName = "connection-count"
52
false
true
0
4
5
11
6
5
null
null
individkid/sidegeo
src/AffTopo/Naive.hs
gpl-3.0
-- all possible regions powerSpace :: [Boundary] -> Place powerSpace b = let count = length b regions = indices (shift 1 count) boundaries = indices count in map (\(x,y) -> (y, [powerSpaceF x regions 0, powerSpaceF x regions 1])) (zip boundaries b)
252
powerSpace :: [Boundary] -> Place powerSpace b = let count = length b regions = indices (shift 1 count) boundaries = indices count in map (\(x,y) -> (y, [powerSpaceF x regions 0, powerSpaceF x regions 1])) (zip boundaries b)
228
powerSpace b = let count = length b regions = indices (shift 1 count) boundaries = indices count in map (\(x,y) -> (y, [powerSpaceF x regions 0, powerSpaceF x regions 1])) (zip boundaries b)
194
true
true
0
12
46
113
59
54
null
null
23Skidoo/xmlhtml
test/suite/Text/XmlHtml/Tests.hs
bsd-3-clause
------------------------------------------------------------------------------ -- XML Parsing Tests --------------------------------------------------------- ------------------------------------------------------------------------------ xmlParsingTests :: [Test] xmlParsingTests = [ testCase "byteOrderMark " byteOrderMark, testIt "emptyDocument " emptyDocument, testIt "publicDocType " publicDocType, testIt "systemDocType " systemDocType, testIt "emptyDocType " emptyDocType, testCase "dtdInternalScan " dtdInternalScan, testIt "textOnly " textOnly, testIt "textWithRefs " textWithRefs, testIt "untermRef " untermRef, testIt "textWithCDATA " textWithCDATA, testIt "cdataOnly " cdataOnly, testIt "commentOnly " commentOnly, testIt "emptyElement " emptyElement, testIt "emptyElement2 " emptyElement2, testIt "elemWithText " elemWithText, testIt "xmlDeclXML " xmlDeclXML, testIt "procInst " procInst, testIt "badDoctype1 " badDoctype1, testIt "badDoctype2 " badDoctype2, testIt "badDoctype3 " badDoctype3, testIt "badDoctype4 " badDoctype4, testIt "badDoctype5 " badDoctype5, testCase "tagNames " tagNames ]
1,490
xmlParsingTests :: [Test] xmlParsingTests = [ testCase "byteOrderMark " byteOrderMark, testIt "emptyDocument " emptyDocument, testIt "publicDocType " publicDocType, testIt "systemDocType " systemDocType, testIt "emptyDocType " emptyDocType, testCase "dtdInternalScan " dtdInternalScan, testIt "textOnly " textOnly, testIt "textWithRefs " textWithRefs, testIt "untermRef " untermRef, testIt "textWithCDATA " textWithCDATA, testIt "cdataOnly " cdataOnly, testIt "commentOnly " commentOnly, testIt "emptyElement " emptyElement, testIt "emptyElement2 " emptyElement2, testIt "elemWithText " elemWithText, testIt "xmlDeclXML " xmlDeclXML, testIt "procInst " procInst, testIt "badDoctype1 " badDoctype1, testIt "badDoctype2 " badDoctype2, testIt "badDoctype3 " badDoctype3, testIt "badDoctype4 " badDoctype4, testIt "badDoctype5 " badDoctype5, testCase "tagNames " tagNames ]
1,252
xmlParsingTests = [ testCase "byteOrderMark " byteOrderMark, testIt "emptyDocument " emptyDocument, testIt "publicDocType " publicDocType, testIt "systemDocType " systemDocType, testIt "emptyDocType " emptyDocType, testCase "dtdInternalScan " dtdInternalScan, testIt "textOnly " textOnly, testIt "textWithRefs " textWithRefs, testIt "untermRef " untermRef, testIt "textWithCDATA " textWithCDATA, testIt "cdataOnly " cdataOnly, testIt "commentOnly " commentOnly, testIt "emptyElement " emptyElement, testIt "emptyElement2 " emptyElement2, testIt "elemWithText " elemWithText, testIt "xmlDeclXML " xmlDeclXML, testIt "procInst " procInst, testIt "badDoctype1 " badDoctype1, testIt "badDoctype2 " badDoctype2, testIt "badDoctype3 " badDoctype3, testIt "badDoctype4 " badDoctype4, testIt "badDoctype5 " badDoctype5, testCase "tagNames " tagNames ]
1,226
true
true
0
6
489
201
103
98
null
null
sgillespie/ghc
compiler/prelude/PrelNames.hs
bsd-3-clause
-- >>> firstAIdKey = mkPreludeMiscIdUnique 182
50
firstAIdKey = mkPreludeMiscIdUnique 182
43
firstAIdKey = mkPreludeMiscIdUnique 182
43
true
false
0
5
9
10
5
5
null
null
lfritz/python-type-inference
python-type-inference/src/Language/Python/TypeInference/CFG/ToFragment.hs
bsd-3-clause
-- | Convert a binary operator. toBinaryOperator :: AST.Op SrcSpan -> TypeInferenceMonad BinaryOperator toBinaryOperator (AST.And _) = return BooleanAnd
166
toBinaryOperator :: AST.Op SrcSpan -> TypeInferenceMonad BinaryOperator toBinaryOperator (AST.And _) = return BooleanAnd
134
toBinaryOperator (AST.And _) = return BooleanAnd
62
true
true
0
8
32
38
18
20
null
null
mreid/papersite
src/exec/scrape.hs
mit
isPDF = isLinkType "pdf"
24
isPDF = isLinkType "pdf"
24
isPDF = isLinkType "pdf"
24
false
false
1
5
3
12
4
8
null
null
asakamirai/kazura-queue
bench/Main.hs
bsd-3-clause
main :: IO () main = do CR.defaultMainWith configSpeed [ CR.bgroup "KazuraQueue" $ testcases $ testSpeed_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testSpeed_ testUChan , CR.bgroup "Chan" $ testcases $ testSpeed_ testChan , CR.bgroup "TQueue" $ testcases $ testSpeed_ testTQueue , CR.bgroup "TChan" $ testcases $ testSpeed_ testTChan ] CR.defaultMainWith configCost [ CR.bgroup "KazuraQueue" $ testcases $ testCost_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testCost_ testUChan , CR.bgroup "Chan" $ testcases $ testCost_ testChan , CR.bgroup "TQueue" $ testcases $ testCost_ testTQueue , CR.bgroup "TChan" $ testcases $ testCost_ testTChan ] where configCost = CR.defaultConfig { CR.reportFile = Just "report_cost.html" } configSpeed = CR.defaultConfig { CR.reportFile = Just "report_speed.html" } testSpeed_ = testSpeed 90000 testCost_ = testCost 20 10 45000 testcases test = [ testcase 1 1 test , testcase 3 1 test , testcase 1 3 test ] testcase wth rth test = CR.bench (show wth ++ "." ++ show rth) $ CR.nfIO $ test wth rth
1,366
main :: IO () main = do CR.defaultMainWith configSpeed [ CR.bgroup "KazuraQueue" $ testcases $ testSpeed_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testSpeed_ testUChan , CR.bgroup "Chan" $ testcases $ testSpeed_ testChan , CR.bgroup "TQueue" $ testcases $ testSpeed_ testTQueue , CR.bgroup "TChan" $ testcases $ testSpeed_ testTChan ] CR.defaultMainWith configCost [ CR.bgroup "KazuraQueue" $ testcases $ testCost_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testCost_ testUChan , CR.bgroup "Chan" $ testcases $ testCost_ testChan , CR.bgroup "TQueue" $ testcases $ testCost_ testTQueue , CR.bgroup "TChan" $ testcases $ testCost_ testTChan ] where configCost = CR.defaultConfig { CR.reportFile = Just "report_cost.html" } configSpeed = CR.defaultConfig { CR.reportFile = Just "report_speed.html" } testSpeed_ = testSpeed 90000 testCost_ = testCost 20 10 45000 testcases test = [ testcase 1 1 test , testcase 3 1 test , testcase 1 3 test ] testcase wth rth test = CR.bench (show wth ++ "." ++ show rth) $ CR.nfIO $ test wth rth
1,366
main = do CR.defaultMainWith configSpeed [ CR.bgroup "KazuraQueue" $ testcases $ testSpeed_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testSpeed_ testUChan , CR.bgroup "Chan" $ testcases $ testSpeed_ testChan , CR.bgroup "TQueue" $ testcases $ testSpeed_ testTQueue , CR.bgroup "TChan" $ testcases $ testSpeed_ testTChan ] CR.defaultMainWith configCost [ CR.bgroup "KazuraQueue" $ testcases $ testCost_ testKZRQueue -- , CR.bgroup "UnagiChan" $ testcases $ testCost_ testUChan , CR.bgroup "Chan" $ testcases $ testCost_ testChan , CR.bgroup "TQueue" $ testcases $ testCost_ testTQueue , CR.bgroup "TChan" $ testcases $ testCost_ testTChan ] where configCost = CR.defaultConfig { CR.reportFile = Just "report_cost.html" } configSpeed = CR.defaultConfig { CR.reportFile = Just "report_speed.html" } testSpeed_ = testSpeed 90000 testCost_ = testCost 20 10 45000 testcases test = [ testcase 1 1 test , testcase 3 1 test , testcase 1 3 test ] testcase wth rth test = CR.bench (show wth ++ "." ++ show rth) $ CR.nfIO $ test wth rth
1,352
false
true
8
12
477
375
168
207
null
null
dysinger/amazonka
amazonka-ec2/gen/Network/AWS/EC2/Types.hs
mpl-2.0
-- | The AWS account ID of the Amazon EBS snapshot owner. sOwnerId :: Lens' Snapshot Text sOwnerId = lens _sOwnerId (\s a -> s { _sOwnerId = a })
145
sOwnerId :: Lens' Snapshot Text sOwnerId = lens _sOwnerId (\s a -> s { _sOwnerId = a })
87
sOwnerId = lens _sOwnerId (\s a -> s { _sOwnerId = a })
55
true
true
0
9
29
40
22
18
null
null
AndrewRademacher/stack
src/Stack/Types/Version.hs
bsd-3-clause
-- | Check if a version is within a version range. withinRange :: Version -> Cabal.VersionRange -> Bool withinRange v r = toCabalVersion v `Cabal.withinRange` r
160
withinRange :: Version -> Cabal.VersionRange -> Bool withinRange v r = toCabalVersion v `Cabal.withinRange` r
109
withinRange v r = toCabalVersion v `Cabal.withinRange` r
56
true
true
0
7
25
38
20
18
null
null
anton-dessiatov/stack
src/Stack/Coverage.hs
bsd-3-clause
readTixOrLog :: HasLogFunc env => Path b File -> RIO env (Maybe Tix) readTixOrLog path = do mtix <- liftIO (readTix (toFilePath path)) `catchAny` \errorCall -> do logError $ "Error while reading tix: " <> T.pack (show errorCall) return Nothing when (isNothing mtix) $ logError $ "Failed to read tix file " <> T.pack (toFilePath path) return mtix -- | Module names which contain '/' have a package name, and so they weren't built into the -- executable.
489
readTixOrLog :: HasLogFunc env => Path b File -> RIO env (Maybe Tix) readTixOrLog path = do mtix <- liftIO (readTix (toFilePath path)) `catchAny` \errorCall -> do logError $ "Error while reading tix: " <> T.pack (show errorCall) return Nothing when (isNothing mtix) $ logError $ "Failed to read tix file " <> T.pack (toFilePath path) return mtix -- | Module names which contain '/' have a package name, and so they weren't built into the -- executable.
489
readTixOrLog path = do mtix <- liftIO (readTix (toFilePath path)) `catchAny` \errorCall -> do logError $ "Error while reading tix: " <> T.pack (show errorCall) return Nothing when (isNothing mtix) $ logError $ "Failed to read tix file " <> T.pack (toFilePath path) return mtix -- | Module names which contain '/' have a package name, and so they weren't built into the -- executable.
420
false
true
0
15
114
145
68
77
null
null
bitemyapp/MiniKanrenT
example.hs
mit
exampleMothers :: IO () exampleMothers = mapM_ print $ nub $ runAll $ do m <- fresh c <- fresh mother m c return m -- Prints out a list of all the fathers
163
exampleMothers :: IO () exampleMothers = mapM_ print $ nub $ runAll $ do m <- fresh c <- fresh mother m c return m -- Prints out a list of all the fathers
163
exampleMothers = mapM_ print $ nub $ runAll $ do m <- fresh c <- fresh mother m c return m -- Prints out a list of all the fathers
139
false
true
0
9
42
66
28
38
null
null
ambiata/tatooine-cli
src/Ambiata/Cli/Incoming.hs
apache-2.0
hashFileOf :: IncomingDir -> IncomingFile -> FilePath hashFileOf dir f = (toWorkingPath dir Hashfiles) </> (T.unpack $ unIncomingFile f)
138
hashFileOf :: IncomingDir -> IncomingFile -> FilePath hashFileOf dir f = (toWorkingPath dir Hashfiles) </> (T.unpack $ unIncomingFile f)
138
hashFileOf dir f = (toWorkingPath dir Hashfiles) </> (T.unpack $ unIncomingFile f)
84
false
true
2
8
20
55
25
30
null
null
opentower/carnap
Carnap-Server/Handler/Info.hs
gpl-3.0
comprehensionTheorem = [st| Show EXAx(F(x)/\G(x)<->X(x)) Show Ax(F(x)/\G(x)<->\y[F(y)/\G(y)](x)) Show F(c)/\G(c)->\y[F(y)/\G(y)](c) F(c)/\G(c):AS \y[F(y)/\G(y)](c):ABS 4 :CD 5 Show \y[F(y)/\G(y)](c)->F(c)/\G(c) \y[F(y)/\G(y)](c):AS F(c)/\G(c):APP 8 :CD 9 F(c)/\G(c)<->\y[F(y)/\G(y)](c):CB 3 7 :UD 11 EXAx(F(x)/\G(x)<->X(x)):EG 2 :DD 13|]
429
comprehensionTheorem = [st| Show EXAx(F(x)/\G(x)<->X(x)) Show Ax(F(x)/\G(x)<->\y[F(y)/\G(y)](x)) Show F(c)/\G(c)->\y[F(y)/\G(y)](c) F(c)/\G(c):AS \y[F(y)/\G(y)](c):ABS 4 :CD 5 Show \y[F(y)/\G(y)](c)->F(c)/\G(c) \y[F(y)/\G(y)](c):AS F(c)/\G(c):APP 8 :CD 9 F(c)/\G(c)<->\y[F(y)/\G(y)](c):CB 3 7 :UD 11 EXAx(F(x)/\G(x)<->X(x)):EG 2 :DD 13|]
429
comprehensionTheorem = [st| Show EXAx(F(x)/\G(x)<->X(x)) Show Ax(F(x)/\G(x)<->\y[F(y)/\G(y)](x)) Show F(c)/\G(c)->\y[F(y)/\G(y)](c) F(c)/\G(c):AS \y[F(y)/\G(y)](c):ABS 4 :CD 5 Show \y[F(y)/\G(y)](c)->F(c)/\G(c) \y[F(y)/\G(y)](c):AS F(c)/\G(c):APP 8 :CD 9 F(c)/\G(c)<->\y[F(y)/\G(y)](c):CB 3 7 :UD 11 EXAx(F(x)/\G(x)<->X(x)):EG 2 :DD 13|]
429
false
false
0
4
121
10
7
3
null
null
mydaum/cabal
cabal-install/Distribution/Client/SetupWrapper.hs
bsd-3-clause
getExternalSetupMethod :: Verbosity -> SetupScriptOptions -> PackageDescription -> BuildType -> IO (Version, SetupMethod, SetupScriptOptions) getExternalSetupMethod verbosity options pkg bt = do debug verbosity $ "Using external setup method with build-type " ++ show bt debug verbosity $ "Using explicit dependencies: " ++ show (useDependenciesExclusive options) createDirectoryIfMissingVerbose verbosity True setupDir (cabalLibVersion, mCabalLibInstalledPkgId, options') <- cabalLibVersionToUse debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion path <- if useCachedSetupExecutable then getCachedSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId else compileSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId False -- Since useWorkingDir can change the relative path, the path argument must -- be turned into an absolute path. On some systems, runProcess' will take -- path as relative to the new working directory instead of the current -- working directory. path' <- tryCanonicalizePath path -- See 'Note: win32 clean hack' above. #ifdef mingw32_HOST_OS -- setupProgFile may not exist if we're using a cached program setupProgFile' <- canonicalizePathNoThrow setupProgFile let win32CleanHackNeeded = (useWin32CleanHack options) -- Skip when a cached setup script is used. && setupProgFile' `equalFilePath` path' #else let win32CleanHackNeeded = False #endif let options'' = options' { useWin32CleanHack = win32CleanHackNeeded } return (cabalLibVersion, ExternalMethod path', options'') where setupDir = workingDir options </> useDistPref options </> "setup" setupVersionFile = setupDir </> "setup" <.> "version" setupHs = setupDir </> "setup" <.> "hs" setupProgFile = setupDir </> "setup" <.> exeExtension platform = fromMaybe buildPlatform (usePlatform options) useCachedSetupExecutable = (bt == Simple || bt == Configure || bt == Make) maybeGetInstalledPackages :: SetupScriptOptions -> Compiler -> ProgramDb -> IO InstalledPackageIndex maybeGetInstalledPackages options' comp progdb = case usePackageIndex options' of Just index -> return index Nothing -> getInstalledPackages verbosity comp (usePackageDB options') progdb -- Choose the version of Cabal to use if the setup script has a dependency on -- Cabal, and possibly update the setup script options. The version also -- determines how to filter the flags to Setup. -- -- We first check whether the dependency solver has specified a Cabal version. -- If it has, we use the solver's version without looking at the installed -- package index (See issue #3436). Otherwise, we pick the Cabal version by -- checking 'useCabalSpecVersion', then the saved version, and finally the -- versions available in the index. -- -- The version chosen here must match the one used in 'compileSetupExecutable' -- (See issue #3433). cabalLibVersionToUse :: IO (Version, Maybe ComponentId ,SetupScriptOptions) cabalLibVersionToUse = case find (isCabalPkgId . snd) (useDependencies options) of Just (unitId, pkgId) -> do let version = pkgVersion pkgId updateSetupScript version bt writeSetupVersionFile version return (version, Just unitId, options) Nothing -> case useCabalSpecVersion options of Just version -> do updateSetupScript version bt writeSetupVersionFile version return (version, Nothing, options) Nothing -> do savedVer <- savedVersion case savedVer of Just version | version `withinRange` useCabalVersion options -> do updateSetupScript version bt -- Does the previously compiled setup executable still exist -- and is it up-to date? useExisting <- canUseExistingSetup version if useExisting then return (version, Nothing, options) else installedVersion _ -> installedVersion where -- This check duplicates the checks in 'getCachedSetupExecutable' / -- 'compileSetupExecutable'. Unfortunately, we have to perform it twice -- because the selected Cabal version may change as a result of this -- check. canUseExistingSetup :: Version -> IO Bool canUseExistingSetup version = if useCachedSetupExecutable then do (_, cachedSetupProgFile) <- cachedSetupDirAndProg options version doesFileExist cachedSetupProgFile else (&&) <$> setupProgFile `existsAndIsMoreRecentThan` setupHs <*> setupProgFile `existsAndIsMoreRecentThan` setupVersionFile writeSetupVersionFile :: Version -> IO () writeSetupVersionFile version = writeFile setupVersionFile (show version ++ "\n") installedVersion :: IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedVersion = do (comp, progdb, options') <- configureCompiler options (version, mipkgid, options'') <- installedCabalVersion options' comp progdb updateSetupScript version bt writeSetupVersionFile version return (version, mipkgid, options'') savedVersion :: IO (Maybe Version) savedVersion = do versionString <- readFile setupVersionFile `catchIO` \_ -> return "" case reads versionString of [(version,s)] | all isSpace s -> return (Just version) _ -> return Nothing -- | Update a Setup.hs script, creating it if necessary. updateSetupScript :: Version -> BuildType -> IO () updateSetupScript _ Custom = do useHs <- doesFileExist customSetupHs useLhs <- doesFileExist customSetupLhs unless (useHs || useLhs) $ die' verbosity "Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script." let src = (if useHs then customSetupHs else customSetupLhs) srcNewer <- src `moreRecentFile` setupHs when srcNewer $ if useHs then copyFileVerbose verbosity src setupHs else runSimplePreProcessor ppUnlit src setupHs verbosity where customSetupHs = workingDir options </> "Setup.hs" customSetupLhs = workingDir options </> "Setup.lhs" updateSetupScript cabalLibVersion _ = rewriteFile verbosity setupHs (buildTypeScript cabalLibVersion) buildTypeScript :: Version -> String buildTypeScript cabalLibVersion = case bt of Simple -> "import Distribution.Simple; main = defaultMain\n" Configure -> "import Distribution.Simple; main = defaultMainWithHooks " ++ if cabalLibVersion >= mkVersion [1,3,10] then "autoconfUserHooks\n" else "defaultUserHooks\n" Make -> "import Distribution.Make; main = defaultMain\n" Custom -> error "buildTypeScript Custom" UnknownBuildType _ -> error "buildTypeScript UnknownBuildType" installedCabalVersion :: SetupScriptOptions -> Compiler -> ProgramDb -> IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedCabalVersion options' compiler progdb = do index <- maybeGetInstalledPackages options' compiler progdb let cabalDep = Dependency (mkPackageName "Cabal") (useCabalVersion options') options'' = options' { usePackageIndex = Just index } case PackageIndex.lookupDependency index cabalDep of [] -> die' verbosity $ "The package '" ++ display (packageName pkg) ++ "' requires Cabal library version " ++ display (useCabalVersion options) ++ " but no suitable version is installed." pkgs -> let ipkginfo = head . snd . bestVersion fst $ pkgs in return (packageVersion ipkginfo ,Just . IPI.installedComponentId $ ipkginfo, options'') bestVersion :: (a -> Version) -> [a] -> a bestVersion f = firstMaximumBy (comparing (preference . f)) where -- Like maximumBy, but picks the first maximum element instead of the -- last. In general, we expect the preferred version to go first in the -- list. For the default case, this has the effect of choosing the version -- installed in the user package DB instead of the global one. See #1463. -- -- Note: firstMaximumBy could be written as just -- `maximumBy cmp . reverse`, but the problem is that the behaviour of -- maximumBy is not fully specified in the case when there is not a single -- greatest element. firstMaximumBy :: (a -> a -> Ordering) -> [a] -> a firstMaximumBy _ [] = error "Distribution.Client.firstMaximumBy: empty list" firstMaximumBy cmp xs = foldl1' maxBy xs where maxBy x y = case cmp x y of { GT -> x; EQ -> x; LT -> y; } preference version = (sameVersion, sameMajorVersion ,stableVersion, latestVersion) where sameVersion = version == cabalVersion sameMajorVersion = majorVersion version == majorVersion cabalVersion majorVersion = take 2 . versionNumbers stableVersion = case versionNumbers version of (_:x:_) -> even x _ -> False latestVersion = version configureCompiler :: SetupScriptOptions -> IO (Compiler, ProgramDb, SetupScriptOptions) configureCompiler options' = do (comp, progdb) <- case useCompiler options' of Just comp -> return (comp, useProgramDb options') Nothing -> do (comp, _, progdb) <- configCompilerEx (Just GHC) Nothing Nothing (useProgramDb options') verbosity return (comp, progdb) -- Whenever we need to call configureCompiler, we also need to access the -- package index, so let's cache it in SetupScriptOptions. index <- maybeGetInstalledPackages options' comp progdb return (comp, progdb, options' { useCompiler = Just comp, usePackageIndex = Just index, useProgramDb = progdb }) -- | Path to the setup exe cache directory and path to the cached setup -- executable. cachedSetupDirAndProg :: SetupScriptOptions -> Version -> IO (FilePath, FilePath) cachedSetupDirAndProg options' cabalLibVersion = do cabalDir <- defaultCabalDir let setupCacheDir = cabalDir </> "setup-exe-cache" cachedSetupProgFile = setupCacheDir </> ("setup-" ++ buildTypeString ++ "-" ++ cabalVersionString ++ "-" ++ platformString ++ "-" ++ compilerVersionString) <.> exeExtension return (setupCacheDir, cachedSetupProgFile) where buildTypeString = show bt cabalVersionString = "Cabal-" ++ (display cabalLibVersion) compilerVersionString = display $ maybe buildCompilerId compilerId $ useCompiler options' platformString = display platform -- | Look up the setup executable in the cache; update the cache if the setup -- executable is not found. getCachedSetupExecutable :: SetupScriptOptions -> Version -> Maybe InstalledPackageId -> IO FilePath getCachedSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId = do (setupCacheDir, cachedSetupProgFile) <- cachedSetupDirAndProg options' cabalLibVersion cachedSetupExists <- doesFileExist cachedSetupProgFile if cachedSetupExists then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else criticalSection' $ do -- The cache may have been populated while we were waiting. cachedSetupExists' <- doesFileExist cachedSetupProgFile if cachedSetupExists' then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else do debug verbosity $ "Setup executable not found in the cache." src <- compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId True createDirectoryIfMissingVerbose verbosity True setupCacheDir installExecutableFile verbosity src cachedSetupProgFile -- Do not strip if we're using GHCJS, since the result may be a script when (maybe True ((/=GHCJS).compilerFlavor) $ useCompiler options') $ Strip.stripExe verbosity platform (useProgramDb options') cachedSetupProgFile return cachedSetupProgFile where criticalSection' = maybe id criticalSection $ setupCacheLock options' -- | If the Setup.hs is out of date wrt the executable then recompile it. -- Currently this is GHC/GHCJS only. It should really be generalised. -- compileSetupExecutable :: SetupScriptOptions -> Version -> Maybe ComponentId -> Bool -> IO FilePath compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId forceCompile = do setupHsNewer <- setupHs `moreRecentFile` setupProgFile cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile let outOfDate = setupHsNewer || cabalVersionNewer when (outOfDate || forceCompile) $ do debug verbosity "Setup executable needs to be updated, compiling..." (compiler, progdb, options'') <- configureCompiler options' let cabalPkgid = PackageIdentifier (mkPackageName "Cabal") cabalLibVersion (program, extraOpts) = case compilerFlavor compiler of GHCJS -> (ghcjsProgram, ["-build-runner"]) _ -> (ghcProgram, ["-threaded"]) cabalDep = maybe [] (\ipkgid -> [(ipkgid, cabalPkgid)]) maybeCabalLibInstalledPkgId -- With 'useDependenciesExclusive' we enforce the deps specified, -- so only the given ones can be used. Otherwise we allow the use -- of packages in the ambient environment, and add on a dep on the -- Cabal library (unless 'useDependencies' already contains one). -- -- With 'useVersionMacros' we use a version CPP macros .h file. -- -- Both of these options should be enabled for packages that have -- opted-in and declared a custom-settup stanza. -- selectedDeps | useDependenciesExclusive options' = useDependencies options' | otherwise = useDependencies options' ++ if any (isCabalPkgId . snd) (useDependencies options') then [] else cabalDep addRenaming (ipid, _) = -- Assert 'DefUnitId' invariant (Backpack.DefiniteUnitId (unsafeMkDefUnitId (newSimpleUnitId ipid)), defaultRenaming) cppMacrosFile = setupDir </> "setup_macros.h" ghcOptions = mempty { -- Respect -v0, but don't crank up verbosity on GHC if -- Cabal verbosity is requested. For that, use --ghc-option=-v instead! ghcOptVerbosity = Flag (min verbosity normal) , ghcOptMode = Flag GhcModeMake , ghcOptInputFiles = toNubListR [setupHs] , ghcOptOutputFile = Flag setupProgFile , ghcOptObjDir = Flag setupDir , ghcOptHiDir = Flag setupDir , ghcOptSourcePathClear = Flag True , ghcOptSourcePath = case bt of Custom -> toNubListR [workingDir options'] _ -> mempty , ghcOptPackageDBs = usePackageDB options'' , ghcOptHideAllPackages = Flag (useDependenciesExclusive options') , ghcOptCabal = Flag (useDependenciesExclusive options') , ghcOptPackages = toNubListR $ map addRenaming selectedDeps , ghcOptCppIncludes = toNubListR [ cppMacrosFile | useVersionMacros options' ] , ghcOptExtra = toNubListR extraOpts } let ghcCmdLine = renderGhcOptions compiler platform ghcOptions when (useVersionMacros options') $ rewriteFile verbosity cppMacrosFile (generatePackageVersionMacros (map snd selectedDeps)) case useLoggingHandle options of Nothing -> runDbProgram verbosity program progdb ghcCmdLine -- If build logging is enabled, redirect compiler output to the log file. (Just logHandle) -> do output <- getDbProgramOutput verbosity program progdb ghcCmdLine hPutStr logHandle output return setupProgFile
17,663
getExternalSetupMethod :: Verbosity -> SetupScriptOptions -> PackageDescription -> BuildType -> IO (Version, SetupMethod, SetupScriptOptions) getExternalSetupMethod verbosity options pkg bt = do debug verbosity $ "Using external setup method with build-type " ++ show bt debug verbosity $ "Using explicit dependencies: " ++ show (useDependenciesExclusive options) createDirectoryIfMissingVerbose verbosity True setupDir (cabalLibVersion, mCabalLibInstalledPkgId, options') <- cabalLibVersionToUse debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion path <- if useCachedSetupExecutable then getCachedSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId else compileSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId False -- Since useWorkingDir can change the relative path, the path argument must -- be turned into an absolute path. On some systems, runProcess' will take -- path as relative to the new working directory instead of the current -- working directory. path' <- tryCanonicalizePath path -- See 'Note: win32 clean hack' above. #ifdef mingw32_HOST_OS -- setupProgFile may not exist if we're using a cached program setupProgFile' <- canonicalizePathNoThrow setupProgFile let win32CleanHackNeeded = (useWin32CleanHack options) -- Skip when a cached setup script is used. && setupProgFile' `equalFilePath` path' #else let win32CleanHackNeeded = False #endif let options'' = options' { useWin32CleanHack = win32CleanHackNeeded } return (cabalLibVersion, ExternalMethod path', options'') where setupDir = workingDir options </> useDistPref options </> "setup" setupVersionFile = setupDir </> "setup" <.> "version" setupHs = setupDir </> "setup" <.> "hs" setupProgFile = setupDir </> "setup" <.> exeExtension platform = fromMaybe buildPlatform (usePlatform options) useCachedSetupExecutable = (bt == Simple || bt == Configure || bt == Make) maybeGetInstalledPackages :: SetupScriptOptions -> Compiler -> ProgramDb -> IO InstalledPackageIndex maybeGetInstalledPackages options' comp progdb = case usePackageIndex options' of Just index -> return index Nothing -> getInstalledPackages verbosity comp (usePackageDB options') progdb -- Choose the version of Cabal to use if the setup script has a dependency on -- Cabal, and possibly update the setup script options. The version also -- determines how to filter the flags to Setup. -- -- We first check whether the dependency solver has specified a Cabal version. -- If it has, we use the solver's version without looking at the installed -- package index (See issue #3436). Otherwise, we pick the Cabal version by -- checking 'useCabalSpecVersion', then the saved version, and finally the -- versions available in the index. -- -- The version chosen here must match the one used in 'compileSetupExecutable' -- (See issue #3433). cabalLibVersionToUse :: IO (Version, Maybe ComponentId ,SetupScriptOptions) cabalLibVersionToUse = case find (isCabalPkgId . snd) (useDependencies options) of Just (unitId, pkgId) -> do let version = pkgVersion pkgId updateSetupScript version bt writeSetupVersionFile version return (version, Just unitId, options) Nothing -> case useCabalSpecVersion options of Just version -> do updateSetupScript version bt writeSetupVersionFile version return (version, Nothing, options) Nothing -> do savedVer <- savedVersion case savedVer of Just version | version `withinRange` useCabalVersion options -> do updateSetupScript version bt -- Does the previously compiled setup executable still exist -- and is it up-to date? useExisting <- canUseExistingSetup version if useExisting then return (version, Nothing, options) else installedVersion _ -> installedVersion where -- This check duplicates the checks in 'getCachedSetupExecutable' / -- 'compileSetupExecutable'. Unfortunately, we have to perform it twice -- because the selected Cabal version may change as a result of this -- check. canUseExistingSetup :: Version -> IO Bool canUseExistingSetup version = if useCachedSetupExecutable then do (_, cachedSetupProgFile) <- cachedSetupDirAndProg options version doesFileExist cachedSetupProgFile else (&&) <$> setupProgFile `existsAndIsMoreRecentThan` setupHs <*> setupProgFile `existsAndIsMoreRecentThan` setupVersionFile writeSetupVersionFile :: Version -> IO () writeSetupVersionFile version = writeFile setupVersionFile (show version ++ "\n") installedVersion :: IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedVersion = do (comp, progdb, options') <- configureCompiler options (version, mipkgid, options'') <- installedCabalVersion options' comp progdb updateSetupScript version bt writeSetupVersionFile version return (version, mipkgid, options'') savedVersion :: IO (Maybe Version) savedVersion = do versionString <- readFile setupVersionFile `catchIO` \_ -> return "" case reads versionString of [(version,s)] | all isSpace s -> return (Just version) _ -> return Nothing -- | Update a Setup.hs script, creating it if necessary. updateSetupScript :: Version -> BuildType -> IO () updateSetupScript _ Custom = do useHs <- doesFileExist customSetupHs useLhs <- doesFileExist customSetupLhs unless (useHs || useLhs) $ die' verbosity "Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script." let src = (if useHs then customSetupHs else customSetupLhs) srcNewer <- src `moreRecentFile` setupHs when srcNewer $ if useHs then copyFileVerbose verbosity src setupHs else runSimplePreProcessor ppUnlit src setupHs verbosity where customSetupHs = workingDir options </> "Setup.hs" customSetupLhs = workingDir options </> "Setup.lhs" updateSetupScript cabalLibVersion _ = rewriteFile verbosity setupHs (buildTypeScript cabalLibVersion) buildTypeScript :: Version -> String buildTypeScript cabalLibVersion = case bt of Simple -> "import Distribution.Simple; main = defaultMain\n" Configure -> "import Distribution.Simple; main = defaultMainWithHooks " ++ if cabalLibVersion >= mkVersion [1,3,10] then "autoconfUserHooks\n" else "defaultUserHooks\n" Make -> "import Distribution.Make; main = defaultMain\n" Custom -> error "buildTypeScript Custom" UnknownBuildType _ -> error "buildTypeScript UnknownBuildType" installedCabalVersion :: SetupScriptOptions -> Compiler -> ProgramDb -> IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedCabalVersion options' compiler progdb = do index <- maybeGetInstalledPackages options' compiler progdb let cabalDep = Dependency (mkPackageName "Cabal") (useCabalVersion options') options'' = options' { usePackageIndex = Just index } case PackageIndex.lookupDependency index cabalDep of [] -> die' verbosity $ "The package '" ++ display (packageName pkg) ++ "' requires Cabal library version " ++ display (useCabalVersion options) ++ " but no suitable version is installed." pkgs -> let ipkginfo = head . snd . bestVersion fst $ pkgs in return (packageVersion ipkginfo ,Just . IPI.installedComponentId $ ipkginfo, options'') bestVersion :: (a -> Version) -> [a] -> a bestVersion f = firstMaximumBy (comparing (preference . f)) where -- Like maximumBy, but picks the first maximum element instead of the -- last. In general, we expect the preferred version to go first in the -- list. For the default case, this has the effect of choosing the version -- installed in the user package DB instead of the global one. See #1463. -- -- Note: firstMaximumBy could be written as just -- `maximumBy cmp . reverse`, but the problem is that the behaviour of -- maximumBy is not fully specified in the case when there is not a single -- greatest element. firstMaximumBy :: (a -> a -> Ordering) -> [a] -> a firstMaximumBy _ [] = error "Distribution.Client.firstMaximumBy: empty list" firstMaximumBy cmp xs = foldl1' maxBy xs where maxBy x y = case cmp x y of { GT -> x; EQ -> x; LT -> y; } preference version = (sameVersion, sameMajorVersion ,stableVersion, latestVersion) where sameVersion = version == cabalVersion sameMajorVersion = majorVersion version == majorVersion cabalVersion majorVersion = take 2 . versionNumbers stableVersion = case versionNumbers version of (_:x:_) -> even x _ -> False latestVersion = version configureCompiler :: SetupScriptOptions -> IO (Compiler, ProgramDb, SetupScriptOptions) configureCompiler options' = do (comp, progdb) <- case useCompiler options' of Just comp -> return (comp, useProgramDb options') Nothing -> do (comp, _, progdb) <- configCompilerEx (Just GHC) Nothing Nothing (useProgramDb options') verbosity return (comp, progdb) -- Whenever we need to call configureCompiler, we also need to access the -- package index, so let's cache it in SetupScriptOptions. index <- maybeGetInstalledPackages options' comp progdb return (comp, progdb, options' { useCompiler = Just comp, usePackageIndex = Just index, useProgramDb = progdb }) -- | Path to the setup exe cache directory and path to the cached setup -- executable. cachedSetupDirAndProg :: SetupScriptOptions -> Version -> IO (FilePath, FilePath) cachedSetupDirAndProg options' cabalLibVersion = do cabalDir <- defaultCabalDir let setupCacheDir = cabalDir </> "setup-exe-cache" cachedSetupProgFile = setupCacheDir </> ("setup-" ++ buildTypeString ++ "-" ++ cabalVersionString ++ "-" ++ platformString ++ "-" ++ compilerVersionString) <.> exeExtension return (setupCacheDir, cachedSetupProgFile) where buildTypeString = show bt cabalVersionString = "Cabal-" ++ (display cabalLibVersion) compilerVersionString = display $ maybe buildCompilerId compilerId $ useCompiler options' platformString = display platform -- | Look up the setup executable in the cache; update the cache if the setup -- executable is not found. getCachedSetupExecutable :: SetupScriptOptions -> Version -> Maybe InstalledPackageId -> IO FilePath getCachedSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId = do (setupCacheDir, cachedSetupProgFile) <- cachedSetupDirAndProg options' cabalLibVersion cachedSetupExists <- doesFileExist cachedSetupProgFile if cachedSetupExists then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else criticalSection' $ do -- The cache may have been populated while we were waiting. cachedSetupExists' <- doesFileExist cachedSetupProgFile if cachedSetupExists' then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else do debug verbosity $ "Setup executable not found in the cache." src <- compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId True createDirectoryIfMissingVerbose verbosity True setupCacheDir installExecutableFile verbosity src cachedSetupProgFile -- Do not strip if we're using GHCJS, since the result may be a script when (maybe True ((/=GHCJS).compilerFlavor) $ useCompiler options') $ Strip.stripExe verbosity platform (useProgramDb options') cachedSetupProgFile return cachedSetupProgFile where criticalSection' = maybe id criticalSection $ setupCacheLock options' -- | If the Setup.hs is out of date wrt the executable then recompile it. -- Currently this is GHC/GHCJS only. It should really be generalised. -- compileSetupExecutable :: SetupScriptOptions -> Version -> Maybe ComponentId -> Bool -> IO FilePath compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId forceCompile = do setupHsNewer <- setupHs `moreRecentFile` setupProgFile cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile let outOfDate = setupHsNewer || cabalVersionNewer when (outOfDate || forceCompile) $ do debug verbosity "Setup executable needs to be updated, compiling..." (compiler, progdb, options'') <- configureCompiler options' let cabalPkgid = PackageIdentifier (mkPackageName "Cabal") cabalLibVersion (program, extraOpts) = case compilerFlavor compiler of GHCJS -> (ghcjsProgram, ["-build-runner"]) _ -> (ghcProgram, ["-threaded"]) cabalDep = maybe [] (\ipkgid -> [(ipkgid, cabalPkgid)]) maybeCabalLibInstalledPkgId -- With 'useDependenciesExclusive' we enforce the deps specified, -- so only the given ones can be used. Otherwise we allow the use -- of packages in the ambient environment, and add on a dep on the -- Cabal library (unless 'useDependencies' already contains one). -- -- With 'useVersionMacros' we use a version CPP macros .h file. -- -- Both of these options should be enabled for packages that have -- opted-in and declared a custom-settup stanza. -- selectedDeps | useDependenciesExclusive options' = useDependencies options' | otherwise = useDependencies options' ++ if any (isCabalPkgId . snd) (useDependencies options') then [] else cabalDep addRenaming (ipid, _) = -- Assert 'DefUnitId' invariant (Backpack.DefiniteUnitId (unsafeMkDefUnitId (newSimpleUnitId ipid)), defaultRenaming) cppMacrosFile = setupDir </> "setup_macros.h" ghcOptions = mempty { -- Respect -v0, but don't crank up verbosity on GHC if -- Cabal verbosity is requested. For that, use --ghc-option=-v instead! ghcOptVerbosity = Flag (min verbosity normal) , ghcOptMode = Flag GhcModeMake , ghcOptInputFiles = toNubListR [setupHs] , ghcOptOutputFile = Flag setupProgFile , ghcOptObjDir = Flag setupDir , ghcOptHiDir = Flag setupDir , ghcOptSourcePathClear = Flag True , ghcOptSourcePath = case bt of Custom -> toNubListR [workingDir options'] _ -> mempty , ghcOptPackageDBs = usePackageDB options'' , ghcOptHideAllPackages = Flag (useDependenciesExclusive options') , ghcOptCabal = Flag (useDependenciesExclusive options') , ghcOptPackages = toNubListR $ map addRenaming selectedDeps , ghcOptCppIncludes = toNubListR [ cppMacrosFile | useVersionMacros options' ] , ghcOptExtra = toNubListR extraOpts } let ghcCmdLine = renderGhcOptions compiler platform ghcOptions when (useVersionMacros options') $ rewriteFile verbosity cppMacrosFile (generatePackageVersionMacros (map snd selectedDeps)) case useLoggingHandle options of Nothing -> runDbProgram verbosity program progdb ghcCmdLine -- If build logging is enabled, redirect compiler output to the log file. (Just logHandle) -> do output <- getDbProgramOutput verbosity program progdb ghcCmdLine hPutStr logHandle output return setupProgFile
17,663
getExternalSetupMethod verbosity options pkg bt = do debug verbosity $ "Using external setup method with build-type " ++ show bt debug verbosity $ "Using explicit dependencies: " ++ show (useDependenciesExclusive options) createDirectoryIfMissingVerbose verbosity True setupDir (cabalLibVersion, mCabalLibInstalledPkgId, options') <- cabalLibVersionToUse debug verbosity $ "Using Cabal library version " ++ display cabalLibVersion path <- if useCachedSetupExecutable then getCachedSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId else compileSetupExecutable options' cabalLibVersion mCabalLibInstalledPkgId False -- Since useWorkingDir can change the relative path, the path argument must -- be turned into an absolute path. On some systems, runProcess' will take -- path as relative to the new working directory instead of the current -- working directory. path' <- tryCanonicalizePath path -- See 'Note: win32 clean hack' above. #ifdef mingw32_HOST_OS -- setupProgFile may not exist if we're using a cached program setupProgFile' <- canonicalizePathNoThrow setupProgFile let win32CleanHackNeeded = (useWin32CleanHack options) -- Skip when a cached setup script is used. && setupProgFile' `equalFilePath` path' #else let win32CleanHackNeeded = False #endif let options'' = options' { useWin32CleanHack = win32CleanHackNeeded } return (cabalLibVersion, ExternalMethod path', options'') where setupDir = workingDir options </> useDistPref options </> "setup" setupVersionFile = setupDir </> "setup" <.> "version" setupHs = setupDir </> "setup" <.> "hs" setupProgFile = setupDir </> "setup" <.> exeExtension platform = fromMaybe buildPlatform (usePlatform options) useCachedSetupExecutable = (bt == Simple || bt == Configure || bt == Make) maybeGetInstalledPackages :: SetupScriptOptions -> Compiler -> ProgramDb -> IO InstalledPackageIndex maybeGetInstalledPackages options' comp progdb = case usePackageIndex options' of Just index -> return index Nothing -> getInstalledPackages verbosity comp (usePackageDB options') progdb -- Choose the version of Cabal to use if the setup script has a dependency on -- Cabal, and possibly update the setup script options. The version also -- determines how to filter the flags to Setup. -- -- We first check whether the dependency solver has specified a Cabal version. -- If it has, we use the solver's version without looking at the installed -- package index (See issue #3436). Otherwise, we pick the Cabal version by -- checking 'useCabalSpecVersion', then the saved version, and finally the -- versions available in the index. -- -- The version chosen here must match the one used in 'compileSetupExecutable' -- (See issue #3433). cabalLibVersionToUse :: IO (Version, Maybe ComponentId ,SetupScriptOptions) cabalLibVersionToUse = case find (isCabalPkgId . snd) (useDependencies options) of Just (unitId, pkgId) -> do let version = pkgVersion pkgId updateSetupScript version bt writeSetupVersionFile version return (version, Just unitId, options) Nothing -> case useCabalSpecVersion options of Just version -> do updateSetupScript version bt writeSetupVersionFile version return (version, Nothing, options) Nothing -> do savedVer <- savedVersion case savedVer of Just version | version `withinRange` useCabalVersion options -> do updateSetupScript version bt -- Does the previously compiled setup executable still exist -- and is it up-to date? useExisting <- canUseExistingSetup version if useExisting then return (version, Nothing, options) else installedVersion _ -> installedVersion where -- This check duplicates the checks in 'getCachedSetupExecutable' / -- 'compileSetupExecutable'. Unfortunately, we have to perform it twice -- because the selected Cabal version may change as a result of this -- check. canUseExistingSetup :: Version -> IO Bool canUseExistingSetup version = if useCachedSetupExecutable then do (_, cachedSetupProgFile) <- cachedSetupDirAndProg options version doesFileExist cachedSetupProgFile else (&&) <$> setupProgFile `existsAndIsMoreRecentThan` setupHs <*> setupProgFile `existsAndIsMoreRecentThan` setupVersionFile writeSetupVersionFile :: Version -> IO () writeSetupVersionFile version = writeFile setupVersionFile (show version ++ "\n") installedVersion :: IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedVersion = do (comp, progdb, options') <- configureCompiler options (version, mipkgid, options'') <- installedCabalVersion options' comp progdb updateSetupScript version bt writeSetupVersionFile version return (version, mipkgid, options'') savedVersion :: IO (Maybe Version) savedVersion = do versionString <- readFile setupVersionFile `catchIO` \_ -> return "" case reads versionString of [(version,s)] | all isSpace s -> return (Just version) _ -> return Nothing -- | Update a Setup.hs script, creating it if necessary. updateSetupScript :: Version -> BuildType -> IO () updateSetupScript _ Custom = do useHs <- doesFileExist customSetupHs useLhs <- doesFileExist customSetupLhs unless (useHs || useLhs) $ die' verbosity "Using 'build-type: Custom' but there is no Setup.hs or Setup.lhs script." let src = (if useHs then customSetupHs else customSetupLhs) srcNewer <- src `moreRecentFile` setupHs when srcNewer $ if useHs then copyFileVerbose verbosity src setupHs else runSimplePreProcessor ppUnlit src setupHs verbosity where customSetupHs = workingDir options </> "Setup.hs" customSetupLhs = workingDir options </> "Setup.lhs" updateSetupScript cabalLibVersion _ = rewriteFile verbosity setupHs (buildTypeScript cabalLibVersion) buildTypeScript :: Version -> String buildTypeScript cabalLibVersion = case bt of Simple -> "import Distribution.Simple; main = defaultMain\n" Configure -> "import Distribution.Simple; main = defaultMainWithHooks " ++ if cabalLibVersion >= mkVersion [1,3,10] then "autoconfUserHooks\n" else "defaultUserHooks\n" Make -> "import Distribution.Make; main = defaultMain\n" Custom -> error "buildTypeScript Custom" UnknownBuildType _ -> error "buildTypeScript UnknownBuildType" installedCabalVersion :: SetupScriptOptions -> Compiler -> ProgramDb -> IO (Version, Maybe InstalledPackageId ,SetupScriptOptions) installedCabalVersion options' compiler progdb = do index <- maybeGetInstalledPackages options' compiler progdb let cabalDep = Dependency (mkPackageName "Cabal") (useCabalVersion options') options'' = options' { usePackageIndex = Just index } case PackageIndex.lookupDependency index cabalDep of [] -> die' verbosity $ "The package '" ++ display (packageName pkg) ++ "' requires Cabal library version " ++ display (useCabalVersion options) ++ " but no suitable version is installed." pkgs -> let ipkginfo = head . snd . bestVersion fst $ pkgs in return (packageVersion ipkginfo ,Just . IPI.installedComponentId $ ipkginfo, options'') bestVersion :: (a -> Version) -> [a] -> a bestVersion f = firstMaximumBy (comparing (preference . f)) where -- Like maximumBy, but picks the first maximum element instead of the -- last. In general, we expect the preferred version to go first in the -- list. For the default case, this has the effect of choosing the version -- installed in the user package DB instead of the global one. See #1463. -- -- Note: firstMaximumBy could be written as just -- `maximumBy cmp . reverse`, but the problem is that the behaviour of -- maximumBy is not fully specified in the case when there is not a single -- greatest element. firstMaximumBy :: (a -> a -> Ordering) -> [a] -> a firstMaximumBy _ [] = error "Distribution.Client.firstMaximumBy: empty list" firstMaximumBy cmp xs = foldl1' maxBy xs where maxBy x y = case cmp x y of { GT -> x; EQ -> x; LT -> y; } preference version = (sameVersion, sameMajorVersion ,stableVersion, latestVersion) where sameVersion = version == cabalVersion sameMajorVersion = majorVersion version == majorVersion cabalVersion majorVersion = take 2 . versionNumbers stableVersion = case versionNumbers version of (_:x:_) -> even x _ -> False latestVersion = version configureCompiler :: SetupScriptOptions -> IO (Compiler, ProgramDb, SetupScriptOptions) configureCompiler options' = do (comp, progdb) <- case useCompiler options' of Just comp -> return (comp, useProgramDb options') Nothing -> do (comp, _, progdb) <- configCompilerEx (Just GHC) Nothing Nothing (useProgramDb options') verbosity return (comp, progdb) -- Whenever we need to call configureCompiler, we also need to access the -- package index, so let's cache it in SetupScriptOptions. index <- maybeGetInstalledPackages options' comp progdb return (comp, progdb, options' { useCompiler = Just comp, usePackageIndex = Just index, useProgramDb = progdb }) -- | Path to the setup exe cache directory and path to the cached setup -- executable. cachedSetupDirAndProg :: SetupScriptOptions -> Version -> IO (FilePath, FilePath) cachedSetupDirAndProg options' cabalLibVersion = do cabalDir <- defaultCabalDir let setupCacheDir = cabalDir </> "setup-exe-cache" cachedSetupProgFile = setupCacheDir </> ("setup-" ++ buildTypeString ++ "-" ++ cabalVersionString ++ "-" ++ platformString ++ "-" ++ compilerVersionString) <.> exeExtension return (setupCacheDir, cachedSetupProgFile) where buildTypeString = show bt cabalVersionString = "Cabal-" ++ (display cabalLibVersion) compilerVersionString = display $ maybe buildCompilerId compilerId $ useCompiler options' platformString = display platform -- | Look up the setup executable in the cache; update the cache if the setup -- executable is not found. getCachedSetupExecutable :: SetupScriptOptions -> Version -> Maybe InstalledPackageId -> IO FilePath getCachedSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId = do (setupCacheDir, cachedSetupProgFile) <- cachedSetupDirAndProg options' cabalLibVersion cachedSetupExists <- doesFileExist cachedSetupProgFile if cachedSetupExists then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else criticalSection' $ do -- The cache may have been populated while we were waiting. cachedSetupExists' <- doesFileExist cachedSetupProgFile if cachedSetupExists' then debug verbosity $ "Found cached setup executable: " ++ cachedSetupProgFile else do debug verbosity $ "Setup executable not found in the cache." src <- compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId True createDirectoryIfMissingVerbose verbosity True setupCacheDir installExecutableFile verbosity src cachedSetupProgFile -- Do not strip if we're using GHCJS, since the result may be a script when (maybe True ((/=GHCJS).compilerFlavor) $ useCompiler options') $ Strip.stripExe verbosity platform (useProgramDb options') cachedSetupProgFile return cachedSetupProgFile where criticalSection' = maybe id criticalSection $ setupCacheLock options' -- | If the Setup.hs is out of date wrt the executable then recompile it. -- Currently this is GHC/GHCJS only. It should really be generalised. -- compileSetupExecutable :: SetupScriptOptions -> Version -> Maybe ComponentId -> Bool -> IO FilePath compileSetupExecutable options' cabalLibVersion maybeCabalLibInstalledPkgId forceCompile = do setupHsNewer <- setupHs `moreRecentFile` setupProgFile cabalVersionNewer <- setupVersionFile `moreRecentFile` setupProgFile let outOfDate = setupHsNewer || cabalVersionNewer when (outOfDate || forceCompile) $ do debug verbosity "Setup executable needs to be updated, compiling..." (compiler, progdb, options'') <- configureCompiler options' let cabalPkgid = PackageIdentifier (mkPackageName "Cabal") cabalLibVersion (program, extraOpts) = case compilerFlavor compiler of GHCJS -> (ghcjsProgram, ["-build-runner"]) _ -> (ghcProgram, ["-threaded"]) cabalDep = maybe [] (\ipkgid -> [(ipkgid, cabalPkgid)]) maybeCabalLibInstalledPkgId -- With 'useDependenciesExclusive' we enforce the deps specified, -- so only the given ones can be used. Otherwise we allow the use -- of packages in the ambient environment, and add on a dep on the -- Cabal library (unless 'useDependencies' already contains one). -- -- With 'useVersionMacros' we use a version CPP macros .h file. -- -- Both of these options should be enabled for packages that have -- opted-in and declared a custom-settup stanza. -- selectedDeps | useDependenciesExclusive options' = useDependencies options' | otherwise = useDependencies options' ++ if any (isCabalPkgId . snd) (useDependencies options') then [] else cabalDep addRenaming (ipid, _) = -- Assert 'DefUnitId' invariant (Backpack.DefiniteUnitId (unsafeMkDefUnitId (newSimpleUnitId ipid)), defaultRenaming) cppMacrosFile = setupDir </> "setup_macros.h" ghcOptions = mempty { -- Respect -v0, but don't crank up verbosity on GHC if -- Cabal verbosity is requested. For that, use --ghc-option=-v instead! ghcOptVerbosity = Flag (min verbosity normal) , ghcOptMode = Flag GhcModeMake , ghcOptInputFiles = toNubListR [setupHs] , ghcOptOutputFile = Flag setupProgFile , ghcOptObjDir = Flag setupDir , ghcOptHiDir = Flag setupDir , ghcOptSourcePathClear = Flag True , ghcOptSourcePath = case bt of Custom -> toNubListR [workingDir options'] _ -> mempty , ghcOptPackageDBs = usePackageDB options'' , ghcOptHideAllPackages = Flag (useDependenciesExclusive options') , ghcOptCabal = Flag (useDependenciesExclusive options') , ghcOptPackages = toNubListR $ map addRenaming selectedDeps , ghcOptCppIncludes = toNubListR [ cppMacrosFile | useVersionMacros options' ] , ghcOptExtra = toNubListR extraOpts } let ghcCmdLine = renderGhcOptions compiler platform ghcOptions when (useVersionMacros options') $ rewriteFile verbosity cppMacrosFile (generatePackageVersionMacros (map snd selectedDeps)) case useLoggingHandle options of Nothing -> runDbProgram verbosity program progdb ghcCmdLine -- If build logging is enabled, redirect compiler output to the log file. (Just logHandle) -> do output <- getDbProgramOutput verbosity program progdb ghcCmdLine hPutStr logHandle output return setupProgFile
17,517
false
true
31
21
5,488
3,150
1,545
1,605
null
null
nevrenato/Hets_Fork
Taxonomy/OntoParser.hs
gpl-2.0
nameDeflOpt :: GenParser Char st (String, String, Maybe String) nameDeflOpt = do (s1, s2) <- nameDefl s3 <- option "" $ braced idParser return (s1, s2, if null s3 then Nothing else Just s3)
195
nameDeflOpt :: GenParser Char st (String, String, Maybe String) nameDeflOpt = do (s1, s2) <- nameDefl s3 <- option "" $ braced idParser return (s1, s2, if null s3 then Nothing else Just s3)
195
nameDeflOpt = do (s1, s2) <- nameDefl s3 <- option "" $ braced idParser return (s1, s2, if null s3 then Nothing else Just s3)
131
false
true
2
11
39
98
45
53
null
null
yi-editor/yi
yi-dynamic-configuration/src/Yi/Main.hs
gpl-2.0
-- | List of editors for which we provide an emulation. editors :: [(String,Config -> Config)] editors = []
107
editors :: [(String,Config -> Config)] editors = []
51
editors = []
12
true
true
0
9
18
34
17
17
null
null
yliu120/K3
src/Language/K3/Core/Declaration.hs
apache-2.0
isAnyDInferredEffectAnn :: Annotation Declaration -> Bool isAnyDInferredEffectAnn a = isDInferredProvenance a || isDInferredEffect a
132
isAnyDInferredEffectAnn :: Annotation Declaration -> Bool isAnyDInferredEffectAnn a = isDInferredProvenance a || isDInferredEffect a
132
isAnyDInferredEffectAnn a = isDInferredProvenance a || isDInferredEffect a
74
false
true
0
7
13
36
15
21
null
null
snoyberg/ghc
compiler/llvmGen/Llvm/PpLlvm.hs
bsd-3-clause
ppMetaStatement :: [MetaAnnot] -> LlvmStatement -> SDoc ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
125
ppMetaStatement :: [MetaAnnot] -> LlvmStatement -> SDoc ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
125
ppMetaStatement meta stmt = ppLlvmStatement stmt <> ppMetaAnnots meta
69
false
true
0
6
15
37
18
19
null
null
garetxe/cabal
cabal-install/Distribution/Client/Sandbox.hs
bsd-3-clause
getSandboxConfigFilePath :: GlobalFlags -> IO FilePath getSandboxConfigFilePath globalFlags = do let sandboxConfigFileFlag = globalSandboxConfigFile globalFlags case sandboxConfigFileFlag of NoFlag -> do pkgEnvDir <- getCurrentDirectory return (pkgEnvDir </> sandboxPackageEnvironmentFile) Flag path -> return path -- | Load the @cabal.sandbox.config@ file (and possibly the optional -- @cabal.config@). In addition to a @PackageEnvironment@, also return a -- canonical path to the sandbox. Exit with error if the sandbox directory or -- the package environment file do not exist.
610
getSandboxConfigFilePath :: GlobalFlags -> IO FilePath getSandboxConfigFilePath globalFlags = do let sandboxConfigFileFlag = globalSandboxConfigFile globalFlags case sandboxConfigFileFlag of NoFlag -> do pkgEnvDir <- getCurrentDirectory return (pkgEnvDir </> sandboxPackageEnvironmentFile) Flag path -> return path -- | Load the @cabal.sandbox.config@ file (and possibly the optional -- @cabal.config@). In addition to a @PackageEnvironment@, also return a -- canonical path to the sandbox. Exit with error if the sandbox directory or -- the package environment file do not exist.
610
getSandboxConfigFilePath globalFlags = do let sandboxConfigFileFlag = globalSandboxConfigFile globalFlags case sandboxConfigFileFlag of NoFlag -> do pkgEnvDir <- getCurrentDirectory return (pkgEnvDir </> sandboxPackageEnvironmentFile) Flag path -> return path -- | Load the @cabal.sandbox.config@ file (and possibly the optional -- @cabal.config@). In addition to a @PackageEnvironment@, also return a -- canonical path to the sandbox. Exit with error if the sandbox directory or -- the package environment file do not exist.
555
false
true
0
14
104
82
39
43
null
null
jleahred/katas
concurrency/haskell3/app/Main.hs
gpl-3.0
main :: IO () main = do let (a, b) = paral2 a b
60
main :: IO () main = do let (a, b) = paral2 a b
60
main = do let (a, b) = paral2 a b
46
false
true
0
10
26
38
18
20
null
null
blitzcode/rust-exp
hs-src/GLHelpers.hs
mit
disableVAOAndShaders :: IO () disableVAOAndShaders = do GL.bindVertexArrayObject GL.$= Nothing GL.currentProgram GL.$= Nothing
141
disableVAOAndShaders :: IO () disableVAOAndShaders = do GL.bindVertexArrayObject GL.$= Nothing GL.currentProgram GL.$= Nothing
141
disableVAOAndShaders = do GL.bindVertexArrayObject GL.$= Nothing GL.currentProgram GL.$= Nothing
111
false
true
0
8
27
38
18
20
null
null
michalrus/kornel
src/Kornel/Common.hs
apache-2.0
decodeHtmlEntities :: Text -> Text decodeHtmlEntities = TL.toStrict . TLB.toLazyText . htmlEncodedText
102
decodeHtmlEntities :: Text -> Text decodeHtmlEntities = TL.toStrict . TLB.toLazyText . htmlEncodedText
102
decodeHtmlEntities = TL.toStrict . TLB.toLazyText . htmlEncodedText
67
false
true
0
7
11
27
14
13
null
null
chreekat/yesod
yesod-core/Yesod/Request.hs
bsd-2-clause
-- | Lookup for GET parameters. lookupGetParams :: Text -> GHandler s m [Text] lookupGetParams pn = do rr <- getRequest return $ lookup' pn $ reqGetParams rr -- | Lookup for GET parameters.
198
lookupGetParams :: Text -> GHandler s m [Text] lookupGetParams pn = do rr <- getRequest return $ lookup' pn $ reqGetParams rr -- | Lookup for GET parameters.
166
lookupGetParams pn = do rr <- getRequest return $ lookup' pn $ reqGetParams rr -- | Lookup for GET parameters.
119
true
true
0
10
42
58
27
31
null
null
sashabu/libcspm
src/CSPM/Evaluator/PatBind.hs
bsd-3-clause
bindAll :: [TCPat] -> AnalyserMonad ([Value] -> Maybe [(Name, Value)]) bindAll ps = let accumulate [] [] bs = Just bs accumulate (p:ps) (x:xs) bs = case p x of Just bs' -> accumulate ps xs (bs' ++ bs) Nothing -> Nothing in do binders <- mapM bind ps return $! \vs -> accumulate binders vs []
375
bindAll :: [TCPat] -> AnalyserMonad ([Value] -> Maybe [(Name, Value)]) bindAll ps = let accumulate [] [] bs = Just bs accumulate (p:ps) (x:xs) bs = case p x of Just bs' -> accumulate ps xs (bs' ++ bs) Nothing -> Nothing in do binders <- mapM bind ps return $! \vs -> accumulate binders vs []
375
bindAll ps = let accumulate [] [] bs = Just bs accumulate (p:ps) (x:xs) bs = case p x of Just bs' -> accumulate ps xs (bs' ++ bs) Nothing -> Nothing in do binders <- mapM bind ps return $! \vs -> accumulate binders vs []
304
false
true
0
14
140
166
82
84
null
null
nfjinjing/bench-euler
src/BenchEuler.hs
bsd-3-clause
main = bench 1 euler
20
main = bench 1 euler
20
main = bench 1 euler
20
false
false
1
5
4
16
5
11
null
null
GaloisInc/saw-script
heapster-saw/src/Verifier/SAW/Heapster/archival/Parser.hs
bsd-3-clause
parseExpr env tp@(StructRepr fld_tps) = spaces >> ((string "struct" >> parseInParens (PExpr_Struct fld_tps <$> parseStructFields env fld_tps)) <|> (PExpr_Var <$> parseVarOfType env tp))
196
parseExpr env tp@(StructRepr fld_tps) = spaces >> ((string "struct" >> parseInParens (PExpr_Struct fld_tps <$> parseStructFields env fld_tps)) <|> (PExpr_Var <$> parseVarOfType env tp))
196
parseExpr env tp@(StructRepr fld_tps) = spaces >> ((string "struct" >> parseInParens (PExpr_Struct fld_tps <$> parseStructFields env fld_tps)) <|> (PExpr_Var <$> parseVarOfType env tp))
196
false
false
3
13
33
79
35
44
null
null
peterokagey/haskellOEIS
src/Poset/A334144.hs
apache-2.0
a334144 :: Integer -> Int a334144 = maximum . map Set.size . wichitaRanks
73
a334144 :: Integer -> Int a334144 = maximum . map Set.size . wichitaRanks
73
a334144 = maximum . map Set.size . wichitaRanks
47
false
true
0
8
12
35
15
20
null
null
christiaanb/Idris-dev
src/Idris/DSL.hs
bsd-3-clause
expandDo dsl (PGoal fc r n sc) = PGoal fc (expandDo dsl r) n (expandDo dsl sc)
82
expandDo dsl (PGoal fc r n sc) = PGoal fc (expandDo dsl r) n (expandDo dsl sc)
82
expandDo dsl (PGoal fc r n sc) = PGoal fc (expandDo dsl r) n (expandDo dsl sc)
82
false
false
0
6
20
53
23
30
null
null
ivanmoore/seedy
lib/Pelias.hs
gpl-3.0
tokeniseChars' _ acc [] = ([], acc)
52
tokeniseChars' _ acc [] = ([], acc)
52
tokeniseChars' _ acc [] = ([], acc)
52
false
false
1
7
23
27
12
15
null
null
phischu/fragnix
tests/packages/scotty/Network.Wai.Handler.Warp.HTTP2.Types.hs
bsd-3-clause
outputMaybeTBQueue :: Output -> Maybe (TBQueue Sequence) outputMaybeTBQueue (Output _ (RspnStreaming _ _ tbq) _ _ _ _) = Just tbq
129
outputMaybeTBQueue :: Output -> Maybe (TBQueue Sequence) outputMaybeTBQueue (Output _ (RspnStreaming _ _ tbq) _ _ _ _) = Just tbq
129
outputMaybeTBQueue (Output _ (RspnStreaming _ _ tbq) _ _ _ _) = Just tbq
72
false
true
0
8
20
60
28
32
null
null
piyush-kurur/shakespeare
hamlet/Text/Hamlet/Parse.hs
bsd-2-clause
compressDoc (DocCase d cs:rest) = DocCase d (map (second compressDoc) cs) : compressDoc rest
96
compressDoc (DocCase d cs:rest) = DocCase d (map (second compressDoc) cs) : compressDoc rest
96
compressDoc (DocCase d cs:rest) = DocCase d (map (second compressDoc) cs) : compressDoc rest
96
false
false
0
10
17
47
22
25
null
null
input-output-hk/cardano-sl
lib/bench/Bench/Pos/Criterion/FollowTheSatoshiBench.hs
apache-2.0
-- [CSL-192]: make a trick and use special unsafe arbitrary instances -- for generation of such things arbitraryUtxoOfSize :: UtxoSize -> Gen [(StakeholderId, Coin)] arbitraryUtxoOfSize n = take n <$> infiniteListOf arbitraryUnsafe
231
arbitraryUtxoOfSize :: UtxoSize -> Gen [(StakeholderId, Coin)] arbitraryUtxoOfSize n = take n <$> infiniteListOf arbitraryUnsafe
128
arbitraryUtxoOfSize n = take n <$> infiniteListOf arbitraryUnsafe
65
true
true
0
8
31
42
22
20
null
null
jcristovao/persistent
persistent-mongoDB/Database/Persist/MongoDB.hs
mit
createPipe :: HostName -> PortID -> IO DB.Pipe createPipe hostname port = DB.connect (DB.Host hostname port)
108
createPipe :: HostName -> PortID -> IO DB.Pipe createPipe hostname port = DB.connect (DB.Host hostname port)
108
createPipe hostname port = DB.connect (DB.Host hostname port)
61
false
true
0
9
15
48
22
26
null
null
gdetrez/haskell-wot
tests/Codec/Archive/ArSpec.hs
gpl-3.0
spec :: Spec spec = do describe "magitAsciiStr" $ do it "succeed with the correct string" $ do let myData = "abc" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Right ("", 3, ()) it "fails if the input is too short" $ do let myData = "a" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left (myData, 0, "demandInput: not enough bytes") it "fails if the input is not the right string" $ do let myData = "cba" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left ("cba", 0, "Invalid magic ASCII string") describe "getArName" $ do it "getArName returns the name of the file, stripped of excessive whitespaces" $ do let myData = "MYNAME " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") it "getArName strips the / at the end of the name (GNU)" $ do let myData = "MYNAME/ " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") describe "getAsciiInt" $ do it "getAsciiInt reads an int" $ do let myData = "1234" runGetOrFail (getAsciiInt 4) myData `shouldBe` Right ("",4, 1234) describe "getEntry" $ do it "reads a simple small entry" $ do let myData = pad "MYNAME" 16 <> pad "12345" 12 <> pad "0" 6 <> pad "0" 6 <> pad "666" 8 <> pad "4" 10 <> "`\LF" <> "abcd" runGet getEntry myData `shouldBe` ("MYNAME", 12345, 0, 0, 666, "abcd") describe "getContent" $ do it "reads a simple content" $ do let myData = pad "8" 10 <> "`\LF" <> "abcdefgh" runGet getContent myData `shouldBe` "abcdefgh" describe "test utils" $ do describe "pad" $ do it "leave the input inchanged if no padding is required" $ pad "abc" 0 `shouldBe` "abc" it "add padding if needed" $ pad "abc" 10 `shouldBe` "abc " describe "parse wot file" $ do it "contains the right number of parts" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let result = readAr file length result `shouldBe` 6 it "yields a first part with the correct name" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let (n,_,_,_,_,_) = head $ readAr file n `shouldBe` "README" -- utils
2,342
spec :: Spec spec = do describe "magitAsciiStr" $ do it "succeed with the correct string" $ do let myData = "abc" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Right ("", 3, ()) it "fails if the input is too short" $ do let myData = "a" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left (myData, 0, "demandInput: not enough bytes") it "fails if the input is not the right string" $ do let myData = "cba" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left ("cba", 0, "Invalid magic ASCII string") describe "getArName" $ do it "getArName returns the name of the file, stripped of excessive whitespaces" $ do let myData = "MYNAME " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") it "getArName strips the / at the end of the name (GNU)" $ do let myData = "MYNAME/ " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") describe "getAsciiInt" $ do it "getAsciiInt reads an int" $ do let myData = "1234" runGetOrFail (getAsciiInt 4) myData `shouldBe` Right ("",4, 1234) describe "getEntry" $ do it "reads a simple small entry" $ do let myData = pad "MYNAME" 16 <> pad "12345" 12 <> pad "0" 6 <> pad "0" 6 <> pad "666" 8 <> pad "4" 10 <> "`\LF" <> "abcd" runGet getEntry myData `shouldBe` ("MYNAME", 12345, 0, 0, 666, "abcd") describe "getContent" $ do it "reads a simple content" $ do let myData = pad "8" 10 <> "`\LF" <> "abcdefgh" runGet getContent myData `shouldBe` "abcdefgh" describe "test utils" $ do describe "pad" $ do it "leave the input inchanged if no padding is required" $ pad "abc" 0 `shouldBe` "abc" it "add padding if needed" $ pad "abc" 10 `shouldBe` "abc " describe "parse wot file" $ do it "contains the right number of parts" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let result = readAr file length result `shouldBe` 6 it "yields a first part with the correct name" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let (n,_,_,_,_,_) = head $ readAr file n `shouldBe` "README" -- utils
2,342
spec = do describe "magitAsciiStr" $ do it "succeed with the correct string" $ do let myData = "abc" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Right ("", 3, ()) it "fails if the input is too short" $ do let myData = "a" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left (myData, 0, "demandInput: not enough bytes") it "fails if the input is not the right string" $ do let myData = "cba" runGetOrFail (magicAsciiStr "abc") myData `shouldBe` Left ("cba", 0, "Invalid magic ASCII string") describe "getArName" $ do it "getArName returns the name of the file, stripped of excessive whitespaces" $ do let myData = "MYNAME " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") it "getArName strips the / at the end of the name (GNU)" $ do let myData = "MYNAME/ " runGetOrFail getArName myData `shouldBe` Right ("", 16, "MYNAME") describe "getAsciiInt" $ do it "getAsciiInt reads an int" $ do let myData = "1234" runGetOrFail (getAsciiInt 4) myData `shouldBe` Right ("",4, 1234) describe "getEntry" $ do it "reads a simple small entry" $ do let myData = pad "MYNAME" 16 <> pad "12345" 12 <> pad "0" 6 <> pad "0" 6 <> pad "666" 8 <> pad "4" 10 <> "`\LF" <> "abcd" runGet getEntry myData `shouldBe` ("MYNAME", 12345, 0, 0, 666, "abcd") describe "getContent" $ do it "reads a simple content" $ do let myData = pad "8" 10 <> "`\LF" <> "abcdefgh" runGet getContent myData `shouldBe` "abcdefgh" describe "test utils" $ do describe "pad" $ do it "leave the input inchanged if no padding is required" $ pad "abc" 0 `shouldBe` "abc" it "add padding if needed" $ pad "abc" 10 `shouldBe` "abc " describe "parse wot file" $ do it "contains the right number of parts" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let result = readAr file length result `shouldBe` 6 it "yields a first part with the correct name" $ do file <- getDataFileName "latest.wot.ar" >>= B.readFile let (n,_,_,_,_,_) = head $ readAr file n `shouldBe` "README" -- utils
2,329
false
true
0
37
699
716
336
380
null
null
anton-dessiatov/ghc
compiler/basicTypes/MkId.hs
bsd-3-clause
magicDictId :: Id -- See Note [magicDictId magic] magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkForAllTys [alphaTyVar] alphaTy --------------------------------------------------------------------------------
290
magicDictId :: Id magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkForAllTys [alphaTyVar] alphaTy --------------------------------------------------------------------------------
257
magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkForAllTys [alphaTyVar] alphaTy --------------------------------------------------------------------------------
239
true
true
0
6
35
47
26
21
null
null
glguy/cereal
src/Data/Serialize/Put.hs
bsd-3-clause
-- Containers ------------------------------------------------------------------ encodeListOf :: (a -> Builder) -> [a] -> Builder encodeListOf f = -- allow inlining with just a single argument \xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend` F.foldMap f xs
293
encodeListOf :: (a -> Builder) -> [a] -> Builder encodeListOf f = -- allow inlining with just a single argument \xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend` F.foldMap f xs
211
encodeListOf f = -- allow inlining with just a single argument \xs -> execPut (putWord64be (fromIntegral $ length xs)) `M.mappend` F.foldMap f xs
162
true
true
0
12
52
73
39
34
null
null
phischu/fragnix
tests/packages/scotty/Data.IP.Op.hs
bsd-3-clause
addrRangePair :: Addr a => AddrRange a -> (a, Int) addrRangePair (AddrRange adr _ len) = (adr, len)
99
addrRangePair :: Addr a => AddrRange a -> (a, Int) addrRangePair (AddrRange adr _ len) = (adr, len)
99
addrRangePair (AddrRange adr _ len) = (adr, len)
48
false
true
0
7
17
54
27
27
null
null
sdiehl/ghc
testsuite/tests/perf/compiler/T16473.hs
bsd-3-clause
put :: s -> Semantic '[State s] () put !s = Semantic $ \k -> k $ Union $! Put s ()
82
put :: s -> Semantic '[State s] () put !s = Semantic $ \k -> k $ Union $! Put s ()
82
put !s = Semantic $ \k -> k $ Union $! Put s ()
47
false
true
2
11
21
64
30
34
null
null
ghc-android/ghc
libraries/base/GHC/Conc/Sync.hs
bsd-3-clause
disableAllocationLimit :: IO () disableAllocationLimit = do ThreadId t <- myThreadId rts_disableThreadAllocationLimit t -- We cannot do these operations safely on another thread, because on -- a 32-bit machine we cannot do atomic operations on a 64-bit value. -- Therefore, we only expose APIs that allow getting and setting the -- limit of the current thread.
365
disableAllocationLimit :: IO () disableAllocationLimit = do ThreadId t <- myThreadId rts_disableThreadAllocationLimit t -- We cannot do these operations safely on another thread, because on -- a 32-bit machine we cannot do atomic operations on a 64-bit value. -- Therefore, we only expose APIs that allow getting and setting the -- limit of the current thread.
365
disableAllocationLimit = do ThreadId t <- myThreadId rts_disableThreadAllocationLimit t -- We cannot do these operations safely on another thread, because on -- a 32-bit machine we cannot do atomic operations on a 64-bit value. -- Therefore, we only expose APIs that allow getting and setting the -- limit of the current thread.
333
false
true
0
8
60
36
18
18
null
null
codemac/yi-editor
src/Yi/Mode/Haskell.hs
gpl-2.0
tokCol = posnCol . tokPosn
26
tokCol = posnCol . tokPosn
26
tokCol = posnCol . tokPosn
26
false
false
0
5
4
10
5
5
null
null
binesiyu/ifl
ifpt-master/ParserTest.hs
mit
l2 = pNum ["1"]
15
l2 = pNum ["1"]
15
l2 = pNum ["1"]
15
false
false
1
6
3
15
6
9
null
null
felipeZ/Dynamics
src/copiaMolcas.hs
bsd-3-clause
isAuto :: MolBlock -> Bool isAuto (ModuleAuto _n _s _modules) = True
68
isAuto :: MolBlock -> Bool isAuto (ModuleAuto _n _s _modules) = True
68
isAuto (ModuleAuto _n _s _modules) = True
41
false
true
0
7
11
28
14
14
null
null
jgm/pandoc-citeproc
src/Text/CSL/Eval/Date.hs
bsd-3-clause
formatDate :: EvalMode -> Text -> [CslTerm] -> [DatePart] -> [RefDate] -> [Output] formatDate em k tm dp date | [d] <- date = concatMap (formatDatePart d) dp | (a:b:_) <- date = addODate . concat $ doRange a b | otherwise = [] where addODate [] = [] addODate xs = [ODate xs] splitDate a b = case split (onSublist $ diff a b dp) dp of [x,y,z] -> (x,y,z) _ -> E.throw ErrorSplittingDate doRange a b = let (x,y,z) = splitDate a b in map (formatDatePart a) x ++ withDelim y (map (formatDatePart a) (rmSuffix y)) (map (formatDatePart b) (rmPrefix y)) ++ map (formatDatePart b) z -- the point of rmPrefix is to remove the blank space that otherwise -- gets added after the delimiter in a range: 24- 26. rmPrefix (dp':rest) = dp'{ dpFormatting = (dpFormatting dp') { prefix = "" } } : rest rmPrefix [] = [] rmSuffix (dp':rest) | null rest = [dp'{ dpFormatting = (dpFormatting dp') { suffix = "" } }] | otherwise = dp':rmSuffix rest rmSuffix [] = [] diff (RefDate ya ma sa da _ _) (RefDate yb mb sb db _ _) = filter (\x -> dpName x `elem` ns) where ns = case () of _ | ya /= yb -> ["year","month","day"] | ma /= mb || sa /= sb -> if isNothing da && isNothing db then ["month"] else ["month","day"] | da /= db -> ["day"] | otherwise -> ["year","month","day"] term f t = let f' = if f `elem` ["verb", "short", "verb-short", "symbol"] then read . T.unpack $ toRead f else Long in maybe "" termPlural $ findTerm t f' tm formatDatePart (RefDate y m e d o _) (DatePart n f _ fm) | "year" <- n, Just y' <- y = return $ OYear (formatYear f y') k fm | "month" <- n, Just m' <- m = output fm (formatMonth f fm m') | "month" <- n, Just e' <- e = case e' of RawSeason s -> [OStr s fm] _ -> output fm . term f . T.pack $ (printf "season-%02d" $ fromMaybe 0 $ seasonToInt e') | "day" <- n, Just d' <- d = output fm (formatDay f m d') | "year" <- n, o /= mempty = output fm (unLiteral o) | otherwise = [] withDelim xs o1 o2 | null (concat o1 ++ concat o2) = [] | otherwise = o1 ++ (case dpRangeDelim <$> last' xs of ["-"] -> [[OPan [Str "\x2013"]]] [s] -> [[OPan [Str s]]] _ -> []) ++ o2 formatYear f y | "short" <- f = T.pack $ printf "%02d" y | isSorting em , y < 0 = T.pack $ printf "-%04d" (abs y) | isSorting em = T.pack $ printf "%04d" y | y < 0 = (T.pack $ printf "%d" (abs y)) <> term "" "bc" | y < 1000 , y > 0 = (T.pack $ printf "%d" y) <> term "" "ad" | y == 0 = "" | otherwise = T.pack $ printf "%d" y formatMonth f fm m | "short" <- f = getMonth $ period . termPlural | "long" <- f = getMonth termPlural | "numeric" <- f = T.pack $ printf "%d" m | otherwise = T.pack $ printf "%02d" m where period = if stripPeriods fm then T.filter (/= '.') else id getMonth g = case findTerm ("month-" <> T.pack (printf "%02d" m)) (read . T.unpack $ toRead f) tm of Nothing -> T.pack (show m) Just x -> g x formatDay f m d | "numeric-leading-zeros" <- f = T.pack $ printf "%02d" d | "ordinal" <- f = ordinal tm ("month-" <> maybe "0" (T.pack . printf "%02d") m) d | otherwise = T.pack $ printf "%d" d
4,391
formatDate :: EvalMode -> Text -> [CslTerm] -> [DatePart] -> [RefDate] -> [Output] formatDate em k tm dp date | [d] <- date = concatMap (formatDatePart d) dp | (a:b:_) <- date = addODate . concat $ doRange a b | otherwise = [] where addODate [] = [] addODate xs = [ODate xs] splitDate a b = case split (onSublist $ diff a b dp) dp of [x,y,z] -> (x,y,z) _ -> E.throw ErrorSplittingDate doRange a b = let (x,y,z) = splitDate a b in map (formatDatePart a) x ++ withDelim y (map (formatDatePart a) (rmSuffix y)) (map (formatDatePart b) (rmPrefix y)) ++ map (formatDatePart b) z -- the point of rmPrefix is to remove the blank space that otherwise -- gets added after the delimiter in a range: 24- 26. rmPrefix (dp':rest) = dp'{ dpFormatting = (dpFormatting dp') { prefix = "" } } : rest rmPrefix [] = [] rmSuffix (dp':rest) | null rest = [dp'{ dpFormatting = (dpFormatting dp') { suffix = "" } }] | otherwise = dp':rmSuffix rest rmSuffix [] = [] diff (RefDate ya ma sa da _ _) (RefDate yb mb sb db _ _) = filter (\x -> dpName x `elem` ns) where ns = case () of _ | ya /= yb -> ["year","month","day"] | ma /= mb || sa /= sb -> if isNothing da && isNothing db then ["month"] else ["month","day"] | da /= db -> ["day"] | otherwise -> ["year","month","day"] term f t = let f' = if f `elem` ["verb", "short", "verb-short", "symbol"] then read . T.unpack $ toRead f else Long in maybe "" termPlural $ findTerm t f' tm formatDatePart (RefDate y m e d o _) (DatePart n f _ fm) | "year" <- n, Just y' <- y = return $ OYear (formatYear f y') k fm | "month" <- n, Just m' <- m = output fm (formatMonth f fm m') | "month" <- n, Just e' <- e = case e' of RawSeason s -> [OStr s fm] _ -> output fm . term f . T.pack $ (printf "season-%02d" $ fromMaybe 0 $ seasonToInt e') | "day" <- n, Just d' <- d = output fm (formatDay f m d') | "year" <- n, o /= mempty = output fm (unLiteral o) | otherwise = [] withDelim xs o1 o2 | null (concat o1 ++ concat o2) = [] | otherwise = o1 ++ (case dpRangeDelim <$> last' xs of ["-"] -> [[OPan [Str "\x2013"]]] [s] -> [[OPan [Str s]]] _ -> []) ++ o2 formatYear f y | "short" <- f = T.pack $ printf "%02d" y | isSorting em , y < 0 = T.pack $ printf "-%04d" (abs y) | isSorting em = T.pack $ printf "%04d" y | y < 0 = (T.pack $ printf "%d" (abs y)) <> term "" "bc" | y < 1000 , y > 0 = (T.pack $ printf "%d" y) <> term "" "ad" | y == 0 = "" | otherwise = T.pack $ printf "%d" y formatMonth f fm m | "short" <- f = getMonth $ period . termPlural | "long" <- f = getMonth termPlural | "numeric" <- f = T.pack $ printf "%d" m | otherwise = T.pack $ printf "%02d" m where period = if stripPeriods fm then T.filter (/= '.') else id getMonth g = case findTerm ("month-" <> T.pack (printf "%02d" m)) (read . T.unpack $ toRead f) tm of Nothing -> T.pack (show m) Just x -> g x formatDay f m d | "numeric-leading-zeros" <- f = T.pack $ printf "%02d" d | "ordinal" <- f = ordinal tm ("month-" <> maybe "0" (T.pack . printf "%02d") m) d | otherwise = T.pack $ printf "%d" d
4,391
formatDate em k tm dp date | [d] <- date = concatMap (formatDatePart d) dp | (a:b:_) <- date = addODate . concat $ doRange a b | otherwise = [] where addODate [] = [] addODate xs = [ODate xs] splitDate a b = case split (onSublist $ diff a b dp) dp of [x,y,z] -> (x,y,z) _ -> E.throw ErrorSplittingDate doRange a b = let (x,y,z) = splitDate a b in map (formatDatePart a) x ++ withDelim y (map (formatDatePart a) (rmSuffix y)) (map (formatDatePart b) (rmPrefix y)) ++ map (formatDatePart b) z -- the point of rmPrefix is to remove the blank space that otherwise -- gets added after the delimiter in a range: 24- 26. rmPrefix (dp':rest) = dp'{ dpFormatting = (dpFormatting dp') { prefix = "" } } : rest rmPrefix [] = [] rmSuffix (dp':rest) | null rest = [dp'{ dpFormatting = (dpFormatting dp') { suffix = "" } }] | otherwise = dp':rmSuffix rest rmSuffix [] = [] diff (RefDate ya ma sa da _ _) (RefDate yb mb sb db _ _) = filter (\x -> dpName x `elem` ns) where ns = case () of _ | ya /= yb -> ["year","month","day"] | ma /= mb || sa /= sb -> if isNothing da && isNothing db then ["month"] else ["month","day"] | da /= db -> ["day"] | otherwise -> ["year","month","day"] term f t = let f' = if f `elem` ["verb", "short", "verb-short", "symbol"] then read . T.unpack $ toRead f else Long in maybe "" termPlural $ findTerm t f' tm formatDatePart (RefDate y m e d o _) (DatePart n f _ fm) | "year" <- n, Just y' <- y = return $ OYear (formatYear f y') k fm | "month" <- n, Just m' <- m = output fm (formatMonth f fm m') | "month" <- n, Just e' <- e = case e' of RawSeason s -> [OStr s fm] _ -> output fm . term f . T.pack $ (printf "season-%02d" $ fromMaybe 0 $ seasonToInt e') | "day" <- n, Just d' <- d = output fm (formatDay f m d') | "year" <- n, o /= mempty = output fm (unLiteral o) | otherwise = [] withDelim xs o1 o2 | null (concat o1 ++ concat o2) = [] | otherwise = o1 ++ (case dpRangeDelim <$> last' xs of ["-"] -> [[OPan [Str "\x2013"]]] [s] -> [[OPan [Str s]]] _ -> []) ++ o2 formatYear f y | "short" <- f = T.pack $ printf "%02d" y | isSorting em , y < 0 = T.pack $ printf "-%04d" (abs y) | isSorting em = T.pack $ printf "%04d" y | y < 0 = (T.pack $ printf "%d" (abs y)) <> term "" "bc" | y < 1000 , y > 0 = (T.pack $ printf "%d" y) <> term "" "ad" | y == 0 = "" | otherwise = T.pack $ printf "%d" y formatMonth f fm m | "short" <- f = getMonth $ period . termPlural | "long" <- f = getMonth termPlural | "numeric" <- f = T.pack $ printf "%d" m | otherwise = T.pack $ printf "%02d" m where period = if stripPeriods fm then T.filter (/= '.') else id getMonth g = case findTerm ("month-" <> T.pack (printf "%02d" m)) (read . T.unpack $ toRead f) tm of Nothing -> T.pack (show m) Just x -> g x formatDay f m d | "numeric-leading-zeros" <- f = T.pack $ printf "%02d" d | "ordinal" <- f = ordinal tm ("month-" <> maybe "0" (T.pack . printf "%02d") m) d | otherwise = T.pack $ printf "%d" d
4,308
false
true
23
16
2,043
1,725
828
897
null
null
Proclivis/wxHaskell
wxcore/src/haskell/Graphics/UI/WXCore/WxcDefs.hs
lgpl-2.1
wxLANGUAGE_UIGHUR :: Int wxLANGUAGE_UIGHUR = 213
48
wxLANGUAGE_UIGHUR :: Int wxLANGUAGE_UIGHUR = 213
48
wxLANGUAGE_UIGHUR = 213
23
false
true
0
4
5
11
6
5
null
null