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
michaelgwelch/bacnet
src/BACnet/Tag/Writer.hs
mit
writeTimeAPTag :: Writer writeTimeAPTag = unsigned8 0xB4
56
writeTimeAPTag :: Writer writeTimeAPTag = unsigned8 0xB4
56
writeTimeAPTag = unsigned8 0xB4
31
false
true
0
6
6
21
8
13
null
null
ilyasergey/GHC-XAppFix
compiler/nativeGen/PPC/Ppr.hs
bsd-3-clause
pprImm platform (ImmCLbl l) = pprCLabel_asm platform l
57
pprImm platform (ImmCLbl l) = pprCLabel_asm platform l
57
pprImm platform (ImmCLbl l) = pprCLabel_asm platform l
57
false
false
0
6
10
24
10
14
null
null
geophf/1HaskellADay
exercises/HAD/Y2017/M10/D03/Solution.hs
mit
archive :: Part -> FilePath archive x = "Y2017/M10/D03/NYTOnline_09-05-17_09-10-17_ALLSecs-pt" ++ show x ++ ".txt.gz"
120
archive :: Part -> FilePath archive x = "Y2017/M10/D03/NYTOnline_09-05-17_09-10-17_ALLSecs-pt" ++ show x ++ ".txt.gz"
120
archive x = "Y2017/M10/D03/NYTOnline_09-05-17_09-10-17_ALLSecs-pt" ++ show x ++ ".txt.gz"
92
false
true
0
7
16
35
15
20
null
null
nevvi/Declarative-D7012E
lab2/Parser.hs
gpl-3.0
(#-) :: Parser a -> Parser b -> Parser a m #- n = (m # n) >-> fst
65
(#-) :: Parser a -> Parser b -> Parser a m #- n = (m # n) >-> fst
65
m #- n = (m # n) >-> fst
24
false
true
0
9
18
47
23
24
null
null
Laar/opengl-xmlspec
src/Text/OpenGL/Xml/CProcess.hs
bsd-3-clause
pTypeDef :: String -> Either String TypeDef pTypeDef s = do d <- parseC' s pAlias d <|> pFuncDef d <|> pStructDef d <|> Left ("Typedef parsing failed for:" ++ s)
178
pTypeDef :: String -> Either String TypeDef pTypeDef s = do d <- parseC' s pAlias d <|> pFuncDef d <|> pStructDef d <|> Left ("Typedef parsing failed for:" ++ s)
178
pTypeDef s = do d <- parseC' s pAlias d <|> pFuncDef d <|> pStructDef d <|> Left ("Typedef parsing failed for:" ++ s)
134
false
true
0
10
47
67
30
37
null
null
tomjefferys/fuligite
src/Scripting/Fuligite/GarbageCollector.hs
mit
setupGCState :: EvalMonad2 GCState setupGCState = do objs <- IdCache.allIds . objCache <$> get let gcState = newGCState objs eids <- getEnvId <$> get return $ foldr moveToGrey gcState eids -- Examines all the current grey objects
239
setupGCState :: EvalMonad2 GCState setupGCState = do objs <- IdCache.allIds . objCache <$> get let gcState = newGCState objs eids <- getEnvId <$> get return $ foldr moveToGrey gcState eids -- Examines all the current grey objects
239
setupGCState = do objs <- IdCache.allIds . objCache <$> get let gcState = newGCState objs eids <- getEnvId <$> get return $ foldr moveToGrey gcState eids -- Examines all the current grey objects
204
false
true
0
10
46
69
32
37
null
null
ekmett/wxHaskell
wxcore/src/haskell/Graphics/UI/WXCore/WxcDefs.hs
lgpl-2.1
wxSTC_MARK_LCORNER :: Int wxSTC_MARK_LCORNER = 10
49
wxSTC_MARK_LCORNER :: Int wxSTC_MARK_LCORNER = 10
49
wxSTC_MARK_LCORNER = 10
23
false
true
0
6
5
18
7
11
null
null
mrmonday/Idris-dev
src/IRTS/Exports.hs
bsd-3-clause
toFDesc :: Term -> FDesc toFDesc (Constant (Str str)) = FStr str
64
toFDesc :: Term -> FDesc toFDesc (Constant (Str str)) = FStr str
64
toFDesc (Constant (Str str)) = FStr str
39
false
true
0
11
11
38
17
21
null
null
jystic/quick-version
src/Main.hs
bsd-3-clause
------------------------------------------------------------------------ printPackageExports :: G.PackageId -> IO () printPackageExports pkgId = do p <- withGhc (getPackage pkgId) putStrLn (showPackage p)
213
printPackageExports :: G.PackageId -> IO () printPackageExports pkgId = do p <- withGhc (getPackage pkgId) putStrLn (showPackage p)
139
printPackageExports pkgId = do p <- withGhc (getPackage pkgId) putStrLn (showPackage p)
95
true
true
0
10
27
54
25
29
null
null
alpmestan/core-server
client.hs
bsd-3-clause
readTilEmpty :: Handle -> IO B.ByteString readTilEmpty h = go where go = do eof <- hIsEOF h if eof then return B.empty else do b <- hReady h if b then do s <- B.hGetNonBlocking h (1024*500) rest <- go return $ s `B.append` rest else return B.empty
502
readTilEmpty :: Handle -> IO B.ByteString readTilEmpty h = go where go = do eof <- hIsEOF h if eof then return B.empty else do b <- hReady h if b then do s <- B.hGetNonBlocking h (1024*500) rest <- go return $ s `B.append` rest else return B.empty
502
readTilEmpty h = go where go = do eof <- hIsEOF h if eof then return B.empty else do b <- hReady h if b then do s <- B.hGetNonBlocking h (1024*500) rest <- go return $ s `B.append` rest else return B.empty
460
false
true
1
17
303
134
61
73
null
null
z0isch/htak
src/Tak/Printer/PTN.hs
bsd-3-clause
printMove (Left Draw) = "1/2-1/2"
33
printMove (Left Draw) = "1/2-1/2"
33
printMove (Left Draw) = "1/2-1/2"
33
false
false
0
7
4
15
7
8
null
null
hesiod/OpenGL
src/Graphics/Rendering/OpenGL/GL/Polygons.hs
bsd-3-clause
polygonOffset :: StateVar (GLfloat, GLfloat) polygonOffset = makeStateVar (liftM2 (,) (getFloat1 id GetPolygonOffsetFactor) (getFloat1 id GetPolygonOffsetUnits)) (uncurry glPolygonOffset)
234
polygonOffset :: StateVar (GLfloat, GLfloat) polygonOffset = makeStateVar (liftM2 (,) (getFloat1 id GetPolygonOffsetFactor) (getFloat1 id GetPolygonOffsetUnits)) (uncurry glPolygonOffset)
234
polygonOffset = makeStateVar (liftM2 (,) (getFloat1 id GetPolygonOffsetFactor) (getFloat1 id GetPolygonOffsetUnits)) (uncurry glPolygonOffset)
189
false
true
0
9
64
60
31
29
null
null
facebookincubator/duckling
Duckling/Time/NB/Rules.hs
bsd-3-clause
ruleDayofmonthordinalNamedmonthYear :: Rule ruleDayofmonthordinalNamedmonthYear = Rule { name = "<day-of-month>(ordinal) <named-month> year" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth , regex "(\\d{2,4})" ] , prod = \tokens -> case tokens of (token: Token Time td: Token RegexMatch (GroupMatch (match:_)): _) -> do y <- parseInt match dom <- intersectDOM td token Token Time <$> intersect dom (year y) _ -> Nothing }
515
ruleDayofmonthordinalNamedmonthYear :: Rule ruleDayofmonthordinalNamedmonthYear = Rule { name = "<day-of-month>(ordinal) <named-month> year" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth , regex "(\\d{2,4})" ] , prod = \tokens -> case tokens of (token: Token Time td: Token RegexMatch (GroupMatch (match:_)): _) -> do y <- parseInt match dom <- intersectDOM td token Token Time <$> intersect dom (year y) _ -> Nothing }
515
ruleDayofmonthordinalNamedmonthYear = Rule { name = "<day-of-month>(ordinal) <named-month> year" , pattern = [ Predicate isDOMOrdinal , Predicate isAMonth , regex "(\\d{2,4})" ] , prod = \tokens -> case tokens of (token: Token Time td: Token RegexMatch (GroupMatch (match:_)): _) -> do y <- parseInt match dom <- intersectDOM td token Token Time <$> intersect dom (year y) _ -> Nothing }
471
false
true
0
20
147
155
77
78
null
null
andrew-quinn/mm
mm.hs
mit
masser (Element a n) = fromIntegral n * amu a where amu = realFracToDecimal precision . atomWeight . elementBySymbol
118
masser (Element a n) = fromIntegral n * amu a where amu = realFracToDecimal precision . atomWeight . elementBySymbol
118
masser (Element a n) = fromIntegral n * amu a where amu = realFracToDecimal precision . atomWeight . elementBySymbol
118
false
false
0
7
20
46
21
25
null
null
np/hlatex
examples/ds/Kit.hs
bsd-3-clause
rawMathLatexItem = B.math . BI.rawMath
38
rawMathLatexItem = B.math . BI.rawMath
38
rawMathLatexItem = B.math . BI.rawMath
38
false
false
0
6
4
14
7
7
null
null
brendanhay/gogol
gogol-spanner/gen/Network/Google/Spanner/Types/Product.hs
mpl-2.0
-- | Creates a value of 'MetricIndexedHotKeys' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'mihkAddtional' metricIndexedHotKeys :: HashMap Text IndexedHotKey -- ^ 'mihkAddtional' -> MetricIndexedHotKeys metricIndexedHotKeys pMihkAddtional_ = MetricIndexedHotKeys' {_mihkAddtional = _Coerce # pMihkAddtional_}
407
metricIndexedHotKeys :: HashMap Text IndexedHotKey -- ^ 'mihkAddtional' -> MetricIndexedHotKeys metricIndexedHotKeys pMihkAddtional_ = MetricIndexedHotKeys' {_mihkAddtional = _Coerce # pMihkAddtional_}
211
metricIndexedHotKeys pMihkAddtional_ = MetricIndexedHotKeys' {_mihkAddtional = _Coerce # pMihkAddtional_}
107
true
true
0
8
62
50
26
24
null
null
facebookincubator/duckling
Duckling/Numeral/MN/Corpus.hs
bsd-3-clause
corpus :: Corpus corpus = (context, testOptions, allExamples)
61
corpus :: Corpus corpus = (context, testOptions, allExamples)
61
corpus = (context, testOptions, allExamples)
44
false
true
0
5
7
20
12
8
null
null
ekmett/ghc
compiler/nativeGen/X86/Ppr.hs
bsd-3-clause
pprInstr g@(GSUB _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GSUB-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fsubrp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GSUB-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fsubp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fsub ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1])
500
pprInstr g@(GSUB _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GSUB-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fsubrp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GSUB-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fsubp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fsub ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1])
500
pprInstr g@(GSUB _ src1 src2 dst) | src1 == dst = pprG g (text "\t#GSUB-xxxcase1" $$ hcat [gtab, gpush src2 0, text " ; fsubrp %st(0),", greg src1 1]) | src2 == dst = pprG g (text "\t#GSUB-xxxcase2" $$ hcat [gtab, gpush src1 0, text " ; fsubp %st(0),", greg src2 1]) | otherwise = pprG g (hcat [gtab, gpush src1 0, text " ; fsub ", greg src2 1, text ",%st(0)", gsemi, gpop dst 1])
500
false
false
1
11
195
197
96
101
null
null
supki/libstackexchange
examples/server-side-authentication.hs
mit
main ∷ IO () main = do tokens ← newIORef [] simpleHTTP nullConf $ msum [ dir "authenticate-me-please" $ seeOther (render $ explicitUserPermission cID rURI) "" , dir "save-token" $ do c ← lookText "code" liftIO $ askSE (explicitAccessToken cID cSecret c rURI) >>= modifyIORef' tokens . (:) ok "Saved." , dir "show-tokens" $ liftIO (readIORef tokens) >>= ok . show ] where rURI = undefined cID = undefined cSecret = undefined
476
main ∷ IO () main = do tokens ← newIORef [] simpleHTTP nullConf $ msum [ dir "authenticate-me-please" $ seeOther (render $ explicitUserPermission cID rURI) "" , dir "save-token" $ do c ← lookText "code" liftIO $ askSE (explicitAccessToken cID cSecret c rURI) >>= modifyIORef' tokens . (:) ok "Saved." , dir "show-tokens" $ liftIO (readIORef tokens) >>= ok . show ] where rURI = undefined cID = undefined cSecret = undefined
476
main = do tokens ← newIORef [] simpleHTTP nullConf $ msum [ dir "authenticate-me-please" $ seeOther (render $ explicitUserPermission cID rURI) "" , dir "save-token" $ do c ← lookText "code" liftIO $ askSE (explicitAccessToken cID cSecret c rURI) >>= modifyIORef' tokens . (:) ok "Saved." , dir "show-tokens" $ liftIO (readIORef tokens) >>= ok . show ] where rURI = undefined cID = undefined cSecret = undefined
463
false
true
0
18
124
174
82
92
null
null
rgaiacs/pandoc
src/Text/Pandoc/Writers/HTML.hs
gpl-2.0
toList :: (Html -> Html) -> WriterOptions -> ([Html] -> Html) toList listop opts items = do if (writerIncremental opts) then if (writerSlideVariant opts /= RevealJsSlides) then (listop $ mconcat items) ! A.class_ "incremental" else listop $ mconcat $ map (! A.class_ "fragment") items else listop $ mconcat items
360
toList :: (Html -> Html) -> WriterOptions -> ([Html] -> Html) toList listop opts items = do if (writerIncremental opts) then if (writerSlideVariant opts /= RevealJsSlides) then (listop $ mconcat items) ! A.class_ "incremental" else listop $ mconcat $ map (! A.class_ "fragment") items else listop $ mconcat items
360
toList listop opts items = do if (writerIncremental opts) then if (writerSlideVariant opts /= RevealJsSlides) then (listop $ mconcat items) ! A.class_ "incremental" else listop $ mconcat $ map (! A.class_ "fragment") items else listop $ mconcat items
298
false
true
0
13
96
126
65
61
null
null
robeverest/accelerate
Data/Array/Accelerate/Interpreter.hs
bsd-3-clause
evalPreOpenAcc (Foreign _ _ _) _ = error "This case is not possible"
70
evalPreOpenAcc (Foreign _ _ _) _ = error "This case is not possible"
70
evalPreOpenAcc (Foreign _ _ _) _ = error "This case is not possible"
70
false
false
0
7
14
24
11
13
null
null
Javran/twitter-conduit
sample/oslist.hs
bsd-2-clause
main :: IO () main = do [screenName] <- getArgs twInfo <- getTWInfoFromEnv mgr <- newManager tlsManagerSettings let sn = ScreenNameParam screenName folids <- runConduit $ sourceWithCursor twInfo mgr (followersIds sn) .| CL.consume friids <- runConduit $ sourceWithCursor twInfo mgr (friendsIds sn) .| CL.consume let folmap = M.fromList $ map (flip (,) True) folids os = filter (\uid -> M.notMember uid folmap) friids bo = filter (\usr -> M.member usr folmap) friids putStrLn "one sided:" print os putStrLn "both following:" print bo
596
main :: IO () main = do [screenName] <- getArgs twInfo <- getTWInfoFromEnv mgr <- newManager tlsManagerSettings let sn = ScreenNameParam screenName folids <- runConduit $ sourceWithCursor twInfo mgr (followersIds sn) .| CL.consume friids <- runConduit $ sourceWithCursor twInfo mgr (friendsIds sn) .| CL.consume let folmap = M.fromList $ map (flip (,) True) folids os = filter (\uid -> M.notMember uid folmap) friids bo = filter (\usr -> M.member usr folmap) friids putStrLn "one sided:" print os putStrLn "both following:" print bo
596
main = do [screenName] <- getArgs twInfo <- getTWInfoFromEnv mgr <- newManager tlsManagerSettings let sn = ScreenNameParam screenName folids <- runConduit $ sourceWithCursor twInfo mgr (followersIds sn) .| CL.consume friids <- runConduit $ sourceWithCursor twInfo mgr (friendsIds sn) .| CL.consume let folmap = M.fromList $ map (flip (,) True) folids os = filter (\uid -> M.notMember uid folmap) friids bo = filter (\usr -> M.member usr folmap) friids putStrLn "one sided:" print os putStrLn "both following:" print bo
582
false
true
0
14
145
220
102
118
null
null
vinnymac/glot-www
Util/Alert.hs
mit
warningText :: Text -> Text warningText = toStrict . renderHtml . warningHtml
77
warningText :: Text -> Text warningText = toStrict . renderHtml . warningHtml
77
warningText = toStrict . renderHtml . warningHtml
49
false
true
1
7
11
30
13
17
null
null
jmikkola/Athena
src/Inference.hs
mit
inferBindGroup :: BindGroup -> Environment -> InferM (TypedDecls, Environment) inferBindGroup bg env = do let expls = explicitBindings bg explicitBindingTypes <- getExplicitTypes expls let env1 = addToEnv explicitBindingTypes env let impls = implicitBindings bg (decls1, env2) <- inferGroups impls env1 let env' = addToEnv env2 env1 decls2 <- tiExpls expls env' return (decls1 ++ decls2, env')
411
inferBindGroup :: BindGroup -> Environment -> InferM (TypedDecls, Environment) inferBindGroup bg env = do let expls = explicitBindings bg explicitBindingTypes <- getExplicitTypes expls let env1 = addToEnv explicitBindingTypes env let impls = implicitBindings bg (decls1, env2) <- inferGroups impls env1 let env' = addToEnv env2 env1 decls2 <- tiExpls expls env' return (decls1 ++ decls2, env')
411
inferBindGroup bg env = do let expls = explicitBindings bg explicitBindingTypes <- getExplicitTypes expls let env1 = addToEnv explicitBindingTypes env let impls = implicitBindings bg (decls1, env2) <- inferGroups impls env1 let env' = addToEnv env2 env1 decls2 <- tiExpls expls env' return (decls1 ++ decls2, env')
332
false
true
5
8
73
130
65
65
null
null
FranklinChen/Idris-dev
src/IRTS/CodegenC.hs
bsd-3-clause
irts_c FAny x = x
17
irts_c FAny x = x
17
irts_c FAny x = x
17
false
false
1
5
4
16
5
11
null
null
junjihashimoto/persistent
persistent/Database/Persist/Sql/Migration.hs
mit
executeMigrate :: MonadIO m => Bool -> Text -> ReaderT SqlBackend m Text executeMigrate silent s = do unless silent $ liftIO $ hPutStrLn stderr $ "Migrating: " ++ unpack s rawExecute s [] return s -- | Sort the alter DB statements so tables are created before constraints are -- added.
298
executeMigrate :: MonadIO m => Bool -> Text -> ReaderT SqlBackend m Text executeMigrate silent s = do unless silent $ liftIO $ hPutStrLn stderr $ "Migrating: " ++ unpack s rawExecute s [] return s -- | Sort the alter DB statements so tables are created before constraints are -- added.
298
executeMigrate silent s = do unless silent $ liftIO $ hPutStrLn stderr $ "Migrating: " ++ unpack s rawExecute s [] return s -- | Sort the alter DB statements so tables are created before constraints are -- added.
225
false
true
0
11
64
84
38
46
null
null
SamirTalwar/advent-of-code
2021/AOC_24_1.hs
mit
lookup (Num n) _ = n
20
lookup (Num n) _ = n
20
lookup (Num n) _ = n
20
false
false
0
6
5
19
8
11
null
null
ghc-android/ghc
testsuite/tests/ghci/should_run/ghcirun004.hs
bsd-3-clause
4265 = 4264
11
4265 = 4264
11
4265 = 4264
11
false
false
1
5
2
10
3
7
null
null
atomb/dalvik
Dalvik/Parser.hs
bsd-3-clause
parseTypeList :: Get [TypeId] parseTypeList = do size <- getWord32le replicateM (fromIntegral size) getWord16le
115
parseTypeList :: Get [TypeId] parseTypeList = do size <- getWord32le replicateM (fromIntegral size) getWord16le
115
parseTypeList = do size <- getWord32le replicateM (fromIntegral size) getWord16le
85
false
true
0
9
17
38
18
20
null
null
xmonad/xmonad-contrib
XMonad/Layout/Decoration.hs
bsd-3-clause
-- | Given a 'Rectangle' and a list of 'Rectangle's is True if the -- 'Rectangle' is not completely contained by any 'Rectangle' of the -- list. isVisible :: Rectangle -> [Rectangle] -> Bool isVisible r = and . foldr f [] where f x xs = if r `isWithin` x then False : xs else True : xs -- | The contrary of 'isVisible'.
324
isVisible :: Rectangle -> [Rectangle] -> Bool isVisible r = and . foldr f [] where f x xs = if r `isWithin` x then False : xs else True : xs -- | The contrary of 'isVisible'.
179
isVisible r = and . foldr f [] where f x xs = if r `isWithin` x then False : xs else True : xs -- | The contrary of 'isVisible'.
133
true
true
0
8
69
74
41
33
null
null
shimanekb/Learn_Haskell
ch2/fntype.hs
gpl-2.0
removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [c | c <- st, c `elem` ['A'..'Z']]
97
removeNonUppercase :: [Char] -> [Char] removeNonUppercase st = [c | c <- st, c `elem` ['A'..'Z']]
97
removeNonUppercase st = [c | c <- st, c `elem` ['A'..'Z']]
58
false
true
0
8
15
50
28
22
null
null
k0001/gtk2hs
tools/c2hs/base/state/CIO.hs
gpl-3.0
-- file handling -- ------------- openFileCIO :: FilePath -> IOMode -> PreCST e s Handle openFileCIO p m = liftIO $ do hnd <- openFile p m #if __GLASGOW_HASKELL__ >= 612 hSetEncoding hnd latin1 #endif return hnd
223
openFileCIO :: FilePath -> IOMode -> PreCST e s Handle openFileCIO p m = liftIO $ do hnd <- openFile p m #if __GLASGOW_HASKELL__ >= 612 hSetEncoding hnd latin1 #endif return hnd
188
openFileCIO p m = liftIO $ do hnd <- openFile p m #if __GLASGOW_HASKELL__ >= 612 hSetEncoding hnd latin1 #endif return hnd
129
true
true
0
9
48
65
31
34
null
null
Persi/shellcheck
ShellCheck/Analytics.hs
gpl-3.0
prop_checkSpacefulness11= verifyTree checkSpacefulness "rm ${10//foo/bar}"
74
prop_checkSpacefulness11= verifyTree checkSpacefulness "rm ${10//foo/bar}"
74
prop_checkSpacefulness11= verifyTree checkSpacefulness "rm ${10//foo/bar}"
74
false
false
0
5
4
11
5
6
null
null
AlexanderPankiv/ghc
compiler/basicTypes/Name.hs
bsd-3-clause
nameSortStableString :: NameSort -> String nameSortStableString System = "$_sys"
80
nameSortStableString :: NameSort -> String nameSortStableString System = "$_sys"
80
nameSortStableString System = "$_sys"
37
false
true
0
5
8
18
9
9
null
null
izgzhen/hadrian
src/Hadrian/Expression.hs
mit
input :: FilePattern -> Predicate c b input f = any (f ?==) <$> getInputs
73
input :: FilePattern -> Predicate c b input f = any (f ?==) <$> getInputs
73
input f = any (f ?==) <$> getInputs
35
false
true
0
7
14
34
17
17
null
null
fmapfmapfmap/amazonka
amazonka-ec2/gen/Network/AWS/EC2/Types/Product.hs
mpl-2.0
-- | The ID of the VPC endpoint. veVPCEndpointId :: Lens' VPCEndpoint (Maybe Text) veVPCEndpointId = lens _veVPCEndpointId (\ s a -> s{_veVPCEndpointId = a})
157
veVPCEndpointId :: Lens' VPCEndpoint (Maybe Text) veVPCEndpointId = lens _veVPCEndpointId (\ s a -> s{_veVPCEndpointId = a})
124
veVPCEndpointId = lens _veVPCEndpointId (\ s a -> s{_veVPCEndpointId = a})
74
true
true
0
9
24
46
25
21
null
null
energyflowanalysis/efa-2.1
src/EFA/Example/Topology/Tripod/State.hs
bsd-3-clause
state3 = identifyFlowState Tripod.topology [undirEdge node0 node2, dirEdge node2 node1]
96
state3 = identifyFlowState Tripod.topology [undirEdge node0 node2, dirEdge node2 node1]
96
state3 = identifyFlowState Tripod.topology [undirEdge node0 node2, dirEdge node2 node1]
96
false
false
0
7
18
29
14
15
null
null
codecurve/FieldML-Haskell-01
src/FieldML/Utility01.hs
bsd-2-clause
codomain (Sin _) = Reals
24
codomain (Sin _) = Reals
24
codomain (Sin _) = Reals
24
false
false
0
6
4
16
7
9
null
null
joncol/mal
haskell/step2/app/Main.hs
mpl-2.0
getClosingToken :: Set (ErrorItem Char) -> Maybe Char getClosingToken ts = listToMaybe $ foldr accum [] ")]" where makeTokens c = Tokens $ c :| [] accum c = bool id ((:) c) $ S.member (makeTokens c) ts
214
getClosingToken :: Set (ErrorItem Char) -> Maybe Char getClosingToken ts = listToMaybe $ foldr accum [] ")]" where makeTokens c = Tokens $ c :| [] accum c = bool id ((:) c) $ S.member (makeTokens c) ts
214
getClosingToken ts = listToMaybe $ foldr accum [] ")]" where makeTokens c = Tokens $ c :| [] accum c = bool id ((:) c) $ S.member (makeTokens c) ts
160
false
true
3
9
50
108
50
58
null
null
jship/metronome
local_deps/netwire/Control/Wire/Interval.hs
bsd-3-clause
-- | After the given time period. -- -- * Depends: now after the given time period. -- -- * Inhibits: for the given time period. after :: (HasTime t s, Monoid e) => t -> Wire s e m a a after t' = mkPure $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Right x, mkId) else (Left mempty, after t)
338
after :: (HasTime t s, Monoid e) => t -> Wire s e m a a after t' = mkPure $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Right x, mkId) else (Left mempty, after t)
208
after t' = mkPure $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Right x, mkId) else (Left mempty, after t)
152
true
true
0
12
111
113
60
53
null
null
tjakway/ghcjvm
compiler/basicTypes/Name.hs
bsd-3-clause
-- This is used for hsigs: we want to use the name of the originally exported -- entity, but edit the location to refer to the reexport site setNameLoc :: Name -> SrcSpan -> Name setNameLoc name loc = name {n_loc = loc}
219
setNameLoc :: Name -> SrcSpan -> Name setNameLoc name loc = name {n_loc = loc}
78
setNameLoc name loc = name {n_loc = loc}
40
true
true
0
7
42
39
20
19
null
null
literate-unitb/literate-unitb
src/Interactive/Pipeline.hs
mit
prover :: Shared -> IO (IO ()) prover (Shared { .. }) = do tok <- newEmptyMVar observe pr_obl tok -- req <- newEmptyMVar req <- newTBQueueIO 20 forM_ [1..40] $ \p -> forkOn p $ worker req return $ forever $ do takeMVar tok inc 1 po <- read_obs pr_obl forM_ (keys po) $ \k -> do po <- reads_obs pr_obl $ M.lookup k case po of Just (po,Nothing) -> do liftIO $ atomically $ writeTBQueue req (k,po) -- liftIO $ putMVar req (k,po) _ -> return () dec 1 where inc x = modify_obs working (return . (+x)) dec x = modify_obs working (return . (+ (-x))) -- handler :: handler lbl@(_,x) (ErrorCall msg) = do write_obs dump_cmd $ Just $ Only x fail ([s|During %s: %s|] (pretty lbl) msg) worker req = forever $ do -- (k,po) <- takeMVar req (k,po) <- atomically $ readTBQueue req let k' = uncurry (</>) k inc 1 r <- catch (discharge k' po) (handler k) dec 1 modify_obs pr_obl $ return . insert k (po,Just $ r == Valid)
1,248
prover :: Shared -> IO (IO ()) prover (Shared { .. }) = do tok <- newEmptyMVar observe pr_obl tok -- req <- newEmptyMVar req <- newTBQueueIO 20 forM_ [1..40] $ \p -> forkOn p $ worker req return $ forever $ do takeMVar tok inc 1 po <- read_obs pr_obl forM_ (keys po) $ \k -> do po <- reads_obs pr_obl $ M.lookup k case po of Just (po,Nothing) -> do liftIO $ atomically $ writeTBQueue req (k,po) -- liftIO $ putMVar req (k,po) _ -> return () dec 1 where inc x = modify_obs working (return . (+x)) dec x = modify_obs working (return . (+ (-x))) -- handler :: handler lbl@(_,x) (ErrorCall msg) = do write_obs dump_cmd $ Just $ Only x fail ([s|During %s: %s|] (pretty lbl) msg) worker req = forever $ do -- (k,po) <- takeMVar req (k,po) <- atomically $ readTBQueue req let k' = uncurry (</>) k inc 1 r <- catch (discharge k' po) (handler k) dec 1 modify_obs pr_obl $ return . insert k (po,Just $ r == Valid)
1,248
prover (Shared { .. }) = do tok <- newEmptyMVar observe pr_obl tok -- req <- newEmptyMVar req <- newTBQueueIO 20 forM_ [1..40] $ \p -> forkOn p $ worker req return $ forever $ do takeMVar tok inc 1 po <- read_obs pr_obl forM_ (keys po) $ \k -> do po <- reads_obs pr_obl $ M.lookup k case po of Just (po,Nothing) -> do liftIO $ atomically $ writeTBQueue req (k,po) -- liftIO $ putMVar req (k,po) _ -> return () dec 1 where inc x = modify_obs working (return . (+x)) dec x = modify_obs working (return . (+ (-x))) -- handler :: handler lbl@(_,x) (ErrorCall msg) = do write_obs dump_cmd $ Just $ Only x fail ([s|During %s: %s|] (pretty lbl) msg) worker req = forever $ do -- (k,po) <- takeMVar req (k,po) <- atomically $ readTBQueue req let k' = uncurry (</>) k inc 1 r <- catch (discharge k' po) (handler k) dec 1 modify_obs pr_obl $ return . insert k (po,Just $ r == Valid)
1,217
false
true
0
21
523
471
227
244
null
null
ezyang/ghc
libraries/template-haskell/Language/Haskell/TH/Lib/Internal.hs
bsd-3-clause
promotedT :: Name -> TypeQ promotedT = return . PromotedT
57
promotedT :: Name -> TypeQ promotedT = return . PromotedT
57
promotedT = return . PromotedT
30
false
true
0
5
9
19
10
9
null
null
infotroph/pandoc
src/Text/Pandoc/Writers/DokuWiki.hs
gpl-2.0
inlineToDokuWiki opts (Quoted SingleQuote lst) = do contents <- inlineListToDokuWiki opts lst return $ "\8216" ++ contents ++ "\8217"
137
inlineToDokuWiki opts (Quoted SingleQuote lst) = do contents <- inlineListToDokuWiki opts lst return $ "\8216" ++ contents ++ "\8217"
137
inlineToDokuWiki opts (Quoted SingleQuote lst) = do contents <- inlineListToDokuWiki opts lst return $ "\8216" ++ contents ++ "\8217"
137
false
false
0
9
22
48
21
27
null
null
buetow/hsbot
HsBot/IRC.hs
bsd-3-clause
ircWrite :: Handle -> String -> String -> IO () ircWrite h s t = do printf "> %s %s\n" s t hPrintf h "%s %s\r\n" s t
125
ircWrite :: Handle -> String -> String -> IO () ircWrite h s t = do printf "> %s %s\n" s t hPrintf h "%s %s\r\n" s t
125
ircWrite h s t = do printf "> %s %s\n" s t hPrintf h "%s %s\r\n" s t
77
false
true
0
10
36
62
27
35
null
null
keithodulaigh/Hets
HasCASL/Builtin.hs
gpl-2.0
parseDAnno :: String -> Annotation parseDAnno str = case parse annotationL "" str of Left _ -> error "parseDAnno" Right a -> a
134
parseDAnno :: String -> Annotation parseDAnno str = case parse annotationL "" str of Left _ -> error "parseDAnno" Right a -> a
134
parseDAnno str = case parse annotationL "" str of Left _ -> error "parseDAnno" Right a -> a
99
false
true
3
6
30
48
23
25
null
null
michalkonecny/mixed-types-num
src/Numeric/MixedTypes/Elementary.hs
bsd-3-clause
{-| HSpec properties that each implementation of CanLog should satisfy. -} specCanLogReal :: _ => T t -> Spec specCanLogReal (T typeName :: T t) = describe (printf "CanLog %s" typeName) $ do it "log(1/x) == -(log x)" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in x !>! 0 && (1/x) !>! 0 ==> log (1/x) ?==?$ -(log x) it "log(x*y) = log(x)+log(y)" $ do property $ \ (x_ :: t) (y_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in let y = enforceRange (Just 0, Nothing) y_ in x !>! 0 && y !>! 0 && x*y !>! 0 ==> (log $ x * y) ?==?$ (log x) + (log y) it "log(exp x) == x" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just (-1000), Just 10000) x_ in let ex = exp x in (ex !>! 0) ==> log ex ?==?$ x where infix 4 ?==?$ (?==?$) :: (HasEqCertainlyAsymmetric a b, Show a, Show b) => a -> b -> Property (?==?$) = printArgsIfFails2 "?==?" (?==?) {- Instances for Integer, Rational etc need an algebraic real or exact real type. Such type is not provided in this package. See eg aern2-real. -}
1,173
specCanLogReal :: _ => T t -> Spec specCanLogReal (T typeName :: T t) = describe (printf "CanLog %s" typeName) $ do it "log(1/x) == -(log x)" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in x !>! 0 && (1/x) !>! 0 ==> log (1/x) ?==?$ -(log x) it "log(x*y) = log(x)+log(y)" $ do property $ \ (x_ :: t) (y_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in let y = enforceRange (Just 0, Nothing) y_ in x !>! 0 && y !>! 0 && x*y !>! 0 ==> (log $ x * y) ?==?$ (log x) + (log y) it "log(exp x) == x" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just (-1000), Just 10000) x_ in let ex = exp x in (ex !>! 0) ==> log ex ?==?$ x where infix 4 ?==?$ (?==?$) :: (HasEqCertainlyAsymmetric a b, Show a, Show b) => a -> b -> Property (?==?$) = printArgsIfFails2 "?==?" (?==?) {- Instances for Integer, Rational etc need an algebraic real or exact real type. Such type is not provided in this package. See eg aern2-real. -}
1,095
specCanLogReal (T typeName :: T t) = describe (printf "CanLog %s" typeName) $ do it "log(1/x) == -(log x)" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in x !>! 0 && (1/x) !>! 0 ==> log (1/x) ?==?$ -(log x) it "log(x*y) = log(x)+log(y)" $ do property $ \ (x_ :: t) (y_ :: t) -> let x = enforceRange (Just 0, Nothing) x_ in let y = enforceRange (Just 0, Nothing) y_ in x !>! 0 && y !>! 0 && x*y !>! 0 ==> (log $ x * y) ?==?$ (log x) + (log y) it "log(exp x) == x" $ do property $ \ (x_ :: t) -> let x = enforceRange (Just (-1000), Just 10000) x_ in let ex = exp x in (ex !>! 0) ==> log ex ?==?$ x where infix 4 ?==?$ (?==?$) :: (HasEqCertainlyAsymmetric a b, Show a, Show b) => a -> b -> Property (?==?$) = printArgsIfFails2 "?==?" (?==?) {- Instances for Integer, Rational etc need an algebraic real or exact real type. Such type is not provided in this package. See eg aern2-real. -}
1,058
true
true
0
25
364
456
228
228
null
null
tedkornish/stack
scripts/release/release.hs
bsd-3-clause
-- | Shake rules. rules :: Global -> [String] -> Rules () rules global@Global{..} args = do case args of [] -> error "No wanted target(s) specified." _ -> want args phony releasePhony $ do need [checkPhony] need [uploadPhony] phony cleanPhony $ removeFilesAfter releaseDir ["//*"] phony checkPhony $ need [releaseCheckDir </> binaryExeFileName] phony uploadPhony $ mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryFileNames phony buildPhony $ mapM_ (\f -> need [releaseDir </> f]) binaryFileNames forM_ distros $ \distro -> do phony (distroUploadPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro <.> uploadExt]) (distroVersions distro) phony (distroPackagesPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro]) (distroVersions distro) releaseDir </> "*" <.> uploadExt %> \out -> do need [dropExtension out] uploadToGithubRelease global (dropExtension out) copyFile' (dropExtension out) out releaseCheckDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] Stdout dirty <- cmd "git status --porcelain" when (not gAllowDirty && not (null (trim dirty))) $ error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") let instExeFile = installBinDir </> stackOrigExeFileName tmpExeFile = installBinDir </> stackOrigExeFileName <.> "tmp" --EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file. liftIO $ renameFile instExeFile tmpExeFile actionFinally (do opt <- addPath [installBinDir] [] () <- cmd opt stackProgName (stackArgs global) "build --pedantic --haddock --no-haddock-deps" () <- cmd opt stackProgName (stackArgs global) "clean" () <- cmd opt stackProgName (stackArgs global) "build" () <- cmd opt stackProgName (stackArgs global) "test --flag stack:integration-tests" return ()) (renameFile tmpExeFile instExeFile) copyFileChanged (installBinDir </> stackOrigExeFileName) out releaseDir </> binaryExeZipFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "zip " ++ (releaseDir </> binaryExeFileName) liftIO $ do entry <- Zip.readEntry [] (releaseDir </> binaryExeFileName) let entry' = entry{Zip.eRelativePath = binaryExeFileName} archive = Zip.addEntryToArchive entry' Zip.emptyArchive L8.writeFile out (Zip.fromArchive archive) releaseDir </> binaryExeTarGzFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "tar gzip " ++ (releaseDir </> binaryExeFileName) liftIO $ do content <- Tar.pack releaseDir [binaryExeFileName] L8.writeFile out $ GZip.compress $ Tar.write content releaseDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] case platformOS of Windows -> -- Windows doesn't have or need a 'strip' command, so skip it. liftIO $ copyFile (installBinDir </> stackOrigExeFileName) out Linux -> cmd "strip -p --strip-unneeded --remove-section=.comment -o" [out, installBinDir </> stackOrigExeFileName] _ -> cmd "strip -o" [out, installBinDir </> stackOrigExeFileName] releaseDir </> binaryExeCompressedAscFileName %> \out -> do need [out -<.> ""] _ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out) cmd "gpg --detach-sig --armor" [ "-u", gGpgKey , dropExtension out ] installBinDir </> stackOrigExeFileName %> \_ -> do alwaysRerun cmd stackProgName (stackArgs global) "build" forM_ distros $ \distro0 -> do distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 <.> uploadExt %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out need [dropExtension out] uploadPackage dvDistro dv (dropExtension out) copyFileChanged (dropExtension out) out distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out need [distroVersionDir dv </> imageIDFileName] liftIO $ createDirectoryIfMissing True (takeDirectory out) cmd "docker run --rm" [ "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-root" ++ ":/mnt/stack-root" , "--env=STACK_ROOT=/mnt/stack-root" , "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-work" ++ ":/mnt/src/.stack-work" , "--volume=" ++ gProjectRoot ++ ":/mnt/src" , "--workdir=/mnt/src" , "--volume=" ++ gProjectRoot </> distroVersionDir dv ++ ":/mnt/out" , "--env=OUTPUT_PKG=/mnt/out/" ++ distroPackageFileName dvDistro , "--env=PKG_VERSION=" ++ distroPackageVersionStr dvDistro , "--env=PKG_MAINTAINER=" ++ maintainer gStackPackageDescription , "--env=PKG_DESCRIPTION=" ++ synopsis gStackPackageDescription , "--env=PKG_LICENSE=" ++ display (license gStackPackageDescription) , "--env=PKG_URL=" ++ homepage gStackPackageDescription , distroVersionDockerImageTag dv ] distroVersionDir anyDistroVersion </> imageIDFileName %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out imageTag = distroVersionDockerImageTag dv need [ distroVersionDockerDir dv </> "Dockerfile" , distroVersionDockerDir dv </> "run.sh" ] _ <- buildDockerImage (distroVersionDockerDir dv) imageTag out return () distroVersionDockerDir anyDistroVersion </> "Dockerfile" %> \out -> do let DistroVersion{..} = distroVersionFromPath out template <- readTemplate (distroTemplateDir dvDistro </> "docker/Dockerfile") writeFileChanged out $ replace "<<DISTRO-VERSION>>" dvVersion $ replace "<<DISTRO>>" dvDistro template distroVersionDockerDir anyDistroVersion </> "run.sh" %> \out -> do let DistroVersion{..} = distroVersionFromPath out writeFileChanged out =<< readTemplate (distroTemplateDir dvDistro </> "docker/run.sh") where distroVersionFromPath path = case stripPrefix (releaseDir ++ "/") path of Nothing -> error ("Cannot determine Ubuntu version from path: " ++ path) Just path' -> DistroVersion (takeDirectory1 path') (takeDirectory1 (dropDirectory1 path')) readTemplate path = readFile' (takeDirectory gScriptPath </> "templates" </> path) releasePhony = "release" checkPhony = "check" uploadPhony = "upload" cleanPhony = "clean" buildPhony = "build" distroPackagesPhony distro = distro ++ "-packages" distroUploadPhony distro = distro ++ "-upload" releaseCheckDir = releaseDir </> "check" installBinDir = gLocalInstallRoot </> "bin" distroVersionDockerDir dv = distroVersionDir dv </> "docker" distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion binaryFileNames = [binaryExeCompressedFileName, binaryExeCompressedAscFileName] binaryExeCompressedAscFileName = binaryExeCompressedFileName <.> ascExt binaryExeCompressedFileName = case platformOS of Windows -> binaryExeZipFileName _ -> binaryExeTarGzFileName binaryExeZipFileName = binaryName global <.> zipExt binaryExeTarGzFileName = binaryName global <.> tarGzExt binaryExeFileName = stackOrigExeFileName stackOrigExeFileName = stackProgName <.> exe distroPackageFileName distro | distroPackageExt distro == debExt = concat [stackProgName, "_", distroPackageVersionStr distro, "_amd64"] <.> debExt | distroPackageExt distro == rpmExt = concat [stackProgName, "-", distroPackageVersionStr distro] <.> "x86_64" <.> rpmExt | distro == archDistro = concat [stackProgName, "_", distroPackageVersionStr distro, "-", "x86_64"] <.> tarGzExt | otherwise = error ("distroPackageFileName: unknown distro: " ++ distro) imageIDFileName = "image-id" zipExt = "zip" tarGzExt = tarExt <.> gzExt gzExt = "gz" tarExt = "tar" ascExt = "asc" uploadExt = "upload" debExt = "deb" rpmExt = "rpm" distroVersionDockerImageTag DistroVersion{..} = "stack_release_tool/" ++ dvDistro ++ ":" ++ dvVersion distroPackageVersionStr distro | distroPackageExt distro == debExt = concat [stackVersionStr global, "-", show gGitRevCount, "-", gGitSha] | distroPackageExt distro == rpmExt = concat [stackVersionStr global, "_", show gGitRevCount, "_", gGitSha] | distro == archDistro = stackVersionStr global | otherwise = error ("distroPackageVersionStr: unknown distro: " ++ distro) distroTemplateDir distro | distroPackageExt distro `elem` [debExt, rpmExt] = distroPackageExt distro | distro == archDistro = "arch" | otherwise = error ("distroTemplateDir: unknown distro: " ++ distro) distroPackageExt distro | distro `elem` [ubuntuDistro, debianDistro] = debExt | distro `elem` [centosDistro, fedoraDistro] = rpmExt | distro == archDistro = tarGzExt | otherwise = error ("distroPackageExt: unknown distro: " ++ distro) distroVersions distro | distro == ubuntuDistro = [ ("12.04", "precise") , ("14.04", "trusty") , ("14.10", "utopic") , ("15.04", "vivid") ] | distro == debianDistro = [ ("7", "wheezy") , ("8", "jessie") ] | distro == centosDistro = [ ("7", "7") , ("6", "6") ] | distro == fedoraDistro = [ ("21", "21") , ("22", "22") ] | distro == archDistro = [ ("current", "current") ] | otherwise = error ("distroVersions: unknown distro: " ++ distro) distroVersionCodeName DistroVersion{..} = fromMaybe ("distroVersionCodeName: unknown " ++ dvDistro ++ " version: " ++ dvVersion) (lookup dvVersion (distroVersions dvDistro)) distros = [ ubuntuDistro , debianDistro , centosDistro , fedoraDistro , archDistro ] ubuntuDistro = "ubuntu" debianDistro = "debian" centosDistro = "centos" fedoraDistro = "fedora" archDistro = "arch" anyDistroVersion = DistroVersion "*" "*" anyDistroVersion' distro = DistroVersion distro "*" uploadPackage :: String -> DistroVersion -> FilePath -> Action () uploadPackage distro dv@DistroVersion{..} pkgFile | distroPackageExt distro == debExt = cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions" [ "--sign=" ++ gGpgKey , "--prefix=" ++ dvDistro ++ "/" ++ distroVersionCodeName dv , pkgFile ] | distroPackageExt distro == rpmExt = do let rpmmacrosFile = gHomeDir </> ".rpmmacros" rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile when rpmmacrosExists $ error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.") actionFinally (do writeFileLines rpmmacrosFile [ "%_signature gpg" , "%_gpg_name " ++ gGpgKey ] cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com" [ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion , pkgFile ]) (liftIO $ removeFile rpmmacrosFile) | distro == archDistro = do () <- cmd "aws s3 cp" [ pkgFile , "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ] putNormal "WARNING: Arch package uploaded, but applying the AUR patch is a manual step." | otherwise = error ("uploadPackage: unknown distro: " ++ distro) -- | Upload file to Github release.
12,854
rules :: Global -> [String] -> Rules () rules global@Global{..} args = do case args of [] -> error "No wanted target(s) specified." _ -> want args phony releasePhony $ do need [checkPhony] need [uploadPhony] phony cleanPhony $ removeFilesAfter releaseDir ["//*"] phony checkPhony $ need [releaseCheckDir </> binaryExeFileName] phony uploadPhony $ mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryFileNames phony buildPhony $ mapM_ (\f -> need [releaseDir </> f]) binaryFileNames forM_ distros $ \distro -> do phony (distroUploadPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro <.> uploadExt]) (distroVersions distro) phony (distroPackagesPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro]) (distroVersions distro) releaseDir </> "*" <.> uploadExt %> \out -> do need [dropExtension out] uploadToGithubRelease global (dropExtension out) copyFile' (dropExtension out) out releaseCheckDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] Stdout dirty <- cmd "git status --porcelain" when (not gAllowDirty && not (null (trim dirty))) $ error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") let instExeFile = installBinDir </> stackOrigExeFileName tmpExeFile = installBinDir </> stackOrigExeFileName <.> "tmp" --EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file. liftIO $ renameFile instExeFile tmpExeFile actionFinally (do opt <- addPath [installBinDir] [] () <- cmd opt stackProgName (stackArgs global) "build --pedantic --haddock --no-haddock-deps" () <- cmd opt stackProgName (stackArgs global) "clean" () <- cmd opt stackProgName (stackArgs global) "build" () <- cmd opt stackProgName (stackArgs global) "test --flag stack:integration-tests" return ()) (renameFile tmpExeFile instExeFile) copyFileChanged (installBinDir </> stackOrigExeFileName) out releaseDir </> binaryExeZipFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "zip " ++ (releaseDir </> binaryExeFileName) liftIO $ do entry <- Zip.readEntry [] (releaseDir </> binaryExeFileName) let entry' = entry{Zip.eRelativePath = binaryExeFileName} archive = Zip.addEntryToArchive entry' Zip.emptyArchive L8.writeFile out (Zip.fromArchive archive) releaseDir </> binaryExeTarGzFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "tar gzip " ++ (releaseDir </> binaryExeFileName) liftIO $ do content <- Tar.pack releaseDir [binaryExeFileName] L8.writeFile out $ GZip.compress $ Tar.write content releaseDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] case platformOS of Windows -> -- Windows doesn't have or need a 'strip' command, so skip it. liftIO $ copyFile (installBinDir </> stackOrigExeFileName) out Linux -> cmd "strip -p --strip-unneeded --remove-section=.comment -o" [out, installBinDir </> stackOrigExeFileName] _ -> cmd "strip -o" [out, installBinDir </> stackOrigExeFileName] releaseDir </> binaryExeCompressedAscFileName %> \out -> do need [out -<.> ""] _ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out) cmd "gpg --detach-sig --armor" [ "-u", gGpgKey , dropExtension out ] installBinDir </> stackOrigExeFileName %> \_ -> do alwaysRerun cmd stackProgName (stackArgs global) "build" forM_ distros $ \distro0 -> do distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 <.> uploadExt %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out need [dropExtension out] uploadPackage dvDistro dv (dropExtension out) copyFileChanged (dropExtension out) out distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out need [distroVersionDir dv </> imageIDFileName] liftIO $ createDirectoryIfMissing True (takeDirectory out) cmd "docker run --rm" [ "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-root" ++ ":/mnt/stack-root" , "--env=STACK_ROOT=/mnt/stack-root" , "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-work" ++ ":/mnt/src/.stack-work" , "--volume=" ++ gProjectRoot ++ ":/mnt/src" , "--workdir=/mnt/src" , "--volume=" ++ gProjectRoot </> distroVersionDir dv ++ ":/mnt/out" , "--env=OUTPUT_PKG=/mnt/out/" ++ distroPackageFileName dvDistro , "--env=PKG_VERSION=" ++ distroPackageVersionStr dvDistro , "--env=PKG_MAINTAINER=" ++ maintainer gStackPackageDescription , "--env=PKG_DESCRIPTION=" ++ synopsis gStackPackageDescription , "--env=PKG_LICENSE=" ++ display (license gStackPackageDescription) , "--env=PKG_URL=" ++ homepage gStackPackageDescription , distroVersionDockerImageTag dv ] distroVersionDir anyDistroVersion </> imageIDFileName %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out imageTag = distroVersionDockerImageTag dv need [ distroVersionDockerDir dv </> "Dockerfile" , distroVersionDockerDir dv </> "run.sh" ] _ <- buildDockerImage (distroVersionDockerDir dv) imageTag out return () distroVersionDockerDir anyDistroVersion </> "Dockerfile" %> \out -> do let DistroVersion{..} = distroVersionFromPath out template <- readTemplate (distroTemplateDir dvDistro </> "docker/Dockerfile") writeFileChanged out $ replace "<<DISTRO-VERSION>>" dvVersion $ replace "<<DISTRO>>" dvDistro template distroVersionDockerDir anyDistroVersion </> "run.sh" %> \out -> do let DistroVersion{..} = distroVersionFromPath out writeFileChanged out =<< readTemplate (distroTemplateDir dvDistro </> "docker/run.sh") where distroVersionFromPath path = case stripPrefix (releaseDir ++ "/") path of Nothing -> error ("Cannot determine Ubuntu version from path: " ++ path) Just path' -> DistroVersion (takeDirectory1 path') (takeDirectory1 (dropDirectory1 path')) readTemplate path = readFile' (takeDirectory gScriptPath </> "templates" </> path) releasePhony = "release" checkPhony = "check" uploadPhony = "upload" cleanPhony = "clean" buildPhony = "build" distroPackagesPhony distro = distro ++ "-packages" distroUploadPhony distro = distro ++ "-upload" releaseCheckDir = releaseDir </> "check" installBinDir = gLocalInstallRoot </> "bin" distroVersionDockerDir dv = distroVersionDir dv </> "docker" distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion binaryFileNames = [binaryExeCompressedFileName, binaryExeCompressedAscFileName] binaryExeCompressedAscFileName = binaryExeCompressedFileName <.> ascExt binaryExeCompressedFileName = case platformOS of Windows -> binaryExeZipFileName _ -> binaryExeTarGzFileName binaryExeZipFileName = binaryName global <.> zipExt binaryExeTarGzFileName = binaryName global <.> tarGzExt binaryExeFileName = stackOrigExeFileName stackOrigExeFileName = stackProgName <.> exe distroPackageFileName distro | distroPackageExt distro == debExt = concat [stackProgName, "_", distroPackageVersionStr distro, "_amd64"] <.> debExt | distroPackageExt distro == rpmExt = concat [stackProgName, "-", distroPackageVersionStr distro] <.> "x86_64" <.> rpmExt | distro == archDistro = concat [stackProgName, "_", distroPackageVersionStr distro, "-", "x86_64"] <.> tarGzExt | otherwise = error ("distroPackageFileName: unknown distro: " ++ distro) imageIDFileName = "image-id" zipExt = "zip" tarGzExt = tarExt <.> gzExt gzExt = "gz" tarExt = "tar" ascExt = "asc" uploadExt = "upload" debExt = "deb" rpmExt = "rpm" distroVersionDockerImageTag DistroVersion{..} = "stack_release_tool/" ++ dvDistro ++ ":" ++ dvVersion distroPackageVersionStr distro | distroPackageExt distro == debExt = concat [stackVersionStr global, "-", show gGitRevCount, "-", gGitSha] | distroPackageExt distro == rpmExt = concat [stackVersionStr global, "_", show gGitRevCount, "_", gGitSha] | distro == archDistro = stackVersionStr global | otherwise = error ("distroPackageVersionStr: unknown distro: " ++ distro) distroTemplateDir distro | distroPackageExt distro `elem` [debExt, rpmExt] = distroPackageExt distro | distro == archDistro = "arch" | otherwise = error ("distroTemplateDir: unknown distro: " ++ distro) distroPackageExt distro | distro `elem` [ubuntuDistro, debianDistro] = debExt | distro `elem` [centosDistro, fedoraDistro] = rpmExt | distro == archDistro = tarGzExt | otherwise = error ("distroPackageExt: unknown distro: " ++ distro) distroVersions distro | distro == ubuntuDistro = [ ("12.04", "precise") , ("14.04", "trusty") , ("14.10", "utopic") , ("15.04", "vivid") ] | distro == debianDistro = [ ("7", "wheezy") , ("8", "jessie") ] | distro == centosDistro = [ ("7", "7") , ("6", "6") ] | distro == fedoraDistro = [ ("21", "21") , ("22", "22") ] | distro == archDistro = [ ("current", "current") ] | otherwise = error ("distroVersions: unknown distro: " ++ distro) distroVersionCodeName DistroVersion{..} = fromMaybe ("distroVersionCodeName: unknown " ++ dvDistro ++ " version: " ++ dvVersion) (lookup dvVersion (distroVersions dvDistro)) distros = [ ubuntuDistro , debianDistro , centosDistro , fedoraDistro , archDistro ] ubuntuDistro = "ubuntu" debianDistro = "debian" centosDistro = "centos" fedoraDistro = "fedora" archDistro = "arch" anyDistroVersion = DistroVersion "*" "*" anyDistroVersion' distro = DistroVersion distro "*" uploadPackage :: String -> DistroVersion -> FilePath -> Action () uploadPackage distro dv@DistroVersion{..} pkgFile | distroPackageExt distro == debExt = cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions" [ "--sign=" ++ gGpgKey , "--prefix=" ++ dvDistro ++ "/" ++ distroVersionCodeName dv , pkgFile ] | distroPackageExt distro == rpmExt = do let rpmmacrosFile = gHomeDir </> ".rpmmacros" rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile when rpmmacrosExists $ error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.") actionFinally (do writeFileLines rpmmacrosFile [ "%_signature gpg" , "%_gpg_name " ++ gGpgKey ] cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com" [ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion , pkgFile ]) (liftIO $ removeFile rpmmacrosFile) | distro == archDistro = do () <- cmd "aws s3 cp" [ pkgFile , "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ] putNormal "WARNING: Arch package uploaded, but applying the AUR patch is a manual step." | otherwise = error ("uploadPackage: unknown distro: " ++ distro) -- | Upload file to Github release.
12,836
rules global@Global{..} args = do case args of [] -> error "No wanted target(s) specified." _ -> want args phony releasePhony $ do need [checkPhony] need [uploadPhony] phony cleanPhony $ removeFilesAfter releaseDir ["//*"] phony checkPhony $ need [releaseCheckDir </> binaryExeFileName] phony uploadPhony $ mapM_ (\f -> need [releaseDir </> f <.> uploadExt]) binaryFileNames phony buildPhony $ mapM_ (\f -> need [releaseDir </> f]) binaryFileNames forM_ distros $ \distro -> do phony (distroUploadPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro <.> uploadExt]) (distroVersions distro) phony (distroPackagesPhony distro) $ mapM_ (\v -> need [distroVersionDir (DistroVersion distro (fst v)) </> distroPackageFileName distro]) (distroVersions distro) releaseDir </> "*" <.> uploadExt %> \out -> do need [dropExtension out] uploadToGithubRelease global (dropExtension out) copyFile' (dropExtension out) out releaseCheckDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] Stdout dirty <- cmd "git status --porcelain" when (not gAllowDirty && not (null (trim dirty))) $ error ("Working tree is dirty. Use --" ++ allowDirtyOptName ++ " option to continue anyway.") let instExeFile = installBinDir </> stackOrigExeFileName tmpExeFile = installBinDir </> stackOrigExeFileName <.> "tmp" --EKB FIXME: once 'stack install --path' implemented, use it instead of this temp file. liftIO $ renameFile instExeFile tmpExeFile actionFinally (do opt <- addPath [installBinDir] [] () <- cmd opt stackProgName (stackArgs global) "build --pedantic --haddock --no-haddock-deps" () <- cmd opt stackProgName (stackArgs global) "clean" () <- cmd opt stackProgName (stackArgs global) "build" () <- cmd opt stackProgName (stackArgs global) "test --flag stack:integration-tests" return ()) (renameFile tmpExeFile instExeFile) copyFileChanged (installBinDir </> stackOrigExeFileName) out releaseDir </> binaryExeZipFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "zip " ++ (releaseDir </> binaryExeFileName) liftIO $ do entry <- Zip.readEntry [] (releaseDir </> binaryExeFileName) let entry' = entry{Zip.eRelativePath = binaryExeFileName} archive = Zip.addEntryToArchive entry' Zip.emptyArchive L8.writeFile out (Zip.fromArchive archive) releaseDir </> binaryExeTarGzFileName %> \out -> do need [releaseDir </> binaryExeFileName] putNormal $ "tar gzip " ++ (releaseDir </> binaryExeFileName) liftIO $ do content <- Tar.pack releaseDir [binaryExeFileName] L8.writeFile out $ GZip.compress $ Tar.write content releaseDir </> binaryExeFileName %> \out -> do need [installBinDir </> stackOrigExeFileName] case platformOS of Windows -> -- Windows doesn't have or need a 'strip' command, so skip it. liftIO $ copyFile (installBinDir </> stackOrigExeFileName) out Linux -> cmd "strip -p --strip-unneeded --remove-section=.comment -o" [out, installBinDir </> stackOrigExeFileName] _ -> cmd "strip -o" [out, installBinDir </> stackOrigExeFileName] releaseDir </> binaryExeCompressedAscFileName %> \out -> do need [out -<.> ""] _ <- liftIO $ tryJust (guard . isDoesNotExistError) (removeFile out) cmd "gpg --detach-sig --armor" [ "-u", gGpgKey , dropExtension out ] installBinDir </> stackOrigExeFileName %> \_ -> do alwaysRerun cmd stackProgName (stackArgs global) "build" forM_ distros $ \distro0 -> do distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 <.> uploadExt %> \out -> do let dv@DistroVersion{..} = distroVersionFromPath out need [dropExtension out] uploadPackage dvDistro dv (dropExtension out) copyFileChanged (dropExtension out) out distroVersionDir (anyDistroVersion' distro0) </> distroPackageFileName distro0 %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out need [distroVersionDir dv </> imageIDFileName] liftIO $ createDirectoryIfMissing True (takeDirectory out) cmd "docker run --rm" [ "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-root" ++ ":/mnt/stack-root" , "--env=STACK_ROOT=/mnt/stack-root" , "--volume=" ++ gProjectRoot </> distroVersionDir dv </> "stack-work" ++ ":/mnt/src/.stack-work" , "--volume=" ++ gProjectRoot ++ ":/mnt/src" , "--workdir=/mnt/src" , "--volume=" ++ gProjectRoot </> distroVersionDir dv ++ ":/mnt/out" , "--env=OUTPUT_PKG=/mnt/out/" ++ distroPackageFileName dvDistro , "--env=PKG_VERSION=" ++ distroPackageVersionStr dvDistro , "--env=PKG_MAINTAINER=" ++ maintainer gStackPackageDescription , "--env=PKG_DESCRIPTION=" ++ synopsis gStackPackageDescription , "--env=PKG_LICENSE=" ++ display (license gStackPackageDescription) , "--env=PKG_URL=" ++ homepage gStackPackageDescription , distroVersionDockerImageTag dv ] distroVersionDir anyDistroVersion </> imageIDFileName %> \out -> do alwaysRerun let dv@DistroVersion{..} = distroVersionFromPath out imageTag = distroVersionDockerImageTag dv need [ distroVersionDockerDir dv </> "Dockerfile" , distroVersionDockerDir dv </> "run.sh" ] _ <- buildDockerImage (distroVersionDockerDir dv) imageTag out return () distroVersionDockerDir anyDistroVersion </> "Dockerfile" %> \out -> do let DistroVersion{..} = distroVersionFromPath out template <- readTemplate (distroTemplateDir dvDistro </> "docker/Dockerfile") writeFileChanged out $ replace "<<DISTRO-VERSION>>" dvVersion $ replace "<<DISTRO>>" dvDistro template distroVersionDockerDir anyDistroVersion </> "run.sh" %> \out -> do let DistroVersion{..} = distroVersionFromPath out writeFileChanged out =<< readTemplate (distroTemplateDir dvDistro </> "docker/run.sh") where distroVersionFromPath path = case stripPrefix (releaseDir ++ "/") path of Nothing -> error ("Cannot determine Ubuntu version from path: " ++ path) Just path' -> DistroVersion (takeDirectory1 path') (takeDirectory1 (dropDirectory1 path')) readTemplate path = readFile' (takeDirectory gScriptPath </> "templates" </> path) releasePhony = "release" checkPhony = "check" uploadPhony = "upload" cleanPhony = "clean" buildPhony = "build" distroPackagesPhony distro = distro ++ "-packages" distroUploadPhony distro = distro ++ "-upload" releaseCheckDir = releaseDir </> "check" installBinDir = gLocalInstallRoot </> "bin" distroVersionDockerDir dv = distroVersionDir dv </> "docker" distroVersionDir DistroVersion{..} = releaseDir </> dvDistro </> dvVersion binaryFileNames = [binaryExeCompressedFileName, binaryExeCompressedAscFileName] binaryExeCompressedAscFileName = binaryExeCompressedFileName <.> ascExt binaryExeCompressedFileName = case platformOS of Windows -> binaryExeZipFileName _ -> binaryExeTarGzFileName binaryExeZipFileName = binaryName global <.> zipExt binaryExeTarGzFileName = binaryName global <.> tarGzExt binaryExeFileName = stackOrigExeFileName stackOrigExeFileName = stackProgName <.> exe distroPackageFileName distro | distroPackageExt distro == debExt = concat [stackProgName, "_", distroPackageVersionStr distro, "_amd64"] <.> debExt | distroPackageExt distro == rpmExt = concat [stackProgName, "-", distroPackageVersionStr distro] <.> "x86_64" <.> rpmExt | distro == archDistro = concat [stackProgName, "_", distroPackageVersionStr distro, "-", "x86_64"] <.> tarGzExt | otherwise = error ("distroPackageFileName: unknown distro: " ++ distro) imageIDFileName = "image-id" zipExt = "zip" tarGzExt = tarExt <.> gzExt gzExt = "gz" tarExt = "tar" ascExt = "asc" uploadExt = "upload" debExt = "deb" rpmExt = "rpm" distroVersionDockerImageTag DistroVersion{..} = "stack_release_tool/" ++ dvDistro ++ ":" ++ dvVersion distroPackageVersionStr distro | distroPackageExt distro == debExt = concat [stackVersionStr global, "-", show gGitRevCount, "-", gGitSha] | distroPackageExt distro == rpmExt = concat [stackVersionStr global, "_", show gGitRevCount, "_", gGitSha] | distro == archDistro = stackVersionStr global | otherwise = error ("distroPackageVersionStr: unknown distro: " ++ distro) distroTemplateDir distro | distroPackageExt distro `elem` [debExt, rpmExt] = distroPackageExt distro | distro == archDistro = "arch" | otherwise = error ("distroTemplateDir: unknown distro: " ++ distro) distroPackageExt distro | distro `elem` [ubuntuDistro, debianDistro] = debExt | distro `elem` [centosDistro, fedoraDistro] = rpmExt | distro == archDistro = tarGzExt | otherwise = error ("distroPackageExt: unknown distro: " ++ distro) distroVersions distro | distro == ubuntuDistro = [ ("12.04", "precise") , ("14.04", "trusty") , ("14.10", "utopic") , ("15.04", "vivid") ] | distro == debianDistro = [ ("7", "wheezy") , ("8", "jessie") ] | distro == centosDistro = [ ("7", "7") , ("6", "6") ] | distro == fedoraDistro = [ ("21", "21") , ("22", "22") ] | distro == archDistro = [ ("current", "current") ] | otherwise = error ("distroVersions: unknown distro: " ++ distro) distroVersionCodeName DistroVersion{..} = fromMaybe ("distroVersionCodeName: unknown " ++ dvDistro ++ " version: " ++ dvVersion) (lookup dvVersion (distroVersions dvDistro)) distros = [ ubuntuDistro , debianDistro , centosDistro , fedoraDistro , archDistro ] ubuntuDistro = "ubuntu" debianDistro = "debian" centosDistro = "centos" fedoraDistro = "fedora" archDistro = "arch" anyDistroVersion = DistroVersion "*" "*" anyDistroVersion' distro = DistroVersion distro "*" uploadPackage :: String -> DistroVersion -> FilePath -> Action () uploadPackage distro dv@DistroVersion{..} pkgFile | distroPackageExt distro == debExt = cmd "deb-s3 upload -b download.fpcomplete.com --preserve-versions" [ "--sign=" ++ gGpgKey , "--prefix=" ++ dvDistro ++ "/" ++ distroVersionCodeName dv , pkgFile ] | distroPackageExt distro == rpmExt = do let rpmmacrosFile = gHomeDir </> ".rpmmacros" rpmmacrosExists <- liftIO $ System.Directory.doesFileExist rpmmacrosFile when rpmmacrosExists $ error ("'" ++ rpmmacrosFile ++ "' already exists. Move it out of the way first.") actionFinally (do writeFileLines rpmmacrosFile [ "%_signature gpg" , "%_gpg_name " ++ gGpgKey ] cmd "rpm-s3 --verbose --sign --bucket=download.fpcomplete.com" [ "--repopath=" ++ dvDistro ++ "/" ++ dvVersion , pkgFile ]) (liftIO $ removeFile rpmmacrosFile) | distro == archDistro = do () <- cmd "aws s3 cp" [ pkgFile , "s3://download.fpcomplete.com/archlinux/" ++ takeFileName pkgFile ] putNormal "WARNING: Arch package uploaded, but applying the AUR patch is a manual step." | otherwise = error ("uploadPackage: unknown distro: " ++ distro) -- | Upload file to Github release.
12,796
true
true
0
23
3,722
3,097
1,515
1,582
null
null
urbanslug/ghc
compiler/rename/RnBinds.hs
bsd-3-clause
-- {-# SPECIALISE #-} pragmas can refer to imported Ids -- so, in the top-level case (when mb_names is Nothing) -- we use lookupOccRn. If there's both an imported and a local 'f' -- then the SPECIALISE pragma is ambiguous, unlike all other signatures renameSig ctxt sig@(SpecSig v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys ; return (SpecSig new_v new_ty inl, fvs) } where do_one (tys,fvs) ty = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty ; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
770
renameSig ctxt sig@(SpecSig v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys ; return (SpecSig new_v new_ty inl, fvs) } where do_one (tys,fvs) ty = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty ; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
518
renameSig ctxt sig@(SpecSig v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys ; return (SpecSig new_v new_ty inl, fvs) } where do_one (tys,fvs) ty = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty ; return ( new_ty:tys, fvs_ty `plusFV` fvs) }
518
true
false
0
12
222
190
102
88
null
null
rwtodd/small_programs
i_ching/haskell/iching.hs
gpl-2.0
disphex :: (Arr.Array Int [String]) -> Hexagram -> IO () disphex descs hex = do disp_lines hex disp_trigrams hex disp_desc $ descs Arr.! (hex_king_wen hex) -- control stuff
185
disphex :: (Arr.Array Int [String]) -> Hexagram -> IO () disphex descs hex = do disp_lines hex disp_trigrams hex disp_desc $ descs Arr.! (hex_king_wen hex) -- control stuff
185
disphex descs hex = do disp_lines hex disp_trigrams hex disp_desc $ descs Arr.! (hex_king_wen hex) -- control stuff
128
false
true
0
9
40
74
35
39
null
null
xkollar/handy-haskell
other/pt-2012-09/main.hs
gpl-3.0
ppList :: Show a => [a] -> IO () ppList = putStr . unlines . map show
69
ppList :: Show a => [a] -> IO () ppList = putStr . unlines . map show
69
ppList = putStr . unlines . map show
36
false
true
2
9
16
49
21
28
null
null
jystic/river
src/River/X64/Pretty.hs
bsd-3-clause
------------------------------------------------------------------------ displayProgram :: Decoration -> [Instruction] -> String displayProgram decoration instructions = let c0main = Label $ Name "__c0_main" doc = Pretty.renderPretty 0.8 80 $ vcat [ annotate AnnKeyword (text ".globl") <+> ppLabel c0main , empty , ppLabel c0main <> text ":" , ppProgram instructions ] put attr str = case decoration of Color -> sgrAttr attr ++ str ++ sgrReset NoColor -> str sgrReset = setSGRCode [Reset] sgrAttr = \case AnnImmediate -> setSGRCode [SetColor Foreground Dull Red] AnnRegister -> setSGRCode [SetColor Foreground Dull Magenta] AnnInstruction -> setSGRCode [SetColor Foreground Dull Cyan] AnnLabel -> setSGRCode [SetColor Foreground Dull Yellow] AnnKeyword -> setSGRCode [SetColor Foreground Dull Blue] in Pretty.displayDecorated put doc
1,046
displayProgram :: Decoration -> [Instruction] -> String displayProgram decoration instructions = let c0main = Label $ Name "__c0_main" doc = Pretty.renderPretty 0.8 80 $ vcat [ annotate AnnKeyword (text ".globl") <+> ppLabel c0main , empty , ppLabel c0main <> text ":" , ppProgram instructions ] put attr str = case decoration of Color -> sgrAttr attr ++ str ++ sgrReset NoColor -> str sgrReset = setSGRCode [Reset] sgrAttr = \case AnnImmediate -> setSGRCode [SetColor Foreground Dull Red] AnnRegister -> setSGRCode [SetColor Foreground Dull Magenta] AnnInstruction -> setSGRCode [SetColor Foreground Dull Cyan] AnnLabel -> setSGRCode [SetColor Foreground Dull Yellow] AnnKeyword -> setSGRCode [SetColor Foreground Dull Blue] in Pretty.displayDecorated put doc
972
displayProgram decoration instructions = let c0main = Label $ Name "__c0_main" doc = Pretty.renderPretty 0.8 80 $ vcat [ annotate AnnKeyword (text ".globl") <+> ppLabel c0main , empty , ppLabel c0main <> text ":" , ppProgram instructions ] put attr str = case decoration of Color -> sgrAttr attr ++ str ++ sgrReset NoColor -> str sgrReset = setSGRCode [Reset] sgrAttr = \case AnnImmediate -> setSGRCode [SetColor Foreground Dull Red] AnnRegister -> setSGRCode [SetColor Foreground Dull Magenta] AnnInstruction -> setSGRCode [SetColor Foreground Dull Cyan] AnnLabel -> setSGRCode [SetColor Foreground Dull Yellow] AnnKeyword -> setSGRCode [SetColor Foreground Dull Blue] in Pretty.displayDecorated put doc
916
true
true
0
15
322
265
129
136
null
null
lenary/Idris-dev
src/Idris/Core/TT.hs
bsd-3-clause
constDocs c@(AType (ATInt (ITFixed IT64))) = "Sixty-four bits (unsigned)"
73
constDocs c@(AType (ATInt (ITFixed IT64))) = "Sixty-four bits (unsigned)"
73
constDocs c@(AType (ATInt (ITFixed IT64))) = "Sixty-four bits (unsigned)"
73
false
false
0
12
8
30
15
15
null
null
evansb/jasper
src/Language/Java/Parser/Core.hs
mit
isLParen _ = False
18
isLParen _ = False
18
isLParen _ = False
18
false
false
0
4
3
10
4
6
null
null
alexander-at-github/eta
compiler/ETA/Main/HscMain.hs
bsd-3-clause
hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey]) hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) | otherwise -> return (Just $ modulePackageKey m, pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageKey m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails dflags (modulePackageKey m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m #ifdef GHCI -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' #else return iface #endif isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageKey m = True | otherwise = False -- | Check the list of packages are trusted.
4,050
hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageKey, [PackageKey]) hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) | otherwise -> return (Just $ modulePackageKey m, pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageKey m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails dflags (modulePackageKey m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m #ifdef GHCI -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' #else return iface #endif isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageKey m = True | otherwise = False -- | Check the list of packages are trusted.
4,050
hscCheckSafe' dflags m l = do (tw, pkgs) <- isModSafe m l case tw of False -> return (Nothing, pkgs) True | isHomePkg m -> return (Nothing, pkgs) | otherwise -> return (Just $ modulePackageKey m, pkgs) where isModSafe :: Module -> SrcSpan -> Hsc (Bool, [PackageKey]) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg dflags l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m -- pkg trust reqs pkgRs = map fst $ filter snd $ dep_pkgs $ mi_deps iface' -- General errors we throw but Safe errors we log errs = case (safeM, safeP) of (True, True ) -> emptyBag (True, False) -> pkgTrustErr (False, _ ) -> modTrustErr in do logWarnings errs return (trust == Sf_Trustworthy, pkgRs) where pkgTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageKey m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkErrMsg dflags l (pkgQual dflags) $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted Sf_None _ _ = False -- shouldn't hit these cases packageTrusted Sf_Unsafe _ _ = False -- prefer for completeness. packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails dflags (modulePackageKey m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m #ifdef GHCI -- the 'lookupIfaceByModule' method will always fail when calling from GHCi -- as the compiler hasn't filled in the various module tables -- so we need to call 'getModuleInterface' to load from disk iface' <- case iface of Just _ -> return iface Nothing -> snd `fmap` (liftIO $ getModuleInterface hsc_env m) return iface' #else return iface #endif isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageKey m = True | otherwise = False -- | Check the list of packages are trusted.
3,963
false
true
3
19
1,592
868
422
446
null
null
rprospero/NeutronPipe
tests/Properties.hs
mit
mean :: [Double] -> Double mean xs = sum xs / (fromIntegral $ length xs)
72
mean :: [Double] -> Double mean xs = sum xs / (fromIntegral $ length xs)
72
mean xs = sum xs / (fromIntegral $ length xs)
45
false
true
0
8
14
38
19
19
null
null
brendanhay/gogol
gogol-serviceuser/gen/Network/Google/ServiceUser/Types/Product.hs
mpl-2.0
-- | Creates a value of 'EnumValue' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'evName' -- -- * 'evOptions' -- -- * 'evNumber' enumValue :: EnumValue enumValue = EnumValue' {_evName = Nothing, _evOptions = Nothing, _evNumber = Nothing}
331
enumValue :: EnumValue enumValue = EnumValue' {_evName = Nothing, _evOptions = Nothing, _evNumber = Nothing}
114
enumValue = EnumValue' {_evName = Nothing, _evOptions = Nothing, _evNumber = Nothing}
87
true
true
0
6
62
40
28
12
null
null
ndmitchell/tagsoup
test/TagSoup/Generate/Type.hs
bsd-3-clause
fromRedex (RCase x xs) = eCase (EVar x) (map (second fromRedex) xs)
67
fromRedex (RCase x xs) = eCase (EVar x) (map (second fromRedex) xs)
67
fromRedex (RCase x xs) = eCase (EVar x) (map (second fromRedex) xs)
67
false
false
0
9
11
42
20
22
null
null
michaelt/streaming-bytestring
bench/benchbuilders.hs
bsd-3-clause
renderCellTB :: Cell -> TB.Builder renderCellTB (StringC cs) = renderStringTB cs
80
renderCellTB :: Cell -> TB.Builder renderCellTB (StringC cs) = renderStringTB cs
80
renderCellTB (StringC cs) = renderStringTB cs
45
false
true
0
7
10
29
14
15
null
null
mcmaniac/ghc
compiler/nativeGen/X86/Regs.hs
bsd-3-clause
globalRegMaybe Hp = Just (RealRegSingle REG_Hp)
69
globalRegMaybe Hp = Just (RealRegSingle REG_Hp)
69
globalRegMaybe Hp = Just (RealRegSingle REG_Hp)
69
false
false
0
7
27
19
8
11
null
null
anton-k/language-css
src/Language/Css/Build/Idents.hs
bsd-3-clause
-- | medium medium :: Idents a => a medium = ident "medium"
59
medium :: Idents a => a medium = ident "medium"
47
medium = ident "medium"
23
true
true
0
7
12
28
12
16
null
null
sgillespie/ghc
compiler/stgSyn/StgLint.hs
bsd-3-clause
checkFunApp :: Type -- The function type -> [Type] -- The arg type(s) -> MsgDoc -- Error message -> LintM (Maybe Type) -- Just ty => result type is accurate checkFunApp fun_ty arg_tys msg = do { case mb_msg of Just msg -> addErrL msg Nothing -> return () ; return mb_ty } where (mb_ty, mb_msg) = cfa True fun_ty arg_tys cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result? , Maybe MsgDoc) -- Errors? cfa accurate fun_ty [] -- Args have run out; that's fine = (if accurate then Just fun_ty else Nothing, Nothing) cfa accurate fun_ty arg_tys@(arg_ty':arg_tys') | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty = if accurate && not (arg_ty `stgEqType` arg_ty') then (Nothing, Just msg) -- Arg type mismatch else cfa accurate res_ty arg_tys' | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty = cfa False fun_ty' arg_tys | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty , isNewTyCon tc = if length tc_args < tyConArity tc then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg ) (Nothing, Nothing) -- This is odd, but I've seen it else cfa False (newTyConInstRhs tc tc_args) arg_tys | Just tc <- tyConAppTyCon_maybe fun_ty , not (isTypeFamilyTyCon tc) -- Definite error = (Nothing, Just msg) -- Too many args | otherwise = (Nothing, Nothing)
1,596
checkFunApp :: Type -- The function type -> [Type] -- The arg type(s) -> MsgDoc -- Error message -> LintM (Maybe Type) checkFunApp fun_ty arg_tys msg = do { case mb_msg of Just msg -> addErrL msg Nothing -> return () ; return mb_ty } where (mb_ty, mb_msg) = cfa True fun_ty arg_tys cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result? , Maybe MsgDoc) -- Errors? cfa accurate fun_ty [] -- Args have run out; that's fine = (if accurate then Just fun_ty else Nothing, Nothing) cfa accurate fun_ty arg_tys@(arg_ty':arg_tys') | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty = if accurate && not (arg_ty `stgEqType` arg_ty') then (Nothing, Just msg) -- Arg type mismatch else cfa accurate res_ty arg_tys' | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty = cfa False fun_ty' arg_tys | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty , isNewTyCon tc = if length tc_args < tyConArity tc then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg ) (Nothing, Nothing) -- This is odd, but I've seen it else cfa False (newTyConInstRhs tc tc_args) arg_tys | Just tc <- tyConAppTyCon_maybe fun_ty , not (isTypeFamilyTyCon tc) -- Definite error = (Nothing, Just msg) -- Too many args | otherwise = (Nothing, Nothing)
1,555
checkFunApp fun_ty arg_tys msg = do { case mb_msg of Just msg -> addErrL msg Nothing -> return () ; return mb_ty } where (mb_ty, mb_msg) = cfa True fun_ty arg_tys cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result? , Maybe MsgDoc) -- Errors? cfa accurate fun_ty [] -- Args have run out; that's fine = (if accurate then Just fun_ty else Nothing, Nothing) cfa accurate fun_ty arg_tys@(arg_ty':arg_tys') | Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty = if accurate && not (arg_ty `stgEqType` arg_ty') then (Nothing, Just msg) -- Arg type mismatch else cfa accurate res_ty arg_tys' | Just (_, fun_ty') <- splitForAllTy_maybe fun_ty = cfa False fun_ty' arg_tys | Just (tc,tc_args) <- splitTyConApp_maybe fun_ty , isNewTyCon tc = if length tc_args < tyConArity tc then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg ) (Nothing, Nothing) -- This is odd, but I've seen it else cfa False (newTyConInstRhs tc tc_args) arg_tys | Just tc <- tyConAppTyCon_maybe fun_ty , not (isTypeFamilyTyCon tc) -- Definite error = (Nothing, Just msg) -- Too many args | otherwise = (Nothing, Nothing)
1,356
true
true
0
11
543
463
232
231
null
null
vTurbine/ghc
compiler/specialise/Rules.hs
bsd-3-clause
match_ty :: RuleMatchEnv -> RuleSubst -> Type -- Template -> Type -- Target -> Maybe RuleSubst -- Matching Core types: use the matcher in TcType. -- Notice that we treat newtypes as opaque. For example, suppose -- we have a specialised version of a function at a newtype, say -- newtype T = MkT Int -- We only want to replace (f T) with f', not (f Int). match_ty renv subst ty1 ty2 = do { tv_subst' <- Unify.ruleMatchTyX (rv_tmpls renv) (rv_lcl renv) tv_subst ty1 ty2 ; return (subst { rs_tv_subst = tv_subst' }) } where tv_subst = rs_tv_subst subst {- Note [Expanding variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is another Very Important rule: if the term being matched is a variable, we expand it so long as its unfolding is "expandable". (Its occurrence information is not necessarily up to date, so we don't use it.) By "expandable" we mean a WHNF or a "constructor-like" application. This is the key reason for "constructor-like" Ids. If we have {-# NOINLINE [1] CONLIKE g #-} {-# RULE f (g x) = h x #-} then in the term let v = g 3 in ....(f v).... we want to make the rule fire, to replace (f v) with (h 3). Note [Do not expand locally-bound variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do *not* expand locally-bound variables, else there's a worry that the unfolding might mention variables that are themselves renamed. Example case x of y { (p,q) -> ...y... } Don't expand 'y' to (p,q) because p,q might themselves have been renamed. Essentially we only expand unfoldings that are "outside" the entire match. Hence, (a) the guard (not (isLocallyBoundR v2)) (b) when we expand we nuke the renaming envt (nukeRnEnvR). Note [Tick annotations in RULE matching] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to unconditionally look through Notes in both template and expression being matched. This is actually illegal for counting or cost-centre-scoped ticks, because we have no place to put them without changing entry counts and/or costs. So now we just fail the match in these cases. On the other hand, where we are allowed to insert new cost into the tick scope, we can float them upwards to the rule application site. cf Note [Notes in call patterns] in SpecConstr Note [Matching lets] ~~~~~~~~~~~~~~~~~~~~ Matching a let-expression. Consider RULE forall x. f (g x) = <rhs> and target expression f (let { w=R } in g E)) Then we'd like the rule to match, to generate let { w=R } in (\x. <rhs>) E In effect, we want to float the let-binding outward, to enable the match to happen. This is the WHOLE REASON for accumulating bindings in the RuleSubst We can only do this if the free variables of R are not bound by the part of the target expression outside the let binding; e.g. f (\v. let w = v+1 in g E) Here we obviously cannot float the let-binding for w. Hence the use of okToFloat. There are a couple of tricky points. (a) What if floating the binding captures a variable? f (let v = x+1 in v) v --> NOT! let v = x+1 in f (x+1) v (b) What if two non-nested let bindings bind the same variable? f (let v = e1 in b1) (let v = e2 in b2) --> NOT! let v = e1 in let v = e2 in (f b2 b2) See testsuite test "RuleFloatLet". Our cunning plan is this: * Along with the growing substitution for template variables we maintain a growing set of floated let-bindings (rs_binds) plus the set of variables thus bound. * The RnEnv2 in the MatchEnv binds only the local binders in the term (lambdas, case) * When we encounter a let in the term to be matched, we check that does not mention any locally bound (lambda, case) variables. If so we fail * We use CoreSubst.substBind to freshen the binding, using an in-scope set that is the original in-scope variables plus the rs_bndrs (currently floated let-bindings). So in (a) above we'll freshen the 'v' binding; in (b) above we'll freshen the *second* 'v' binding. * We apply that freshening substitution, in a lexically-scoped way to the term, although lazily; this is the rv_fltR field. Note [Matching cases] ~~~~~~~~~~~~~~~~~~~~~ {- NOTE: This idea is currently disabled. It really only works if the primops involved are OkForSpeculation, and, since they have side effects readIntOfAddr and touch are not. Maybe we'll get back to this later . -} Consider f (case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> I# n# } } ) This happened in a tight loop generated by stream fusion that Roman encountered. We'd like to treat this just like the let case, because the primops concerned are ok-for-speculation. That is, we'd like to behave as if it had been case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> f (I# n# } } ) Note [Lookup in-scope] ~~~~~~~~~~~~~~~~~~~~~~ Consider this example foo :: Int -> Maybe Int -> Int foo 0 (Just n) = n foo m (Just n) = foo (m-n) (Just n) SpecConstr sees this fragment: case w_smT of wild_Xf [Just A] { Data.Maybe.Nothing -> lvl_smf; Data.Maybe.Just n_acT [Just S(L)] -> case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] -> \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf }}; and correctly generates the rule RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int# sc_snn :: GHC.Prim.Int#} \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr)) = \$s\$wfoo_sno y_amr sc_snn ;] BUT we must ensure that this rule matches in the original function! Note that the call to \$wfoo is \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf During matching we expand wild_Xf to (Just n_acT). But then we must also expand n_acT to (I# y_amr). And we can only do that if we look up n_acT in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding at all. That is why the 'lookupRnInScope' call in the (Var v2) case of 'match' is so important. ************************************************************************ * * Rule-check the program * * ************************************************************************ We want to know what sites have rules that could have fired but didn't. This pass runs over the tree (without changing it) and reports such. -} -- | Report partial matches for rules beginning with the specified -- string for the purposes of error reporting
6,871
match_ty :: RuleMatchEnv -> RuleSubst -> Type -- Template -> Type -- Target -> Maybe RuleSubst match_ty renv subst ty1 ty2 = do { tv_subst' <- Unify.ruleMatchTyX (rv_tmpls renv) (rv_lcl renv) tv_subst ty1 ty2 ; return (subst { rs_tv_subst = tv_subst' }) } where tv_subst = rs_tv_subst subst {- Note [Expanding variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is another Very Important rule: if the term being matched is a variable, we expand it so long as its unfolding is "expandable". (Its occurrence information is not necessarily up to date, so we don't use it.) By "expandable" we mean a WHNF or a "constructor-like" application. This is the key reason for "constructor-like" Ids. If we have {-# NOINLINE [1] CONLIKE g #-} {-# RULE f (g x) = h x #-} then in the term let v = g 3 in ....(f v).... we want to make the rule fire, to replace (f v) with (h 3). Note [Do not expand locally-bound variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do *not* expand locally-bound variables, else there's a worry that the unfolding might mention variables that are themselves renamed. Example case x of y { (p,q) -> ...y... } Don't expand 'y' to (p,q) because p,q might themselves have been renamed. Essentially we only expand unfoldings that are "outside" the entire match. Hence, (a) the guard (not (isLocallyBoundR v2)) (b) when we expand we nuke the renaming envt (nukeRnEnvR). Note [Tick annotations in RULE matching] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to unconditionally look through Notes in both template and expression being matched. This is actually illegal for counting or cost-centre-scoped ticks, because we have no place to put them without changing entry counts and/or costs. So now we just fail the match in these cases. On the other hand, where we are allowed to insert new cost into the tick scope, we can float them upwards to the rule application site. cf Note [Notes in call patterns] in SpecConstr Note [Matching lets] ~~~~~~~~~~~~~~~~~~~~ Matching a let-expression. Consider RULE forall x. f (g x) = <rhs> and target expression f (let { w=R } in g E)) Then we'd like the rule to match, to generate let { w=R } in (\x. <rhs>) E In effect, we want to float the let-binding outward, to enable the match to happen. This is the WHOLE REASON for accumulating bindings in the RuleSubst We can only do this if the free variables of R are not bound by the part of the target expression outside the let binding; e.g. f (\v. let w = v+1 in g E) Here we obviously cannot float the let-binding for w. Hence the use of okToFloat. There are a couple of tricky points. (a) What if floating the binding captures a variable? f (let v = x+1 in v) v --> NOT! let v = x+1 in f (x+1) v (b) What if two non-nested let bindings bind the same variable? f (let v = e1 in b1) (let v = e2 in b2) --> NOT! let v = e1 in let v = e2 in (f b2 b2) See testsuite test "RuleFloatLet". Our cunning plan is this: * Along with the growing substitution for template variables we maintain a growing set of floated let-bindings (rs_binds) plus the set of variables thus bound. * The RnEnv2 in the MatchEnv binds only the local binders in the term (lambdas, case) * When we encounter a let in the term to be matched, we check that does not mention any locally bound (lambda, case) variables. If so we fail * We use CoreSubst.substBind to freshen the binding, using an in-scope set that is the original in-scope variables plus the rs_bndrs (currently floated let-bindings). So in (a) above we'll freshen the 'v' binding; in (b) above we'll freshen the *second* 'v' binding. * We apply that freshening substitution, in a lexically-scoped way to the term, although lazily; this is the rv_fltR field. Note [Matching cases] ~~~~~~~~~~~~~~~~~~~~~ {- NOTE: This idea is currently disabled. It really only works if the primops involved are OkForSpeculation, and, since they have side effects readIntOfAddr and touch are not. Maybe we'll get back to this later . -} Consider f (case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> I# n# } } ) This happened in a tight loop generated by stream fusion that Roman encountered. We'd like to treat this just like the let case, because the primops concerned are ok-for-speculation. That is, we'd like to behave as if it had been case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> f (I# n# } } ) Note [Lookup in-scope] ~~~~~~~~~~~~~~~~~~~~~~ Consider this example foo :: Int -> Maybe Int -> Int foo 0 (Just n) = n foo m (Just n) = foo (m-n) (Just n) SpecConstr sees this fragment: case w_smT of wild_Xf [Just A] { Data.Maybe.Nothing -> lvl_smf; Data.Maybe.Just n_acT [Just S(L)] -> case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] -> \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf }}; and correctly generates the rule RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int# sc_snn :: GHC.Prim.Int#} \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr)) = \$s\$wfoo_sno y_amr sc_snn ;] BUT we must ensure that this rule matches in the original function! Note that the call to \$wfoo is \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf During matching we expand wild_Xf to (Just n_acT). But then we must also expand n_acT to (I# y_amr). And we can only do that if we look up n_acT in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding at all. That is why the 'lookupRnInScope' call in the (Var v2) case of 'match' is so important. ************************************************************************ * * Rule-check the program * * ************************************************************************ We want to know what sites have rules that could have fired but didn't. This pass runs over the tree (without changing it) and reports such. -} -- | Report partial matches for rules beginning with the specified -- string for the purposes of error reporting
6,605
match_ty renv subst ty1 ty2 = do { tv_subst' <- Unify.ruleMatchTyX (rv_tmpls renv) (rv_lcl renv) tv_subst ty1 ty2 ; return (subst { rs_tv_subst = tv_subst' }) } where tv_subst = rs_tv_subst subst {- Note [Expanding variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is another Very Important rule: if the term being matched is a variable, we expand it so long as its unfolding is "expandable". (Its occurrence information is not necessarily up to date, so we don't use it.) By "expandable" we mean a WHNF or a "constructor-like" application. This is the key reason for "constructor-like" Ids. If we have {-# NOINLINE [1] CONLIKE g #-} {-# RULE f (g x) = h x #-} then in the term let v = g 3 in ....(f v).... we want to make the rule fire, to replace (f v) with (h 3). Note [Do not expand locally-bound variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Do *not* expand locally-bound variables, else there's a worry that the unfolding might mention variables that are themselves renamed. Example case x of y { (p,q) -> ...y... } Don't expand 'y' to (p,q) because p,q might themselves have been renamed. Essentially we only expand unfoldings that are "outside" the entire match. Hence, (a) the guard (not (isLocallyBoundR v2)) (b) when we expand we nuke the renaming envt (nukeRnEnvR). Note [Tick annotations in RULE matching] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to unconditionally look through Notes in both template and expression being matched. This is actually illegal for counting or cost-centre-scoped ticks, because we have no place to put them without changing entry counts and/or costs. So now we just fail the match in these cases. On the other hand, where we are allowed to insert new cost into the tick scope, we can float them upwards to the rule application site. cf Note [Notes in call patterns] in SpecConstr Note [Matching lets] ~~~~~~~~~~~~~~~~~~~~ Matching a let-expression. Consider RULE forall x. f (g x) = <rhs> and target expression f (let { w=R } in g E)) Then we'd like the rule to match, to generate let { w=R } in (\x. <rhs>) E In effect, we want to float the let-binding outward, to enable the match to happen. This is the WHOLE REASON for accumulating bindings in the RuleSubst We can only do this if the free variables of R are not bound by the part of the target expression outside the let binding; e.g. f (\v. let w = v+1 in g E) Here we obviously cannot float the let-binding for w. Hence the use of okToFloat. There are a couple of tricky points. (a) What if floating the binding captures a variable? f (let v = x+1 in v) v --> NOT! let v = x+1 in f (x+1) v (b) What if two non-nested let bindings bind the same variable? f (let v = e1 in b1) (let v = e2 in b2) --> NOT! let v = e1 in let v = e2 in (f b2 b2) See testsuite test "RuleFloatLet". Our cunning plan is this: * Along with the growing substitution for template variables we maintain a growing set of floated let-bindings (rs_binds) plus the set of variables thus bound. * The RnEnv2 in the MatchEnv binds only the local binders in the term (lambdas, case) * When we encounter a let in the term to be matched, we check that does not mention any locally bound (lambda, case) variables. If so we fail * We use CoreSubst.substBind to freshen the binding, using an in-scope set that is the original in-scope variables plus the rs_bndrs (currently floated let-bindings). So in (a) above we'll freshen the 'v' binding; in (b) above we'll freshen the *second* 'v' binding. * We apply that freshening substitution, in a lexically-scoped way to the term, although lazily; this is the rv_fltR field. Note [Matching cases] ~~~~~~~~~~~~~~~~~~~~~ {- NOTE: This idea is currently disabled. It really only works if the primops involved are OkForSpeculation, and, since they have side effects readIntOfAddr and touch are not. Maybe we'll get back to this later . -} Consider f (case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> I# n# } } ) This happened in a tight loop generated by stream fusion that Roman encountered. We'd like to treat this just like the let case, because the primops concerned are ok-for-speculation. That is, we'd like to behave as if it had been case readIntOffAddr# p# i# realWorld# of { (# s#, n# #) -> case touch# fp s# of { _ -> f (I# n# } } ) Note [Lookup in-scope] ~~~~~~~~~~~~~~~~~~~~~~ Consider this example foo :: Int -> Maybe Int -> Int foo 0 (Just n) = n foo m (Just n) = foo (m-n) (Just n) SpecConstr sees this fragment: case w_smT of wild_Xf [Just A] { Data.Maybe.Nothing -> lvl_smf; Data.Maybe.Just n_acT [Just S(L)] -> case n_acT of wild1_ams [Just A] { GHC.Base.I# y_amr [Just L] -> \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf }}; and correctly generates the rule RULES: "SC:$wfoo1" [0] __forall {y_amr [Just L] :: GHC.Prim.Int# sc_snn :: GHC.Prim.Int#} \$wfoo_smW sc_snn (Data.Maybe.Just @ GHC.Base.Int (GHC.Base.I# y_amr)) = \$s\$wfoo_sno y_amr sc_snn ;] BUT we must ensure that this rule matches in the original function! Note that the call to \$wfoo is \$wfoo_smW (GHC.Prim.-# ds_Xmb y_amr) wild_Xf During matching we expand wild_Xf to (Just n_acT). But then we must also expand n_acT to (I# y_amr). And we can only do that if we look up n_acT in the in-scope set, because in wild_Xf's unfolding it won't have an unfolding at all. That is why the 'lookupRnInScope' call in the (Var v2) case of 'match' is so important. ************************************************************************ * * Rule-check the program * * ************************************************************************ We want to know what sites have rules that could have fired but didn't. This pass runs over the tree (without changing it) and reports such. -} -- | Report partial matches for rules beginning with the specified -- string for the purposes of error reporting
6,444
true
true
0
10
1,766
112
61
51
null
null
sdiehl/ghc
compiler/basicTypes/Literal.hs
bsd-3-clause
-- | A nonsense literal of type @forall (a :: 'TYPE' 'UnliftedRep'). a@. rubbishLit :: Literal rubbishLit = LitRubbish
118
rubbishLit :: Literal rubbishLit = LitRubbish
45
rubbishLit = LitRubbish
23
true
true
0
6
18
19
8
11
null
null
qpliu/esolang
flower/hs/Parse.hs
gpl-3.0
resolveSendAll :: Definition -> Either [ParseError] Definition resolveSendAll (Definition position name inputs outputs statements) = do (unsent,resolved) <- resolveSends inputs outputs statements [] if null unsent then return (Definition position name inputs outputs resolved) else Left [newErrorMessage (Message ("Unused output(s):" ++ show (map symbolName unsent))) position] where resolveSends locals outputs statements resolved = case statements of [] -> Right (outputs,reverse resolved) (SendAllStatement position:statements) -> let (sent,unsent) = partition (`elem` locals) outputs in resolveSends locals unsent statements (SendStatement position True (map ExpressionBound sent) sent:resolved) (IfStatement position ifBlocks:statements) -> resolveIfBlocks locals outputs statements resolved position ifBlocks (statement@(SendStatement position _ _ symbols):statements) -> case (filter (`notElem` outputs) symbols,filter (`notElem` symbols) outputs) of ([],unsent) -> resolveSends locals unsent statements (statement:resolved) (invalid,_) -> Left [newErrorMessage (Message ("Invalid output(s):" ++ show (map symbolName invalid))) position] (statement@(BindStatement _ symbols _):statements) -> resolveSends (symbols ++ locals) outputs statements (statement:resolved) ifBlockStatements (IfBlock _ _ statements) = statements resolveIfBlocks locals outputs statements resolved ifPosition ifBlocks = case partitionEithers (map (flip (resolveSends locals outputs) [] . ifBlockStatements) ifBlocks) of ([],resolvedBlocks) -> checkBlocks resolvedBlocks (errors,_) -> Left (concat errors) where checkBlocks blockResolutions | length (nub (map (sort . fst) blockResolutions)) /= 1 = Left [newErrorMessage (Message "Unmatching outputs in if-branches") ifPosition] | otherwise = resolveSends locals (fst (head blockResolutions)) statements (IfStatement ifPosition (zipWith replaceBody blockResolutions ifBlocks):resolved) replaceBody (_,statements) (IfBlock position expressions _) = IfBlock position expressions statements -- resolve undetermined expressions
2,383
resolveSendAll :: Definition -> Either [ParseError] Definition resolveSendAll (Definition position name inputs outputs statements) = do (unsent,resolved) <- resolveSends inputs outputs statements [] if null unsent then return (Definition position name inputs outputs resolved) else Left [newErrorMessage (Message ("Unused output(s):" ++ show (map symbolName unsent))) position] where resolveSends locals outputs statements resolved = case statements of [] -> Right (outputs,reverse resolved) (SendAllStatement position:statements) -> let (sent,unsent) = partition (`elem` locals) outputs in resolveSends locals unsent statements (SendStatement position True (map ExpressionBound sent) sent:resolved) (IfStatement position ifBlocks:statements) -> resolveIfBlocks locals outputs statements resolved position ifBlocks (statement@(SendStatement position _ _ symbols):statements) -> case (filter (`notElem` outputs) symbols,filter (`notElem` symbols) outputs) of ([],unsent) -> resolveSends locals unsent statements (statement:resolved) (invalid,_) -> Left [newErrorMessage (Message ("Invalid output(s):" ++ show (map symbolName invalid))) position] (statement@(BindStatement _ symbols _):statements) -> resolveSends (symbols ++ locals) outputs statements (statement:resolved) ifBlockStatements (IfBlock _ _ statements) = statements resolveIfBlocks locals outputs statements resolved ifPosition ifBlocks = case partitionEithers (map (flip (resolveSends locals outputs) [] . ifBlockStatements) ifBlocks) of ([],resolvedBlocks) -> checkBlocks resolvedBlocks (errors,_) -> Left (concat errors) where checkBlocks blockResolutions | length (nub (map (sort . fst) blockResolutions)) /= 1 = Left [newErrorMessage (Message "Unmatching outputs in if-branches") ifPosition] | otherwise = resolveSends locals (fst (head blockResolutions)) statements (IfStatement ifPosition (zipWith replaceBody blockResolutions ifBlocks):resolved) replaceBody (_,statements) (IfBlock position expressions _) = IfBlock position expressions statements -- resolve undetermined expressions
2,383
resolveSendAll (Definition position name inputs outputs statements) = do (unsent,resolved) <- resolveSends inputs outputs statements [] if null unsent then return (Definition position name inputs outputs resolved) else Left [newErrorMessage (Message ("Unused output(s):" ++ show (map symbolName unsent))) position] where resolveSends locals outputs statements resolved = case statements of [] -> Right (outputs,reverse resolved) (SendAllStatement position:statements) -> let (sent,unsent) = partition (`elem` locals) outputs in resolveSends locals unsent statements (SendStatement position True (map ExpressionBound sent) sent:resolved) (IfStatement position ifBlocks:statements) -> resolveIfBlocks locals outputs statements resolved position ifBlocks (statement@(SendStatement position _ _ symbols):statements) -> case (filter (`notElem` outputs) symbols,filter (`notElem` symbols) outputs) of ([],unsent) -> resolveSends locals unsent statements (statement:resolved) (invalid,_) -> Left [newErrorMessage (Message ("Invalid output(s):" ++ show (map symbolName invalid))) position] (statement@(BindStatement _ symbols _):statements) -> resolveSends (symbols ++ locals) outputs statements (statement:resolved) ifBlockStatements (IfBlock _ _ statements) = statements resolveIfBlocks locals outputs statements resolved ifPosition ifBlocks = case partitionEithers (map (flip (resolveSends locals outputs) [] . ifBlockStatements) ifBlocks) of ([],resolvedBlocks) -> checkBlocks resolvedBlocks (errors,_) -> Left (concat errors) where checkBlocks blockResolutions | length (nub (map (sort . fst) blockResolutions)) /= 1 = Left [newErrorMessage (Message "Unmatching outputs in if-branches") ifPosition] | otherwise = resolveSends locals (fst (head blockResolutions)) statements (IfStatement ifPosition (zipWith replaceBody blockResolutions ifBlocks):resolved) replaceBody (_,statements) (IfBlock position expressions _) = IfBlock position expressions statements -- resolve undetermined expressions
2,320
false
true
0
20
558
724
368
356
null
null
rodsol/atomspace
opencog/haskell/OpenCog/AtomSpace/Template.hs
agpl-3.0
removeComm [] = []
18
removeComm [] = []
18
removeComm [] = []
18
false
false
0
6
3
13
6
7
null
null
IreneKnapp/haskell-to-idris
Haskell/Main.hs
mit
main :: IO () main = do parameters <- IO.getArgs case parameters of [inputPath, outputPath] -> do convertFile inputPath outputPath _ -> do putStrLn $ "Usage: haskell-to-idris input.hs output.idr"
219
main :: IO () main = do parameters <- IO.getArgs case parameters of [inputPath, outputPath] -> do convertFile inputPath outputPath _ -> do putStrLn $ "Usage: haskell-to-idris input.hs output.idr"
219
main = do parameters <- IO.getArgs case parameters of [inputPath, outputPath] -> do convertFile inputPath outputPath _ -> do putStrLn $ "Usage: haskell-to-idris input.hs output.idr"
205
false
true
0
12
52
65
31
34
null
null
reouno/gradient-method
.stack-work/dist/x86_64-osx/Cabal-1.22.5.0/build/autogen/Paths_Gradient_Method.hs
bsd-3-clause
getLibexecDir = catchIO (getEnv "Gradient_Method_libexecdir") (\_ -> return libexecdir)
87
getLibexecDir = catchIO (getEnv "Gradient_Method_libexecdir") (\_ -> return libexecdir)
87
getLibexecDir = catchIO (getEnv "Gradient_Method_libexecdir") (\_ -> return libexecdir)
87
false
false
1
8
8
31
14
17
null
null
creichert/hsebaysdk
Web/Ebay.hs
bsd-3-clause
requestHeadersFromConfig :: FindVerb -> EbayConfig -> [HTTP.Header] requestHeadersFromConfig fb EbayConfig{..} = [ ("Content-Type", "application/json") , ("X-EBAY-SOA-SERVICE-NAME", utf8 ebService) , ("X-EBAY-SOA-SERVICE-VERSION", utf8 ebVersion) , ("X-EBAY-SOA-SECURITY-APPNAME", utf8 ebAppId) , ("X-EBAY-SOA-GLOBAL-ID", utf8 ebSiteId) , ("X-EBAY-SOA-OPERATION-NAME", encodedFindVerb) , ("X-EBAY-SOA-REQUEST-DATA-FORMAT", dataFormatEncode ebRequestEncoding) , ("X-EBAY-SOA-RESPONSE-DATA-FORMAT", dataFormatEncode ebResponseEncoding) ] where utf8 = T.encodeUtf8 dataFormatEncode JsonEncoding = utf8 "JSON" dataFormatEncode XmlEncoding = utf8 "XML" encodedFindVerb = T.encodeUtf8 $ findVerbToOperation fb False -- | Convert the FindVerb to Text suitable for ebay request headers.
836
requestHeadersFromConfig :: FindVerb -> EbayConfig -> [HTTP.Header] requestHeadersFromConfig fb EbayConfig{..} = [ ("Content-Type", "application/json") , ("X-EBAY-SOA-SERVICE-NAME", utf8 ebService) , ("X-EBAY-SOA-SERVICE-VERSION", utf8 ebVersion) , ("X-EBAY-SOA-SECURITY-APPNAME", utf8 ebAppId) , ("X-EBAY-SOA-GLOBAL-ID", utf8 ebSiteId) , ("X-EBAY-SOA-OPERATION-NAME", encodedFindVerb) , ("X-EBAY-SOA-REQUEST-DATA-FORMAT", dataFormatEncode ebRequestEncoding) , ("X-EBAY-SOA-RESPONSE-DATA-FORMAT", dataFormatEncode ebResponseEncoding) ] where utf8 = T.encodeUtf8 dataFormatEncode JsonEncoding = utf8 "JSON" dataFormatEncode XmlEncoding = utf8 "XML" encodedFindVerb = T.encodeUtf8 $ findVerbToOperation fb False -- | Convert the FindVerb to Text suitable for ebay request headers.
836
requestHeadersFromConfig fb EbayConfig{..} = [ ("Content-Type", "application/json") , ("X-EBAY-SOA-SERVICE-NAME", utf8 ebService) , ("X-EBAY-SOA-SERVICE-VERSION", utf8 ebVersion) , ("X-EBAY-SOA-SECURITY-APPNAME", utf8 ebAppId) , ("X-EBAY-SOA-GLOBAL-ID", utf8 ebSiteId) , ("X-EBAY-SOA-OPERATION-NAME", encodedFindVerb) , ("X-EBAY-SOA-REQUEST-DATA-FORMAT", dataFormatEncode ebRequestEncoding) , ("X-EBAY-SOA-RESPONSE-DATA-FORMAT", dataFormatEncode ebResponseEncoding) ] where utf8 = T.encodeUtf8 dataFormatEncode JsonEncoding = utf8 "JSON" dataFormatEncode XmlEncoding = utf8 "XML" encodedFindVerb = T.encodeUtf8 $ findVerbToOperation fb False -- | Convert the FindVerb to Text suitable for ebay request headers.
768
false
true
3
8
132
174
96
78
null
null
gorkinovich/Haskell
Problems/Problem0019.hs
mit
intToDate :: Integer -> Date intToDate n = (y, m, d) where y = getYearFromInt n md = fromIntegral $ remYearFromInt' n y dbm = getDaysByMonth y gdm md' m' | md' > d' = gdm (md' - d') (m' + 1) | otherwise = (m', md') where d' = dbm !! (m' - 1) (m, d) = gdm md 1 -- *************************************************************** -- (1900, 1, 1) -> Monday
441
intToDate :: Integer -> Date intToDate n = (y, m, d) where y = getYearFromInt n md = fromIntegral $ remYearFromInt' n y dbm = getDaysByMonth y gdm md' m' | md' > d' = gdm (md' - d') (m' + 1) | otherwise = (m', md') where d' = dbm !! (m' - 1) (m, d) = gdm md 1 -- *************************************************************** -- (1900, 1, 1) -> Monday
441
intToDate n = (y, m, d) where y = getYearFromInt n md = fromIntegral $ remYearFromInt' n y dbm = getDaysByMonth y gdm md' m' | md' > d' = gdm (md' - d') (m' + 1) | otherwise = (m', md') where d' = dbm !! (m' - 1) (m, d) = gdm md 1 -- *************************************************************** -- (1900, 1, 1) -> Monday
412
false
true
6
10
157
154
79
75
null
null
thoughtpolice/infinity
Setup.hs
bsd-3-clause
copyInfinity _ _ _ _ = do copyFile (joinPath ["dist","build","infinity",inf]) inf ignore (createDirectory "Log" >> createDirectory "State")
143
copyInfinity _ _ _ _ = do copyFile (joinPath ["dist","build","infinity",inf]) inf ignore (createDirectory "Log" >> createDirectory "State")
143
copyInfinity _ _ _ _ = do copyFile (joinPath ["dist","build","infinity",inf]) inf ignore (createDirectory "Log" >> createDirectory "State")
143
false
false
0
10
20
60
29
31
null
null
exitmouse/proper
glfw-demo/src/Main.hs
gpl-3.0
windowIconifyCallback tc win ia = atomically $ writeTQueue tc $ EventWindowIconify win ia
101
windowIconifyCallback tc win ia = atomically $ writeTQueue tc $ EventWindowIconify win ia
101
windowIconifyCallback tc win ia = atomically $ writeTQueue tc $ EventWindowIconify win ia
101
false
false
0
7
24
29
13
16
null
null
andersjel/hlit
hlit-types/src/Text/Lit/RenderFloat.hs
gpl-3.0
-- The exponent -- | A thin wrapper around Numeric.floatToDigits toFloatD :: RealFloat a => a -> FloatD toFloatD x = FloatD (x < 0) ds ex where (ds, ex) = Numeric.floatToDigits 10 (abs x) -- | Round off to /sig/ digits. Includes trailing zeros.
250
toFloatD :: RealFloat a => a -> FloatD toFloatD x = FloatD (x < 0) ds ex where (ds, ex) = Numeric.floatToDigits 10 (abs x) -- | Round off to /sig/ digits. Includes trailing zeros.
184
toFloatD x = FloatD (x < 0) ds ex where (ds, ex) = Numeric.floatToDigits 10 (abs x) -- | Round off to /sig/ digits. Includes trailing zeros.
145
true
true
0
8
50
77
37
40
null
null
jecisc/TP_PF_L3
PF-TP3/src/TP3_PF_FERLICOT/Main.hs
mit
ilbert :: LSysteme hilbert = lsysteme "X" regles where regles 'X' = "+YF-XFX-FY+" regles 'Y' = "-XF+YFY+FX-" regles s = [s]
150
hilbert :: LSysteme hilbert = lsysteme "X" regles where regles 'X' = "+YF-XFX-FY+" regles 'Y' = "-XF+YFY+FX-" regles s = [s]
150
hilbert = lsysteme "X" regles where regles 'X' = "+YF-XFX-FY+" regles 'Y' = "-XF+YFY+FX-" regles s = [s]
130
false
true
0
6
47
52
24
28
null
null
tjakway/ghcjvm
compiler/utils/Util.hs
bsd-3-clause
-- | @spanEnd p l == reverse (span p (reverse l))@. The first list -- returns actually comes after the second list (when you look at the -- input list). spanEnd :: (a -> Bool) -> [a] -> ([a], [a]) spanEnd p l = go l [] [] l where go yes _rev_yes rev_no [] = (yes, reverse rev_no) go yes rev_yes rev_no (x:xs) | p x = go yes (x : rev_yes) rev_no xs | otherwise = go xs [] (x : rev_yes ++ rev_no) xs
463
spanEnd :: (a -> Bool) -> [a] -> ([a], [a]) spanEnd p l = go l [] [] l where go yes _rev_yes rev_no [] = (yes, reverse rev_no) go yes rev_yes rev_no (x:xs) | p x = go yes (x : rev_yes) rev_no xs | otherwise = go xs [] (x : rev_yes ++ rev_no) xs
310
spanEnd p l = go l [] [] l where go yes _rev_yes rev_no [] = (yes, reverse rev_no) go yes rev_yes rev_no (x:xs) | p x = go yes (x : rev_yes) rev_no xs | otherwise = go xs [] (x : rev_yes ++ rev_no) xs
266
true
true
1
10
152
191
88
103
null
null
lywaterman/parconc-examples
server.hs
bsd-3-clause
port :: Int port = 44444
24
port :: Int port = 44444
24
port = 44444
12
false
true
0
6
5
18
7
11
null
null
ProLambda/Times
Utilities/Chat/Server.hs
gpl-3.0
talk :: WS.Connection -> MVar MsgCache -> MVar ServerState -> Client -> IO () talk conn mcache' state (user, _) = forever $ do msg <- WS.receiveData conn ctime <- liftIO $ getCurrentTime let time = T.pack $ drop 11 $ take 16 $ show ctime msg' = user `mappend` "@" `mappend` time `mappend` ": " `mappend` msg modifyMVar_ mcache' $ \x -> return $ addMsg msg' x readMVar state >>= broadcast msg'
428
talk :: WS.Connection -> MVar MsgCache -> MVar ServerState -> Client -> IO () talk conn mcache' state (user, _) = forever $ do msg <- WS.receiveData conn ctime <- liftIO $ getCurrentTime let time = T.pack $ drop 11 $ take 16 $ show ctime msg' = user `mappend` "@" `mappend` time `mappend` ": " `mappend` msg modifyMVar_ mcache' $ \x -> return $ addMsg msg' x readMVar state >>= broadcast msg'
428
talk conn mcache' state (user, _) = forever $ do msg <- WS.receiveData conn ctime <- liftIO $ getCurrentTime let time = T.pack $ drop 11 $ take 16 $ show ctime msg' = user `mappend` "@" `mappend` time `mappend` ": " `mappend` msg modifyMVar_ mcache' $ \x -> return $ addMsg msg' x readMVar state >>= broadcast msg'
330
false
true
0
15
108
185
89
96
null
null
ekmett/wxHaskell
wxdirect/src/CompileClasses.hs
lgpl-2.1
haskellToCArgIO :: String -> Bool -> Arg -> String haskellToCArgIO methodName' isSelf arg = case argType arg of String _ -> "withCWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCStringName (argName arg) ++ " -> " ++ nl ByteString Lazy -> "withArray (LB.unpack " ++ haskellName (argName arg) ++ ") $ \\" ++ haskellByteStringName (argName arg) ++ " -> " ++ nl ByteString _ -> "B.useAsCStringLen " ++ haskellName (argName arg) ++ " $ \\" ++ "(" ++ haskellByteStringName (argName arg) ++ ", " ++ haskellByteStringLenName (argName arg) ++ ") " ++ " -> " ++ nl ArrayString _ -> "withArrayWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayObject _tp _ -> "withArrayObject " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayInt _ -> "withArrayInt " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayIntPtr _ -> "withArrayIntPtr " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl Object obj -> (if isSelf then withSelf (classInfo obj) ("\"" ++ methodName' ++ "\"") else withPtr (classInfo obj)) ++ " " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCObjectName (argName arg) ++ " -> " ++ nl _other -> ""
1,962
haskellToCArgIO :: String -> Bool -> Arg -> String haskellToCArgIO methodName' isSelf arg = case argType arg of String _ -> "withCWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCStringName (argName arg) ++ " -> " ++ nl ByteString Lazy -> "withArray (LB.unpack " ++ haskellName (argName arg) ++ ") $ \\" ++ haskellByteStringName (argName arg) ++ " -> " ++ nl ByteString _ -> "B.useAsCStringLen " ++ haskellName (argName arg) ++ " $ \\" ++ "(" ++ haskellByteStringName (argName arg) ++ ", " ++ haskellByteStringLenName (argName arg) ++ ") " ++ " -> " ++ nl ArrayString _ -> "withArrayWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayObject _tp _ -> "withArrayObject " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayInt _ -> "withArrayInt " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayIntPtr _ -> "withArrayIntPtr " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl Object obj -> (if isSelf then withSelf (classInfo obj) ("\"" ++ methodName' ++ "\"") else withPtr (classInfo obj)) ++ " " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCObjectName (argName arg) ++ " -> " ++ nl _other -> ""
1,962
haskellToCArgIO methodName' isSelf arg = case argType arg of String _ -> "withCWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCStringName (argName arg) ++ " -> " ++ nl ByteString Lazy -> "withArray (LB.unpack " ++ haskellName (argName arg) ++ ") $ \\" ++ haskellByteStringName (argName arg) ++ " -> " ++ nl ByteString _ -> "B.useAsCStringLen " ++ haskellName (argName arg) ++ " $ \\" ++ "(" ++ haskellByteStringName (argName arg) ++ ", " ++ haskellByteStringLenName (argName arg) ++ ") " ++ " -> " ++ nl ArrayString _ -> "withArrayWString " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayObject _tp _ -> "withArrayObject " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayInt _ -> "withArrayInt " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl ArrayIntPtr _ -> "withArrayIntPtr " ++ haskellName (argName arg) ++ " $ \\" ++ haskellArrayLenName (argName arg) ++ " " ++ haskellArrayName (argName arg) ++ " -> " ++ nl Object obj -> (if isSelf then withSelf (classInfo obj) ("\"" ++ methodName' ++ "\"") else withPtr (classInfo obj)) ++ " " ++ haskellName (argName arg) ++ " $ \\" ++ haskellCObjectName (argName arg) ++ " -> " ++ nl _other -> ""
1,911
false
true
0
19
751
565
267
298
null
null
ddssff/pandoc
src/Text/Pandoc/Parsing.hs
gpl-2.0
-- | Parse a string with a given parser and state readWith :: Parser [Char] st a -> st -> String -> Either PandocError a readWith p t inp = runIdentity $ readWithM p t inp
198
readWith :: Parser [Char] st a -> st -> String -> Either PandocError a readWith p t inp = runIdentity $ readWithM p t inp
148
readWith p t inp = runIdentity $ readWithM p t inp
50
true
true
2
9
62
65
29
36
null
null
pubnub/haskell
src/Network/Pubnub.hs
mit
userIdOptions :: PN -> [(B.ByteString, B.ByteString)] userIdOptions pn = maybe [] (\u -> [("uuid", encodeUtf8 u)]) (uuid_key pn) ++ maybe [] (\a -> [("auth", encodeUtf8 a)]) (auth_key pn)
191
userIdOptions :: PN -> [(B.ByteString, B.ByteString)] userIdOptions pn = maybe [] (\u -> [("uuid", encodeUtf8 u)]) (uuid_key pn) ++ maybe [] (\a -> [("auth", encodeUtf8 a)]) (auth_key pn)
191
userIdOptions pn = maybe [] (\u -> [("uuid", encodeUtf8 u)]) (uuid_key pn) ++ maybe [] (\a -> [("auth", encodeUtf8 a)]) (auth_key pn)
137
false
true
0
11
31
105
57
48
null
null
kelnage/tamarin-prover
src/Web/Types.hs
gpl-3.0
-- | We use the ordering in order to display loaded theories to the user. -- We first compare by name, then by time loaded, and then by source: Theories -- that were loaded from the command-line are displayed earlier then -- interactively loaded ones. compareTI :: TheoryInfo -> TheoryInfo -> Ordering compareTI (TheoryInfo _ i1 t1 p1 a1 o1 _) (TheoryInfo _ i2 t2 p2 a2 o2 _) = mconcat [ comparing (get thyName) i1 i2 , comparing zonedTimeToUTC t1 t2 , compare a1 a2 , compare p1 p2 , compare o1 o2 ]
526
compareTI :: TheoryInfo -> TheoryInfo -> Ordering compareTI (TheoryInfo _ i1 t1 p1 a1 o1 _) (TheoryInfo _ i2 t2 p2 a2 o2 _) = mconcat [ comparing (get thyName) i1 i2 , comparing zonedTimeToUTC t1 t2 , compare a1 a2 , compare p1 p2 , compare o1 o2 ]
274
compareTI (TheoryInfo _ i1 t1 p1 a1 o1 _) (TheoryInfo _ i2 t2 p2 a2 o2 _) = mconcat [ comparing (get thyName) i1 i2 , comparing zonedTimeToUTC t1 t2 , compare a1 a2 , compare p1 p2 , compare o1 o2 ]
224
true
true
0
9
120
117
60
57
null
null
glutamate/probably-base
Math/Probably/NelderMead.hs
bsd-3-clause
secondLast (x:y:[]) = x
23
secondLast (x:y:[]) = x
23
secondLast (x:y:[]) = x
23
false
false
0
8
3
23
11
12
null
null
urbanslug/ghc
compiler/coreSyn/CoreSyn.hs
bsd-3-clause
isTyCoArg _ = False
31
isTyCoArg _ = False
31
isTyCoArg _ = False
31
false
false
0
4
15
10
4
6
null
null
ice1000/OI-codes
codewars/authoring/haskell/TypeTranspiler.hs
agpl-3.0
stringP (c : cs) = do charP c stringP cs return $ c : cs --
65
stringP (c : cs) = do charP c stringP cs return $ c : cs --
65
stringP (c : cs) = do charP c stringP cs return $ c : cs --
65
false
false
0
8
21
41
18
23
null
null
arne-schroppe/dash
src/Language/Dash/Normalization/Recursion.hs
mit
pullUpUnresolvedFreeVars :: String -> [String] -> [String] -> [String] pullUpUnresolvedFreeVars name currentEfv nextEfv = -- pull up all new free vars that are not resolved by this context let cleanedEfv = delete name currentEfv in let nextContextAllEfv = union cleanedEfv nextEfv in nextContextAllEfv
309
pullUpUnresolvedFreeVars :: String -> [String] -> [String] -> [String] pullUpUnresolvedFreeVars name currentEfv nextEfv = -- pull up all new free vars that are not resolved by this context let cleanedEfv = delete name currentEfv in let nextContextAllEfv = union cleanedEfv nextEfv in nextContextAllEfv
309
pullUpUnresolvedFreeVars name currentEfv nextEfv = -- pull up all new free vars that are not resolved by this context let cleanedEfv = delete name currentEfv in let nextContextAllEfv = union cleanedEfv nextEfv in nextContextAllEfv
238
false
true
0
11
50
72
36
36
null
null
NCrashed/PowerCom
src/powercom/Channel/Processing.hs
gpl-3.0
receiveFrameHandler :: ProcessId -> ProcessId -> MessageBuffer -> Connection -> InnerChannelOptions -> (ProcessId, String, BS.ByteString) -> Process Bool receiveFrameHandler physLayerId transitId messageBuffer conn optionsRef (_, com, byteFrame) = do options <- getOptions optionsRef case decodeFrame byteFrame of Just frame -> case frame of AckFrame -> return () RetFrame -> return () _ -> do -- prevent double sending for not fully processed frames when (com /= "frame-acked") $ sendFrame physLayerId AckFrame processFrame frame options _ -> do informSenderError transitId "Failed to recieve frame!" when (com /= "frame-acked") $ sendFrame physLayerId RetFrame return True where getRemoteNames :: [(String, String)] -> Maybe (String, String) getRemoteNames props = (,) <$> getValue props "remoteNameNew" <*> getValue props "remoteNameOld" getValue :: [(String, String)] -> String -> Maybe String getValue props key = snd <$> find (\(k, _) -> k == key) props word2int :: Word32 -> Int word2int = fromInteger . toInteger processFrame (InformationFrame name n) _ = clearBuffer messageBuffer name (word2int n) processFrame (DataPartFrame s) _ = do addMessagePart messageBuffer s filled <- isMessageReady messageBuffer when filled $ do (name, msg) <- collectMessage messageBuffer sendMessage transitId name msg processFrame (OptionFrame props) options = do case getRemoteNames props of Just (newName, oldName) -> do informSender transitId $ "Remote name changing, " ++ oldName ++ " to " ++ newName sendDisconnectUser transitId oldName sendConnectUser transitId newName Nothing -> return () let newOptions = updateOptionsFromPairs props options setOptions optionsRef newOptions informSender transitId "Recieved new options from other side, changing..." sendReopenPort physLayerId newOptions sendUpdateOptions transitId newOptions processFrame (LinkFrame name) options = do sendConnectUser transitId name setRemoteUsername conn name ifNotConnected conn $ do informSender transitId "Remote host connected!" sendFrameWithAck physLayerId $ LinkFrame $ userName options openConnection conn processFrame (UnlinkFrame name) options = do sendDisconnectUser transitId name ifConnected conn $ do informSender transitId "Remote host disconnected!" sendFrameWithAck physLayerId $ UnlinkFrame $ userName options closeConnection conn processFrame (RetFrame) _ = informSender transitId "Main handler got ret frame, it is bad!" processFrame (AckFrame) _ = informSender transitId "Main handler got ack frame, it is bad!" processFrame (Upcheck) _ = return () --informSender transitId "Upcheck got"
3,297
receiveFrameHandler :: ProcessId -> ProcessId -> MessageBuffer -> Connection -> InnerChannelOptions -> (ProcessId, String, BS.ByteString) -> Process Bool receiveFrameHandler physLayerId transitId messageBuffer conn optionsRef (_, com, byteFrame) = do options <- getOptions optionsRef case decodeFrame byteFrame of Just frame -> case frame of AckFrame -> return () RetFrame -> return () _ -> do -- prevent double sending for not fully processed frames when (com /= "frame-acked") $ sendFrame physLayerId AckFrame processFrame frame options _ -> do informSenderError transitId "Failed to recieve frame!" when (com /= "frame-acked") $ sendFrame physLayerId RetFrame return True where getRemoteNames :: [(String, String)] -> Maybe (String, String) getRemoteNames props = (,) <$> getValue props "remoteNameNew" <*> getValue props "remoteNameOld" getValue :: [(String, String)] -> String -> Maybe String getValue props key = snd <$> find (\(k, _) -> k == key) props word2int :: Word32 -> Int word2int = fromInteger . toInteger processFrame (InformationFrame name n) _ = clearBuffer messageBuffer name (word2int n) processFrame (DataPartFrame s) _ = do addMessagePart messageBuffer s filled <- isMessageReady messageBuffer when filled $ do (name, msg) <- collectMessage messageBuffer sendMessage transitId name msg processFrame (OptionFrame props) options = do case getRemoteNames props of Just (newName, oldName) -> do informSender transitId $ "Remote name changing, " ++ oldName ++ " to " ++ newName sendDisconnectUser transitId oldName sendConnectUser transitId newName Nothing -> return () let newOptions = updateOptionsFromPairs props options setOptions optionsRef newOptions informSender transitId "Recieved new options from other side, changing..." sendReopenPort physLayerId newOptions sendUpdateOptions transitId newOptions processFrame (LinkFrame name) options = do sendConnectUser transitId name setRemoteUsername conn name ifNotConnected conn $ do informSender transitId "Remote host connected!" sendFrameWithAck physLayerId $ LinkFrame $ userName options openConnection conn processFrame (UnlinkFrame name) options = do sendDisconnectUser transitId name ifConnected conn $ do informSender transitId "Remote host disconnected!" sendFrameWithAck physLayerId $ UnlinkFrame $ userName options closeConnection conn processFrame (RetFrame) _ = informSender transitId "Main handler got ret frame, it is bad!" processFrame (AckFrame) _ = informSender transitId "Main handler got ack frame, it is bad!" processFrame (Upcheck) _ = return () --informSender transitId "Upcheck got"
3,296
receiveFrameHandler physLayerId transitId messageBuffer conn optionsRef (_, com, byteFrame) = do options <- getOptions optionsRef case decodeFrame byteFrame of Just frame -> case frame of AckFrame -> return () RetFrame -> return () _ -> do -- prevent double sending for not fully processed frames when (com /= "frame-acked") $ sendFrame physLayerId AckFrame processFrame frame options _ -> do informSenderError transitId "Failed to recieve frame!" when (com /= "frame-acked") $ sendFrame physLayerId RetFrame return True where getRemoteNames :: [(String, String)] -> Maybe (String, String) getRemoteNames props = (,) <$> getValue props "remoteNameNew" <*> getValue props "remoteNameOld" getValue :: [(String, String)] -> String -> Maybe String getValue props key = snd <$> find (\(k, _) -> k == key) props word2int :: Word32 -> Int word2int = fromInteger . toInteger processFrame (InformationFrame name n) _ = clearBuffer messageBuffer name (word2int n) processFrame (DataPartFrame s) _ = do addMessagePart messageBuffer s filled <- isMessageReady messageBuffer when filled $ do (name, msg) <- collectMessage messageBuffer sendMessage transitId name msg processFrame (OptionFrame props) options = do case getRemoteNames props of Just (newName, oldName) -> do informSender transitId $ "Remote name changing, " ++ oldName ++ " to " ++ newName sendDisconnectUser transitId oldName sendConnectUser transitId newName Nothing -> return () let newOptions = updateOptionsFromPairs props options setOptions optionsRef newOptions informSender transitId "Recieved new options from other side, changing..." sendReopenPort physLayerId newOptions sendUpdateOptions transitId newOptions processFrame (LinkFrame name) options = do sendConnectUser transitId name setRemoteUsername conn name ifNotConnected conn $ do informSender transitId "Remote host connected!" sendFrameWithAck physLayerId $ LinkFrame $ userName options openConnection conn processFrame (UnlinkFrame name) options = do sendDisconnectUser transitId name ifConnected conn $ do informSender transitId "Remote host disconnected!" sendFrameWithAck physLayerId $ UnlinkFrame $ userName options closeConnection conn processFrame (RetFrame) _ = informSender transitId "Main handler got ret frame, it is bad!" processFrame (AckFrame) _ = informSender transitId "Main handler got ack frame, it is bad!" processFrame (Upcheck) _ = return () --informSender transitId "Upcheck got"
3,137
false
true
46
18
1,064
706
362
344
null
null
tel/hs-nanomsg
src/Network/Nanomsg/C.hs
apache-2.0
prio5 = Priority 5
24
prio5 = Priority 5
24
prio5 = Priority 5
24
false
false
1
5
9
12
4
8
null
null
abhean/phffp-examples
src/Lib.hs
bsd-3-clause
myWords s = firstWord : myWords rest where firstWord = takeWhile (/= ' ') s rest = dropWhile (== ' ') . dropWhile (/= ' ') $ s
136
myWords s = firstWord : myWords rest where firstWord = takeWhile (/= ' ') s rest = dropWhile (== ' ') . dropWhile (/= ' ') $ s
136
myWords s = firstWord : myWords rest where firstWord = takeWhile (/= ' ') s rest = dropWhile (== ' ') . dropWhile (/= ' ') $ s
136
false
false
1
8
37
61
31
30
null
null
nomeata/ghc
compiler/nativeGen/RegAlloc/Graph/Spill.hs
bsd-3-clause
akeSpillStats :: SpillS -> SpillStats makeSpillStats s = SpillStats { spillStoreLoad = stateSpillSL s }
127
makeSpillStats :: SpillS -> SpillStats makeSpillStats s = SpillStats { spillStoreLoad = stateSpillSL s }
127
makeSpillStats s = SpillStats { spillStoreLoad = stateSpillSL s }
88
false
true
0
7
38
37
17
20
null
null
spinningfire/aikatsu
test/Spec.hs
bsd-3-clause
photoMaria = Photo "Himesato Maria" Maria 60 1400 "Cute Flash" 7800 R Cute 54 (AppealUp 15) AuroraFantasy
105
photoMaria = Photo "Himesato Maria" Maria 60 1400 "Cute Flash" 7800 R Cute 54 (AppealUp 15) AuroraFantasy
105
photoMaria = Photo "Himesato Maria" Maria 60 1400 "Cute Flash" 7800 R Cute 54 (AppealUp 15) AuroraFantasy
105
false
false
1
7
16
39
17
22
null
null
jarmond/locomotive-haskell
src/Loco/Eval.hs
gpl-3.0
-- |Execute a command. command :: String -> [LocoValue] -> IOLocoEval Jump command name args = maybe (throwError $ UnknownCommand name) ($ args) (lookupCmd name)
213
command :: String -> [LocoValue] -> IOLocoEval Jump command name args = maybe (throwError $ UnknownCommand name) ($ args) (lookupCmd name)
190
command name args = maybe (throwError $ UnknownCommand name) ($ args) (lookupCmd name)
138
true
true
0
8
76
58
30
28
null
null
vTurbine/ghc
compiler/prelude/TysWiredIn.hs
bsd-3-clause
-- The type ('PtrRepLifted) ptrRepLiftedTy :: Type ptrRepLiftedTy = mkTyConTy $ promoteDataCon ptrRepLiftedDataCon
114
ptrRepLiftedTy :: Type ptrRepLiftedTy = mkTyConTy $ promoteDataCon ptrRepLiftedDataCon
86
ptrRepLiftedTy = mkTyConTy $ promoteDataCon ptrRepLiftedDataCon
63
true
true
2
6
12
27
11
16
null
null
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/ECSTaskDefinitionTmpfs.hs
mit
ecsTaskDefinitionTmpfs :: ECSTaskDefinitionTmpfs ecsTaskDefinitionTmpfs = ECSTaskDefinitionTmpfs { _eCSTaskDefinitionTmpfsContainerPath = Nothing , _eCSTaskDefinitionTmpfsMountOptions = Nothing , _eCSTaskDefinitionTmpfsSize = Nothing }
248
ecsTaskDefinitionTmpfs :: ECSTaskDefinitionTmpfs ecsTaskDefinitionTmpfs = ECSTaskDefinitionTmpfs { _eCSTaskDefinitionTmpfsContainerPath = Nothing , _eCSTaskDefinitionTmpfsMountOptions = Nothing , _eCSTaskDefinitionTmpfsSize = Nothing }
248
ecsTaskDefinitionTmpfs = ECSTaskDefinitionTmpfs { _eCSTaskDefinitionTmpfsContainerPath = Nothing , _eCSTaskDefinitionTmpfsMountOptions = Nothing , _eCSTaskDefinitionTmpfsSize = Nothing }
197
false
true
1
7
31
38
20
18
null
null
rgaiacs/pandoc
src/Text/Pandoc/Readers/Org.hs
gpl-2.0
metaKey :: OrgParser String metaKey = map toLower <$> many1 (noneOf ": \n\r") <* char ':' <* skipSpaces
149
metaKey :: OrgParser String metaKey = map toLower <$> many1 (noneOf ": \n\r") <* char ':' <* skipSpaces
149
metaKey = map toLower <$> many1 (noneOf ": \n\r") <* char ':' <* skipSpaces
121
false
true
0
10
63
41
19
22
null
null
duplode/stack
src/main/Main.hs
bsd-3-clause
pathCmd :: [Text] -> GlobalOpts -> IO () pathCmd keys go = withBuildConfigAndLock go (\_ -> do env <- ask let cfg = envConfig env bc = envConfigBuildConfig cfg menv <- getMinimalEnvOverride snap <- packageDatabaseDeps local <- packageDatabaseLocal snaproot <- installationRootDeps localroot <- installationRootLocal distDir <- distRelativeDir forM_ (filter (\(_,key,_) -> null keys || elem key keys) paths) (\(_,key,path) -> liftIO $ T.putStrLn ((if length keys == 1 then "" else key <> ": ") <> path (PathInfo bc menv snap local snaproot localroot distDir))))
1,222
pathCmd :: [Text] -> GlobalOpts -> IO () pathCmd keys go = withBuildConfigAndLock go (\_ -> do env <- ask let cfg = envConfig env bc = envConfigBuildConfig cfg menv <- getMinimalEnvOverride snap <- packageDatabaseDeps local <- packageDatabaseLocal snaproot <- installationRootDeps localroot <- installationRootLocal distDir <- distRelativeDir forM_ (filter (\(_,key,_) -> null keys || elem key keys) paths) (\(_,key,path) -> liftIO $ T.putStrLn ((if length keys == 1 then "" else key <> ": ") <> path (PathInfo bc menv snap local snaproot localroot distDir))))
1,222
pathCmd keys go = withBuildConfigAndLock go (\_ -> do env <- ask let cfg = envConfig env bc = envConfigBuildConfig cfg menv <- getMinimalEnvOverride snap <- packageDatabaseDeps local <- packageDatabaseLocal snaproot <- installationRootDeps localroot <- installationRootLocal distDir <- distRelativeDir forM_ (filter (\(_,key,_) -> null keys || elem key keys) paths) (\(_,key,path) -> liftIO $ T.putStrLn ((if length keys == 1 then "" else key <> ": ") <> path (PathInfo bc menv snap local snaproot localroot distDir))))
1,181
false
true
0
20
746
235
117
118
null
null
cgmckeever/contests
2011-mebipenny/contest/hexcode/hexcode.hs
mit
main = do line <- getLine handleInput line
50
main = do line <- getLine handleInput line
50
main = do line <- getLine handleInput line
50
false
false
0
7
15
19
8
11
null
null
angerman/data-bitcode-edsl
src/EDSL/Monad/Types.hs
bsd-3-clause
i8 = i 8
8
i8 = i 8
8
i8 = i 8
8
false
false
1
5
3
13
4
9
null
null
CRogers/stack
src/Stack/Upload.hs
bsd-3-clause
-- | Upload a single tarball with the given @Uploader@. -- -- Since 0.1.0.0 upload :: Uploader -> FilePath -> IO () upload = upload_
132
upload :: Uploader -> FilePath -> IO () upload = upload_
56
upload = upload_
16
true
true
0
9
24
33
16
17
null
null
romanb/amazonka
amazonka-elasticbeanstalk/gen/Network/AWS/ElasticBeanstalk/CreateConfigurationTemplate.hs
mpl-2.0
-- | The name of the solution stack this configuration set uses. cctrSolutionStackName :: Lens' CreateConfigurationTemplateResponse (Maybe Text) cctrSolutionStackName = lens _cctrSolutionStackName (\s a -> s { _cctrSolutionStackName = a })
243
cctrSolutionStackName :: Lens' CreateConfigurationTemplateResponse (Maybe Text) cctrSolutionStackName = lens _cctrSolutionStackName (\s a -> s { _cctrSolutionStackName = a })
178
cctrSolutionStackName = lens _cctrSolutionStackName (\s a -> s { _cctrSolutionStackName = a })
98
true
true
1
9
34
52
25
27
null
null
robbinch/tinc
src/Run.hs
mit
callExec :: Facts -> String -> [String] -> IO () callExec Facts{..} name args = do pid <- if factsUseNix then uncurry spawnProcess $ nixShell name args else spawnProcess "cabal" ("exec" : "--" : name : args) waitForProcess pid >>= throwIO
250
callExec :: Facts -> String -> [String] -> IO () callExec Facts{..} name args = do pid <- if factsUseNix then uncurry spawnProcess $ nixShell name args else spawnProcess "cabal" ("exec" : "--" : name : args) waitForProcess pid >>= throwIO
250
callExec Facts{..} name args = do pid <- if factsUseNix then uncurry spawnProcess $ nixShell name args else spawnProcess "cabal" ("exec" : "--" : name : args) waitForProcess pid >>= throwIO
201
false
true
1
14
52
111
51
60
null
null