code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE ScopedTypeVariables #-} module CAProtoMain where import ProtoTypes import ProtoMonad import ProtoActions import Keys import TPM import TPMUtil import VChanUtil hiding (send, receive) import System.IO import System.Random import Control.Monad.IO.Class --import qualified Control.Monad.Trans.Reader as T import Data.Binary import Data.Digest.Pure.SHA (bytestringDigest, sha1) import Crypto.Cipher.AES import Codec.Crypto.RSA hiding (sign, verify, PublicKey, PrivateKey, encrypt, decrypt, decrypt') import Data.ByteString.Lazy hiding (replicate, putStrLn) iPass = tpm_digest_pass aikPass oPass = tpm_digest_pass ownerPass caEntity_Att :: Proto () caEntity_Att = do pId <- protoIs liftIO $ pcrReset liftIO $ pcrModify "a" case pId of 1 -> do req@ [AAEvidenceDescriptor dList, reqNonce@(ANonce nApp), ATPM_PCR_SELECTION pcrSelect] <- receive 1 (iKeyHandle, aikContents) <- tpmMk_Id (ekEncBlob, kEncBlob) <- caAtt_CA aikContents {- (ekEncBlob, kEncBlob) <- runWithLinks [(1, 2)] (caAtt_CA aikContents) -} sessKey <- tpmAct_Id iKeyHandle ekEncBlob let caCert :: (SignedData TPM_PUBKEY) caCert = decrypt' sessKey kEncBlob evidence <- caAtt_Mea dList let quoteExData = [AEvidence evidence, ANonce nApp, ASignedData $ SignedData (ATPM_PUBKEY (dat caCert)) (sig caCert)] (pcrComp, qSig) <- tpmQuote iKeyHandle pcrSelect quoteExData let response = [(quoteExData !! 0), reqNonce, ATPM_PCR_COMPOSITE pcrComp, (quoteExData !! 2), ASignature qSig] send 1 response return () 2 -> do [reqNonce@(ANonce nApp), ATPM_PCR_SELECTION pcrSelect] <- receive 1 (iKeyHandle, aikContents) <- tpmMk_Id (ekEncBlob, kEncBlob) <- caAtt_CA aikContents {- (ekEncBlob, kEncBlob) <- runWithLinks [(1, 2)] (caAtt_CA aikContents) -} sessKey <- tpmAct_Id iKeyHandle ekEncBlob let caCert :: (SignedData TPM_PUBKEY) caCert = decrypt' sessKey kEncBlob --evidence <- caAtt_Mea dList evidence <- return [] let quoteExData = [AEvidence evidence, ANonce nApp, ASignedData $ SignedData (ATPM_PUBKEY (dat caCert)) (sig caCert)] (pcrComp, qSig) <- tpmQuote iKeyHandle pcrSelect quoteExData let response = [reqNonce, ATPM_PCR_COMPOSITE pcrComp, (quoteExData !! 2), ASignature qSig] send 1 response return () caAtt_CA :: AikContents -> Proto (CipherText, CipherText) caAtt_CA signedContents = do myInfo <- getEntityInfo 0 let val = SignedData (ATPM_IDENTITY_CONTENTS (dat signedContents)) (sig signedContents) attChan <- liftIO $ client_init 4 send' attChan [AEntityInfo myInfo, ASignedData val] --send 2 {-1-} [AEntityInfo myInfo, ASignedData val] [ACipherText ekEncBlob, ACipherText kEncBlob] <- receive' attChan --[ACipherText ekEncBlob, ACipherText kEncBlob] <- receive 2 --1 liftIO $ close attChan return (ekEncBlob, kEncBlob) caAtt_Mea :: EvidenceDescriptor -> Proto Evidence caAtt_Mea eds = return [0,1,2] caEntity_App :: EvidenceDescriptor -> Nonce -> TPM_PCR_SELECTION -> Proto (Evidence, Nonce, TPM_PCR_COMPOSITE, (SignedData TPM_PUBKEY), Signature) caEntity_App d nonceA pcrSelect = do -- let nonceA = 34 pId <- protoIs let request = case pId of 1 -> [AAEvidenceDescriptor d, ANonce nonceA, ATPM_PCR_SELECTION pcrSelect] 2 -> [ANonce nonceA, ATPM_PCR_SELECTION pcrSelect] send 1 request case pId of 1 -> do [AEvidence e, ANonce nA, ATPM_PCR_COMPOSITE pComp, ASignedData (SignedData (ATPM_PUBKEY aikPub) aikSig), ASignature sig] <- receive 1 return (e, nA, pComp, SignedData aikPub aikSig, sig) 2 -> do [ANonce nA, ATPM_PCR_COMPOSITE pComp, ASignedData (SignedData (ATPM_PUBKEY aikPub) aikSig), ASignature sig] <- receive 1 return ([], nA, pComp, SignedData aikPub aikSig, sig) --do checks here... --return (e, nA, pComp, SignedData aikPub aikSig, sig) caEntity_CA :: LibXenVChan -> Proto () caEntity_CA attChan = do --attChan <- liftIO $ server_init vId {-[AEntityInfo eInfo, ASignedData (SignedData (ATPM_IDENTITY_CONTENTS pubKey) sig)] <- receive 1 -} [AEntityInfo eInfo, ASignedData (SignedData (ATPM_IDENTITY_CONTENTS pubKey) sig)] <- receive' attChan ekPubKey <- liftIO readPubEK let iPubKey = identityPubKey pubKey iDigest = tpm_digest $ encode iPubKey asymContents = contents iDigest blob = encode asymContents encBlob <- liftIO $ tpm_rsa_pubencrypt ekPubKey blob (_,caPriKey) <- liftIO generateCAKeyPair let caCert = realSign caPriKey (encode iPubKey) certBytes = encode (SignedData iPubKey caCert) strictCert = toStrict certBytes encryptedCert = encryptCTR aes ctr strictCert enc = fromStrict encryptedCert send' attChan [ACipherText encBlob, ACipherText enc] --send 1 [ACipherText encBlob, ACipherText enc] where symKey = TPM_SYMMETRIC_KEY (tpm_alg_aes128) (tpm_es_sym_ctr) key v:: Word8 v = 1 key = ({-B.-}Data.ByteString.Lazy.pack $ replicate 16 v) --strictKey = toStrict key aes = initAES $ toStrict key ctr = toStrict key contents dig = TPM_ASYM_CA_CONTENTS symKey dig tpmMk_Id :: Proto (TPM_KEY_HANDLE, AikContents) tpmMk_Id = liftIO $ do (aikHandle, iSig) <- makeAndLoadAIK aikPub <- attGetPubKey aikHandle iPass let aikContents = TPM_IDENTITY_CONTENTS iPass aikPub return (aikHandle, SignedData aikContents iSig) tpmAct_Id :: TPM_KEY_HANDLE -> CipherText -> Proto SymmKey tpmAct_Id iKeyHandle actInput = liftIO $ do iShn <- tpm_session_oiap tpm oShn <- tpm_session_oiap tpm sessionKey <- tpm_activateidentity tpm iShn oShn iKeyHandle iPass oPass actInput return sessionKey tpmQuote :: TPM_KEY_HANDLE -> TPM_PCR_SELECTION -> [ArmoredData] -> Proto (TPM_PCR_COMPOSITE, Signature) tpmQuote qKeyHandle pcrSelect exDataList = liftIO $ do let evBlob = packImpl exDataList evBlobSha1 = bytestringDigest $ sha1 evBlob (comp, sig) <- mkQuote qKeyHandle iPass pcrSelect evBlobSha1 return (comp, sig)
armoredsoftware/protocol
tpm/mainline/protoMonad/CAProtoMain.hs
bsd-3-clause
6,602
0
21
1,740
1,726
872
854
148
3
module System.HFind.Expr.Types ( module X , TypedName(..) ) where import qualified Data.Text as T import System.HFind.Expr.Types.AST as X import System.HFind.Expr.Types.Value as X data TypedName = TypedName !X.ValueType !X.Name instance Show TypedName where show (TypedName ty name) = show ty ++ " " ++ T.unpack name
xcv-/pipes-find
src/System/HFind/Expr/Types.hs
mit
333
0
8
61
106
64
42
13
0
{-# LANGUAGE OverloadedStrings, ExtendedDefaultRules #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {-| Plot traces to html using blaze-html Example code: @ plotHtml :: Html () plotHtml = toHtml $ plotly "myDiv" [trace] & layout . title ?~ "my plot" & layout . width ?~ 300 @ where `trace` is a value of type `Trace` -} module Graphics.Plotly.Blaze where import Text.Blaze import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Graphics.Plotly.Base import Data.Monoid ((<>)) import Data.Text.Encoding (decodeUtf8) import Data.ByteString.Lazy (toStrict) import Data.Aeson -- |`script` tag to go in the header to import the plotly.js javascript from the official CDN plotlyCDN :: H.Html plotlyCDN = H.script ! A.src "https://cdn.plot.ly/plotly-latest.min.js" $ "" -- |Activate a plot defined by a `Plotly` value plotlyJS :: Plotly -> H.Html plotlyJS (Plotly divNm trs lay) = let trJSON = decodeUtf8 $ toStrict $ encode trs layoutJSON = decodeUtf8 $ toStrict $ encode lay in H.script $ H.toHtml ("Plotly.newPlot('"<>divNm<>"', "<>trJSON<>","<>layoutJSON<>", {displayModeBar: false});") -- |Create a div for a Plotly value plotlyDiv :: Plotly -> H.Html plotlyDiv (Plotly divNm _ _) = H.div ! A.id (toValue divNm) $ "" instance ToMarkup Plotly where toMarkup pl = plotlyDiv pl >> plotlyJS pl
diffusionkinetics/open
plotlyhs/src/Graphics/Plotly/Blaze.hs
mit
1,393
0
15
262
290
161
129
23
1
{- Copyright 2012-2013 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE OverloadedStrings #-} module Plush.Run.BuiltIns.ShellState ( complete, context, set, shift, export, readonly, unset, alias, unalias, env, ) where import Control.Applicative import Data.Aeson import Data.Aeson.Types (Pair) import Data.Either (lefts) import qualified Data.HashMap.Strict as M import Data.List (foldl', sort) import Plush.Parser import Plush.Parser.Aliases (Aliases, aliasNameChar) import Plush.Run.Annotate import Plush.Run.BuiltIns.Utilities import Plush.Run.BuiltIns.Syntax import Plush.Run.Command import Plush.Run.Posix import Plush.Run.Posix.Return import Plush.Run.Posix.Utilities import Plush.Run.ShellExec import Plush.Run.ShellFlags import Plush.Run.Types import Plush.Types import Plush.Types.CommandSummary import Plush.Utilities (readMaybe) context :: (PosixLike m) => SpecialUtility m context = SpecialUtility . const $ Utility contextExec noArgsAnnotate where contextExec _args = do ctxJson <$> getVars <*> getWorkingDirectory >>= jsonOut success ctxJson vars cwd = object [ "cwd" .= cwd , "vars" .= map varInfo (sort $ M.toList vars) ] where varInfo (n,(s,m,v)) = object [ "name" .= n , "scope" .= scopeStr s , "mode" .= modeStr m , "value" .= v ] scopeStr VarShellOnly = "shell" :: String scopeStr VarExported = "env" modeStr VarReadWrite = "rw" :: String modeStr VarReadOnly = "ro" complete :: (PosixLike m) => SpecialUtility m complete = SpecialUtility $ stdSyntax [argOpt 'c'] "" go where go "" [cmdline] = go' Nothing cmdline >>= jsonOut >> success go optC [cmdline] = case readMaybe optC of Just n -> go' (Just n) cmdline >>= jsonOut >> success _ -> exitMsg 2 "non-numeric -c argument" go _ _ = exitMsg 1 "One argument only" go' optC cmdline = do aliases <- getAliases case parseCommand aliases cmdline of Left errs -> return $ object [ "parseError" .= errs ] Right (cl, _rest) -> do spans <- annotate cl optC return $ object [ "spans" .= map jsonSpan spans ] jsonSpan (Span s e, annos) = object [ "start" .= s, "end" .= e, "annotations" .= map jsonAnno annos ] jsonAnno (ExpandedTo s) = object [ "expansion" .= s ] jsonAnno (FoundCommandAnno (SpecialCommand)) = object [ ct "special" ] jsonAnno (FoundCommandAnno (DirectCommand)) = object [ ct "direct" ] jsonAnno (FoundCommandAnno (BuiltInCommand fp)) = object [ ct "builtin", "path" .= fp ] jsonAnno (FoundCommandAnno FunctionCall) = object [ ct "function" ] jsonAnno (FoundCommandAnno (ExecutableCommand fp)) = object [ ct "executable", "path" .= fp ] jsonAnno (FoundCommandAnno (UnknownCommand)) = object [ ct "unknown" ] jsonAnno (CommandSummaryAnno (CommandSummary name synop _)) = object [ "command" .= name , "synopsis" .= synop ] jsonAnno (OptionAnno d) = object [ "option" .= d ] jsonAnno (Completions cs) = object [ "completions" .= cs ] jsonAnno (UnusedAnno) = object [ "unused" .= True ] ct :: String -> Pair ct = ("commandType" .=) shift :: (PosixLike m) => SpecialUtility m shift = SpecialUtility . const $ Utility shiftExec emptyAnnotate where shiftExec [] = doShift 1 shiftExec [arg] = case readMaybe arg of Nothing -> exitMsg 1 "shift argument not numeric" Just n -> doShift n shiftExec _ = exitMsg 1 "shift takes at most one argument" doShift n = do args <- getArgs case () of _ | n < 0 -> exitMsg 1 "shift count can't be negative" | n == 0 -> success | n <= length args -> setArgs (drop n args) >> success | otherwise -> exitMsg 1 "shift count too large" -- | The set special built-in is a marvel: -- -- * It can output, but not set, shell variables: @set@ -- -- * It can set, but not output, shell positional parameters: @set a b c@ -- -- * It can set, in two different ways, shell flags: @set -x@ and @set -o xtrace@ -- -- * It can output, in two different ways, shell flags: @set -o@ and @set +o@ set :: (PosixLike m) => SpecialUtility m set = SpecialUtility . const $ Utility setExec setAnno where setExec args = case args of [] -> showVars >> success ["-o"] -> showFlags reportFmt >> success ["+o"] -> showFlags scriptFmt >> success _ -> do let (flagF, args') = processFlagArgs args getFlags >>= setFlags . flagF case args' of ("--":args'') -> setArgs args'' [] -> return () _ -> setArgs args' -- TODO: should error if there are any - or + args left success setAnno = emptyAnnotate -- TODO: should really annotate these flags showVars = getVars >>= mapM_ (outStrLn . varFmt) . sort . M.toList varFmt (n,(_,_,v)) = n ++ "=" ++ maybe "" quote v showFlags fmt = do flags <- getFlags mapM_ (outStrLn . fmt flags) flagDescriptions reportFmt flags desc = padTo 17 (fdLongName desc) ++ onOff (fdGetter desc flags) padTo n s = s ++ replicate (n - length s) ' ' onOff b = if b then "on" else "off" scriptFmt flags desc = "set" ++ plusMinus (fdGetter desc flags) ++ (fdLongName desc) plusMinus b = if b then " -o " else " +o " unset :: (PosixLike m) => SpecialUtility m unset = SpecialUtility $ stdSyntax options "" go where options = [ flag 'v', flag 'f' ] go "v" names = unsetVars names >>= returnError go "f" names = unsetFuns names go _flags names = unsetVars names >>= ifError returnError (unsetFuns names) unsetVars names = untilErrorM $ map unsetVarEntry names unsetFuns names = mapM_ unsetFun names >> success modifyVar cmdName hasModifier mkVarEntry = SpecialUtility $ stdSyntax options "" go where options = [ flag 'p' ] -- echo exports go "p" [] = showVars >> success go _flags nameVals = untilErrorM (map defVar nameVals) >>= returnError showVars = getVars >>= mapM_ (outStr . varFmt) . sort . M.toList varFmt (n, ve@(_, _, val)) | hasModifier ve = case val of Just v -> cmdName ++ " " ++ n ++ "=" ++ quote v ++ "\n" Nothing -> cmdName ++ " " ++ n ++ "\n" varFmt _ = "" defVar nameVal = do case break (== '=') nameVal of ([], v) -> errStrLn ("missing variable name: " ++ v) >> failure (name, ('=':v)) -> setVarEntry name $ mkVarEntry (Just v) (name, _) -> setVarEntry name $ mkVarEntry Nothing export :: (PosixLike m) => SpecialUtility m export = modifyVar "export" isExported (\v -> (VarExported, VarReadWrite, v)) where isExported (VarExported, _, _) = True isExported _ = False readonly :: (PosixLike m) => SpecialUtility m readonly = modifyVar "readonly" isReadOnly (\v -> (VarShellOnly, VarReadOnly, v)) where isReadOnly (_, VarReadOnly, _) = True isReadOnly _ = False alias :: (PosixLike m) => DirectUtility m alias = DirectUtility $ stdSyntax options "" (doAlias . format) where options = [ flag 'p' ] -- not POSIX, but common and matches -p in other -- POSIX commands like readonly and export doAlias fmt [] = do getAliases >>= mapM_ (outStrLn . uncurry fmt) . sort . M.toList success doAlias fmt args = modifyAliases $ \m -> foldl' (doOne fmt) ([],m) args doOne fmt (us, m) arg = let (n,w) = break (== '=') arg in if all aliasNameChar n then case w of [] -> ((maybe (Left $ "unknown alias: " ++ n) (\v -> Right $ fmt n v) $ M.lookup n m):us, m) (_:v) -> (us, M.insert n v m) -- the first char is the '=' else (Left ("invalid alias name: " ++ n) : us, m) format flags n v = prefix flags ++ n ++ '=' : quote v prefix flags = if ('p' `elem` flags) then "alias " else "" unalias :: (PosixLike m) => DirectUtility m unalias = DirectUtility $ stdSyntax [ flag 'a' ] "" doUnalias where doUnalias "a" _ = setAliases M.empty >> success doUnalias _ args = modifyAliases $ \m -> foldl' remove ([], m) args remove (us, m) n = if M.member n m then (us, M.delete n m) else ((Left $ "unknown alias: " ++ n):us, m) modifyAliases :: (PosixLike m) => (Aliases -> ([Either String String], Aliases)) -> ShellExec m ExitCode modifyAliases f = do (msgs, newAliases) <- f `fmap` getAliases setAliases newAliases mapM_ (either errStrLn outStrLn) $ reverse msgs if null $ lefts msgs then success else failure quote :: String -> String quote v = '\'' : concatMap qchar v ++ "'" where qchar '\'' = "'\"'\"'" qchar c = [c] env :: (PosixLike m) => DirectUtility m env = DirectUtility $ stdSyntax [] "" doEnv where doEnv :: (PosixLike m) => String -> Args -> ShellExec m ExitCode doEnv _flags (_:_) = exitMsg 1 "only env with no arguments is currently supported" doEnv _ _ = do bindings <- getEnv mapM_ (\(k, v) -> outStrLn $ k ++ "=" ++ v) bindings success
mzero/plush
src/Plush/Run/BuiltIns/ShellState.hs
apache-2.0
9,946
0
21
2,785
3,094
1,605
1,489
207
15
module L06.MoreParser where import L01.Validation import L03.Parser import Data.Char import Numeric import Control.Applicative import Control.Monad -- Parses the given input and returns the result. -- The remaining input is ignored. (<.>) :: Parser a -> Input -> Validation a (<.>) = error "todo" -- Exercise 1 -- Write a Functor instance for a Parser. -- ~~~ Use bindParser and valueParser ~~~ instance Functor Parser where fmap = error "todo" -- Exercise 2 -- Write an Applicative functor instance for a Parser. -- ~~~ Use bindParser and valueParser ~~~ instance Applicative Parser where pure = error "todo" (<*>) = error "todo" -- Exercise 3 -- Write a Monad instance for a Parser. instance Monad Parser where return = error "todo" (>>=) = error "todo" -- Exercise 4 -- Read documentation, ask questions. {- Check out the libraries now available to Parsers as a result of the Applicative and Monad instances. 4.1 http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Applicative.html 4.2 http://www.haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Control-Monad.html 4.3 http://haskell.org/ghc/docs/6.12.2/html/libraries/base-4.2.0.1/Data-Traversable.html 4.4 Learn about do-notation, now that we have just written a Monad instance 4.4.1 http://en.wikibooks.org/wiki/Haskell/do_Notation 4.4.2 http://www.haskell.org/onlinereport/exps.html#sect3.14 We will gently start using these libraries. Identify the pattern of computation in the problems below. -} -- Exercise 5 -- Write a parser that will parse zero or more spaces. spaces :: Parser String spaces = error "todo" -- Exercise 6 -- Write a function that applies the given parser, then parses 0 or more spaces, -- then produces the result of the original parser. -- ~~~ Use the monad instance ~~~ tok :: Parser a -> Parser a tok = error "todo" -- Exercise 7 -- Write a function that parses the given char followed by 0 or more spaces. -- ~~~ Use tok and is ~~~ charTok :: Char -> Parser Char charTok = error "todo" -- Exercise 8 -- Write a parser that parses a comma ',' followed by 0 or more spaces. -- ~~~ Use charTok ~~~ commaTok :: Parser Char commaTok = error "todo" -- Exercise 9 -- Write a parser that parses either a double-quote or a single-quote. -- ~~~ Use is and (|||) ~~~ quote :: Parser Char quote = error "todo" -- Exercise 10 -- Write a function that parses the given string (fails otherwise). -- ~~~ Use is and mapM ~~~ string :: String -> Parser String string = error "todo" -- Exercise 11 -- Write a function that parsers the given string, followed by 0 or more spaces. -- ~~~ Use tok and string ~~~ stringTok :: String -> Parser String stringTok = error "todo" -- Exercise 12 -- Write a function that tries the given parser, otherwise succeeds by producing the given value. -- ~~~ Use (|||) ~~~ option :: a -> Parser a -> Parser a option = error "todo" -- Exercise 13 -- Write a parser that parses 1 or more digits. -- ~~~ Use many1 and digit ~~~ digits1 :: Parser String digits1 = error "todo" -- Exercise 14 -- Write a function that parses one of the characters in the given string. -- ~~~ Use satisfy and elem ~~~ oneof :: String -> Parser Char oneof = error "todo" -- Exercise 15 -- Write a function that parses any character, but fails if it is in the given string. -- ~~~ Use satisfy and notElem ~~~ noneof :: String -> Parser Char noneof = error "todo" -- Exercise 16 -- Write a function that applies the first parser, runs the second parser keeping the result, -- then runs the third parser and produces the obtained result. -- ~~~ Use the Monad instance ~~~ between :: Parser o -> Parser c -> Parser a -> Parser a between = error "todo" -- Exercise 17 -- Write a function that applies the given parser in between the two given characters. -- ~~~ Use between and charTok ~~~ betweenCharTok :: Char -> Char -> Parser a -> Parser a betweenCharTok = error "todo" -- Exercise 18 -- Write a function that parses the character 'u' followed by 4 hex digits and return the character value. -- ~~~ Use readHex, isHexDigit, replicateM, satisfy and the Monad instance ~~~ hex :: Parser Char hex = error "todo" -- Exercise 19 -- Write a function that produces a non-empty list of values coming off the given parser (which must succeed at least once), -- separated by the second given parser. -- ~~~ Use list and the Monad instance ~~~ sepby1 :: Parser a -> Parser s -> Parser [a] sepby1 = error "todo" -- Exercise 20 -- Write a function that produces a list of values coming off the given parser, -- separated by the second given parser. -- ~~~ Use sepby1 and (|||) ~~~ sepby :: Parser a -> Parser s -> Parser [a] sepby = error "todo" -- Exercise 21 -- Write a parser that asserts that there is no remaining input. eof :: Parser () eof = error "todo" -- Exercise 22 -- Write a parser that produces a characer that satisfies all of the given predicates. -- ~~~ Use sequence and Data.List.and ~~~ satisfyAll :: [Char -> Bool] -> Parser Char satisfyAll = error "todo" -- Exercise 23 -- Write a parser that produces a characer that satisfies any of the given predicates. -- ~~~ Use sequence and Data.List.or ~~~ satisfyAny :: [Char -> Bool] -> Parser Char satisfyAny = error "todo" -- Exercise 24 -- Write a parser that parses between the two given characters, separated by a comma character ','. -- ~~~ Use betweenCharTok, sepby and charTok ~~~ betweenSepbyComma :: Char -> Char -> Parser a -> Parser [a] betweenSepbyComma = error "todo"
juretta/course
src/L06/MoreParser.hs
bsd-3-clause
5,629
0
9
1,125
678
381
297
129
1
{- Monads -} -- Functor => Applicative Functor => Monads fmap :: (Functor f) => (a -> b) -> f a -> f b (<*>) :: (Applicative f) => f (a -> b) -> f a -> f b (>>=) :: (Monad m) => m a -> (a -> m b) -> m b -- notice the differences among the functions intaken. {- # Monad Class every monad is an applicative functor -} class Monad' m where return :: a -> m a -- boxing (>>=) :: m a -> (a -> m b) -> m b -- bind, then class Monad m where return :: a -> m a -- like pure in ap functor (>>=) :: m a -> (a -> m b) -> m b (>>) :: m a -> m b -> m b -- default x >> y = x >>= \_ -> y fail :: String -> m a -- default fail msg = error msg instance Monad Maybe where return x = Just x Nothing >>= f = Nothing Just x >>= f = f x fail _ = Nothing {- # Walk the line -} type Birds = Int type Pole = (Birds,Birds) landLeft :: Birds -> Pole -> Pole landLeft n (left,right) = (left + n,right) landRight :: Birds -> Pole -> Pole landRight n (left,right) = (left,right + n) {- >>= -} ex1 = return (0,0) >>= landRight 2 >>= landLeft 2 >>= landRight 2 {- >> passing some value to a function that ignores its parameter and always just returns some predetermined value would always result in that predetermined value. With monads how- ever, their context and meaning has to be considered as well. ghci> Nothing >> Just 3 Nothing ghci> Just 3 >> Just 4 Just 4 ghci> Just 3 >> Nothing Nothing -} ex2 = return (0,0) >>= landLeft 1 >> Nothing >>= landRight 1 {- # do notation -} -- assign 3 to x, "!" to y foo :: Maybe String foo = Just 3 >>= (\x -> Just "!" >>= (\y -> Just (show x ++ y))) foo :: Maybe String foo = do x <- Just 3 y <- Just "!" Just (show x ++ y) {- do - imperative code? do expressions are written line by line, they may look like imperative code to some people. But the thing is, they're just sequential, as each value in each line relies on the result of the previous ones, along with their contexts More like nested-functions -} routine :: Maybe Pole routine = do start <- return (0,0) first <- landLeft 2 start second <- landRight 2 first landLeft 1 second routine :: Maybe Pole routine = do start <- return (0,0) first <- landLeft 2 start Nothing -- sequence the monadic value but we ignore its result second <- landRight 2 first landLeft 1 second -- pattern matching on the LHS. If fail, fail msg justH :: Maybe Char justH = do (x:xs) <- Just "hello" return x {- # List monad non-deterministic values -} instance Monad [] where return x = [x] xs >>= f = concat (map f xs) -- flatten fail _ = [] {- > [1,2] >>= \n -> ['a','b'] >>= \ch -> return (n,ch) [(1,'a'),(1,'b'),(2,'a'),(2,'b')] > [ (n,ch) | n <- [1,2], ch <- ['a','b'] ] [(1,'a'),(1,'b'),(2,'a'),(2,'b')] list comprehensions are just syntactic sugar for using lists as monads. In the end, list comprehensions and lists in do notation translate to using >>= to do computations that feature non-determinism. -} listOfTuples :: [(Int,Char)] listOfTuples = do n <- [1,2] ch <- ['a','b'] return (n,ch) {- MonadPlus type class is for monads that can also act as monoids -} class Monad m => MonadPlus m where mzero :: m a mplus :: m a -> m a -> m a instance MonadPlus [] where mzero = [] mplus = (++) {- > [1..50] >>= (\x -> guard ('7' `elem` show x) >> return x) [7,17,27,37,47] -} guard :: (MonadPlus m) => Bool -> m () guard True = return () guard False = mzero {- # Monad law Left identity Right identity Associativity -} {- Left identity return x >>= f \equiv f x -} li1 = return 3 >>= (\x -> Just (x+100000)) li2 = (\x -> Just (x+100000)) 3 {- Right identity m >>= return \equiv m -} ri = Just "move on up" >>= (\x -> return x) {- Associativity (m >>= f) >>= g \equiv m >>= (\x -> f x >>= g) -} assoc1 = return (0,0) >>= landRight 2 >>= landLeft 2 >>= landRight 2 assoc2 = return (0,0) >>= (\x -> landRight 2 x >>= (\y -> landLeft 2 y >>= (\z -> landRight 2 z))) -- function composition at monad level (<=<) :: (Monad m) => (b -> m c) -> (a -> m b) -> (a -> m c) f <=< g = (\x -> g x >>= f)
idf/haskell-examples
fundamentals/11_monads.hs
bsd-3-clause
4,186
0
14
1,069
1,282
662
620
80
1
{-# LANGUAGE Haskell2010 #-} {-# LINE 1 "Network/HPACK/Types.hs" #-} {-# LANGUAGE DeriveDataTypeable #-} module Network.HPACK.Types ( -- * Header HeaderName , HeaderValue , HeaderStuff , Header , HeaderList , TokenHeader , TokenHeaderList -- * Misc , Index , HIndex(..) -- * Encoding and decoding , CompressionAlgo(..) , EncodeStrategy(..) , defaultEncodeStrategy , DecodeError(..) -- * Buffer , Buffer , BufferSize , BufferOverrun(..) ) where import Control.Exception as E import Data.ByteString (ByteString) import Data.Typeable import Data.Word (Word8) import Foreign.Ptr (Ptr) import Network.HPACK.Token (Token) ---------------------------------------------------------------- -- | Header name. type HeaderName = ByteString -- | Header value. type HeaderValue = ByteString -- | Header. type Header = (HeaderName, HeaderValue) -- | Header list. type HeaderList = [Header] -- | To be a 'HeaderName' or 'HeaderValue'. type HeaderStuff = ByteString type TokenHeader = (Token, HeaderValue) type TokenHeaderList = [TokenHeader] ---------------------------------------------------------------- -- | Index for table. type Index = Int data HIndex = SIndex Int | DIndex Int deriving (Eq, Ord, Show) ---------------------------------------------------------------- -- | Compression algorithms for HPACK encoding. data CompressionAlgo = Naive -- ^ No compression | Static -- ^ Using indices in the static table only | Linear -- ^ Using indices deriving (Eq, Show) -- | Strategy for HPACK encoding. data EncodeStrategy = EncodeStrategy { -- | Which compression algorithm is used. compressionAlgo :: !CompressionAlgo -- | Whether or not to use Huffman encoding for strings. , useHuffman :: !Bool } deriving (Eq, Show) -- | Default 'EncodeStrategy'. -- -- >>> defaultEncodeStrategy -- EncodeStrategy {compressionAlgo = Linear, useHuffman = False} defaultEncodeStrategy :: EncodeStrategy defaultEncodeStrategy = EncodeStrategy { compressionAlgo = Linear , useHuffman = False } ---------------------------------------------------------------- -- | Errors for decoder. data DecodeError = IndexOverrun Index -- ^ Index is out of range | EosInTheMiddle -- ^ Eos appears in the middle of huffman string | IllegalEos -- ^ Non-eos appears in the end of huffman string | TooLongEos -- ^ Eos of huffman string is more than 7 bits | EmptyEncodedString -- ^ Encoded string has no length | TooSmallTableSize -- ^ A peer set the dynamic table size less than 32 | TooLargeTableSize -- ^ A peer tried to change the dynamic table size over the limit | IllegalTableSizeUpdate -- ^ Table size update at the non-beginning | HeaderBlockTruncated | IllegalHeaderName deriving (Eq,Show,Typeable) instance Exception DecodeError ---------------------------------------------------------------- -- | Buffer type. type Buffer = Ptr Word8 -- | The size of buffer. type BufferSize = Int data BufferOverrun = BufferOverrun -- ^ The buffer size is not enough deriving (Eq,Show,Typeable) instance Exception BufferOverrun
phischu/fragnix
tests/packages/scotty/Network.HPACK.Types.hs
bsd-3-clause
3,322
0
9
758
450
293
157
68
1
{- (c) The GRASP/AQUA Project, Glasgow University, 1993-1998 \section[Specialise]{Stamping out overloading, and (optionally) polymorphism} -} {-# LANGUAGE CPP #-} module ETA.Specialise.Specialise ( specProgram, specUnfolding ) where #include "HsVersions.h" import ETA.BasicTypes.Id import ETA.TypeCheck.TcType hiding( substTy, extendTvSubstList ) import ETA.Types.Type hiding( substTy, extendTvSubstList ) import ETA.Types.Coercion( Coercion ) import ETA.BasicTypes.Module( Module ) import ETA.SimplCore.CoreMonad import qualified ETA.Core.CoreSubst as CoreSubst import ETA.Core.CoreUnfold import ETA.BasicTypes.VarSet import ETA.BasicTypes.VarEnv import ETA.Core.CoreSyn import ETA.Specialise.Rules import ETA.Core.PprCore ( pprParendExpr ) import ETA.Core.CoreUtils ( exprIsTrivial, applyTypeToArgs ) import ETA.Core.CoreFVs ( exprFreeVars, exprsFreeVars, idFreeVars ) import ETA.BasicTypes.UniqSupply import ETA.BasicTypes.Name import ETA.BasicTypes.MkId ( voidArgId, voidPrimId ) import ETA.Utils.Maybes ( catMaybes, isJust ) import ETA.BasicTypes.BasicTypes import ETA.Main.HscTypes import ETA.Utils.Bag import ETA.Main.DynFlags import ETA.Utils.Util import ETA.Utils.Outputable import ETA.Utils.FastString import ETA.Utils.State #if __GLASGOW_HASKELL__ < 709 import Control.Applicative (Applicative(..)) #endif import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import qualified ETA.Utils.FiniteMap as Map {- ************************************************************************ * * \subsection[notes-Specialise]{Implementation notes [SLPJ, Aug 18 1993]} * * ************************************************************************ These notes describe how we implement specialisation to eliminate overloading. The specialisation pass works on Core syntax, complete with all the explicit dictionary application, abstraction and construction as added by the type checker. The existing type checker remains largely as it is. One important thought: the {\em types} passed to an overloaded function, and the {\em dictionaries} passed are mutually redundant. If the same function is applied to the same type(s) then it is sure to be applied to the same dictionary(s)---or rather to the same {\em values}. (The arguments might look different but they will evaluate to the same value.) Second important thought: we know that we can make progress by treating dictionary arguments as static and worth specialising on. So we can do without binding-time analysis, and instead specialise on dictionary arguments and no others. The basic idea ~~~~~~~~~~~~~~ Suppose we have let f = <f_rhs> in <body> and suppose f is overloaded. STEP 1: CALL-INSTANCE COLLECTION We traverse <body>, accumulating all applications of f to types and dictionaries. (Might there be partial applications, to just some of its types and dictionaries? In principle yes, but in practice the type checker only builds applications of f to all its types and dictionaries, so partial applications could only arise as a result of transformation, and even then I think it's unlikely. In any case, we simply don't accumulate such partial applications.) STEP 2: EQUIVALENCES So now we have a collection of calls to f: f t1 t2 d1 d2 f t3 t4 d3 d4 ... Notice that f may take several type arguments. To avoid ambiguity, we say that f is called at type t1/t2 and t3/t4. We take equivalence classes using equality of the *types* (ignoring the dictionary args, which as mentioned previously are redundant). STEP 3: SPECIALISATION For each equivalence class, choose a representative (f t1 t2 d1 d2), and create a local instance of f, defined thus: f@t1/t2 = <f_rhs> t1 t2 d1 d2 f_rhs presumably has some big lambdas and dictionary lambdas, so lots of simplification will now result. However we don't actually *do* that simplification. Rather, we leave it for the simplifier to do. If we *did* do it, though, we'd get more call instances from the specialised RHS. We can work out what they are by instantiating the call-instance set from f's RHS with the types t1, t2. Add this new id to f's IdInfo, to record that f has a specialised version. Before doing any of this, check that f's IdInfo doesn't already tell us about an existing instance of f at the required type/s. (This might happen if specialisation was applied more than once, or it might arise from user SPECIALIZE pragmas.) Recursion ~~~~~~~~~ Wait a minute! What if f is recursive? Then we can't just plug in its right-hand side, can we? But it's ok. The type checker *always* creates non-recursive definitions for overloaded recursive functions. For example: f x = f (x+x) -- Yes I know its silly becomes f a (d::Num a) = let p = +.sel a d in letrec fl (y::a) = fl (p y y) in fl We still have recusion for non-overloaded functions which we speciailise, but the recursive call should get specialised to the same recursive version. Polymorphism 1 ~~~~~~~~~~~~~~ All this is crystal clear when the function is applied to *constant types*; that is, types which have no type variables inside. But what if it is applied to non-constant types? Suppose we find a call of f at type t1/t2. There are two possibilities: (a) The free type variables of t1, t2 are in scope at the definition point of f. In this case there's no problem, we proceed just as before. A common example is as follows. Here's the Haskell: g y = let f x = x+x in f y + f y After typechecking we have g a (d::Num a) (y::a) = let f b (d'::Num b) (x::b) = +.sel b d' x x in +.sel a d (f a d y) (f a d y) Notice that the call to f is at type type "a"; a non-constant type. Both calls to f are at the same type, so we can specialise to give: g a (d::Num a) (y::a) = let f@a (x::a) = +.sel a d x x in +.sel a d (f@a y) (f@a y) (b) The other case is when the type variables in the instance types are *not* in scope at the definition point of f. The example we are working with above is a good case. There are two instances of (+.sel a d), but "a" is not in scope at the definition of +.sel. Can we do anything? Yes, we can "common them up", a sort of limited common sub-expression deal. This would give: g a (d::Num a) (y::a) = let +.sel@a = +.sel a d f@a (x::a) = +.sel@a x x in +.sel@a (f@a y) (f@a y) This can save work, and can't be spotted by the type checker, because the two instances of +.sel weren't originally at the same type. Further notes on (b) * There are quite a few variations here. For example, the defn of +.sel could be floated ouside the \y, to attempt to gain laziness. It certainly mustn't be floated outside the \d because the d has to be in scope too. * We don't want to inline f_rhs in this case, because that will duplicate code. Just commoning up the call is the point. * Nothing gets added to +.sel's IdInfo. * Don't bother unless the equivalence class has more than one item! Not clear whether this is all worth it. It is of course OK to simply discard call-instances when passing a big lambda. Polymorphism 2 -- Overloading ~~~~~~~~~~~~~~ Consider a function whose most general type is f :: forall a b. Ord a => [a] -> b -> b There is really no point in making a version of g at Int/Int and another at Int/Bool, because it's only instancing the type variable "a" which buys us any efficiency. Since g is completely polymorphic in b there ain't much point in making separate versions of g for the different b types. That suggests that we should identify which of g's type variables are constrained (like "a") and which are unconstrained (like "b"). Then when taking equivalence classes in STEP 2, we ignore the type args corresponding to unconstrained type variable. In STEP 3 we make polymorphic versions. Thus: f@t1/ = /\b -> <f_rhs> t1 b d1 d2 We do this. Dictionary floating ~~~~~~~~~~~~~~~~~~~ Consider this f a (d::Num a) = let g = ... in ...(let d1::Ord a = Num.Ord.sel a d in g a d1)... Here, g is only called at one type, but the dictionary isn't in scope at the definition point for g. Usually the type checker would build a definition for d1 which enclosed g, but the transformation system might have moved d1's defn inward. Solution: float dictionary bindings outwards along with call instances. Consider f x = let g p q = p==q h r s = (r+s, g r s) in h x x Before specialisation, leaving out type abstractions we have f df x = let g :: Eq a => a -> a -> Bool g dg p q = == dg p q h :: Num a => a -> a -> (a, Bool) h dh r s = let deq = eqFromNum dh in (+ dh r s, g deq r s) in h df x x After specialising h we get a specialised version of h, like this: h' r s = let deq = eqFromNum df in (+ df r s, g deq r s) But we can't naively make an instance for g from this, because deq is not in scope at the defn of g. Instead, we have to float out the (new) defn of deq to widen its scope. Notice that this floating can't be done in advance -- it only shows up when specialisation is done. User SPECIALIZE pragmas ~~~~~~~~~~~~~~~~~~~~~~~ Specialisation pragmas can be digested by the type checker, and implemented by adding extra definitions along with that of f, in the same way as before f@t1/t2 = <f_rhs> t1 t2 d1 d2 Indeed the pragmas *have* to be dealt with by the type checker, because only it knows how to build the dictionaries d1 and d2! For example g :: Ord a => [a] -> [a] {-# SPECIALIZE f :: [Tree Int] -> [Tree Int] #-} Here, the specialised version of g is an application of g's rhs to the Ord dictionary for (Tree Int), which only the type checker can conjure up. There might not even *be* one, if (Tree Int) is not an instance of Ord! (All the other specialision has suitable dictionaries to hand from actual calls.) Problem. The type checker doesn't have to hand a convenient <f_rhs>, because it is buried in a complex (as-yet-un-desugared) binding group. Maybe we should say f@t1/t2 = f* t1 t2 d1 d2 where f* is the Id f with an IdInfo which says "inline me regardless!". Indeed all the specialisation could be done in this way. That in turn means that the simplifier has to be prepared to inline absolutely any in-scope let-bound thing. Again, the pragma should permit polymorphism in unconstrained variables: h :: Ord a => [a] -> b -> b {-# SPECIALIZE h :: [Int] -> b -> b #-} We *insist* that all overloaded type variables are specialised to ground types, (and hence there can be no context inside a SPECIALIZE pragma). We *permit* unconstrained type variables to be specialised to - a ground type - or left as a polymorphic type variable but nothing in between. So {-# SPECIALIZE h :: [Int] -> [c] -> [c] #-} is *illegal*. (It can be handled, but it adds complication, and gains the programmer nothing.) SPECIALISING INSTANCE DECLARATIONS ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider instance Foo a => Foo [a] where ... {-# SPECIALIZE instance Foo [Int] #-} The original instance decl creates a dictionary-function definition: dfun.Foo.List :: forall a. Foo a -> Foo [a] The SPECIALIZE pragma just makes a specialised copy, just as for ordinary function definitions: dfun.Foo.List@Int :: Foo [Int] dfun.Foo.List@Int = dfun.Foo.List Int dFooInt The information about what instance of the dfun exist gets added to the dfun's IdInfo in the same way as a user-defined function too. Automatic instance decl specialisation? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Can instance decls be specialised automatically? It's tricky. We could collect call-instance information for each dfun, but then when we specialised their bodies we'd get new call-instances for ordinary functions; and when we specialised their bodies, we might get new call-instances of the dfuns, and so on. This all arises because of the unrestricted mutual recursion between instance decls and value decls. Still, there's no actual problem; it just means that we may not do all the specialisation we could theoretically do. Furthermore, instance decls are usually exported and used non-locally, so we'll want to compile enough to get those specialisations done. Lastly, there's no such thing as a local instance decl, so we can survive solely by spitting out *usage* information, and then reading that back in as a pragma when next compiling the file. So for now, we only specialise instance decls in response to pragmas. SPITTING OUT USAGE INFORMATION ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ To spit out usage information we need to traverse the code collecting call-instance information for all imported (non-prelude?) functions and data types. Then we equivalence-class it and spit it out. This is done at the top-level when all the call instances which escape must be for imported functions and data types. *** Not currently done *** Partial specialisation by pragmas ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What about partial specialisation: k :: (Ord a, Eq b) => [a] -> b -> b -> [a] {-# SPECIALIZE k :: Eq b => [Int] -> b -> b -> [a] #-} or even {-# SPECIALIZE k :: Eq b => [Int] -> [b] -> [b] -> [a] #-} Seems quite reasonable. Similar things could be done with instance decls: instance (Foo a, Foo b) => Foo (a,b) where ... {-# SPECIALIZE instance Foo a => Foo (a,Int) #-} {-# SPECIALIZE instance Foo b => Foo (Int,b) #-} Ho hum. Things are complex enough without this. I pass. Requirements for the simplifer ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The simplifier has to be able to take advantage of the specialisation. * When the simplifier finds an application of a polymorphic f, it looks in f's IdInfo in case there is a suitable instance to call instead. This converts f t1 t2 d1 d2 ===> f_t1_t2 Note that the dictionaries get eaten up too! * Dictionary selection operations on constant dictionaries must be short-circuited: +.sel Int d ===> +Int The obvious way to do this is in the same way as other specialised calls: +.sel has inside it some IdInfo which tells that if it's applied to the type Int then it should eat a dictionary and transform to +Int. In short, dictionary selectors need IdInfo inside them for constant methods. * Exactly the same applies if a superclass dictionary is being extracted: Eq.sel Int d ===> dEqInt * Something similar applies to dictionary construction too. Suppose dfun.Eq.List is the function taking a dictionary for (Eq a) to one for (Eq [a]). Then we want dfun.Eq.List Int d ===> dEq.List_Int Where does the Eq [Int] dictionary come from? It is built in response to a SPECIALIZE pragma on the Eq [a] instance decl. In short, dfun Ids need IdInfo with a specialisation for each constant instance of their instance declaration. All this uses a single mechanism: the SpecEnv inside an Id What does the specialisation IdInfo look like? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The SpecEnv of an Id maps a list of types (the template) to an expression [Type] |-> Expr For example, if f has this SpecInfo: [Int, a] -> \d:Ord Int. f' a it means that we can replace the call f Int t ===> (\d. f' t) This chucks one dictionary away and proceeds with the specialised version of f, namely f'. What can't be done this way? ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is no way, post-typechecker, to get a dictionary for (say) Eq a from a dictionary for Eq [a]. So if we find ==.sel [t] d we can't transform to eqList (==.sel t d') where eqList :: (a->a->Bool) -> [a] -> [a] -> Bool Of course, we currently have no way to automatically derive eqList, nor to connect it to the Eq [a] instance decl, but you can imagine that it might somehow be possible. Taking advantage of this is permanently ruled out. Still, this is no great hardship, because we intend to eliminate overloading altogether anyway! A note about non-tyvar dictionaries ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Ids have types like forall a,b,c. Eq a -> Ord [a] -> tau This seems curious at first, because we usually only have dictionary args whose types are of the form (C a) where a is a type variable. But this doesn't hold for the functions arising from instance decls, which sometimes get arguments with types of form (C (T a)) for some type constructor T. Should we specialise wrt this compound-type dictionary? We used to say "no", saying: "This is a heuristic judgement, as indeed is the fact that we specialise wrt only dictionaries. We choose *not* to specialise wrt compound dictionaries because at the moment the only place they show up is in instance decls, where they are simply plugged into a returned dictionary. So nothing is gained by specialising wrt them." But it is simpler and more uniform to specialise wrt these dicts too; and in future GHC is likely to support full fledged type signatures like f :: Eq [(a,b)] => ... ************************************************************************ * * \subsubsection{The new specialiser} * * ************************************************************************ Our basic game plan is this. For let(rec) bound function f :: (C a, D c) => (a,b,c,d) -> Bool * Find any specialised calls of f, (f ts ds), where ts are the type arguments t1 .. t4, and ds are the dictionary arguments d1 .. d2. * Add a new definition for f1 (say): f1 = /\ b d -> (..body of f..) t1 b t3 d d1 d2 Note that we abstract over the unconstrained type arguments. * Add the mapping [t1,b,t3,d] |-> \d1 d2 -> f1 b d to the specialisations of f. This will be used by the simplifier to replace calls (f t1 t2 t3 t4) da db by (\d1 d1 -> f1 t2 t4) da db All the stuff about how many dictionaries to discard, and what types to apply the specialised function to, are handled by the fact that the SpecEnv contains a template for the result of the specialisation. We don't build *partial* specialisations for f. For example: f :: Eq a => a -> a -> Bool {-# SPECIALISE f :: (Eq b, Eq c) => (b,c) -> (b,c) -> Bool #-} Here, little is gained by making a specialised copy of f. There's a distinct danger that the specialised version would first build a dictionary for (Eq b, Eq c), and then select the (==) method from it! Even if it didn't, not a great deal is saved. We do, however, generate polymorphic, but not overloaded, specialisations: f :: Eq a => [a] -> b -> b -> b ... SPECIALISE f :: [Int] -> b -> b -> b ... Hence, the invariant is this: *** no specialised version is overloaded *** ************************************************************************ * * \subsubsection{The exported function} * * ************************************************************************ -} specProgram :: ModGuts -> CoreM ModGuts specProgram guts@(ModGuts { mg_module = this_mod , mg_rules = local_rules , mg_binds = binds }) = do { dflags <- getDynFlags -- Specialise the bindings of this module ; (binds', uds) <- runSpecM dflags (go binds) -- Specialise imported functions ; hpt_rules <- getRuleBase ; let rule_base = extendRuleBaseList hpt_rules local_rules ; (new_rules, spec_binds) <- specImports dflags this_mod emptyVarSet rule_base uds ; let final_binds | null spec_binds = binds' | otherwise = Rec (flattenBinds spec_binds) : binds' -- Note [Glom the bindings if imported functions are specialised] ; return (guts { mg_binds = final_binds , mg_rules = new_rules ++ local_rules }) } where -- We need to start with a Subst that knows all the things -- that are in scope, so that the substitution engine doesn't -- accidentally re-use a unique that's already in use -- Easiest thing is to do it all at once, as if all the top-level -- decls were mutually recursive top_subst = SE { se_subst = CoreSubst.mkEmptySubst $ mkInScopeSet $ mkVarSet $ bindersOfBinds binds , se_interesting = emptyVarSet } go [] = return ([], emptyUDs) go (bind:binds) = do (binds', uds) <- go binds (bind', uds') <- specBind top_subst bind uds return (bind' ++ binds', uds') specImports :: DynFlags -> Module -> VarSet -- Don't specialise these ones -- See Note [Avoiding recursive specialisation] -> RuleBase -- Rules from this module and the home package -- (but not external packages, which can change) -> UsageDetails -- Calls for imported things, and floating bindings -> CoreM ( [CoreRule] -- New rules , [CoreBind] ) -- Specialised bindings and floating bindings specImports dflags this_mod done rule_base uds = do { let import_calls = varEnvElts (ud_calls uds) ; (rules, spec_binds) <- go rule_base import_calls ; return (rules, wrapDictBinds (ud_binds uds) spec_binds) } where go _ [] = return ([], []) go rb (CIS fn calls_for_fn : other_calls) = do { (rules1, spec_binds1) <- specImport dflags this_mod done rb fn $ Map.toList calls_for_fn ; (rules2, spec_binds2) <- go (extendRuleBaseList rb rules1) other_calls ; return (rules1 ++ rules2, spec_binds1 ++ spec_binds2) } specImport :: DynFlags -> Module -> VarSet -- Don't specialise these -- See Note [Avoiding recursive specialisation] -> RuleBase -- Rules from this module -> Id -> [CallInfo] -- Imported function and calls for it -> CoreM ( [CoreRule] -- New rules , [CoreBind] ) -- Specialised bindings specImport dflags this_mod done rb fn calls_for_fn | fn `elemVarSet` done = return ([], []) -- No warning. This actually happens all the time -- when specialising a recursive function, because -- the RHS of the specialised function contains a recursive -- call to the original function | null calls_for_fn -- We filtered out all the calls in deleteCallsMentioning = return ([], []) | wantSpecImport dflags unfolding , Just rhs <- maybeUnfoldingTemplate unfolding = do { -- Get rules from the external package state -- We keep doing this in case we "page-fault in" -- more rules as we go along ; hsc_env <- getHscEnv ; eps <- liftIO $ hscEPS hsc_env ; let full_rb = unionRuleBase rb (eps_rule_base eps) rules_for_fn = getRules full_rb fn ; (rules1, spec_pairs, uds) <- runSpecM dflags $ specCalls (Just this_mod) emptySpecEnv rules_for_fn calls_for_fn fn rhs ; let spec_binds1 = [NonRec b r | (b,r) <- spec_pairs] -- After the rules kick in we may get recursion, but -- we rely on a global GlomBinds to sort that out later -- See Note [Glom the bindings if imported functions are specialised] -- Now specialise any cascaded calls ; (rules2, spec_binds2) <- -- pprTrace "specImport" (ppr fn $$ ppr uds $$ ppr rhs) $ specImports dflags this_mod (extendVarSet done fn) (extendRuleBaseList rb rules1) uds ; return (rules2 ++ rules1, spec_binds2 ++ spec_binds1) } | otherwise = WARN( True, hang (ptext (sLit "specImport discarding:") <+> ppr fn <+> dcolon <+> ppr (idType fn)) 2 ( (text "want:" <+> ppr (wantSpecImport dflags unfolding)) $$ (text "stable:" <+> ppr (isStableUnfolding unfolding)) $$ (text "calls:" <+> vcat (map (pprCallInfo fn) calls_for_fn)) ) ) return ([], []) where unfolding = realIdUnfolding fn -- We want to see the unfolding even for loop breakers wantSpecImport :: DynFlags -> Unfolding -> Bool -- See Note [Specialise imported INLINABLE things] wantSpecImport dflags unf = case unf of NoUnfolding -> False OtherCon {} -> False DFunUnfolding {} -> True CoreUnfolding { uf_src = src, uf_guidance = _guidance } | gopt Opt_SpecialiseAggressively dflags -> True | isStableSource src -> True -- Specialise even INLINE things; it hasn't inlined yet, -- so perhaps it never will. Moreover it may have calls -- inside it that we want to specialise | otherwise -> False -- Stable, not INLINE, hence INLINEABLE {- Note [Specialise imported INLINABLE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What imported functions do we specialise? The basic set is * DFuns and things with INLINABLE pragmas. but with -fspecialise-aggressively we add * Anything with an unfolding template Trac #8874 has a good example of why we want to auto-specialise DFuns. We have the -fspecialise-aggressively flag (usually off), because we risk lots of orphan modules from over-vigorous specialisation. However it's not a big deal: anything non-recursive with an unfolding-template will probably have been inlined already. Note [Glom the bindings if imported functions are specialised] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Suppose we have an imported, *recursive*, INLINABLE function f :: Eq a => a -> a f = /\a \d x. ...(f a d)... In the module being compiled we have g x = f (x::Int) Now we'll make a specialised function f_spec :: Int -> Int f_spec = \x -> ...(f Int dInt)... {-# RULE f Int _ = f_spec #-} g = \x. f Int dInt x Note that f_spec doesn't look recursive After rewriting with the RULE, we get f_spec = \x -> ...(f_spec)... BUT since f_spec was non-recursive before it'll *stay* non-recursive. The occurrence analyser never turns a NonRec into a Rec. So we must make sure that f_spec is recursive. Easiest thing is to make all the specialisations for imported bindings recursive. Note [Avoiding recursive specialisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we specialise 'f' we may find new overloaded calls to 'g', 'h' in 'f's RHS. So we want to specialise g,h. But we don't want to specialise f any more! It's possible that f's RHS might have a recursive yet-more-specialised call, so we'd diverge in that case. And if the call is to the same type, one specialisation is enough. Avoiding this recursive specialisation loop is the reason for the 'done' VarSet passed to specImports and specImport. ************************************************************************ * * \subsubsection{@specExpr@: the main function} * * ************************************************************************ -} data SpecEnv = SE { se_subst :: CoreSubst.Subst -- We carry a substitution down: -- a) we must clone any binding that might float outwards, -- to avoid name clashes -- b) we carry a type substitution to use when analysing -- the RHS of specialised bindings (no type-let!) , se_interesting :: VarSet -- Dict Ids that we know something about -- and hence may be worth specialising against -- See Note [Interesting dictionary arguments] } emptySpecEnv :: SpecEnv emptySpecEnv = SE { se_subst = CoreSubst.emptySubst, se_interesting = emptyVarSet} specVar :: SpecEnv -> Id -> CoreExpr specVar env v = CoreSubst.lookupIdSubst (text "specVar") (se_subst env) v specExpr :: SpecEnv -> CoreExpr -> SpecM (CoreExpr, UsageDetails) ---------------- First the easy cases -------------------- specExpr env (Type ty) = return (Type (substTy env ty), emptyUDs) specExpr env (Coercion co) = return (Coercion (substCo env co), emptyUDs) specExpr env (Var v) = return (specVar env v, emptyUDs) specExpr _ (Lit lit) = return (Lit lit, emptyUDs) specExpr env (Cast e co) = do { (e', uds) <- specExpr env e ; return ((Cast e' (substCo env co)), uds) } specExpr env (Tick tickish body) = do { (body', uds) <- specExpr env body ; return (Tick (specTickish env tickish) body', uds) } ---------------- Applications might generate a call instance -------------------- specExpr env expr@(App {}) = go expr [] where go (App fun arg) args = do (arg', uds_arg) <- specExpr env arg (fun', uds_app) <- go fun (arg':args) return (App fun' arg', uds_arg `plusUDs` uds_app) go (Var f) args = case specVar env f of Var f' -> return (Var f', mkCallUDs env f' args) e' -> return (e', emptyUDs) -- I don't expect this! go other _ = specExpr env other ---------------- Lambda/case require dumping of usage details -------------------- specExpr env e@(Lam _ _) = do (body', uds) <- specExpr env' body let (free_uds, dumped_dbs) = dumpUDs bndrs' uds return (mkLams bndrs' (wrapDictBindsE dumped_dbs body'), free_uds) where (bndrs, body) = collectBinders e (env', bndrs') = substBndrs env bndrs -- More efficient to collect a group of binders together all at once -- and we don't want to split a lambda group with dumped bindings specExpr env (Case scrut case_bndr ty alts) = do { (scrut', scrut_uds) <- specExpr env scrut ; (scrut'', case_bndr', alts', alts_uds) <- specCase env scrut' case_bndr alts ; return (Case scrut'' case_bndr' (substTy env ty) alts' , scrut_uds `plusUDs` alts_uds) } ---------------- Finally, let is the interesting case -------------------- specExpr env (Let bind body) = do { -- Clone binders (rhs_env, body_env, bind') <- cloneBindSM env bind -- Deal with the body ; (body', body_uds) <- specExpr body_env body -- Deal with the bindings ; (binds', uds) <- specBind rhs_env bind' body_uds -- All done ; return (foldr Let body' binds', uds) } specTickish :: SpecEnv -> Tickish Id -> Tickish Id specTickish env (Breakpoint ix ids) = Breakpoint ix [ id' | id <- ids, Var id' <- [specVar env id]] -- drop vars from the list if they have a non-variable substitution. -- should never happen, but it's harmless to drop them anyway. specTickish _ other_tickish = other_tickish specCase :: SpecEnv -> CoreExpr -- Scrutinee, already done -> Id -> [CoreAlt] -> SpecM ( CoreExpr -- New scrutinee , Id , [CoreAlt] , UsageDetails) specCase env scrut' case_bndr [(con, args, rhs)] | isDictId case_bndr -- See Note [Floating dictionaries out of cases] , interestingDict env scrut' , not (isDeadBinder case_bndr && null sc_args') = do { (case_bndr_flt : sc_args_flt) <- mapM clone_me (case_bndr' : sc_args') ; let sc_rhss = [ Case (Var case_bndr_flt) case_bndr' (idType sc_arg') [(con, args', Var sc_arg')] | sc_arg' <- sc_args' ] -- Extend the substitution for RHS to map the *original* binders -- to their floated verions. mb_sc_flts :: [Maybe DictId] mb_sc_flts = map (lookupVarEnv clone_env) args' clone_env = zipVarEnv sc_args' sc_args_flt subst_prs = (case_bndr, Var case_bndr_flt) : [ (arg, Var sc_flt) | (arg, Just sc_flt) <- args `zip` mb_sc_flts ] env_rhs' = env_rhs { se_subst = CoreSubst.extendIdSubstList (se_subst env_rhs) subst_prs , se_interesting = se_interesting env_rhs `extendVarSetList` (case_bndr_flt : sc_args_flt) } ; (rhs', rhs_uds) <- specExpr env_rhs' rhs ; let scrut_bind = mkDB (NonRec case_bndr_flt scrut') case_bndr_set = unitVarSet case_bndr_flt sc_binds = [(NonRec sc_arg_flt sc_rhs, case_bndr_set) | (sc_arg_flt, sc_rhs) <- sc_args_flt `zip` sc_rhss ] flt_binds = scrut_bind : sc_binds (free_uds, dumped_dbs) = dumpUDs (case_bndr':args') rhs_uds all_uds = flt_binds `addDictBinds` free_uds alt' = (con, args', wrapDictBindsE dumped_dbs rhs') ; return (Var case_bndr_flt, case_bndr', [alt'], all_uds) } where (env_rhs, (case_bndr':args')) = substBndrs env (case_bndr:args) sc_args' = filter is_flt_sc_arg args' clone_me bndr = do { uniq <- getUniqueM ; return (mkUserLocal occ uniq ty loc) } where name = idName bndr ty = idType bndr occ = nameOccName name loc = getSrcSpan name arg_set = mkVarSet args' is_flt_sc_arg var = isId var && not (isDeadBinder var) && isDictTy var_ty && not (tyVarsOfType var_ty `intersectsVarSet` arg_set) where var_ty = idType var specCase env scrut case_bndr alts = do { (alts', uds_alts) <- mapAndCombineSM spec_alt alts ; return (scrut, case_bndr', alts', uds_alts) } where (env_alt, case_bndr') = substBndr env case_bndr spec_alt (con, args, rhs) = do (rhs', uds) <- specExpr env_rhs rhs let (free_uds, dumped_dbs) = dumpUDs (case_bndr' : args') uds return ((con, args', wrapDictBindsE dumped_dbs rhs'), free_uds) where (env_rhs, args') = substBndrs env_alt args {- Note [Floating dictionaries out of cases] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider g = \d. case d of { MkD sc ... -> ...(f sc)... } Naively we can't float d2's binding out of the case expression, because 'sc' is bound by the case, and that in turn means we can't specialise f, which seems a pity. So we invert the case, by floating out a binding for 'sc_flt' thus: sc_flt = case d of { MkD sc ... -> sc } Now we can float the call instance for 'f'. Indeed this is just what'll happen if 'sc' was originally bound with a let binding, but case is more efficient, and necessary with equalities. So it's good to work with both. You might think that this won't make any difference, because the call instance will only get nuked by the \d. BUT if 'g' itself is specialised, then transitively we should be able to specialise f. In general, given case e of cb { MkD sc ... -> ...(f sc)... } we transform to let cb_flt = e sc_flt = case cb_flt of { MkD sc ... -> sc } in case cb_flt of bg { MkD sc ... -> ....(f sc_flt)... } The "_flt" things are the floated binds; we use the current substitution to substitute sc -> sc_flt in the RHS ************************************************************************ * * Dealing with a binding * * ************************************************************************ -} specBind :: SpecEnv -- Use this for RHSs -> CoreBind -> UsageDetails -- Info on how the scope of the binding -> SpecM ([CoreBind], -- New bindings UsageDetails) -- And info to pass upstream -- Returned UsageDetails: -- No calls for binders of this bind specBind rhs_env (NonRec fn rhs) body_uds = do { (rhs', rhs_uds) <- specExpr rhs_env rhs ; (fn', spec_defns, body_uds1) <- specDefn rhs_env body_uds fn rhs ; let pairs = spec_defns ++ [(fn', rhs')] -- fn' mentions the spec_defns in its rules, -- so put the latter first combined_uds = body_uds1 `plusUDs` rhs_uds -- This way round a call in rhs_uds of a function f -- at type T will override a call of f at T in body_uds1; and -- that is good because it'll tend to keep "earlier" calls -- See Note [Specialisation of dictionary functions] (free_uds, dump_dbs, float_all) = dumpBindUDs [fn] combined_uds -- See Note [From non-recursive to recursive] final_binds :: [DictBind] final_binds | isEmptyBag dump_dbs = [mkDB $ NonRec b r | (b,r) <- pairs] | otherwise = [flattenDictBinds dump_dbs pairs] ; if float_all then -- Rather than discard the calls mentioning the bound variables -- we float this binding along with the others return ([], free_uds `snocDictBinds` final_binds) else -- No call in final_uds mentions bound variables, -- so we can just leave the binding here return (map fst final_binds, free_uds) } specBind rhs_env (Rec pairs) body_uds -- Note [Specialising a recursive group] = do { let (bndrs,rhss) = unzip pairs ; (rhss', rhs_uds) <- mapAndCombineSM (specExpr rhs_env) rhss ; let scope_uds = body_uds `plusUDs` rhs_uds -- Includes binds and calls arising from rhss ; (bndrs1, spec_defns1, uds1) <- specDefns rhs_env scope_uds pairs ; (bndrs3, spec_defns3, uds3) <- if null spec_defns1 -- Common case: no specialisation then return (bndrs1, [], uds1) else do { -- Specialisation occurred; do it again (bndrs2, spec_defns2, uds2) <- specDefns rhs_env uds1 (bndrs1 `zip` rhss) ; return (bndrs2, spec_defns2 ++ spec_defns1, uds2) } ; let (final_uds, dumped_dbs, float_all) = dumpBindUDs bndrs uds3 bind = flattenDictBinds dumped_dbs (spec_defns3 ++ zip bndrs3 rhss') ; if float_all then return ([], final_uds `snocDictBind` bind) else return ([fst bind], final_uds) } --------------------------- specDefns :: SpecEnv -> UsageDetails -- Info on how it is used in its scope -> [(Id,CoreExpr)] -- The things being bound and their un-processed RHS -> SpecM ([Id], -- Original Ids with RULES added [(Id,CoreExpr)], -- Extra, specialised bindings UsageDetails) -- Stuff to fling upwards from the specialised versions -- Specialise a list of bindings (the contents of a Rec), but flowing usages -- upwards binding by binding. Example: { f = ...g ...; g = ...f .... } -- Then if the input CallDetails has a specialised call for 'g', whose specialisation -- in turn generates a specialised call for 'f', we catch that in this one sweep. -- But not vice versa (it's a fixpoint problem). specDefns _env uds [] = return ([], [], uds) specDefns env uds ((bndr,rhs):pairs) = do { (bndrs1, spec_defns1, uds1) <- specDefns env uds pairs ; (bndr1, spec_defns2, uds2) <- specDefn env uds1 bndr rhs ; return (bndr1 : bndrs1, spec_defns1 ++ spec_defns2, uds2) } --------------------------- specDefn :: SpecEnv -> UsageDetails -- Info on how it is used in its scope -> Id -> CoreExpr -- The thing being bound and its un-processed RHS -> SpecM (Id, -- Original Id with added RULES [(Id,CoreExpr)], -- Extra, specialised bindings UsageDetails) -- Stuff to fling upwards from the specialised versions specDefn env body_uds fn rhs = do { let (body_uds_without_me, calls_for_me) = callsForMe fn body_uds rules_for_me = idCoreRules fn ; (rules, spec_defns, spec_uds) <- specCalls Nothing env rules_for_me calls_for_me fn rhs ; return ( fn `addIdSpecialisations` rules , spec_defns , body_uds_without_me `plusUDs` spec_uds) } -- It's important that the `plusUDs` is this way -- round, because body_uds_without_me may bind -- dictionaries that are used in calls_for_me passed -- to specDefn. So the dictionary bindings in -- spec_uds may mention dictionaries bound in -- body_uds_without_me --------------------------- specCalls :: Maybe Module -- Just this_mod => specialising imported fn -- Nothing => specialising local fn -> SpecEnv -> [CoreRule] -- Existing RULES for the fn -> [CallInfo] -> Id -> CoreExpr -> SpecM ([CoreRule], -- New RULES for the fn [(Id,CoreExpr)], -- Extra, specialised bindings UsageDetails) -- New usage details from the specialised RHSs -- This function checks existing rules, and does not create -- duplicate ones. So the caller does not need to do this filtering. -- See 'already_covered' specCalls mb_mod env rules_for_me calls_for_me fn rhs -- The first case is the interesting one | rhs_tyvars `lengthIs` n_tyvars -- Rhs of fn's defn has right number of big lambdas && rhs_ids `lengthAtLeast` n_dicts -- and enough dict args && notNull calls_for_me -- And there are some calls to specialise && not (isNeverActive (idInlineActivation fn)) -- Don't specialise NOINLINE things -- See Note [Auto-specialisation and RULES] -- && not (certainlyWillInline (idUnfolding fn)) -- And it's not small -- See Note [Inline specialisation] for why we do not -- switch off specialisation for inline functions = -- pprTrace "specDefn: some" (ppr fn $$ ppr calls_for_me $$ ppr rules_for_me) $ do { stuff <- mapM spec_call calls_for_me ; let (spec_defns, spec_uds, spec_rules) = unzip3 (catMaybes stuff) ; return (spec_rules, spec_defns, plusUDList spec_uds) } | otherwise -- No calls or RHS doesn't fit our preconceptions = WARN( not (exprIsTrivial rhs) && notNull calls_for_me, ptext (sLit "Missed specialisation opportunity for") <+> ppr fn $$ _trace_doc ) -- Note [Specialisation shape] -- pprTrace "specDefn: none" (ppr fn <+> ppr calls_for_me) $ return ([], [], emptyUDs) where _trace_doc = sep [ ppr rhs_tyvars, ppr n_tyvars , ppr rhs_ids, ppr n_dicts , ppr (idInlineActivation fn) ] fn_type = idType fn fn_arity = idArity fn fn_unf = realIdUnfolding fn -- Ignore loop-breaker-ness here (tyvars, theta, _) = tcSplitSigmaTy fn_type n_tyvars = length tyvars n_dicts = length theta inl_prag = idInlinePragma fn inl_act = inlinePragmaActivation inl_prag is_local = isLocalId fn -- Figure out whether the function has an INLINE pragma -- See Note [Inline specialisations] (rhs_tyvars, rhs_ids, rhs_body) = collectTyAndValBinders rhs rhs_dict_ids = take n_dicts rhs_ids body = mkLams (drop n_dicts rhs_ids) rhs_body -- Glue back on the non-dict lambdas already_covered :: DynFlags -> [CoreExpr] -> Bool already_covered dflags args -- Note [Specialisations already covered] = isJust (lookupRule dflags (CoreSubst.substInScope (se_subst env), realIdUnfolding) (const True) fn args rules_for_me) mk_ty_args :: [Maybe Type] -> [TyVar] -> [CoreExpr] mk_ty_args [] poly_tvs = ASSERT( null poly_tvs ) [] mk_ty_args (Nothing : call_ts) (poly_tv : poly_tvs) = Type (mkTyVarTy poly_tv) : mk_ty_args call_ts poly_tvs mk_ty_args (Just ty : call_ts) poly_tvs = Type ty : mk_ty_args call_ts poly_tvs mk_ty_args (Nothing : _) [] = panic "mk_ty_args" ---------------------------------------------------------- -- Specialise to one particular call pattern spec_call :: CallInfo -- Call instance -> SpecM (Maybe ((Id,CoreExpr), -- Specialised definition UsageDetails, -- Usage details from specialised body CoreRule)) -- Info for the Id's SpecEnv spec_call (CallKey call_ts, (call_ds, _)) = ASSERT( call_ts `lengthIs` n_tyvars && call_ds `lengthIs` n_dicts ) -- Suppose f's defn is f = /\ a b c -> \ d1 d2 -> rhs -- Supppose the call is for f [Just t1, Nothing, Just t3] [dx1, dx2] -- Construct the new binding -- f1 = SUBST[a->t1,c->t3, d1->d1', d2->d2'] (/\ b -> rhs) -- PLUS the usage-details -- { d1' = dx1; d2' = dx2 } -- where d1', d2' are cloned versions of d1,d2, with the type substitution -- applied. These auxiliary bindings just avoid duplication of dx1, dx2 -- -- Note that the substitution is applied to the whole thing. -- This is convenient, but just slightly fragile. Notably: -- * There had better be no name clashes in a/b/c do { let -- poly_tyvars = [b] in the example above -- spec_tyvars = [a,c] -- ty_args = [t1,b,t3] spec_tv_binds = [(tv,ty) | (tv, Just ty) <- rhs_tyvars `zip` call_ts] env1 = extendTvSubstList env spec_tv_binds (rhs_env, poly_tyvars) = substBndrs env1 [tv | (tv, Nothing) <- rhs_tyvars `zip` call_ts] -- Clone rhs_dicts, including instantiating their types ; inst_dict_ids <- mapM (newDictBndr rhs_env) rhs_dict_ids ; let (rhs_env2, dx_binds, spec_dict_args) = bindAuxiliaryDicts rhs_env rhs_dict_ids call_ds inst_dict_ids ty_args = mk_ty_args call_ts poly_tyvars rule_args = ty_args ++ map Var inst_dict_ids rule_bndrs = poly_tyvars ++ inst_dict_ids ; dflags <- getDynFlags ; if already_covered dflags rule_args then return Nothing else do { -- Figure out the type of the specialised function let body_ty = applyTypeToArgs rhs fn_type rule_args (lam_args, app_args) -- Add a dummy argument if body_ty is unlifted | isUnLiftedType body_ty -- C.f. WwLib.mkWorkerArgs = (poly_tyvars ++ [voidArgId], poly_tyvars ++ [voidPrimId]) | otherwise = (poly_tyvars, poly_tyvars) spec_id_ty = mkPiTypes lam_args body_ty ; spec_f <- newSpecIdSM fn spec_id_ty ; (spec_rhs, rhs_uds) <- specExpr rhs_env2 (mkLams lam_args body) ; let -- The rule to put in the function's specialisation is: -- forall b, d1',d2'. f t1 b t3 d1' d2' = f1 b herald = case mb_mod of Nothing -- Specialising local fn -> ptext (sLit "SPEC") Just this_mod -- Specialising imoprted fn -> ptext (sLit "SPEC/") <> ppr this_mod rule_name = mkFastString $ showSDocForUser dflags neverQualify $ herald <+> ppr fn <+> hsep (map ppr_call_key_ty call_ts) -- This name ends up in interface files, so use showSDocForUser, -- otherwise uniques end up there, making builds -- less deterministic (See #4012 comment:61 ff) spec_env_rule = mkRule True {- Auto generated -} is_local rule_name inl_act -- Note [Auto-specialisation and RULES] (idName fn) rule_bndrs rule_args (mkVarApps (Var spec_f) app_args) -- Add the { d1' = dx1; d2' = dx2 } usage stuff final_uds = foldr consDictBind rhs_uds dx_binds -------------------------------------- -- Add a suitable unfolding if the spec_inl_prag says so -- See Note [Inline specialisations] (spec_inl_prag, spec_unf) | not is_local && isStrongLoopBreaker (idOccInfo fn) = (neverInlinePragma, noUnfolding) -- See Note [Specialising imported functions] in OccurAnal | InlinePragma { inl_inline = Inlinable } <- inl_prag = (inl_prag { inl_inline = EmptyInlineSpec }, noUnfolding) | otherwise = (inl_prag, specUnfolding dflags (se_subst env) poly_tyvars (ty_args ++ spec_dict_args) fn_unf) -------------------------------------- -- Adding arity information just propagates it a bit faster -- See Note [Arity decrease] in Simplify -- Copy InlinePragma information from the parent Id. -- So if f has INLINE[1] so does spec_f spec_f_w_arity = spec_f `setIdArity` max 0 (fn_arity - n_dicts) `setInlinePragma` spec_inl_prag `setIdUnfolding` spec_unf ; return (Just ((spec_f_w_arity, spec_rhs), final_uds, spec_env_rule)) } } bindAuxiliaryDicts :: SpecEnv -> [DictId] -> [CoreExpr] -- Original dict bndrs, and the witnessing expressions -> [DictId] -- A cloned dict-id for each dict arg -> (SpecEnv, -- Substitute for all orig_dicts [DictBind], -- Auxiliary dict bindings [CoreExpr]) -- Witnessing expressions (all trivial) -- Bind any dictionary arguments to fresh names, to preserve sharing bindAuxiliaryDicts env@(SE { se_subst = subst, se_interesting = interesting }) orig_dict_ids call_ds inst_dict_ids = (env', dx_binds, spec_dict_args) where (dx_binds, spec_dict_args) = go call_ds inst_dict_ids env' = env { se_subst = CoreSubst.extendIdSubstList subst (orig_dict_ids `zip` spec_dict_args) , se_interesting = interesting `unionVarSet` interesting_dicts } interesting_dicts = mkVarSet [ dx_id | (NonRec dx_id dx, _) <- dx_binds , interestingDict env dx ] -- See Note [Make the new dictionaries interesting] go :: [CoreExpr] -> [CoreBndr] -> ([DictBind], [CoreExpr]) go [] _ = ([], []) go (dx:dxs) (dx_id:dx_ids) | exprIsTrivial dx = (dx_binds, dx:args) | otherwise = (mkDB (NonRec dx_id dx) : dx_binds, Var dx_id : args) where (dx_binds, args) = go dxs dx_ids -- In the first case extend the substitution but not bindings; -- in the latter extend the bindings but not the substitution. -- For the former, note that we bind the *original* dict in the substitution, -- overriding any d->dx_id binding put there by substBndrs go _ _ = pprPanic "bindAuxiliaryDicts" (ppr orig_dict_ids $$ ppr call_ds $$ ppr inst_dict_ids) {- Note [Make the new dictionaries interesting] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Important! We're going to substitute dx_id1 for d and we want it to look "interesting", else we won't gather *any* consequential calls. E.g. f d = ...g d.... If we specialise f for a call (f (dfun dNumInt)), we'll get a consequent call (g d') with an auxiliary definition d' = df dNumInt We want that consequent call to look interesting Note [From non-recursive to recursive] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even in the non-recursive case, if any dict-binds depend on 'fn' we might have built a recursive knot f a d x = <blah> MkUD { ud_binds = d7 = MkD ..f.. , ud_calls = ...(f T d7)... } The we generate Rec { fs x = <blah>[T/a, d7/d] f a d x = <blah> RULE f T _ = fs d7 = ...f... } Here the recursion is only through the RULE. Note [Specialisation of dictionary functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is a nasty example that bit us badly: see Trac #3591 class Eq a => C a instance Eq [a] => C [a] --------------- dfun :: Eq [a] -> C [a] dfun a d = MkD a d (meth d) d4 :: Eq [T] = <blah> d2 :: C [T] = dfun T d4 d1 :: Eq [T] = $p1 d2 d3 :: C [T] = dfun T d1 None of these definitions is recursive. What happened was that we generated a specialisation: RULE forall d. dfun T d = dT :: C [T] dT = (MkD a d (meth d)) [T/a, d1/d] = MkD T d1 (meth d1) But now we use the RULE on the RHS of d2, to get d2 = dT = MkD d1 (meth d1) d1 = $p1 d2 and now d1 is bottom! The problem is that when specialising 'dfun' we should first dump "below" the binding all floated dictionary bindings that mention 'dfun' itself. So d2 and d3 (and hence d1) must be placed below 'dfun', and thus unavailable to it when specialising 'dfun'. That in turn means that the call (dfun T d1) must be discarded. On the other hand, the call (dfun T d4) is fine, assuming d4 doesn't mention dfun. But look at this: class C a where { foo,bar :: [a] -> [a] } instance C Int where foo x = r_bar x bar xs = reverse xs r_bar :: C a => [a] -> [a] r_bar xs = bar (xs ++ xs) That translates to: r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs) Rec { $fCInt :: C Int = MkC foo_help reverse foo_help (xs::[Int]) = r_bar Int $fCInt xs } The call (r_bar $fCInt) mentions $fCInt, which mentions foo_help, which mentions r_bar But we DO want to specialise r_bar at Int: Rec { $fCInt :: C Int = MkC foo_help reverse foo_help (xs::[Int]) = r_bar Int $fCInt xs r_bar a (c::C a) (xs::[a]) = bar a d (xs ++ xs) RULE r_bar Int _ = r_bar_Int r_bar_Int xs = bar Int $fCInt (xs ++ xs) } Note that, because of its RULE, r_bar joins the recursive group. (In this case it'll unravel a short moment later.) Conclusion: we catch the nasty case using filter_dfuns in callsForMe. To be honest I'm not 100% certain that this is 100% right, but it works. Sigh. Note [Specialising a recursive group] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider let rec { f x = ...g x'... ; g y = ...f y'.... } in f 'a' Here we specialise 'f' at Char; but that is very likely to lead to a specialisation of 'g' at Char. We must do the latter, else the whole point of specialisation is lost. But we do not want to keep iterating to a fixpoint, because in the presence of polymorphic recursion we might generate an infinite number of specialisations. So we use the following heuristic: * Arrange the rec block in dependency order, so far as possible (the occurrence analyser already does this) * Specialise it much like a sequence of lets * Then go through the block a second time, feeding call-info from the RHSs back in the bottom, as it were In effect, the ordering maxmimises the effectiveness of each sweep, and we do just two sweeps. This should catch almost every case of monomorphic recursion -- the exception could be a very knotted-up recursion with multiple cycles tied up together. This plan is implemented in the Rec case of specBindItself. Note [Specialisations already covered] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We obviously don't want to generate two specialisations for the same argument pattern. There are two wrinkles 1. We do the already-covered test in specDefn, not when we generate the CallInfo in mkCallUDs. We used to test in the latter place, but we now iterate the specialiser somewhat, and the Id at the call site might therefore not have all the RULES that we can see in specDefn 2. What about two specialisations where the second is an *instance* of the first? If the more specific one shows up first, we'll generate specialisations for both. If the *less* specific one shows up first, we *don't* currently generate a specialisation for the more specific one. (See the call to lookupRule in already_covered.) Reasons: (a) lookupRule doesn't say which matches are exact (bad reason) (b) if the earlier specialisation is user-provided, it's far from clear that we should auto-specialise further Note [Auto-specialisation and RULES] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider: g :: Num a => a -> a g = ... f :: (Int -> Int) -> Int f w = ... {-# RULE f g = 0 #-} Suppose that auto-specialisation makes a specialised version of g::Int->Int That version won't appear in the LHS of the RULE for f. So if the specialisation rule fires too early, the rule for f may never fire. It might be possible to add new rules, to "complete" the rewrite system. Thus when adding RULE forall d. g Int d = g_spec also add RULE f g_spec = 0 But that's a bit complicated. For now we ask the programmer's help, by *copying the INLINE activation pragma* to the auto-specialised rule. So if g says {-# NOINLINE[2] g #-}, then the auto-spec rule will also not be active until phase 2. And that's what programmers should jolly well do anyway, even aside from specialisation, to ensure that g doesn't inline too early. This in turn means that the RULE would never fire for a NOINLINE thing so not much point in generating a specialisation at all. Note [Specialisation shape] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ We only specialise a function if it has visible top-level lambdas corresponding to its overloading. E.g. if f :: forall a. Eq a => .... then its body must look like f = /\a. \d. ... Reason: when specialising the body for a call (f ty dexp), we want to substitute dexp for d, and pick up specialised calls in the body of f. This doesn't always work. One example I came across was this: newtype Gen a = MkGen{ unGen :: Int -> a } choose :: Eq a => a -> Gen a choose n = MkGen (\r -> n) oneof = choose (1::Int) It's a silly exapmle, but we get choose = /\a. g `cast` co where choose doesn't have any dict arguments. Thus far I have not tried to fix this (wait till there's a real example). Mind you, then 'choose' will be inlined (since RHS is trivial) so it doesn't matter. This comes up with single-method classes class C a where { op :: a -> a } instance C a => C [a] where .... ==> $fCList :: C a => C [a] $fCList = $copList |> (...coercion>...) ....(uses of $fCList at particular types)... So we suppress the WARN if the rhs is trivial. Note [Inline specialisations] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Here is what we do with the InlinePragma of the original function * Activation/RuleMatchInfo: both transferred to the specialised function * InlineSpec: (a) An INLINE pragma is transferred (b) An INLINABLE pragma is *not* transferred Why (a): transfer INLINE pragmas? The point of INLINE was precisely to specialise the function at its call site, and arguably that's not so important for the specialised copies. BUT *pragma-directed* specialisation now takes place in the typechecker/desugarer, with manually specified INLINEs. The specialisation here is automatic. It'd be very odd if a function marked INLINE was specialised (because of some local use), and then forever after (including importing modules) the specialised version wasn't INLINEd. After all, the programmer said INLINE! You might wonder why we specialise INLINE functions at all. After all they should be inlined, right? Two reasons: * Even INLINE functions are sometimes not inlined, when they aren't applied to interesting arguments. But perhaps the type arguments alone are enough to specialise (even though the args are too boring to trigger inlining), and it's certainly better to call the specialised version. * The RHS of an INLINE function might call another overloaded function, and we'd like to generate a specialised version of that function too. This actually happens a lot. Consider replicateM_ :: (Monad m) => Int -> m a -> m () {-# INLINABLE replicateM_ #-} replicateM_ d x ma = ... The strictness analyser may transform to replicateM_ :: (Monad m) => Int -> m a -> m () {-# INLINE replicateM_ #-} replicateM_ d x ma = case x of I# x' -> $wreplicateM_ d x' ma $wreplicateM_ :: (Monad m) => Int# -> m a -> m () {-# INLINABLE $wreplicateM_ #-} $wreplicateM_ = ... Now an importing module has a specialised call to replicateM_, say (replicateM_ dMonadIO). We certainly want to specialise $wreplicateM_! This particular example had a huge effect on the call to replicateM_ in nofib/shootout/n-body. Why (b): discard INLINEABLE pragmas? See Trac #4874 for persuasive examples. Suppose we have {-# INLINABLE f #-} f :: Ord a => [a] -> Int f xs = letrec f' = ...f'... in f' Then, when f is specialised and optimised we might get wgo :: [Int] -> Int# wgo = ...wgo... f_spec :: [Int] -> Int f_spec xs = case wgo xs of { r -> I# r } and we clearly want to inline f_spec at call sites. But if we still have the big, un-optimised of f (albeit specialised) captured in an INLINABLE pragma for f_spec, we won't get that optimisation. So we simply drop INLINABLE pragmas when specialising. It's not really a complete solution; ignoring specalisation for now, INLINABLE functions don't get properly strictness analysed, for example. But it works well for examples involving specialisation, which is the dominant use of INLINABLE. See Trac #4874. ************************************************************************ * * \subsubsection{UsageDetails and suchlike} * * ************************************************************************ -} data UsageDetails = MkUD { ud_binds :: !(Bag DictBind), -- Floated dictionary bindings -- The order is important; -- in ds1 `union` ds2, bindings in ds2 can depend on those in ds1 -- (Remember, Bags preserve order in GHC.) ud_calls :: !CallDetails -- INVARIANT: suppose bs = bindersOf ud_binds -- Then 'calls' may *mention* 'bs', -- but there should be no calls *for* bs } instance Outputable UsageDetails where ppr (MkUD { ud_binds = dbs, ud_calls = calls }) = ptext (sLit "MkUD") <+> braces (sep (punctuate comma [ptext (sLit "binds") <+> equals <+> ppr dbs, ptext (sLit "calls") <+> equals <+> ppr calls])) -- | A 'DictBind' is a binding along with a cached set containing its free -- variables (both type variables and dictionaries) type DictBind = (CoreBind, VarSet) type DictExpr = CoreExpr emptyUDs :: UsageDetails emptyUDs = MkUD { ud_binds = emptyBag, ud_calls = emptyVarEnv } ------------------------------------------------------------ type CallDetails = IdEnv CallInfoSet newtype CallKey = CallKey [Maybe Type] -- Nothing => unconstrained type argument -- CallInfo uses a Map, thereby ensuring that -- we record only one call instance for any key -- -- The list of types and dictionaries is guaranteed to -- match the type of f data CallInfoSet = CIS Id (Map CallKey ([DictExpr], VarSet)) -- Range is dict args and the vars of the whole -- call (including tyvars) -- [*not* include the main id itself, of course] type CallInfo = (CallKey, ([DictExpr], VarSet)) instance Outputable CallInfoSet where ppr (CIS fn map) = hang (ptext (sLit "CIS") <+> ppr fn) 2 (ppr map) pprCallInfo :: Id -> CallInfo -> SDoc pprCallInfo fn (CallKey mb_tys, (dxs, _)) = hang (ppr fn) 2 (fsep (map ppr_call_key_ty mb_tys ++ map pprParendExpr dxs)) ppr_call_key_ty :: Maybe Type -> SDoc ppr_call_key_ty Nothing = char '_' ppr_call_key_ty (Just ty) = char '@' <+> pprParendType ty instance Outputable CallKey where ppr (CallKey ts) = ppr ts -- Type isn't an instance of Ord, so that we can control which -- instance we use. That's tiresome here. Oh well instance Eq CallKey where k1 == k2 = case k1 `compare` k2 of { EQ -> True; _ -> False } instance Ord CallKey where compare (CallKey k1) (CallKey k2) = cmpList cmp k1 k2 where cmp Nothing Nothing = EQ cmp Nothing (Just _) = LT cmp (Just _) Nothing = GT cmp (Just t1) (Just t2) = cmpType t1 t2 unionCalls :: CallDetails -> CallDetails -> CallDetails unionCalls c1 c2 = plusVarEnv_C unionCallInfoSet c1 c2 unionCallInfoSet :: CallInfoSet -> CallInfoSet -> CallInfoSet unionCallInfoSet (CIS f calls1) (CIS _ calls2) = CIS f (calls1 `Map.union` calls2) callDetailsFVs :: CallDetails -> VarSet callDetailsFVs calls = foldVarEnv (unionVarSet . callInfoFVs) emptyVarSet calls callInfoFVs :: CallInfoSet -> VarSet callInfoFVs (CIS _ call_info) = Map.foldRight (\(_,fv) vs -> unionVarSet fv vs) emptyVarSet call_info ------------------------------------------------------------ singleCall :: Id -> [Maybe Type] -> [DictExpr] -> UsageDetails singleCall id tys dicts = MkUD {ud_binds = emptyBag, ud_calls = unitVarEnv id $ CIS id $ Map.singleton (CallKey tys) (dicts, call_fvs) } where call_fvs = exprsFreeVars dicts `unionVarSet` tys_fvs tys_fvs = tyVarsOfTypes (catMaybes tys) -- The type args (tys) are guaranteed to be part of the dictionary -- types, because they are just the constrained types, -- and the dictionary is therefore sure to be bound -- inside the binding for any type variables free in the type; -- hence it's safe to neglect tyvars free in tys when making -- the free-var set for this call -- BUT I don't trust this reasoning; play safe and include tys_fvs -- -- We don't include the 'id' itself. mkCallUDs, mkCallUDs' :: SpecEnv -> Id -> [CoreExpr] -> UsageDetails mkCallUDs env f args = -- pprTrace "mkCallUDs" (vcat [ ppr f, ppr args, ppr res ]) res where res = mkCallUDs' env f args mkCallUDs' env f args | not (want_calls_for f) -- Imported from elsewhere || null theta -- Not overloaded = emptyUDs | not (all type_determines_value theta) || not (spec_tys `lengthIs` n_tyvars) || not ( dicts `lengthIs` n_dicts) || not (any (interestingDict env) dicts) -- Note [Interesting dictionary arguments] -- See also Note [Specialisations already covered] = -- pprTrace "mkCallUDs: discarding" _trace_doc emptyUDs -- Not overloaded, or no specialisation wanted | otherwise = -- pprTrace "mkCallUDs: keeping" _trace_doc singleCall f spec_tys dicts where _trace_doc = vcat [ppr f, ppr args, ppr n_tyvars, ppr n_dicts , ppr (map (interestingDict env) dicts)] (tyvars, theta, _) = tcSplitSigmaTy (idType f) constrained_tyvars = closeOverKinds (tyVarsOfTypes theta) n_tyvars = length tyvars n_dicts = length theta spec_tys = [mk_spec_ty tv ty | (tv, Type ty) <- tyvars `zip` args] dicts = [dict_expr | (_, dict_expr) <- theta `zip` (drop n_tyvars args)] mk_spec_ty tyvar ty | tyvar `elemVarSet` constrained_tyvars = Just ty | otherwise = Nothing want_calls_for f = isLocalId f || isJust (maybeUnfoldingTemplate (realIdUnfolding f)) -- For imported things, we gather call instances if -- there is an unfolding that we could in principle specialise -- We might still decide not to use it (consulting dflags) -- in specImports -- Use 'realIdUnfolding' to ignore the loop-breaker flag! type_determines_value pred -- See Note [Type determines value] = case classifyPredType pred of ClassPred cls _ -> not (isIPClass cls) TuplePred ps -> all type_determines_value ps EqPred {} -> True IrredPred {} -> True -- Things like (D []) where D is a -- Constraint-ranged family; Trac #7785 {- Note [Type determines value] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Only specialise if all overloading is on non-IP *class* params, because these are the ones whose *type* determines their *value*. In parrticular, with implicit params, the type args *don't* say what the value of the implicit param is! See Trac #7101 However, consider type family D (v::*->*) :: Constraint type instance D [] = () f :: D v => v Char -> Int If we see a call (f "foo"), we'll pass a "dictionary" () |> (g :: () ~ D []) and it's good to specialise f at this dictionary. So the question is: can an implicit parameter "hide inside" a type-family constraint like (D a). Well, no. We don't allow type instance D Maybe = ?x:Int Hence the IrredPred case in type_determines_value. See Trac #7785. Note [Interesting dictionary arguments] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this \a.\d:Eq a. let f = ... in ...(f d)... There really is not much point in specialising f wrt the dictionary d, because the code for the specialised f is not improved at all, because d is lambda-bound. We simply get junk specialisations. What is "interesting"? Just that it has *some* structure. But what about variables? * A variable might be imported, in which case its unfolding will tell us whether it has useful structure * Local variables are cloned on the way down (to avoid clashes when we float dictionaries), and cloning drops the unfolding (cloneIdBndr). Moreover, we make up some new bindings, and it's a nuisance to give them unfoldings. So we keep track of the "interesting" dictionaries as a VarSet in SpecEnv. We have to take care to put any new interesting dictionary bindings in the set. We accidentally lost accurate tracking of local variables for a long time, because cloned variables don't have unfoldings. But makes a massive difference in a few cases, eg Trac #5113. For nofib as a whole it's only a small win: 2.2% improvement in allocation for ansi, 1.2% for bspt, but mostly 0.0! Average 0.1% increase in binary size. -} interestingDict :: SpecEnv -> CoreExpr -> Bool -- A dictionary argument is interesting if it has *some* structure interestingDict env (Var v) = hasSomeUnfolding (idUnfolding v) || isDataConWorkId v || v `elemVarSet` se_interesting env interestingDict _ (Type _) = False interestingDict _ (Coercion _) = False interestingDict env (App fn (Type _)) = interestingDict env fn interestingDict env (App fn (Coercion _)) = interestingDict env fn interestingDict env (Tick _ a) = interestingDict env a interestingDict env (Cast e _) = interestingDict env e interestingDict _ _ = True plusUDs :: UsageDetails -> UsageDetails -> UsageDetails plusUDs (MkUD {ud_binds = db1, ud_calls = calls1}) (MkUD {ud_binds = db2, ud_calls = calls2}) = MkUD { ud_binds = db1 `unionBags` db2 , ud_calls = calls1 `unionCalls` calls2 } plusUDList :: [UsageDetails] -> UsageDetails plusUDList = foldr plusUDs emptyUDs ----------------------------- _dictBindBndrs :: Bag DictBind -> [Id] _dictBindBndrs dbs = foldrBag ((++) . bindersOf . fst) [] dbs -- | Construct a 'DictBind' from a 'CoreBind' mkDB :: CoreBind -> DictBind mkDB bind = (bind, bind_fvs bind) -- | Identify the free variables of a 'CoreBind' bind_fvs :: CoreBind -> VarSet bind_fvs (NonRec bndr rhs) = pair_fvs (bndr,rhs) bind_fvs (Rec prs) = foldl delVarSet rhs_fvs bndrs where bndrs = map fst prs rhs_fvs = unionVarSets (map pair_fvs prs) pair_fvs :: (Id, CoreExpr) -> VarSet pair_fvs (bndr, rhs) = exprFreeVars rhs `unionVarSet` idFreeVars bndr -- Don't forget variables mentioned in the -- rules of the bndr. C.f. OccAnal.addRuleUsage -- Also tyvars mentioned in its type; they may not appear in the RHS -- type T a = Int -- x :: T a = 3 -- | Flatten a set of 'DictBind's and some other binding pairs into a single -- recursive binding, including some additional bindings. flattenDictBinds :: Bag DictBind -> [(Id,CoreExpr)] -> DictBind flattenDictBinds dbs pairs = (Rec bindings, fvs) where (bindings, fvs) = foldrBag add ([], emptyVarSet) (dbs `snocBag` mkDB (Rec pairs)) add (NonRec b r, fvs') (pairs, fvs) = ((b,r) : pairs, fvs `unionVarSet` fvs') add (Rec prs1, fvs') (pairs, fvs) = (prs1 ++ pairs, fvs `unionVarSet` fvs') snocDictBinds :: UsageDetails -> [DictBind] -> UsageDetails -- Add ud_binds to the tail end of the bindings in uds snocDictBinds uds dbs = uds { ud_binds = ud_binds uds `unionBags` foldr consBag emptyBag dbs } consDictBind :: DictBind -> UsageDetails -> UsageDetails consDictBind bind uds = uds { ud_binds = bind `consBag` ud_binds uds } addDictBinds :: [DictBind] -> UsageDetails -> UsageDetails addDictBinds binds uds = uds { ud_binds = listToBag binds `unionBags` ud_binds uds } snocDictBind :: UsageDetails -> DictBind -> UsageDetails snocDictBind uds bind = uds { ud_binds = ud_binds uds `snocBag` bind } wrapDictBinds :: Bag DictBind -> [CoreBind] -> [CoreBind] wrapDictBinds dbs binds = foldrBag add binds dbs where add (bind,_) binds = bind : binds wrapDictBindsE :: Bag DictBind -> CoreExpr -> CoreExpr wrapDictBindsE dbs expr = foldrBag add expr dbs where add (bind,_) expr = Let bind expr ---------------------- dumpUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind) -- Used at a lambda or case binder; just dump anything mentioning the binder dumpUDs bndrs uds@(MkUD { ud_binds = orig_dbs, ud_calls = orig_calls }) | null bndrs = (uds, emptyBag) -- Common in case alternatives | otherwise = -- pprTrace "dumpUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $ (free_uds, dump_dbs) where free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls } bndr_set = mkVarSet bndrs (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set free_calls = deleteCallsMentioning dump_set $ -- Drop calls mentioning bndr_set on the floor deleteCallsFor bndrs orig_calls -- Discard calls for bndr_set; there should be -- no calls for any of the dicts in dump_dbs dumpBindUDs :: [CoreBndr] -> UsageDetails -> (UsageDetails, Bag DictBind, Bool) -- Used at a lambda or case binder; just dump anything mentioning the binder dumpBindUDs bndrs (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls }) = -- pprTrace "dumpBindUDs" (ppr bndrs $$ ppr free_uds $$ ppr dump_dbs) $ (free_uds, dump_dbs, float_all) where free_uds = MkUD { ud_binds = free_dbs, ud_calls = free_calls } bndr_set = mkVarSet bndrs (free_dbs, dump_dbs, dump_set) = splitDictBinds orig_dbs bndr_set free_calls = deleteCallsFor bndrs orig_calls float_all = dump_set `intersectsVarSet` callDetailsFVs free_calls callsForMe :: Id -> UsageDetails -> (UsageDetails, [CallInfo]) callsForMe fn (MkUD { ud_binds = orig_dbs, ud_calls = orig_calls }) = -- pprTrace ("callsForMe") -- (vcat [ppr fn, -- text "Orig dbs =" <+> ppr (_dictBindBndrs orig_dbs), -- text "Orig calls =" <+> ppr orig_calls, -- text "Dep set =" <+> ppr dep_set, -- text "Calls for me =" <+> ppr calls_for_me]) $ (uds_without_me, calls_for_me) where uds_without_me = MkUD { ud_binds = orig_dbs, ud_calls = delVarEnv orig_calls fn } calls_for_me = case lookupVarEnv orig_calls fn of Nothing -> [] Just (CIS _ calls) -> filter_dfuns (Map.toList calls) dep_set = foldlBag go (unitVarSet fn) orig_dbs go dep_set (db,fvs) | fvs `intersectsVarSet` dep_set = extendVarSetList dep_set (bindersOf db) | otherwise = dep_set -- Note [Specialisation of dictionary functions] filter_dfuns | isDFunId fn = filter ok_call | otherwise = \cs -> cs ok_call (_, (_,fvs)) = not (fvs `intersectsVarSet` dep_set) ---------------------- splitDictBinds :: Bag DictBind -> IdSet -> (Bag DictBind, Bag DictBind, IdSet) -- Returns (free_dbs, dump_dbs, dump_set) splitDictBinds dbs bndr_set = foldlBag split_db (emptyBag, emptyBag, bndr_set) dbs -- Important that it's foldl not foldr; -- we're accumulating the set of dumped ids in dump_set where split_db (free_dbs, dump_dbs, dump_idset) db@(bind, fvs) | dump_idset `intersectsVarSet` fvs -- Dump it = (free_dbs, dump_dbs `snocBag` db, extendVarSetList dump_idset (bindersOf bind)) | otherwise -- Don't dump it = (free_dbs `snocBag` db, dump_dbs, dump_idset) ---------------------- deleteCallsMentioning :: VarSet -> CallDetails -> CallDetails -- Remove calls *mentioning* bs deleteCallsMentioning bs calls = mapVarEnv filter_calls calls where filter_calls :: CallInfoSet -> CallInfoSet filter_calls (CIS f calls) = CIS f (Map.filter keep_call calls) keep_call (_, fvs) = not (fvs `intersectsVarSet` bs) deleteCallsFor :: [Id] -> CallDetails -> CallDetails -- Remove calls *for* bs deleteCallsFor bs calls = delVarEnvList calls bs {- ************************************************************************ * * \subsubsection{Boring helper functions} * * ************************************************************************ -} newtype SpecM a = SpecM (State SpecState a) data SpecState = SpecState { spec_uniq_supply :: UniqSupply, spec_dflags :: DynFlags } instance Functor SpecM where fmap = liftM instance Applicative SpecM where pure = return (<*>) = ap instance Monad SpecM where SpecM x >>= f = SpecM $ do y <- x case f y of SpecM z -> z return x = SpecM $ return x fail str = SpecM $ fail str instance MonadUnique SpecM where getUniqueSupplyM = SpecM $ do st <- get let (us1, us2) = splitUniqSupply $ spec_uniq_supply st put $ st { spec_uniq_supply = us2 } return us1 getUniqueM = SpecM $ do st <- get let (u,us') = takeUniqFromSupply $ spec_uniq_supply st put $ st { spec_uniq_supply = us' } return u instance HasDynFlags SpecM where getDynFlags = SpecM $ liftM spec_dflags get runSpecM :: DynFlags -> SpecM a -> CoreM a runSpecM dflags (SpecM spec) = do us <- getUniqueSupplyM let initialState = SpecState { spec_uniq_supply = us, spec_dflags = dflags } return $ evalState spec initialState mapAndCombineSM :: (a -> SpecM (b, UsageDetails)) -> [a] -> SpecM ([b], UsageDetails) mapAndCombineSM _ [] = return ([], emptyUDs) mapAndCombineSM f (x:xs) = do (y, uds1) <- f x (ys, uds2) <- mapAndCombineSM f xs return (y:ys, uds1 `plusUDs` uds2) extendTvSubstList :: SpecEnv -> [(TyVar,Type)] -> SpecEnv extendTvSubstList env tv_binds = env { se_subst = CoreSubst.extendTvSubstList (se_subst env) tv_binds } substTy :: SpecEnv -> Type -> Type substTy env ty = CoreSubst.substTy (se_subst env) ty substCo :: SpecEnv -> Coercion -> Coercion substCo env co = CoreSubst.substCo (se_subst env) co substBndr :: SpecEnv -> CoreBndr -> (SpecEnv, CoreBndr) substBndr env bs = case CoreSubst.substBndr (se_subst env) bs of (subst', bs') -> (env { se_subst = subst' }, bs') substBndrs :: SpecEnv -> [CoreBndr] -> (SpecEnv, [CoreBndr]) substBndrs env bs = case CoreSubst.substBndrs (se_subst env) bs of (subst', bs') -> (env { se_subst = subst' }, bs') cloneBindSM :: SpecEnv -> CoreBind -> SpecM (SpecEnv, SpecEnv, CoreBind) -- Clone the binders of the bind; return new bind with the cloned binders -- Return the substitution to use for RHSs, and the one to use for the body cloneBindSM env@(SE { se_subst = subst, se_interesting = interesting }) (NonRec bndr rhs) = do { us <- getUniqueSupplyM ; let (subst', bndr') = CoreSubst.cloneIdBndr subst us bndr interesting' | interestingDict env rhs = interesting `extendVarSet` bndr' | otherwise = interesting ; return (env, env { se_subst = subst', se_interesting = interesting' } , NonRec bndr' rhs) } cloneBindSM env@(SE { se_subst = subst, se_interesting = interesting }) (Rec pairs) = do { us <- getUniqueSupplyM ; let (subst', bndrs') = CoreSubst.cloneRecIdBndrs subst us (map fst pairs) env' = env { se_subst = subst' , se_interesting = interesting `extendVarSetList` [ v | (v,r) <- pairs, interestingDict env r ] } ; return (env', env', Rec (bndrs' `zip` map snd pairs)) } newDictBndr :: SpecEnv -> CoreBndr -> SpecM CoreBndr -- Make up completely fresh binders for the dictionaries -- Their bindings are going to float outwards newDictBndr env b = do { uniq <- getUniqueM ; let n = idName b ty' = substTy env (idType b) ; return (mkUserLocal (nameOccName n) uniq ty' (getSrcSpan n)) } newSpecIdSM :: Id -> Type -> SpecM Id -- Give the new Id a similar occurrence name to the old one newSpecIdSM old_id new_ty = do { uniq <- getUniqueM ; let name = idName old_id new_occ = mkSpecOcc (nameOccName name) new_id = mkUserLocal new_occ uniq new_ty (getSrcSpan name) ; return new_id } {- Old (but interesting) stuff about unboxed bindings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ What should we do when a value is specialised to a *strict* unboxed value? map_*_* f (x:xs) = let h = f x t = map f xs in h:t Could convert let to case: map_*_Int# f (x:xs) = case f x of h# -> let t = map f xs in h#:t This may be undesirable since it forces evaluation here, but the value may not be used in all branches of the body. In the general case this transformation is impossible since the mutual recursion in a letrec cannot be expressed as a case. There is also a problem with top-level unboxed values, since our implementation cannot handle unboxed values at the top level. Solution: Lift the binding of the unboxed value and extract it when it is used: map_*_Int# f (x:xs) = let h = case (f x) of h# -> _Lift h# t = map f xs in case h of _Lift h# -> h#:t Now give it to the simplifier and the _Lifting will be optimised away. The benfit is that we have given the specialised "unboxed" values a very simplep lifted semantics and then leave it up to the simplifier to optimise it --- knowing that the overheads will be removed in nearly all cases. In particular, the value will only be evaluted in the branches of the program which use it, rather than being forced at the point where the value is bound. For example: filtermap_*_* p f (x:xs) = let h = f x t = ... in case p x of True -> h:t False -> t ==> filtermap_*_Int# p f (x:xs) = let h = case (f x) of h# -> _Lift h# t = ... in case p x of True -> case h of _Lift h# -> h#:t False -> t The binding for h can still be inlined in the one branch and the _Lifting eliminated. Question: When won't the _Lifting be eliminated? Answer: When they at the top-level (where it is necessary) or when inlining would duplicate work (or possibly code depending on options). However, the _Lifting will still be eliminated if the strictness analyser deems the lifted binding strict. -}
alexander-at-github/eta
compiler/ETA/Specialise/Specialise.hs
bsd-3-clause
87,509
1
22
25,401
10,739
5,829
4,910
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE GADTs #-} -- This module is full of orphans, unfortunately module GHCi.TH.Binary () where import Prelude -- See note [Why do we import Prelude here?] import Data.Binary import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import GHC.Serialized import qualified Language.Haskell.TH as TH import qualified Language.Haskell.TH.Syntax as TH -- Put these in a separate module because they take ages to compile instance Binary TH.Loc instance Binary TH.Name instance Binary TH.ModName instance Binary TH.NameFlavour instance Binary TH.PkgName instance Binary TH.NameSpace instance Binary TH.Module instance Binary TH.Info instance Binary TH.Type instance Binary TH.TyLit instance Binary TH.TyVarBndr instance Binary TH.Role instance Binary TH.Lit instance Binary TH.Range instance Binary TH.Stmt instance Binary TH.Pat instance Binary TH.Exp instance Binary TH.Dec instance Binary TH.Overlap instance Binary TH.DerivClause instance Binary TH.DerivStrategy instance Binary TH.Guard instance Binary TH.Body instance Binary TH.Match instance Binary TH.Fixity instance Binary TH.TySynEqn instance Binary TH.FunDep instance Binary TH.AnnTarget instance Binary TH.RuleBndr instance Binary TH.Phases instance Binary TH.RuleMatch instance Binary TH.Inline instance Binary TH.Pragma instance Binary TH.Safety instance Binary TH.Callconv instance Binary TH.Foreign instance Binary TH.Bang instance Binary TH.SourceUnpackedness instance Binary TH.SourceStrictness instance Binary TH.DecidedStrictness instance Binary TH.FixityDirection instance Binary TH.OccName instance Binary TH.Con instance Binary TH.AnnLookup instance Binary TH.ModuleInfo instance Binary TH.Clause instance Binary TH.InjectivityAnn instance Binary TH.FamilyResultSig instance Binary TH.TypeFamilyHead instance Binary TH.PatSynDir instance Binary TH.PatSynArgs -- We need Binary TypeRep for serializing annotations instance Binary Serialized where put (Serialized tyrep wds) = put tyrep >> put (B.pack wds) get = Serialized <$> get <*> (B.unpack <$> get) instance Binary TH.Bytes where put (TH.Bytes ptr off sz) = put bs where bs = B.PS ptr (fromIntegral off) (fromIntegral sz) get = do B.PS ptr off sz <- get return (TH.Bytes ptr (fromIntegral off) (fromIntegral sz))
sdiehl/ghc
libraries/ghci/GHCi/TH/Binary.hs
bsd-3-clause
2,451
0
12
347
703
342
361
73
0
-- -- Copyright (c) 2013 Citrix Systems, Inc. -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- module Vm.Utility ( withMountedDisk, copyFileFromDisk , tapCreate , tapCreateVhd , tapDestroy , PartitionNum ) where import qualified Control.Exception as E import Control.Applicative import Data.Int import Data.List import Data.Maybe import System.IO import System.IO.Error import System.FilePath import Text.Printf import Directory import Tools.Misc import Tools.Process import Tools.Text import Tools.PartTable import Vm.DmTypes type PartitionNum = Int finally' = flip E.finally mount :: FilePath -> FilePath -> Int64 -> Bool -> Bool -> IO () mount dev dir off loop ro = void $ readProcessOrDie "mount" ["-o", opts, dev, dir] "" where opts = intercalate "," . filter (not.null) $ [ro_opt,off_opt,loop_opt] ro_opt | ro = "ro" | otherwise = "" off_opt | off == 0 = "" | otherwise = "offset=" ++ show off loop_opt | not loop = "" | otherwise = "loop" umount :: FilePath -> IO () umount dir = void $ readProcessOrDie "umount" [dir] "" tapCreate ty extraEnv ro path = chomp <$> readProcessOrDieWithEnv extraEnv "tap-ctl" ( ["create"] ++ (if ro then ["-R"] else []) ++ ["-a", ty++":"++path] ) "" tapCreateVhd = tapCreate "vhd" tapCreateVdi = tapCreate "vdi" tapCreateAio = tapCreate "aio" tapDestroy dev = void $ readProcessOrDie "tap-ctl" ["destroy","-d",dev] "" withTempDirectory :: FilePath -> (FilePath -> IO a) -> IO a withTempDirectory root_path action = do directory <- attempt 1 action directory `E.finally` removeDirectory directory where attempt n = let name = templated_name n in ( do createDirectory name return name ) `E.catch` create_error n create_error :: Int -> IOError -> IO FilePath create_error n e | isAlreadyExistsError e = attempt (n+1) | otherwise = E.throw e templated_name magic_num = root_path </> printf "tempdir-%08d" magic_num withMountedDisk :: [(String,String)] -> DiskType -> Bool -> FilePath -> Maybe PartitionNum -> (FilePath -> IO a) -> IO a withMountedDisk _ QemuCopyOnWrite _ _ _ _ = error "qcow unsupported" withMountedDisk extraEnv diskT ro phys_path part action = withTempDirectory "/tmp" $ \temp_dir -> do dev <- create_dev diskT finally' (destroy_dev diskT dev) $ do off <- mountOffset dev part mount dev temp_dir off (loop diskT) ro finally' (umount temp_dir) $ action temp_dir where create_dev DiskImage = return phys_path create_dev PhysicalDevice = return phys_path create_dev VirtualHardDisk = tapCreateVhd extraEnv ro phys_path create_dev ExternalVdi = tapCreateVdi extraEnv ro phys_path create_dev Aio = tapCreateAio extraEnv ro phys_path create_dev _ = error "unsupported" destroy_dev t dev | t `elem` [VirtualHardDisk, ExternalVdi, Aio] = tapDestroy dev destroy_dev _ _ = return () loop DiskImage = True loop _ = False mountOffset :: FilePath -> Maybe PartitionNum -> IO Int64 mountOffset dev Nothing = return 0 mountOffset dev (Just pnum) = do ptable <- fromMaybe (error $ "failed to read parition table of " ++ dev) <$> readPartTable dev case filter (\p -> partNum p == pnum) ptable of [] -> error $ "partition " ++ show pnum ++ " not found in " ++ show dev (x:_) -> return $ partStart x deslash ('/':xs) = xs deslash xs = xs copyFileFromDisk :: [(String, String)] -> DiskType -> Bool -> FilePath -> (Maybe PartitionNum,FilePath) -> FilePath -> IO () copyFileFromDisk extraEnv diskT ro phys_path (part,src_path) dst_path = withMountedDisk extraEnv diskT ro phys_path part $ \contents -> void $ readProcessOrDie "cp" [contents </> deslash src_path, dst_path] ""
jean-edouard/manager
xenmgr/Vm/Utility.hs
gpl-2.0
4,525
0
15
1,013
1,287
656
631
82
8
{-# LANGUAGE RebindableSyntax, NPlusKPatterns #-} {-# OPTIONS -Wno-error=missing-monadfail-instances #-} module Main where { -- import Prelude; import qualified Prelude; import Prelude(String,undefined,Maybe(..),IO,putStrLn, Integer,(++),Rational, (==), (>=) ); debugFunc :: String -> IO a -> IO a; debugFunc s ioa = (putStrLn ("++ " ++ s)) Prelude.>> (ioa Prelude.>>= (\a -> (putStrLn ("-- " ++ s)) Prelude.>> (Prelude.return a) )); infixl 1 >>=; infixl 1 >>; class MyMonad m where { return :: a -> m a; (>>=) :: m a -> (a -> m b) -> m b; (>>) :: m a -> m b -> m b; fail :: String -> m a; }; instance MyMonad IO where { return a = debugFunc "return" (Prelude.return a); (>>=) ma amb = debugFunc ">>=" ((Prelude.>>=) ma amb); (>>) ma mb = debugFunc ">>" ((Prelude.>>) ma mb); fail s = debugFunc "fail" (Prelude.return undefined); -- fail s = debugFunc "fail" (Prelude.fail s); }; fromInteger :: Integer -> Integer; fromInteger a = a Prelude.+ a Prelude.+ a Prelude.+ a Prelude.+ a; -- five times fromRational :: Rational -> Rational; fromRational a = a Prelude.+ a Prelude.+ a; -- three times negate :: a -> a; negate a = a; -- don't actually negate (-) :: a -> a -> a; (-) x y = y; -- changed function test_do f g = do { f; -- >> Just a <- g; -- >>= (and fail if g returns Nothing) return a; -- return }; test_fromInteger = 27; test_fromRational = 31.5; test_negate a = - a; test_fromInteger_pattern a@1 = "1=" ++ (Prelude.show a); test_fromInteger_pattern a@(-2) = "(-2)=" ++ (Prelude.show a); test_fromInteger_pattern (a + 7) = "(a + 7)=" ++ Prelude.show a; test_fromRational_pattern [email protected] = "0.5=" ++ (Prelude.show a); test_fromRational_pattern a@(-0.7) = "(-0.7)=" ++ (Prelude.show a); test_fromRational_pattern a = "_=" ++ (Prelude.show a); doTest :: String -> IO a -> IO (); doTest s ioa = (putStrLn ("start test " ++ s)) Prelude.>> ioa Prelude.>> (putStrLn ("end test " ++ s)); main :: IO (); main = (doTest "test_do failure" (test_do (Prelude.return ()) (Prelude.return Nothing)) ) Prelude.>> (doTest "test_do success" (test_do (Prelude.return ()) (Prelude.return (Just ()))) ) Prelude.>> (doTest "test_fromInteger" (putStrLn (Prelude.show test_fromInteger)) ) Prelude.>> (doTest "test_fromRational" (putStrLn (Prelude.show test_fromRational)) ) Prelude.>> (doTest "test_negate" (putStrLn (Prelude.show (test_negate 3))) ) Prelude.>> (doTest "test_fromInteger_pattern 1" (putStrLn (test_fromInteger_pattern 1)) ) Prelude.>> (doTest "test_fromInteger_pattern (-2)" (putStrLn (test_fromInteger_pattern (-2))) ) Prelude.>> (doTest "test_fromInteger_pattern 9" (putStrLn (test_fromInteger_pattern 9)) ) Prelude.>> (doTest "test_fromRational_pattern 0.5" (putStrLn (test_fromRational_pattern 0.5)) ) Prelude.>> (doTest "test_fromRational_pattern (-0.7)" (putStrLn (test_fromRational_pattern (-0.7))) ) Prelude.>> (doTest "test_fromRational_pattern 1.7" (putStrLn (test_fromRational_pattern 1.7)) ); }
sdiehl/ghc
testsuite/tests/rebindable/rebindable4.hs
bsd-3-clause
4,543
1
23
2,059
1,144
625
519
84
1
{- hsc2hs program as a temporary solution, this is a wrapper around an existing hsc2hs, this should be replaced by a custom preprocessor to generate the code for the JS architecture. -} import Data.Char import Data.List import System.Exit import System.Process import qualified System.Info as Info import Compiler.Info (getFullArguments) main :: IO () main = do args <- getFullArguments exitWith =<< rawSystem "hsc2hs" (filter (\x -> isELF Info.os || not (isELFArg x)) args) {- when Setup.hs is compiled to JS, we have a regular, non-dynamic-too GHCJS. Cabal assumes that the ghcjs OS is ELF. this confuses the wrapped hsc2hs on non-ELF platforms -} isELFArg :: String -> Bool isELFArg xs = any (`isPrefixOf` xs) ["--lflags=-Wl,-R,", "--lflag=-Wl,-R,"] isELF :: String -> Bool isELF xs = map toLower xs `notElem` ["mingw32", "win32", "cygwin32", "darwin", "osx", "ghcjs"]
beni55/ghcjs
src-bin/Hsc2Hs.hs
mit
950
0
16
211
189
106
83
15
1
module LilRender.Image.DrawingPrimitives (drawFilledTriangle , drawTri, wrapColorGetter, wrapGetColor ) where import Control.Monad.Primitive import qualified Data.Vector.Storable as V import qualified Data.Vector.Storable.Mutable as MV import Foreign.C import Foreign.ForeignPtr import Foreign.Marshal import Foreign.Ptr import Foreign.Storable import LilRender.Color import LilRender.Image.Mutable import LilRender.Math.Geometry foreign import ccall safe "src/LilRender/Image/DrawingPrimitives.h drawTri" drawTri :: Ptr CChar -> Ptr Int -> Int -> FunPtr (Ptr (Barycentric (Point3 Double)) -> IO (Ptr (Maybe RGBColor))) -> Ptr (Point3 Double) -> Ptr (Point3 Double) -> Ptr (Point3 Double) -> IO () foreign import ccall "wrapper" wrapColorGetter :: (Ptr (Barycentric (Point3 Double)) -> IO (Ptr (Maybe RGBColor))) -> IO (FunPtr (Ptr (Barycentric (Point3 Double)) -> IO (Ptr (Maybe RGBColor)))) {-# INLINE drawFilledTriangle #-} drawFilledTriangle :: MutableImage (PrimState IO) -> (Barycentric (Point3 Double) -> Maybe RGBColor) -> Triangle (Screen (Point3 Double)) -> IO () drawFilledTriangle (MutableImage pixels zBuffer width _) getColor (Triangle (Screen vertex1) (Screen vertex2) (Screen vertex3)) = withForeignPtr (fst $ MV.unsafeToForeignPtr0 pixels) (\pixBuf -> withForeignPtr (fst $ MV.unsafeToForeignPtr0 zBuffer) (\zBuf -> do colorLookup <- wrapGetColor getColor vtx1 <- new . fmap realToFrac $ vertex1 vtx2 <- new . fmap realToFrac $ vertex2 vtx3 <- new . fmap realToFrac $ vertex3 drawTri (castPtr pixBuf) zBuf width colorLookup vtx1 vtx2 vtx3 ) ) {-# INLINE wrapGetColor #-} wrapGetColor :: (Barycentric (Point3 Double) -> Maybe RGBColor) -> IO (FunPtr (Ptr (Barycentric (Point3 Double)) -> IO (Ptr (Maybe RGBColor)))) wrapGetColor getColor = wrapColorGetter (\ptr -> do point <- peek ptr Foreign.Marshal.new $ getColor point )
SASinestro/lil-render
src/LilRender/Image/DrawingPrimitives.hs
isc
2,090
0
17
487
680
345
335
30
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE LambdaCase #-} import Control.Concurrent.STM (atomically) import Control.Concurrent.STM.TVar (swapTVar, readTVar) import Data.Conduit import qualified Data.Conduit.List as CL import qualified Data.Conduit.Combinators as CC import qualified Data.Conduit.Network.UDP as UDP import Data.Monoid ((<>)) import Control.Monad.Identity import Control.Monad.IO.Class (MonadIO (liftIO)) import qualified Data.Map.Strict as Map import Data.Time.Calendar ( Day(ModifiedJulianDay) ) import Data.Time.Clock ( UTCTime(..) ) import Data.Word ( Word16 ) import Network.Socket.Internal ( SockAddr(SockAddrInet), PortNumber ) import Network.Socket ( HostAddress, inet_addr ) import Data.Serialize (decode, encode) import qualified Data.List.NonEmpty as NEL import Test.Hspec import Data.MessagePack.Aeson (packAeson, unpackAeson) import qualified Data.Aeson as A import qualified Core import Types import Util withStore :: (Store -> IO ()) -> IO () withStore f = configure >>= \ case Left e -> liftIO $ fail $ "configure failed" <> show e Right store -> f store zeroTime :: UTCTime zeroTime = UTCTime (ModifiedJulianDay 0) 0 localhost :: IO HostAddress localhost = inet_addr "127.0.0.1" sockAddr :: HostAddress -> PortNumber -> SockAddr sockAddr = flip SockAddrInet makeMembers :: HostAddress -> [Member] makeMembers host = let seeds = [ ("alive", IsAliveC, zeroTime, sockAddr host 4001) , ("suspect", IsSuspectC, zeroTime, sockAddr host 4002) , ("dead", IsDeadC, zeroTime, sockAddr host 4003)] in map (\(name, status, timeChanged, addr) -> Member { memberName = name , memberHost = "127.0.0.1" , memberAlive = status , memberIncarnation = 0 , memberLastChange = timeChanged , memberHostNew = addr }) seeds membersMap :: [Member] -> Map.Map String Member membersMap ms = Map.fromList $ map (\m -> (memberName m, m)) ms currentIncarnation :: Store -> IO Int currentIncarnation Store{..} = atomically $ readTVar storeIncarnation envelope :: [Message] -> Envelope envelope msgs = Envelope $ NEL.fromList msgs backAndForthForeverAndEver :: [Message] -> Either String Envelope backAndForthForeverAndEver msgs = decode (encode $ envelope msgs) main :: IO () main = localhost >>= \hostAddr -> hspec $ do let addr = sockAddr hostAddr 4000 defaultMembers = makeMembers hostAddr describe "wire protocol" $ it "encodes & decodes" $ do let msgPack = unpackAeson . packAeson json = A.decode . A.encode ping = Ping { seqNo = 1, node = "a" } indirectPing = IndirectPing { seqNo = 2, target = 1, port = 4000 :: Word16, node = "b" } ack = Ack { seqNo = 2, payload = [] } ping2 = Ping { seqNo = 3, node = "b" } ack2 = Ack { seqNo = 4, payload = [] } msgs = [ping, ack, ping2, ack2] json ping `shouldBe` Just ping json indirectPing `shouldBe` Just indirectPing msgPack ping `shouldBe` Just ping msgPack indirectPing `shouldBe` Just indirectPing backAndForthForeverAndEver [ping] `shouldBe` Right (envelope [ping]) backAndForthForeverAndEver [indirectPing] `shouldBe` Right (envelope [indirectPing]) backAndForthForeverAndEver msgs `shouldBe` Right (envelope msgs) describe "Core.removeDeadNodes" $ it "removes dead members" $ withStore $ \s@Store{..} -> do _ <- atomically $ do void $ swapTVar storeMembers $ membersMap defaultMembers void $ Core.removeDeadNodes s mems' <- atomically $ readTVar storeMembers Map.notMember "dead" mems' `shouldBe` True Map.size mems' `shouldBe` 2 describe "Core.kRandomMembers" $ do let ms = defaultMembers it "takes no nodes if n is 0" $ withStore $ \s@Store{..} -> do void $ atomically $ swapTVar storeMembers $ membersMap ms rand <- Core.kRandomMembers s 0 ms length rand `shouldBe` 0 it "filters non-alive nodes" $ withStore $ \s@Store{..} -> do void $ atomically $ swapTVar storeMembers $ membersMap ms rand <- Core.kRandomMembers s 3 [] length rand `shouldBe` 1 head rand `shouldBe` head ms it "filters exclusion nodes" $ withStore $ \s@Store{..} -> do void $ atomically $ swapTVar storeMembers $ membersMap ms rand <- Core.kRandomMembers s 3 [head ms] length rand `shouldBe` 0 it "shuffles" $ withStore $ \s@Store{..} -> do let alives = zipWith (\m i -> m { memberName = "alive-" <> show i }) (replicate total $ head defaultMembers) ([0..] :: [Integer]) total = 200 n = 50 void $ atomically $ swapTVar storeMembers $ membersMap alives rand <- Core.kRandomMembers s n [] length rand `shouldBe` n total `shouldNotBe` n rand `shouldNotBe` alives describe "Core.handleUDPMessage" $ do let ping = Ping 1 "myself" ack = Ack 1 [] indirectPing (SockAddrInet port target) = IndirectPing 1 (fromIntegral target) (fromIntegral port) "other" send s msg = do let udpMsg = UDP.Message (encode $ envelope [msg]) addr CL.sourceList [udpMsg] $$ Core.handleUDPMessage s =$= CC.sinkList invokesAckHandler = undefined it "gets Ping for us, responds with Ack" $ withStore $ \s@Store{..} -> do gossip <- send s ping gossip `shouldBe` [Direct (Ack 1 []) addr] it "gets Ping for someone else, ignores msg" $ withStore $ \s@Store{..} -> do gossip <- send s $ Ping 1 "unknown-node" gossip `shouldBe` [] it "gets Ack, invokes ackHandler" $ withStore $ \s@Store{..} -> do pending gossip <- send s ack gossip `shouldBe` [] it "gets IndirectPing, sends Ping" $ withStore $ \s@Store{..} -> do let indirectPing' = indirectPing addr udpMsg = UDP.Message (encode $ envelope [indirectPing']) addr beforeInc <- currentIncarnation s gossip <- send s indirectPing' afterInc <- currentIncarnation s beforeInc + 1 `shouldBe` afterInc gossip `shouldBe` [Direct (Ping 1 (node indirectPing')) addr] it "gets Suspect" $ withStore $ \s@Store{..} -> do pending it "gets Dead" $ withStore $ \s@Store{..} -> do pending it "gets Alive" $ withStore $ \s@Store{..} -> do pending
jpfuentes2/swim
test/Spec.hs
mit
6,743
0
26
1,887
2,159
1,130
1,029
143
2
module CCNxPacketGenerator ( preparePacket , produceInterestPackets , produceInterests , produceContents , produceNamelessContents , produceContentPackets , producePacketPairs , balancedManifestTree , createInterest , createContent , createPayload ) where import System.IO import System.Random import Control.Monad import Data.Text import Data.Bits import Data.Word import Data.Maybe import Data.ByteString.Char8 import qualified Data.ByteString.Lazy.Char8 as Lazy import Data.ByteString import qualified Data.Digest.Pure.SHA as SHA import Debug.Trace import Numeric (readHex) import Generator class Serializer t where serialize :: t -> ByteString class Encoder t where toTLV :: t -> TLV encodingSize :: t -> Int data TwoByte = TType Word8 Word8 | Length Word8 Word8 deriving(Show) intToTType :: Int -> TwoByte intToTType x = (TType (fromIntegral (x `shiftR` 8)) (fromIntegral x)) intToLength :: Int -> TwoByte intToLength x = (Length (fromIntegral (x `shiftR` 8)) (fromIntegral x)) intTo2Bytes :: Int -> [Word8] intTo2Bytes x = [(fromIntegral (x `shiftR` 8)), (fromIntegral x)] data TLV = RawTLV { tlv_type :: TwoByte, tlv_length :: TwoByte, tlv_raw_value :: Data.ByteString.ByteString } | NestedTLV { tlv_type :: TwoByte, tlv_length :: TwoByte, tlv_nested_value :: [TLV] } deriving (Show) instance Serializer TLV where serialize (RawTLV (TType t1 t2) (Length l1 l2) v) = let bytelist = [(Data.ByteString.singleton t1), (Data.ByteString.singleton t2), (Data.ByteString.singleton l1), (Data.ByteString.singleton l2), v] in (Data.ByteString.concat bytelist) serialize (NestedTLV (TType t1 t2) (Length l1 l2) v) = let bytelist = [(Data.ByteString.singleton t1), (Data.ByteString.singleton t2), (Data.ByteString.singleton l1), (Data.ByteString.singleton l2)] ++ (Prelude.map serialize v) -- v :: [TLV], so we need to serialize each and then append it to the list in (Data.ByteString.concat bytelist) data NameComponent = NameComponent {value :: String} | PayloadId {value :: String} deriving (Show) instance Encoder NameComponent where toTLV (NameComponent value) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_raw_value = bvalue } where bvalue = (Data.ByteString.Char8.pack value) blength = (Data.ByteString.length bvalue) toTLV (PayloadId value) = RawTLV {tlv_type = (intToTType 2), tlv_length = (intToLength blength), tlv_raw_value = bvalue } where bvalue = (Data.ByteString.Char8.pack value) blength = (Data.ByteString.length bvalue) encodingSize (NameComponent value) = 4 + (Data.ByteString.length bvalue) where bvalue = (Data.ByteString.Char8.pack value) encodingSize (PayloadId value) = 4 + (Data.ByteString.length bvalue) where bvalue = (Data.ByteString.Char8.pack value) data Name = Name {components :: [NameComponent]} deriving (Show) instance Encoder Name where toTLV (Name components) = NestedTLV {tlv_type = (intToTType 0), tlv_length = (intToLength csize), tlv_nested_value = nvalue } where nvalue = (Prelude.map toTLV components) csize = (sum (Prelude.map encodingSize components)) encodingSize (Name components) = 4 + (sum (Prelude.map encodingSize components)) name :: [String] -> Maybe Name name nc = Just (Name [ NameComponent s | s <- nc ]) type Version = Word8 type PacketType = Word8 type PacketLength = Word16 type HeaderLength = Word8 type VaidationType = Word16 type Cert = [Word8] type PubKey = [Word8] type KeyName = Name data Payload = Payload [Word8] deriving(Show) instance Encoder Payload where toTLV (Payload bytes) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_raw_value = bvalue } where bvalue = (Data.ByteString.pack bytes) blength = (Data.ByteString.length bvalue) encodingSize (Payload bytes) = 4 + (Data.ByteString.length (Data.ByteString.pack bytes)) data KeyId = KeyId [Word8] deriving(Show) instance Encoder KeyId where toTLV (KeyId bytes) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_raw_value = bvalue } where bvalue = (Data.ByteString.pack bytes) blength = (Data.ByteString.length bvalue) encodingSize (KeyId bytes) = 4 + (Data.ByteString.length (Data.ByteString.pack bytes)) data ContentId = ContentId [Word8] deriving(Show) instance Encoder ContentId where toTLV (ContentId bytes) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_raw_value = bvalue } where bvalue = (Data.ByteString.pack bytes) blength = (Data.ByteString.length bvalue) encodingSize (ContentId bytes) = 4 + (Data.ByteString.length (Data.ByteString.pack bytes)) createKeyId :: [Char] -> Maybe KeyId createKeyId string | Prelude.length string > 0 = Just (KeyId (stringToBytes string)) | otherwise = Nothing createContentId :: [Char] -> Maybe ContentId createContentId string | Prelude.length string > 0 = Just (ContentId (stringToBytes string)) | otherwise = Nothing class Packet t where preparePacket :: Maybe t -> Maybe Data.ByteString.ByteString type NamedPayload = (Name, Payload) data ValidationDependentData = ValidationDependentData KeyId PubKey Cert KeyName deriving(Show) data ValidationPayload = ValidationPayload [Word8] deriving(Show) data ValidationAlg = ValidationAlg VaidationType ValidationDependentData deriving(Show) data Validation = Validation ValidationAlg ValidationPayload deriving(Show) data Interest = SimpleInterest Name | RestrictedInterest Name (Maybe KeyId) (Maybe ContentId) | InterestWithPayload NamedPayload | SignedInterest NamedPayload Validation deriving(Show) instance Encoder Interest where toTLV (SimpleInterest name) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name)] blength = (encodingSize name) toTLV (InterestWithPayload (name, payload)) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name), (toTLV payload)] blength = (sum [(encodingSize name), (encodingSize payload)]) toTLV (RestrictedInterest name Nothing Nothing) = toTLV (SimpleInterest name) toTLV (RestrictedInterest name (Just keyId) Nothing) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name), (toTLV keyId)] blength = (sum [(encodingSize name), (encodingSize keyId)]) toTLV (RestrictedInterest name Nothing (Just contentId)) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name), (toTLV contentId)] blength = (sum [(encodingSize name), (encodingSize contentId)]) toTLV (RestrictedInterest name (Just keyId) (Just contentId)) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name), (toTLV keyId), (toTLV contentId)] blength = (sum [(encodingSize name), (encodingSize keyId), (encodingSize contentId)]) encodingSize (SimpleInterest name) = 4 + (encodingSize name) encodingSize (InterestWithPayload (name, payload)) = 4 + (sum [(encodingSize name), (encodingSize payload)]) encodingSize (RestrictedInterest name Nothing Nothing) = 4 + (encodingSize name) encodingSize (RestrictedInterest name (Just keyId) Nothing) = 4 + (sum [(encodingSize name), (encodingSize keyId)]) encodingSize (RestrictedInterest name Nothing (Just contentId)) = 4 + (sum [(encodingSize name), (encodingSize contentId)]) encodingSize (RestrictedInterest name (Just keyId) (Just contentId)) = 4 + (sum [(encodingSize name), (encodingSize keyId), (encodingSize contentId)]) instance Packet Interest where preparePacket (Just (SimpleInterest name)) = Just (prependFixedHeader 1 0 (serialize (toTLV (SimpleInterest name)))) preparePacket (Just (RestrictedInterest name keyId contentId)) = Just (prependFixedHeader 1 0 (serialize (toTLV (RestrictedInterest name keyId contentId)))) preparePacket (Just (InterestWithPayload (name, payload))) = Just (prependFixedHeader 1 0 (serialize (toTLV (InterestWithPayload (name, payload))))) preparePacket Nothing = Nothing data Content = NamelessContent Payload | SimpleContent NamedPayload | SignedContent NamedPayload Validation deriving (Show) instance Encoder Content where -- TL type is 2 toTLV (SimpleContent (name, payload)) = NestedTLV { tlv_type = (intToTType 2), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name), (toTLV payload)] blength = (sum [(encodingSize name), (encodingSize payload)]) -- TL type is 2 toTLV (NamelessContent payload) = NestedTLV { tlv_type = (intToTType 2), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV payload)] blength = (encodingSize payload) encodingSize (SimpleContent (name, payload)) = 4 + (sum [(encodingSize name), (encodingSize payload)]) encodingSize (NamelessContent payload) = 4 + (encodingSize payload) instance Packet Content where preparePacket (Just (SimpleContent (name, payload))) = Just (prependFixedHeader 1 1 (serialize (toTLV (SimpleContent (name, payload))))) preparePacket (Just (NamelessContent payload)) = Just (prependFixedHeader 1 1 (serialize (toTLV (NamelessContent payload)))) preparePacket Nothing = Nothing data HashGroupPointer = DataPointer ByteString | ManifestPointer ByteString deriving (Show) instance Encoder HashGroupPointer where toTLV (DataPointer bytes) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength (Data.ByteString.length bytes)), tlv_raw_value = bytes } -- where -- bvalue = (Data.ByteString.pack bytes) -- blength = (Data.ByteString.length bvalue) toTLV (ManifestPointer bytes) = RawTLV { tlv_type = (intToTType 1), tlv_length = (intToLength (Data.ByteString.length bytes)), tlv_raw_value = bytes } -- where -- bvalue = (Data.ByteString.pack bytes) -- blength = (Data.ByteString.length bvalue) encodingSize (DataPointer bytes) = 4 + (Data.ByteString.length bytes) encodingSize (ManifestPointer bytes) = 4 + (Data.ByteString.length bytes) data ManifestHashGroup = ManifestHashGroup [HashGroupPointer] deriving (Show) instance Encoder ManifestHashGroup where toTLV (ManifestHashGroup pointers) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = Prelude.map toTLV pointers blength = sum (Prelude.map encodingSize pointers) encodingSize (ManifestHashGroup pointers) = 4 + (sum (Prelude.map encodingSize pointers)) type ManifestBody = [ManifestHashGroup] data Manifest = SimpleManifest Name ManifestBody | NamelessManifest ManifestBody | SignedManifest Name ManifestBody Validation deriving (Show) instance Encoder Manifest where toTLV (SimpleManifest name body) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = [(toTLV name)] ++ (Prelude.map toTLV body) blength = sum ([(encodingSize name)] ++ (Prelude.map encodingSize body)) toTLV (NamelessManifest body) = NestedTLV { tlv_type = (intToTType 1), tlv_length = (intToLength blength), tlv_nested_value = bvalue } where bvalue = Prelude.map toTLV body blength = sum (Prelude.map encodingSize body) -- TODO: implement the validation encoder -- toTLV (SignedManifest name body validation) encodingSize (SimpleManifest name body) = 4 + (sum ([(encodingSize name)] ++ (Prelude.map encodingSize body))) encodingSize (NamelessManifest body) = 4 + (sum (Prelude.map encodingSize body)) instance Packet Manifest where preparePacket (Just (SimpleManifest name body)) = Just (prependFixedHeader 1 1 (serialize (toTLV (SimpleManifest name body)))) preparePacket (Just (NamelessManifest body)) = Just (prependFixedHeader 1 1 (serialize (toTLV (NamelessManifest body)))) preparePacket Nothing = Nothing -- We have three types of messages: Interest, Content Object, and (FLIC) Manifest data Message = IMessage Interest | CMessage Content | MMessage Manifest deriving (Show) instance Packet Message where preparePacket (Just (IMessage interest)) = preparePacket (Just interest) preparePacket (Just (CMessage content)) = preparePacket (Just content) preparePacket (Just (MMessage manifest)) = preparePacket (Just manifest) preparePacket Nothing = Nothing createSimpleInterest :: [String] -> Maybe Interest createSimpleInterest s = case (name s) of Nothing -> Nothing Just (Name nc) -> Just (SimpleInterest (Name nc)) -- Helper stringToByte :: [Char] -> Word8 stringToByte string = fromIntegral (fst ((readHex string) !! 0)) stringToBytes :: [Char] -> [Word8] stringToBytes string | Prelude.length string > 2 = [(stringToByte (Prelude.take 2 string))] ++ (stringToBytes (Prelude.drop 2 string)) | otherwise = [(stringToByte (Prelude.take 2 string))] createInterest :: [String] -> String -> String -> Maybe Interest createInterest nameString keyId contentId = case (name nameString) of Nothing -> Nothing Just (Name nc) -> Just (RestrictedInterest (Name nc) (createKeyId keyId) (createContentId contentId)) createContent :: Payload -> [String] -> Maybe Content createContent p s = case (name s) of Nothing -> Nothing Just (Name nc) -> Just (SimpleContent ((Name nc), p)) createNamelessContent :: Payload -> Maybe Content createNamelessContent p = Just (NamelessContent p) createPayload :: [Word8] -> Payload createPayload d = Payload d messagesToHashDigests :: [Message] -> [ByteString] messagesToHashDigests messages = do let rawPackets = Prelude.map Data.Maybe.fromJust (Prelude.map preparePacket (Prelude.map (\x -> Just x) messages)) let hashChunks = Prelude.reverse (Prelude.map SHA.sha256 (fmap Lazy.fromStrict rawPackets)) in Prelude.map Lazy.toStrict (Prelude.map SHA.bytestringDigest hashChunks) manifestFromPointers :: [HashGroupPointer] -> Manifest manifestFromPointers pointers = do let hashGroup = ManifestHashGroup pointers in NamelessManifest [hashGroup] namedManifestFromPointers :: Name -> [HashGroupPointer] -> Manifest namedManifestFromPointers n pointers = do let hashGroup = ManifestHashGroup pointers in SimpleManifest n [hashGroup] splitIntoChunks _ [] = [] splitIntoChunks n s | n > 0 = (Prelude.take n s) : (splitIntoChunks n (Prelude.drop n s)) | otherwise = error "Error: the splitIntoChunks parameter must be positive" balancedManifestTreeFromPointers :: [Message] -> Name -> Int -> [HashGroupPointer] -> [Message] balancedManifestTreeFromPointers messageList rootName numPointers pointers -- Base case: when we don't need to extend the tree to add more pointers | (Prelude.length pointers) < numPointers = do -- System.IO.putStrLn "balancedManifestTreeFromPointers leaf" let manifestNode = MMessage (namedManifestFromPointers rootName pointers) in messageList ++ [manifestNode] -- Recurse and add more pointers to the tree | otherwise = do -- System.IO.putStrLn "balancedManifestTreeFromPointers inner node" [] let pointerChunks = splitIntoChunks numPointers pointers -- Note: this will build a tree of manifests let manifestNodes = Prelude.map manifestFromPointers pointerChunks let rawPackets = Prelude.map Data.Maybe.fromJust (Prelude.map preparePacket (Prelude.map (\x -> Just x) manifestNodes)) let hashChunks = Prelude.reverse (Prelude.map SHA.sha256 (fmap Lazy.fromStrict rawPackets)) let manifestPointers = Prelude.map ManifestPointer (Prelude.map Lazy.toStrict (Prelude.map SHA.bytestringDigest hashChunks)) in balancedManifestTreeFromPointers (messageList ++ (Prelude.map MMessage manifestNodes)) rootName numPointers manifestPointers balancedManifestTree :: [String] -> Int -> [Content] -> [Message] balancedManifestTree s numPointers datas = case (name s) of Nothing -> [] Just (Name nc) -> do let rawContents = Prelude.map CMessage datas let rawPackets = Prelude.map Data.Maybe.fromJust (Prelude.map preparePacket (Prelude.map (\x -> Just x) datas)) let lazyHashChunks = Prelude.reverse (Prelude.map SHA.bytestringDigest (Prelude.map SHA.sha256 (fmap Lazy.fromStrict rawPackets))) let strictHashChunks = Prelude.map Lazy.toStrict lazyHashChunks let dataPointers = Prelude.map DataPointer strictHashChunks balancedManifestTreeFromPointers rawContents (Name nc) numPointers dataPointers -- stupid test function testManifesTree :: [Message] testManifesTree = do let seed = 100 let number = 1 let nmin = 3 let nmax = 5 let ncmin = 2 let ncmax = 5 let pmin = 16 let pmax = 32 let payloadStream = Prelude.take number (randomListOfByteArrays (pmin, pmax) number (mkStdGen seed)) let contents = produceNamelessContents payloadStream balancedManifestTree ["abc","def"] 4096 contents data FixedHeader = FixedHeader Version PacketType PacketLength deriving(Show) prependFixedHeader :: Version -> PacketType -> Data.ByteString.ByteString -> Data.ByteString.ByteString prependFixedHeader pv pt body = let bytes = [(Data.ByteString.singleton pv), (Data.ByteString.singleton pt), (Data.ByteString.pack (intTo2Bytes ((Data.ByteString.length body) + 8))), -- header length is 8 bytes (Data.ByteString.pack [255,0,0,8]), -- the header length is 8 bytes; no optional headers, yet. 255 is hop limit. body] in (Data.ByteString.concat bytes) produceInterests :: [[String]] -> [Maybe Interest] produceInterests (s:xs) = case (createSimpleInterest s) of Nothing -> [] Just (SimpleInterest msg) -> [Just (SimpleInterest msg)] ++ (produceInterests xs) produceInterests [] = [] produceInterestPackets :: [[String]] -> [Maybe ByteString] produceInterestPackets s = fmap preparePacket (produceInterests s) produceContents :: [[String]] -> [[Word8]] -> [Maybe Content] produceContents (n:ns) (p:ps) = case (createContent (Payload p) n) of Nothing -> [] Just (SimpleContent msg) -> [Just (SimpleContent msg)] ++ (produceContents ns ps) produceContents [] _ = [] produceContents _ [] = [] produceNamelessContents :: [[Word8]] -> [Content] produceNamelessContents (p:ps) = [NamelessContent (Payload p)] ++ (produceNamelessContents ps) produceNamelessContents [] = [] produceContentPackets :: [[String]] -> [[Word8]] -> [Maybe ByteString] produceContentPackets names payloads = fmap preparePacket (produceContents names payloads) producePacketPairs :: [[String]] -> [[Word8]] -> [(Maybe ByteString, Maybe ByteString)] producePacketPairs n p = do let interests = produceInterestPackets n let contents = produceContentPackets n p in Prelude.zip interests contents produceManifests :: [[String]] -> [ByteString] -> [Maybe Manifest] produceManifests names datas = do let hashChunks = splitIntoChunks 2 (Prelude.reverse (Prelude.map SHA.sha256 (Prelude.map Lazy.fromStrict datas))) in -- TODO: use foldl to create a manifest, and insert the new value into the list (hashed), and continue with the creation --Prelude.foldl [] -- case (content (Payload p) n) of -- Nothing -> [] -- Just (Content msg) -> [Just (Content msg)] ++ (produceManifests ns ps) produceManifestPackets :: [[String]] -> [ByteString] -> [Maybe ByteString] produceManifestPackets names datas = fmap preparePacket (produceManifests names datas)
chris-wood/ccnx-pktgen
src/CCNxPacketGenerator.hs
mit
21,023
0
20
4,647
6,479
3,445
3,034
338
2
module Tarefa1_2017li1g183 where import LI11718 --------------- from Nuno testesT1 :: [Caminho] testesT1 = [c_ex1,c_ex1',c_ex2,c_ex4,c_ex5,c_ex6 ,c_exOP,c_exDM,c_exOL,c_exHM,c_exR,c_exE] -- ,m_ex1,m_ex2,m_ex3 -- ,m_exPI,m_exLV,m_exEX,m_exLH] c_ex1 :: Caminho c_ex1 = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Desce,Avanca,CurvaEsq,CurvaDir ,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca ,Desce,CurvaDir,CurvaDir,Avanca,Avanca,Desce,CurvaEsq,CurvaDir,Sobe,CurvaDir ,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Sobe,Sobe,Avanca,Avanca,CurvaDir,Avanca] c_ex1' :: Caminho c_ex1' = [Avanca,CurvaEsq,Avanca,CurvaDir,Avanca,CurvaDir,Sobe,Avanca,CurvaEsq,CurvaDir ,CurvaEsq,CurvaDir,CurvaDir,CurvaEsq,CurvaDir,CurvaEsq,CurvaEsq,Avanca,Avanca ,Sobe,CurvaDir,CurvaDir,Avanca,Avanca,Sobe,CurvaEsq,CurvaDir,Desce,CurvaDir ,CurvaEsq,CurvaDir,CurvaEsq,Avanca,CurvaDir,Desce,Desce,Avanca,Avanca,CurvaDir,Avanca] c_ex2 :: Caminho c_ex2 = [Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq] -- mapa sobreposto, altura /= da inicial c_ex3 :: Caminho c_ex3 = [Desce,CurvaEsq,CurvaEsq,Desce,CurvaEsq,CurvaEsq ,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,CurvaEsq] -- caminho em 8, cruza c_ex4 :: Caminho c_ex4 = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Avanca,CurvaEsq,Avanca ,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Avanca,CurvaDir] -- caminho minimo válido c_ex5 :: Caminho c_ex5 = [CurvaDir,CurvaDir,CurvaDir,CurvaDir] -- caminho minimo sem vizinhos c_ex6 :: Caminho c_ex6 = [Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir,Avanca,CurvaDir] -- mapa nao geravel por caminhos, lava extra a volta m_ex1 = Mapa ((2,1),Este) [[Peca Lava 2, Peca Lava 2, Peca Lava 2, Peca Lava 2] ,[Peca Lava 2, Peca (Curva Norte) 2,Peca (Curva Este) 2, Peca Lava 2] ,[Peca Lava 2, Peca (Curva Oeste) 2,Peca (Curva Sul) 2, Peca Lava 2] ,[Peca Lava 2, Peca Lava 2, Peca Lava 2, Peca Lava 2]] -- mapa nao geravel por caminhos, altura /= inicial sem possibilidade de rampas m_ex2 = Mapa ((1,0),Este) [[Peca (Curva Norte) 5,Peca (Curva Este) 5],[Peca (Curva Oeste) 5,Peca (Curva Sul) 5]] -- mapa minimo sem vizinhos m_ex3 = Mapa ((1,0),Este) [[Peca (Curva Norte) 2,Peca Recta 2,Peca (Curva Este) 2],[Peca Recta 2,Peca Lava 2,Peca Recta 2],[Peca (Curva Oeste) 2,Peca Recta 2,Peca (Curva Sul) 2]] -- testes invalidos -- aberto c_exOP :: Caminho c_exOP = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir ,Avanca,Avanca,Avanca,CurvaDir,CurvaEsq,Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca] -- fecha mas direcao errada c_exDM :: Caminho c_exDM = [Sobe,CurvaEsq,CurvaEsq,Sobe,CurvaEsq,CurvaEsq ,Avanca,CurvaEsq,CurvaEsq,Avanca,CurvaEsq,Avanca] -- overlaps, aberto c_exOL :: Caminho c_exOL = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir ,Avanca,CurvaDir,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca] -- height mismatch c_exHM :: Caminho c_exHM = [Avanca,Avanca,CurvaDir,Avanca,Avanca,CurvaEsq,Avanca,CurvaDir,CurvaDir ,Avanca,Sobe,Avanca,CurvaDir,CurvaEsq,Avanca,CurvaDir,Avanca,Avanca,CurvaDir,Avanca] -- cruza com alturas invalidas c_exR :: Caminho c_exR = [Avanca,CurvaDir,Avanca,Avanca,Avanca,CurvaEsq,Sobe,CurvaEsq,Avanca ,CurvaEsq,Avanca,Avanca,Avanca,CurvaDir,Desce,CurvaDir] {- let map = constroi c_exR printHeight map -} -- caminho vazio c_exE :: Caminho c_exE = [] constroi :: Caminho -> Mapa constroi c = Mapa (partida c,dirInit) tab where Mapa (finishPos,finishDir) tab = constroiAux (Mapa (partida c,dirInit) (initTab c)) altInit c initTab :: Caminho -> Tabuleiro initTab c = replicate y $ replicate x $ Peca Lava altLava where (x,y) = dimensao c constroiAux :: Mapa -> Altura -> Caminho -> Mapa constroiAux m _ [] = m constroiAux (Mapa (pos,dir) tab) a (i:is) = constroiAux (Mapa (p',d') novoMapa) a' is where (p',d',a',novoMapa) = insere i pos dir a tab insere Avanca pos dir a tab = (go pos dir, dir, a, coloca (Peca Recta a) pos tab) insere Sobe pos dir a tab = (go pos dir, dir, a+1, coloca (Peca (Rampa dir) a) pos tab) insere Desce pos dir a tab = (go pos dir, dir, a-1, coloca (Peca (Rampa (swap dir)) (a-1)) pos tab) -- insere CurvaEsq pos dir a tab = (go pos des, des, a, coloca (Peca (Curva (tr dir)) a) pos tab) insere CurvaEsq pos dir a tab = (go pos des, des, a, coloca (Peca (Curva (dir)) a) pos tab) where des = tr.tr.tr$dir insere CurvaDir pos dir a tab = (go pos ddi, ddi, a, coloca (Peca (Curva dir) a) pos tab) where ddi = tr dir swap = tr.tr coloca :: a -> Posicao -> [[a]] -> [[a]] coloca peca (0,0) ((_:l):ls) = (peca:l):ls coloca p (x,0) ((h:t):ls) = let (a2:b2) = coloca p (x-1,0) (t:ls) in (h:a2):b2 coloca p (x,y) (l:ls) = l : (coloca p (x,y-1) ls) go (x,y) Norte = (x,y-1) go (x,y) Sul = (x,y+1) go (x,y) Este = (x+1,y) go (x,y) Oeste = (x-1,y) tr Norte = Este tr Este = Sul tr Sul = Oeste tr Oeste = Norte
hpacheco/HAAP
examples/plab/svn/2017li1g183/src/Tarefa1_2017li1g183.hs
mit
5,198
0
12
954
2,161
1,259
902
83
1
{-# LANGUAGE DataKinds, FlexibleContexts, FlexibleInstances, GADTs, MultiParamTypeClasses, TypeFamilies, TypeOperators, UndecidableInstances #-} module Data.Nested.Naturals where import GHC.TypeLits hiding ((+)(), (*)(), (-)(), (^)()) import qualified GHC.TypeLits as N -- Peano Numbers for type-level computation. data Peano = Zero | Succ Peano deriving (Eq, Show) type N0 = Zero type N1 = Succ N0 type N2 = Succ N1 type N3 = Succ N2 type N4 = Succ N3 type N5 = Succ N4 type family (x :: Peano) + (y :: Peano) :: Peano where 'Zero + y = y ('Succ x) + y = 'Succ (x + y) type family (x :: Peano) - (y :: Peano) :: Peano where x - 'Zero = x ('Succ x) - ('Succ y) = x - y type family (x :: Peano) * (y :: Peano) :: Peano where x * 'Zero = 'Zero x * ('Succ y) = x + x * y type family (x :: Peano) ^ (y :: Peano) :: Peano where x ^ 'Zero = 'Succ 'Zero x ^ ('Succ y) = x * x ^ y type family (x :: Peano) == (y :: Peano) :: Bool where 'Zero == 'Zero = 'True x == 'Zero = 'False 'Zero == y = 'False 'Succ x == 'Succ y = x == y type family (x :: Peano) < (y :: Peano) :: Bool where x < 'Zero = 'False 'Zero < y = 'True 'Succ x < 'Succ y = x < y type family Min (x :: Peano) (y :: Peano) :: Peano where Min x 'Zero = 'Zero Min 'Zero y = 'Zero Min ('Succ x) ('Succ y) = 'Succ (Min x y) type family Max (x :: Peano) (y :: Peano) :: Peano where Max x 'Zero = x Max 'Zero y = y Max ('Succ x) ('Succ y) = 'Succ (Max x y) type family FromPeano (n :: Peano) :: Nat where FromPeano 'Zero = 0 FromPeano ('Succ n) = 1 N.+ (FromPeano n) type family ToPeano (n :: Nat) :: Peano where ToPeano 0 = 'Zero ToPeano n = 'Succ (ToPeano (n N.- 1))
filonik/nfunctors
src/Data/Nested/Naturals.hs
mit
1,694
11
10
427
853
478
375
-1
-1
module Tfoo.Foundation where import Tfoo.Game import Yesod.Static import Control.Concurrent.MVar data Tfoo = Tfoo { seed :: Int, games :: MVar [IO Game], nextGameId :: MVar Int, tfooStatic :: Static } -- Increment Tfoo's Game counter and return id of the next new Game. newGame :: Tfoo -> IO Int newGame tfoo = modifyMVar (nextGameId tfoo) incrementMVar where incrementMVar :: Int -> IO (Int, Int) incrementMVar value = return (value+1, value)
nbartlomiej/tfoo
Tfoo/Foundation.hs
mit
490
0
11
116
140
78
62
14
1
module Challenge263.Intermediate where import Data.List import Data.Map (Map, (!)) import qualified Data.Map as Map import Data.Maybe import qualified Text.Read as R import Text.Trifecta import Text.Trifecta.Delta type Stress = Integer data PhonemeType = Vowel Stress | Stop | Affricate | Fricative | Aspirate | Liquid | Semivowel | Nasal deriving (Show, Eq, Ord) data Phoneme = Phoneme String PhonemeType deriving (Show, Eq, Ord) isVowel (Phoneme _ (Vowel _)) = True isVowel _ = False challengeIsMatchingPhoneme :: Phoneme -> Phoneme -> Bool challengeIsMatchingPhoneme (Phoneme a1 (Vowel s1)) (Phoneme a2 (Vowel s2)) = a1 == a2 challengeIsMatchingPhoneme p1 p2 = p1 == p2 isMatchingPhoneme :: Phoneme -> Phoneme -> Bool isMatchingPhoneme = (==) numMatchingPhonemes :: (Phoneme -> Phoneme -> Bool) -> [Phoneme] -> [Phoneme] -> Integer numMatchingPhonemes eq x y = genericLength $ takeWhile (== True) $ zipWith eq (reverse x) (reverse y) rhymeWords :: (Phoneme -> Phoneme -> Bool) -> Map String [Phoneme] -> String -> Map String (Integer,[Phoneme]) rhymeWords eq d s = Map.map (\a -> (numMatchingPhonemes eq pS a, a)) $ Map.filter (\a -> all (== True) $ zipWith eq (lastSyllable a) (lastSyllable pS)) d where pS = d ! s lastSyllable :: [Phoneme] -> [Phoneme] lastSyllable = reverse . takeWhileInclusive (not . isVowel) . reverse takeWhileInclusive :: (t -> Bool) -> [t] -> [t] takeWhileInclusive _ [] = [] takeWhileInclusive p (x:xs) = x : if p x then takeWhileInclusive p xs else [] pronouncingDictionary :: String -> IO (Map String [Phoneme]) pronouncingDictionary s = do test <- parseFromFile parseDictionaryFile s case test of Nothing -> return Map.empty Just ts -> return ts parseDictionaryFile :: Parser (Map String [Phoneme]) parseDictionaryFile = Map.fromList <$> (some commentLine *> manyTill dictionaryLine (try eof)) dictionaryLine :: Parser (String,[Phoneme]) dictionaryLine = f <$> manyTill anyChar (try (string " ")) <*> some alphaNum `sepBy1` char ' ' <* endOfLine where f s p = (s, map phoneme p) commentLine :: Parser String commentLine = string ";;;" *> manyTill anyChar endOfLine endOfLine :: Parser Char endOfLine = choice [newline,char '\r' *> newline] phoneme :: String -> Phoneme phoneme s | isJust (R.readMaybe [last s] :: Maybe Integer) = Phoneme (init s) (Vowel $ read [last s]) | otherwise = nonVowelPhoneme s where nonVowelPhoneme "B" = Phoneme "B" Stop nonVowelPhoneme "CH" = Phoneme "CH" Affricate nonVowelPhoneme "D" = Phoneme "D" Stop nonVowelPhoneme "DH" = Phoneme "DH" Fricative nonVowelPhoneme "F" = Phoneme "F" Fricative nonVowelPhoneme "G" = Phoneme "G" Stop nonVowelPhoneme "HH" = Phoneme "HH" Aspirate nonVowelPhoneme "JH" = Phoneme "JH" Affricate nonVowelPhoneme "K" = Phoneme "K" Stop nonVowelPhoneme "L" = Phoneme "L" Liquid nonVowelPhoneme "M" = Phoneme "M" Nasal nonVowelPhoneme "N" = Phoneme "N" Nasal nonVowelPhoneme "NG" = Phoneme "NG" Nasal nonVowelPhoneme "P" = Phoneme "P" Stop nonVowelPhoneme "R" = Phoneme "R" Liquid nonVowelPhoneme "S" = Phoneme "S" Fricative nonVowelPhoneme "SH" = Phoneme "SH" Fricative nonVowelPhoneme "T" = Phoneme "T" Stop nonVowelPhoneme "TH" = Phoneme "TH" Fricative nonVowelPhoneme "V" = Phoneme "V" Fricative nonVowelPhoneme "W" = Phoneme "W" Semivowel nonVowelPhoneme "Y" = Phoneme "Y" Semivowel nonVowelPhoneme "Z" = Phoneme "Z" Fricative nonVowelPhoneme "ZH" = Phoneme "ZH" Fricative
z0isch/reddit-dailyprogrammer
Challenge263/src/Challenge263/Intermediate.hs
mit
3,589
0
13
734
1,262
646
616
75
24
module Main where import Graphics.GLUtil (offset0) import Graphics.Rendering.OpenGL import Graphics.UI.GLUT import Foreign.Marshal.Array (withArray) import Foreign.Storable (sizeOf) main :: IO () main = do getArgsAndInitialize initialDisplayMode $= [DoubleBuffered, RGBAMode] initialWindowSize $= Size 1024 768 initialWindowPosition $= Position 100 100 createWindow "Tutorial 03" vbo <- createVertexBuffer initializeGlutCallbacks vbo clearColor $= Color4 0 0 0 0 mainLoop initializeGlutCallbacks :: BufferObject -> IO () initializeGlutCallbacks vbo = displayCallback $= renderSceneCB vbo createVertexBuffer :: IO BufferObject createVertexBuffer = do vbo <- genObjectName bindBuffer ArrayBuffer $= Just vbo withArray vertices $ \ptr -> bufferData ArrayBuffer $= (size, ptr, StaticDraw) return vbo where vertices :: [Vertex3 GLfloat] vertices = [ Vertex3 (-1) (-1) 0 , Vertex3 1 (-1) 0 , Vertex3 0 1 0 ] numVertices = length vertices vertexSize = sizeOf (head vertices) size = fromIntegral (numVertices * vertexSize) renderSceneCB :: BufferObject -> IO () renderSceneCB vbo = do clear [ColorBuffer] vertexAttribArray vPosition $= Enabled bindBuffer ArrayBuffer $= Just vbo vertexAttribPointer vPosition $= (ToFloat, VertexArrayDescriptor 3 Float 0 offset0) drawArrays Triangles 0 3 vertexAttribArray vPosition $= Disabled swapBuffers where vPosition = AttribLocation 0
triplepointfive/hogldev
tutorial03/Tutorial03.hs
mit
1,604
0
10
414
451
221
230
45
1
{-# htermination (fromIntRatio :: MyInt -> Ratio MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ratio a = CnPc a a; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; intToRatio x = CnPc (fromIntMyInt x) (fromIntMyInt (Pos (Succ Zero))); fromIntRatio :: MyInt -> Ratio MyInt fromIntRatio = intToRatio;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/fromInt_1.hs
mit
443
0
11
98
152
86
66
11
1
module First where
JoshuaGross/haskell-learning-log
Code/Haskellbook/State/src/First.hs
mit
20
0
2
4
4
3
1
1
0
{-# LANGUAGE FlexibleContexts #-} module Env where import Control.Monad.Except import Data.IORef import Data.Maybe import Types nullEnv :: (MonadIO m) => m Env nullEnv = liftIO $ newIORef [] isBound :: (MonadIO m) => Env -> String -> m Bool isBound envRef var = do env <- liftIO $ readIORef envRef return . isJust $ lookup var env getVar :: (MonadError LispError m, MonadIO m) => Env -> String -> m LispVal getVar envRef var = do env <- liftIO $ readIORef envRef maybe (throwError $ UnboundVar "Getting an unbound variable" var) (liftIO . readIORef) (lookup var env) setVar :: (MonadError LispError m, MonadIO m) => Env -> String -> LispVal -> m LispVal setVar envRef var val = do env <- liftIO $ readIORef envRef case lookup var env of Nothing -> throwError $ UnboundVar "Setting an unbound variable" var Just varRef -> liftIO $ writeIORef varRef val return val defineVar :: (MonadIO m) => Env -> String -> LispVal -> m LispVal defineVar envRef var val = liftIO $ do env <- readIORef envRef case lookup var env of Nothing -> do varRef <- newIORef val writeIORef envRef ((var, varRef):env) Just varRef -> writeIORef varRef val return val bindVars :: (MonadIO m) => Env -> [(String, LispVal)] -> m Env bindVars envRef bindings = liftIO $ do env <- readIORef envRef -- TODO: do something about binding to already-bound variables env' <- (++ env) <$> mapM addBinding bindings newIORef env' where addBinding (var, val) = (\r -> (var, r)) <$> newIORef val
ublubu/wyascheme
src/Env.hs
mit
1,644
0
16
446
574
284
290
54
2
module CompileTex ( processExternal ) where import System.Process (system) import GHC.IO.Exception (ExitCode(..)) import Data.List (intersperse) import Control.Monad (when) type VerboseFlag = Bool type FileName = String type TexHeader = String type TexCommands = String type TexWrap = (TexHeader, TexCommands) type TexContent = String type TexDocument = String type Executable = String type NumberOfFiles = Int processExternal :: VerboseFlag -> FileName -> TexWrap -> [TexContent] -> IO () processExternal verbose filename wrap contents = do when (verbose) $ putStrLn ("Wrap extracted LaTeX code into a proper Document:\n " ++ filename) externalize filename wrap contents -- in verbose mode, we want pdflatex to print its progress -- and to halt if there are issues with the LaTeX file when (verbose) $ putStrLn ("LaTeX Compilation:\n " ++ texShellCommand verbose filename) when (verbose) $ putStrLn "\n--------------------------------------------------\n" latexexitcode <- system $ (texShellCommand verbose) filename when (verbose) $ putStrLn "\n--------------------------------------------------\n" if latexexitcode /= ExitSuccess then putStrLn pdferror else do let pdffile = replaceSuffix "pdf" filename when (verbose) $ putStrLn ("Convert to SVG images. " ++ "Run once for each page number <n>:\n " ++ "pdf2svg " ++ pdffile ++ " " ++ replaceSuffix "<n>.svg" filename ++ " " ++ "<n>") svgexitcode <- pdf2svg (length contents) (replaceSuffix "pdf" filename) if svgexitcode /= ExitSuccess then putStrLn svgerror else return () where pdferror = "Error in pdflatex: Probably a syntax error.\n " ++ "Run in verbose mode [-v] for the error report of pdflatex" svgerror = "Error in pdf2svg" replaceSuffix :: String -> FileName -> FileName replaceSuffix suffix filename = ((reverse . dropWhile (/= '.') . reverse) filename) ++ suffix -- the pdflatex executable for the shell texShellCommand :: VerboseFlag -> FileName -> String texShellCommand verbose ifile = if (verbose) then "pdflatex " ++ ifile else "pdflatex --interaction=nonstopmode " ++ ifile ++ " >/dev/null" -- wraps LaTex into a proper document and writes it to a file externalize :: FilePath -> TexWrap -> [TexContent] -> IO () externalize filepath wrap contents = writeFile filepath (wrapTex wrap contents) -- wrap extracted LaTex into a proper LaTex document wrapTex :: TexWrap -> [TexContent] -> TexDocument wrapTex (header, commands) contents = header ++ begin ++ commands ++ pagination ++ end where pagination = concat $ ["\n\\begin{page}\n"] ++ (intersperse "\n\\end{page}\n\\begin{page}\n" contents) ++ ["\n\\end{page}\n"] begin = "\n\\begin{document}\n" end = "\n\\end{document}\n" -- compile LaTex pdfLatex :: (Executable -> String) -> FilePath -> IO ExitCode pdfLatex exe filepath = system $ exe filepath -- convert PDF to SVG pdf2svg :: NumberOfFiles -> FilePath -> IO ExitCode pdf2svg i pdfFile = if i > 0 then do transform i pdf2svg (i - 1) pdfFile else return ExitSuccess where transform i = system $ "pdf2svg " ++ pdfFile ++ " " ++ (svgFile i) ++ " " ++ (show i) svgFile i = replaceSuffix ((show i) ++ ".svg") pdfFile
dino-r/TexErupter
src/CompileTex.hs
mit
3,738
0
19
1,109
838
439
399
67
3
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Language.Pal.Eval ( eval , initialEnv ) where import Control.Applicative import Control.Error import Control.Monad.Error (MonadError, throwError) import Control.Monad.State import Data.Monoid ((<>)) import Language.Pal.Types newtype EvalT m a = EvalT { unEvalT :: EitherT EvalError (StateT Env m) a } deriving (Monad, MonadError EvalError, MonadState Env) instance MonadTrans EvalT where lift = EvalT . lift . lift unpackStateT :: EvalT m a -> StateT Env m (Either EvalError a) unpackStateT = runEitherT . unEvalT runEvalT :: Monad m => EvalT m a -> Env -> m (Either EvalError a, Env) runEvalT = runStateT . unpackStateT evalEvalT :: Monad m => EvalT m a -> Env -> m (Either EvalError a) evalEvalT = evalStateT . unpackStateT localEnv :: Monad m => (Env -> Env) -> EvalT m a -> EvalT m a localEnv f e = do modifiedEnv <- gets f eOrV <- lift $ evalEvalT e modifiedEnv liftEither eOrV liftEither :: Monad m => Either EvalError a -> EvalT m a liftEither = EvalT . hoistEither eval :: (Applicative m, Monad m) => LValue -> Env -> m (Either EvalError LValue, Env) eval val = runEvalT (eval' val) eval' :: (Applicative m, Monad m) => LValue -> EvalT m LValue eval' v@(Number _) = return v eval' v@(String _) = return v eval' v@(Bool _) = return v eval' (List l) = evalForm l eval' (Atom name) = atom name eval' v@(BuiltinFunction _) = return v eval' v@(LispFunction _) = return v evalForm :: (Applicative m, Monad m) => LList -> EvalT m LValue evalForm [Atom "quote", e] = return e evalForm [Atom "set!", Atom v, e] = do rval <- eval' e modify (setAtom v rval) return rval evalForm [Atom "if", condExpr, thenExpr, elseExpr] = do cond <- eval' condExpr b <- liftEither $ coerceBool cond if b then eval' thenExpr else eval' elseExpr evalForm (Atom "lambda" : List params : body) = do paramNames <- liftEither $ mapM coerceAtom params scope <- get return $ LispFunction LLispFunction { lfScope = scope , lfParams = paramNames , lfBody = body } evalForm (funExp : argExps) = do fun <- eval' funExp args <- mapM eval' argExps apply fun args evalForm [] = throwError "can't eval empty list" apply :: (Applicative m, Monad m) => LValue -> [LValue] -> EvalT m LValue apply (BuiltinFunction (LBuiltinFunction _ f)) args = liftEither $ f args apply (LispFunction (LLispFunction scope params body)) args = do _ <- liftEither $ params `checkSameLength` args localEnv (const fnScope) $ foldM (\_ e -> eval' e) nil body where fnScope = argBindings <> scope argBindings = Env $ zip params args apply v _ = throwError $ "not a function: " ++ show v atom :: (Applicative m, Monad m) => LAtom -> EvalT m LValue atom name = EvalT $ do env <- get lookupAtom name env ?? ("not found: " ++ name) builtin :: LAtom -> TFunction -> (LAtom, LValue) builtin name f = (name, BuiltinFunction (LBuiltinFunction name f)) data Tag = TagSymbol | TagList | TagNumber | TagString | TagBool | TagFunction deriving (Eq) instance Show Tag where show TagSymbol = "symbol" show TagList = "list" show TagNumber = "number" show TagString = "string" show TagBool = "boolean" show TagFunction = "function" tag :: LValue -> Tag tag (Atom _) = TagSymbol tag (List _) = TagList tag (Number _) = TagNumber tag (String _) = TagString tag (Bool _) = TagBool tag (BuiltinFunction _) = TagFunction tag (LispFunction _) = TagFunction builtinTagPred :: Tag -> (LAtom, LValue) builtinTagPred t = (name, BuiltinFunction (LBuiltinFunction name p)) where name = show t ++ "?" p = unop ((== t) . tag) Bool return check :: Tag -> LValue -> Either EvalError LValue check t v | tag v == t = Right v | otherwise = throwError $ "expected " ++ show t ++ ", got " ++ show (tag v) coerceAtom :: LValue -> Either EvalError LAtom coerceAtom = fmap lvAtom . check TagSymbol coerceNumber :: LValue -> Either EvalError LNumber coerceNumber = fmap lvNumber . check TagNumber coerceString :: LValue -> Either EvalError LString coerceString = fmap lvString . check TagString coerceBool :: LValue -> Either EvalError Bool coerceBool = fmap lvBool . check TagBool checkN :: Int -> [a] -> Either EvalError [a] checkN n = fmap (take n) . flip checkSameLength (replicate n undefined) unop :: (a -> b) -> (b -> LValue) -> (LValue -> Either EvalError a) -> [LValue] -> Either EvalError LValue unop f outputCtor inputCoercion = fmap (outputCtor . f) . inputCoercion <=< fmap head . checkN 1 binop :: (a -> a -> b) -> (b -> LValue) -> (LValue -> Either EvalError a) -> [LValue] -> Either EvalError LValue binop f outputCtor inputCoercion = fmap (outputCtor . apply2) . mapM inputCoercion <=< checkN 2 where apply2 [x, y] = f x y apply2 xs = error $ "binop called with " ++ show (length xs) ++ " arguments!" varop :: ([a] -> b) -> (b -> LValue) -> (LValue -> Either EvalError a) -> [LValue] -> Either EvalError LValue varop f outputCtor inputCoercion = fmap (outputCtor . f) . mapM inputCoercion checkSameLength :: [a] -> [b] -> Either EvalError [a] checkSameLength actual expected | nAct == nExp = Right actual | nAct < nExp = Left $ "not enough arguments: expected " ++ show nExp ++ ", got " ++ show nAct | otherwise = Left $ "too many arguments: expected " ++ show nExp ++ ", got " ++ show nAct where nAct = length actual; nExp = length expected initialEnv :: Env initialEnv = Env $ map (uncurry builtin) [ ("+", varop sum Number coerceNumber) , ("-", binop (-) Number coerceNumber) , ("*", varop product Number coerceNumber) , ("/", binop div Number coerceNumber) , ("<", binop (<) Bool coerceNumber) , (">", binop (>) Bool coerceNumber) , ("concat", varop concat String coerceString) , ("typeof", unop (show . tag) String return) ] ++ map builtinTagPred [ TagSymbol , TagList , TagNumber , TagString , TagBool , TagFunction ]
samstokes/pal
Language/Pal/Eval.hs
mit
5,920
0
12
1,235
2,387
1,215
1,172
-1
-1
{-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-type-defaults #-} module Lambda_utils where import LmLanguage import LmPathfinder (pathfind, fPathfind, pathfindModule, coordEq) import Lmcompile hiding (block) import Lambda_compiler_2 import Quad_tree import Prelude (Num(..), ($), (.), String, Bool(..), Maybe(..), fromIntegral, Show(..), Monad(..), Int) import Prelude (Either(..), putStrLn) ---------------------------------------- --- Data Defitions ---------------------------------------- -- Enum for each cell in map state kCellSymWall = 0 kCellSymEmpty = 1 kCellSymPill = 2 kCellSymPowerPill = 3 kCellSymFruitLocation = 4 kCellSymLMStartPos = 5 kCellSymGhostStartingPosition = 6 -- Enum for player/ghost direction kDirectionUp = 0 kDirectionRight = 1 kDirectionDown = 2 kDirectionLeft = 3 -- Types type MapState = [[Int]] type LambdaManState = (Int, ((Int, Int), (Int, (Int, Int)))) type GhostState = (Int, ((Int, Int), Int)) type FruitState = Int -- Enum for ghost vitality kGhostStandard = 0 kGhostFright = 1 kGhostInvisible = 2 -- This is the main world state passed in init and every step. Technically we shouldn't need -- to parse the MapState every frame as it only contains the initial starting positions, and -- we can derive the current pallet pill locations etc type WorldState = (MapState, (LambdaManState, ([GhostState], FruitState))) -- (PlayerX, PlayerY) type CellInfo = Int -- refer to kCellSymbol* type MapQuadTree = QuadTree CellInfo type MapPos = (Int, Int) type MapSize = Int -- single dimension for simplicity. it will be the max type ParsedState = (MapQuadTree, MapSize) type AIState = (ParsedState, Int) -- to Extend. Second parameter not doing anything right now type MaybeMapPos = Maybe MapPos type MapInfo = (MaybeMapPos, (MaybeMapPos, MaybeMapPos)) getPosX :: TExpr (Int, Int) -> TExpr Int getPosX = fst getPosY :: TExpr (Int, Int) -> TExpr Int getPosY = snd -- WorldState getMapState :: (TExpr WorldState) -> TExpr MapState getMapState = fst getLMState :: (TExpr WorldState) -> TExpr LambdaManState getLMState = fst . snd getGhostState :: (TExpr WorldState) -> TExpr [GhostState] getGhostState = fst . snd .snd getFruitState :: (TExpr WorldState) -> TExpr FruitState getFruitState = snd . snd .snd -- LambdaManState getLMVitality :: (TExpr LambdaManState) -> TExpr Int getLMVitality = fst getLMPos :: TExpr LambdaManState -> TExpr (Int, Int) getLMPos = fst . snd getLMDir :: TExpr LambdaManState -> TExpr Int getLMDir = fst . snd . snd getLMRemainingLives :: TExpr LambdaManState -> TExpr Int getLMRemainingLives = fst . snd . snd . snd getLMCurScore :: TExpr LambdaManState -> TExpr Int getLMCurScore = snd . snd . snd . snd -- Ghost State getGhostVitality :: (TExpr GhostState) -> TExpr Int getGhostVitality = fst getGhostPos :: (TExpr GhostState) -> TExpr (Int, Int) getGhostPos = fst . snd getGhostDir :: (TExpr GhostState) -> TExpr Int getGhostDir = snd . snd -- ParsedState initParsedState :: (TExpr ParsedState) initParsedState = pair (makeQuadLeaf 1) 0 {-setPlayerPos :: (TExpr ParsedState) -> TExpr Int -> TExpr Int -> (TExpr ParsedState)-} {-setPlayerPos _ y x = pair y x-} getMapQuadTree :: TExpr ParsedState -> TExpr MapQuadTree getMapQuadTree = fst setMapQuadTree :: TExpr ParsedState -> TExpr MapQuadTree -> TExpr ParsedState setMapQuadTree state quadTree = pair quadTree (snd state) getMapSize :: TExpr ParsedState -> TExpr Int getMapSize = snd setMapSize :: TExpr ParsedState -> TExpr Int -> TExpr ParsedState setMapSize state size = pair (fst state) size {-getPlayerX :: (TExpr ParsedState) -> TExpr Int-} {-getPlayerX = fst-} {-getPlayerY :: (TExpr ParsedState) -> TExpr Int-} {-getPlayerY = snd-} -- AI State getAIParsedState :: TExpr AIState -> TExpr ParsedState getAIParsedState = fst setAIParsedState :: TExpr AIState -> TExpr ParsedState -> TExpr AIState setAIParsedState aiState parsedState = pair parsedState (snd aiState) makeAIState :: TExpr ParsedState -> TExpr AIState makeAIState parsedState = pair parsedState (int 1) -- 1 is bogus for now ---------------------------------------- --- World Parsing ---------------------------------------- fParseMapRow :: TFunction ((Arg MapState, Arg Int, Arg ParsedState) -> ParsedState) fParseMapRow = function3 "parseMapRow" ("mapRows", "curRow", "parsedState") $ \(mapRows, curRow, parsedState) -> do ifm (null mapRows) (return parsedState) $ do withRec "parseCol" (\parseCol -> lam3 ("remainRow","col","curParsedState") $ \(remainRow,col,curParsedState) -> return $ ifv (null remainRow) curParsedState (let value = head remainRow quadTree = getMapQuadTree curParsedState newQuadTree = replaceQuadLeaf quadTree (getMapSize curParsedState) value (pair col curRow) newParsedState = setMapQuadTree curParsedState newQuadTree in ap3 parseCol (tail remainRow) (col + 1) newParsedState) ) {-in (ifv (head remainRow == kCellSymLMStartPos)-} {-parsedState $-} {-ap2 parseCol (tail remainRow) (col + 1))) )-} (\parseCol -> return $ parseMapRow (tail mapRows) (curRow + 1) $ ap3 parseCol (head mapRows) 0 parsedState) parseMapRow = bindAp3 fParseMapRow fParseMapSize :: TFunction ((Arg MapState, Arg ParsedState) -> ParsedState) fParseMapSize = function2 "parseMapSize" ("mapState", "parsedState") $ \(mapState, parsedState) -> return $ let vLength = length mapState hLength = length (head mapState) mapSize = roundUpToPower2 (max vLength hLength) in setMapSize parsedState mapSize parseMapSize = bindAp2 fParseMapSize fParseMapState :: TFunction ((Arg MapState, Arg Int, Arg ParsedState) -> ParsedState) fParseMapState = function3 "parseMapState" ("mapState", "curRow", "parsedState") $ \(mapState, curRow, parsedState) -> do with "parsedSizeState" (return $ parseMapSize mapState parsedState) $ \parsedSizeState -> return $ let allocatedQuadTree = allocateQuadTree (getMapSize parsedSizeState) kCellSymWall allocatedQuadTreeState = setMapQuadTree parsedSizeState allocatedQuadTree in {- debugTrace (getMapQuadTree allocatedQuadTreeState) $ -} parseMapRow mapState curRow allocatedQuadTreeState parseMapState = bindAp3 fParseMapState fParseWorldState :: TFunction (Arg WorldState -> ParsedState) fParseWorldState = function1 "parseWorldState" "worldState" $ \worldState -> return $ (parseMapState (fst worldState) (int 0) (initParsedState)) parseWorldState = bindAp1 fParseWorldState {- TODO TEMP ONLY. Inefficient lookup -} fMapLookup :: TFunction ((Arg MapState, Arg Int, Arg Int) -> Int) fMapLookup = function3 "mapLookup" ("mapState", "posX", "posY") $ \(mapState, posX, posY) ->return $ nth (nth mapState posY) posX mapLookup = bindAp3 fMapLookup fFastMapLookup :: TFunction ((Arg ParsedState, Arg Int, Arg Int) -> Int) fFastMapLookup = function3 "fastMapLookup" ("parsedState", "posX", "posY") $ \(parsedState, posX, posY) ->return $ let quadTree = getMapQuadTree parsedState in findQuadLeaf quadTree (getMapSize parsedState) (pair posX posY) fastMapLookup = bindAp3 fFastMapLookup ---------------------------------------- --- AI logic ---------------------------------------- {- TODO Test function to show basic decision making -} fLMDecideDirection :: TFunction ((Arg ParsedState, Arg LambdaManState) -> Int) fLMDecideDirection = function2 "lmDecideDirection" ("parsedState", "curLMPos") $ \(parsedState, curLMState) -> do with "leftSpot" (return $ fastMapLookup parsedState (getPosX (getLMPos curLMState) - 1) (getPosY $ getLMPos curLMState)) $ \leftSpot -> do with "rightSpot" (return $ fastMapLookup parsedState (getPosX (getLMPos curLMState) + 1) (getPosY $ getLMPos curLMState)) $ \rightSpot -> do with "curDir" (return $ getLMDir curLMState) $ \curDir -> return $ ifv ((rightSpot == kCellSymWall) `and` (curDir == kDirectionRight)) kDirectionLeft (ifv (or3 (curDir == kDirectionDown) (curDir == kDirectionUp) ((leftSpot == kCellSymWall) `and` (curDir == kDirectionLeft))) kDirectionRight curDir) lmDecideDirection = bindAp2 fLMDecideDirection ---------------------------------------- --- AI logic Jeff ---------------------------------------- kInfDistance = 100000 kPowerPillCutoffDistance = 10 kPowerPillDistanceDefault = kPowerPillCutoffDistance + 1 kFruitCutoffDistance = 70 lam_subtractPos = function2 "lam_subtractPos" ("posA", "posB") $ \(posA, posB) -> do with "diffX" (return $ (fst posA) - (fst posB)) $ \diffX -> do with "diffY" (return $ (snd posA) - (snd posB)) $ \diffY -> do return $ pair diffX diffY subtractPos = bindAp2 lam_subtractPos lam_myAbs = function1 "lam_myAbs" ("n") $ \n -> ifm (n < 0) (return (-n)) (return n) myAbs = bindAp1 lam_myAbs lam_absPos = function1 "lam_abs" ("pos") $ \pos -> do with "absX" (return $ myAbs $ fst pos) $ \absX-> do with "absY" (return $ myAbs $ snd pos) $ \absY -> do return $ pair absX absY absPos = bindAp1 lam_absPos lam_manhattanDistance :: TFunction ((Arg (Int, Int), Arg (Int, Int)) -> Int) lam_manhattanDistance = function2 "lam_manhattanDistance" ("posA", "posB") $ \(posA, posB) -> do with "diff" (return $ subtractPos posA posB) $ \diff -> do with "absDiff" (return $ absPos diff) $ \absDiff -> do with "sumDiff" (return $ (fst absDiff) + (snd absDiff)) $ \sumDiff -> do return $ sumDiff manhattanDistance :: TExpr (Int, Int) -> TExpr (Int, Int) -> TExpr Int manhattanDistance = bindAp2 lam_manhattanDistance kMaxPathfindDistance = 120 lam_pathfindDistance :: TFunction ((Arg (Int, Int), Arg (Int, Int), Arg ParsedState) -> Int) lam_pathfindDistance = function3 "lam_pathfindDistance" ("posA", "posB", "parsedState") $ \(posA, posB, parsedState) -> do -- return $ manhattanDistance posA posB ifm (coordEq posA posB) (return 0) (with "pathfindResult" (return $ pathfind posA posB kMaxPathfindDistance parsedState) $ \pathfindResult -> do return $ snd $ debugTrace (pair (pair posA posB) pathfindResult) pathfindResult) --pathfindDistance :: TExpr (Int, Int) -> TExpr (Int, Int) -> TExpr Int pathfindDistance = bindAp3 lam_pathfindDistance --lam_mapOver = function2 "lam_mapOver" ("func", "list") $ \(func, list) -> do -- ifv (null list) -- (return nil) -- (with "element" (return $ head list) $ \element -> do -- with "newElement" (return $ func element) $ \newElement -> do -- with "rest" (return $ tail list) $ \rest-> do -- with "newRest" (return $ mapOver func rest) \ newRest -> do -- return $ cons newElement newRest -- ) --mapOver = bindAp2 lam_mapOver -- lam_selectMin :: (a -> Int) -> a -> a -> a lam_selectMin = function3 "lam_selectMin" ("func", "v0", "v1") $ \(func, v0, v1) -> ifm (ap1 func v0 < ap1 func v1) (return v0) (return v1) selectMin = bindAp3 lam_selectMin -- minimumOver :: (a -> ord) -> [a] -> a lam_minimumOver = function2 "lam_minimumOver" ("func", "list") $ \(func, list) -> do lam <- block $ lam2 ("v0", "v1") $ \(v0, v1) -> do return $ selectMin func v0 v1 return $ foldr1 (lam) list minimumOver = bindAp2 lam_minimumOver lam_hasOneElement = function1 "lam_hasOneElement" ("list") $ \list -> do ifm (null list) (return $ toExpr False) (ifm (null $ tail list) (return $ toExpr True) (return $ toExpr False) ) hasOneElement = bindAp1 lam_hasOneElement lam_foldr1 = function2 "lam_foldr1" ("func", "list") $ \(func, list) -> do ifm (hasOneElement list) (return $ head list) (return $ ap2 func (head list) (foldr1 func $ tail list)) foldr1 = bindAp2 lam_foldr1 --type MapCoords [((Int, Int), Int)] --toMapCoords :: MapState -> MapCoords --lam_toMapCoords -> -- with "mapState" (return $ getMapState worldState) $ \mapState -> -- zip -- return pair (pair curX curY) curElement lam_zip = function2 "lam_zip" ("list0", "list1") $ \(list0, list1) -> do ifm (null list0) (return nil) (ifm (null list1) (return nil) (return $ cons (pair (head list0) (head list1)) (zip (tail list0) (tail list1)) ) ) zip = bindAp2 lam_zip -- coord :: MapCoord -> (Int, Int) -- element :: MapCoord -> Int -- lam_coord = fst -- lam_element = snd lam_filter = function2 "lam_filter" ("func", "list") $ \(func, list) -> do ifm (null list) (return nil) (ifm (ap1 func $ head list) (return $ cons (head list) (filter func (tail list)) ) (return $ filter func (tail list)) ) filter = bindAp2 lam_filter -- TODO -- lam_getInfoFromMap :: WorldState -> (maybe neareset power pill, maybe nearest fruit, nearest pill) --lam_getInfoFromMapRowCol = function2 "lam_getInfoFromMap" "worldState" $ \(mapElement, rowIndex, colIndex) -> do -- return $ pair element (pair rowIndex colIndex) lam_makeMapInfo :: TFunction ((Arg MaybeMapPos, Arg MaybeMapPos, Arg MaybeMapPos) -> MapInfo) lam_makeMapInfo = function3 "lam_makeMapInfo" ("powerPill", "fruit", "pill") $ \(powerPill, fruit, pill) -> do return $ pair powerPill (pair fruit pill) makeMapInfo :: TExpr MaybeMapPos -> TExpr MaybeMapPos -> TExpr MaybeMapPos -> TExpr MapInfo makeMapInfo = bindAp3 lam_makeMapInfo lam_closerLocation = function3 "lam_closerLocation" ("sourceCoord", "maybeOldCoord", "newCoord") $ \(sourceCoord, maybeOldCoord, newCoord) -> do ifm (isNothing maybeOldCoord) (return $ toExpr True) (ifm (manhattanDistance sourceCoord newCoord < manhattanDistance sourceCoord (fromJust $ maybeOldCoord)) (return $ toExpr True) (return $ toExpr False) ) closerLocation = bindAp3 lam_closerLocation mapInfo_Pill :: TExpr MapInfo -> TExpr MaybeMapPos mapInfo_Pill = snd . snd mapInfo_PowerPill :: TExpr MapInfo -> TExpr MaybeMapPos mapInfo_PowerPill = fst mapInfo_Fruit :: TExpr MapInfo -> TExpr MaybeMapPos mapInfo_Fruit = fst . snd lam_tryImprovePowerPill :: TFunction ((Arg MapPos, Arg MapInfo, Arg MapPos) -> MapInfo) lam_tryImprovePowerPill = function3 "lam_tryImprovePowerPill" ("sourceCoord", "bestResultsSoFar", "newCoord") $ \(sourceCoord, bestResultsSoFar, newCoord) -> do ifm (closerLocation sourceCoord (mapInfo_Pill bestResultsSoFar) newCoord) (return $ makeMapInfo (just newCoord) (mapInfo_Fruit bestResultsSoFar) (mapInfo_Pill bestResultsSoFar)) (return $ bestResultsSoFar) tryImprovePowerPill = bindAp3 lam_tryImprovePowerPill lam_tryImprovePill :: TFunction ((Arg MapPos, Arg MapInfo, Arg MapPos) -> MapInfo) lam_tryImprovePill = function3 "lam_tryImprovePill" ("sourceCoord", "bestResultsSoFar", "newCoord") $ \(sourceCoord, bestResultsSoFar, newCoord) -> do ifm (closerLocation sourceCoord (mapInfo_Pill bestResultsSoFar) newCoord) (return $ makeMapInfo (mapInfo_PowerPill bestResultsSoFar) (mapInfo_Fruit bestResultsSoFar) (just $ newCoord)) (return $ bestResultsSoFar) tryImprovePill = bindAp3 lam_tryImprovePill lam_tryImproveFruit :: TFunction ((Arg MapPos, Arg MapInfo, Arg MapPos) -> MapInfo) lam_tryImproveFruit = function3 "lam_tryImproveFruit" ("sourceCoord", "bestResultsSoFar", "newCoord") $ \(sourceCoord, bestResultsSoFar, newCoord) -> do ifm (closerLocation sourceCoord (mapInfo_Fruit bestResultsSoFar) newCoord) (return $ makeMapInfo (mapInfo_PowerPill bestResultsSoFar) (just newCoord) (mapInfo_Pill bestResultsSoFar)) (return bestResultsSoFar) tryImproveFruit = bindAp3 lam_tryImproveFruit lam_tryImproveResults :: TFunction ((Arg MapPos, Arg MapInfo, Arg Int, Arg MapPos) -> MapInfo) lam_tryImproveResults = function4 "lam_tryImproveResults" ("sourceCoord", "bestResultsSoFar", "newElement", "newCoord") $ \(sourceCoord, bestResultsSoFar, newElement, newCoord) -> do ifm (newElement == kCellSymPill) (return $ tryImprovePill sourceCoord bestResultsSoFar newCoord) (ifm (newElement == kCellSymFruitLocation) (return $ tryImproveFruit sourceCoord bestResultsSoFar newCoord) (ifm (newElement == kCellSymPowerPill) (return $ tryImprovePowerPill sourceCoord bestResultsSoFar newCoord) (return $ bestResultsSoFar) ) ) tryImproveResults = bindAp4 lam_tryImproveResults lam_getInfoFromMapRecursive = function6 "lam_getInfoFromMapRecursive" ("sourceCoord", "bestResultsSoFar", "mapCurrentRow", "mapCurrentCol", "rowIndex", "colIndex") $ \(sourceCoord, bestResultsSoFar, mapCurrentRow, mapCurrentCol, rowIndex, colIndex) -> do ifm (null mapCurrentCol) (ifm (null mapCurrentRow) (return $ bestResultsSoFar) (return $ getInfoFromMapRecursive sourceCoord bestResultsSoFar (tail mapCurrentRow) (head mapCurrentRow) (rowIndex+1) (0)) ) (return $ getInfoFromMapRecursive sourceCoord (tryImproveResults sourceCoord bestResultsSoFar (head mapCurrentCol) (pair colIndex rowIndex)) mapCurrentRow (tail mapCurrentCol) (rowIndex) (colIndex+1) ) getInfoFromMapRecursive = bindAp6 lam_getInfoFromMapRecursive lam_getInfoFromMap = function1 "lam_getInfoFromMap" "worldState" $ \worldState -> do with "mapGrid" (return $ getMapState worldState) $ \mapGrid -> do with "playerCoord" (return $ getLMPos $ getLMState worldState) $ \playerCoord -> do return $ getInfoFromMapRecursive (playerCoord) (makeMapInfo nothing nothing nothing) (tail mapGrid) (head mapGrid) 0 0 getInfoFromMap = bindAp1 lam_getInfoFromMap --getPowerPills _x = error "undefined" -- can implemnt getNearestPowerPill instead --getPills _x = error "undefined" -- can implemnt getNearestPill instead --getFruitLocation _x = pair 0 0 -- --nothing :: TExpr (Maybe a) --nothing = unsafeCast nil {- lam_isNothing = function1 ("lam_isNothing") $ \v -> do ifm (fst v == nil) (return True) (return False) isNothing = bindAp1 lam_isNothing lam_fromJust = function1 "lam_fromJust" ("v") $ \v -> do return $ snd v fromJust = bindAp1 lam_fromJust -} {- lam_getNearestPowerPill = function2 "lam_getNearestPowerPill" ("worldState", "coord") $ \(worldState, coord) -> do with "powerPills" (return $ getPowerPills worldState) $ \powerPills -> do ifm (null powerPills) (return nothing) (do lam <- block $ lam1 ("lamCoord") $ \lamCoord -> do return $ manhattanDistance coord lamCoord with "bestPill" (return $ minimumOver (lam) powerPills) $ \bestPill -> return $ just $ bestPill ) getNearestPowerPill = bindAp2 lam_getNearestPowerPill -} {- lam_getNearestPill = function2 "lam_getNearestPill" ("worldState", "coord") $ \(worldState, coord) -> do with "pills" (return $ getPills worldState) $ \pills -> do lam <- block $ lam1 ("lamCoord") $ \lamCoord -> do return $ manhattanDistance coord lamCoord with "bestPill" (return $ minimumOver (lam) pills) $ \bestPill -> return $ bestPill getNearestPill = bindAp2 lam_getNearestPill -} type EnhancedWorldState = (WorldState, MapInfo) lam_getDistanceToPowerPill :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Maybe Int) lam_getDistanceToPowerPill = function3 "lam_getDistanceToPowerPill" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do ifm (isNothing $ mapInfo_PowerPill $ snd enhancedWorldState) (return $ nothing) (return $ just $ pathfindDistance coord (fromJust $ mapInfo_PowerPill $ snd enhancedWorldState) parsedState) getDistanceToPowerPill = bindAp3 lam_getDistanceToPowerPill -- getNearest_Pill_PowerPill_Fruit lam_getDistanceToFruit :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Maybe Int) lam_getDistanceToFruit = function3 "lam_getDistanceToFruit" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do ifm (getFruitState (fst enhancedWorldState) == 0) (return nothing) (return $ just $ pathfindDistance coord (fromJust $ mapInfo_Fruit $ snd enhancedWorldState) parsedState) getDistanceToFruit = bindAp3 lam_getDistanceToFruit lam_getDistanceToPill :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_getDistanceToPill = function3 "lam_getDistanceToPill" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do with "pill" (return $ fromJust $ mapInfo_Pill $ snd enhancedWorldState) $ \pill -> do (return $ pathfindDistance coord (pill) parsedState) getDistanceToPill = bindAp3 lam_getDistanceToPill lam_identity = function1 "lam_identity" ("a") $ \a -> return a minimum = minimumOver (global lam_identity) lam_isGhostVisible = function1 "lam_isGhostVisible" "ghost" $ \ghost -> do return (getGhostVitality ghost /= kGhostInvisible) lam_getDistanceToGhost :: TFunction ((Arg WorldState, Arg MapPos) -> Maybe Int) lam_getDistanceToGhost = function2 "lam_getDistanceToGhost" ("worldState", "coord") $ \(worldState, coord) -> do with "ghosts" (return $ getGhostState worldState) $ \ghosts-> do with "visibleGhosts" (return $ filter (global lam_isGhostVisible) ghosts) $ \visibleGhosts -> do lam <- block $ lam1 ("ghost") $ \ghost -> do return $ manhattanDistance coord (getGhostPos ghost) with "visibleGhostDistances" (return $ map (lam) visibleGhosts) $ \visibleGhostDistances -> do ifm (null visibleGhostDistances) (return nothing) (return $ just $ minimum visibleGhostDistances) getDistanceToGhost = bindAp2 lam_getDistanceToGhost lam_foldl :: TFunction((Arg ((Arg b, Arg a) -> b), Arg b, Arg [a]) -> b) lam_foldl = function3 "lam_foldl" ("function", "accum", "list") $ \(func, accum, list) -> ifm (null list) (return accum) (return $ foldl (func) (ap2 func accum (head list)) (tail list) ) foldl = bindAp3 lam_foldl lam_count :: TFunction((Arg Int, Arg a) -> Int) lam_count = function2 ("lam_count") ("a", "b") $ \(a, _) -> do return $ a + (int 1) length :: TExpr [a] -> TExpr Int length = foldl (global lam_count) 0 lam_plus = function2 ("lam_plus") ("a", "b") $ \(a, b) -> do return $ a+b lam_sum = function1 "lam_sum" ("list") $ \list -> do return $ foldl (global lam_plus) 0 list sum = bindAp1 lam_sum lam_totalGhostDanger :: TFunction ((Arg WorldState, Arg MapPos) -> Int) lam_totalGhostDanger = function2 "lam_totalGhostDanger" ("worldState", "coord") $ \(worldState, coord) -> do with "ghosts" (return $ getGhostState worldState) $ \ghosts-> do with "visibleGhosts" (return $ filter (global lam_isGhostVisible) ghosts) $ \visibleGhosts -> do lam <- block $ lam1 "ghost" $ \ghost -> do return $ calcGhostDangerAtPoint coord ghost with "visibleGhostDanger" (return $ map lam visibleGhosts) $ \visibleGhostDanger -> do return $ sum visibleGhostDanger totalGhostDanger = bindAp2 lam_totalGhostDanger kGhostDangerCuttoff = 15 lam_max = function2 "lam_max" ("v0", "v1") $ \(v0, v1) -> do return $ ifv (v0 > v1) v0 v1 max = bindAp2 lam_max lam_calcGhostDangerAtPoint = function2 "lam_calcGhostDangerAtPoint" ("coord", "ghost") $ \(coord, ghost) -> do with "dist" (return $ manhattanDistance coord (getGhostPos ghost) ) $ \dist -> do ifm (dist > kGhostDangerCuttoff) (return 0) (return $ kGhostDangerCuttoff - dist) calcGhostDangerAtPoint = bindAp2 lam_calcGhostDangerAtPoint lam_getDistanceToBest_Safe :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_getDistanceToBest_Safe = function3 "lam_getDistanceToBest_Safe" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do with "distFruit" (return $ getDistanceToFruit parsedState enhancedWorldState coord) $ \distFruit -> do with "dist" ( ifm (fromMaybe distFruit (kFruitCutoffDistance + 1) < kFruitCutoffDistance) (return $ (-50) + fromMaybe distFruit (kFruitCutoffDistance + 1)) (return $ getDistanceToPill parsedState enhancedWorldState coord) ) $ \dist -> do --return $ debugTrace dist dist return $ 8 * dist + (totalGhostDanger (fst enhancedWorldState) coord) getDistanceToBest_Safe = bindAp3 lam_getDistanceToBest_Safe lam_getDistanceToBest_Scared :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_getDistanceToBest_Scared = function3 "lam_getDistanceToBest_Scared" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do with "distPowerPill" (return $ getDistanceToPowerPill parsedState enhancedWorldState coord) $ \distPowerPill -> do with "distFruit" (return $ getDistanceToFruit parsedState enhancedWorldState coord) $ \distFruit -> do with "dist" ( ifm (fromMaybe distPowerPill kPowerPillDistanceDefault < kPowerPillCutoffDistance) (return $ (-100) + fromMaybe distPowerPill kPowerPillDistanceDefault) (ifm (fromMaybe distFruit (kFruitCutoffDistance + 1) < kFruitCutoffDistance) (return $ (-50) + fromMaybe distFruit (kFruitCutoffDistance + 1)) (return $ getDistanceToPill parsedState enhancedWorldState coord) ) ) $ \dist -> do with "distanceToGhost" (return $ getDistanceToGhost (fst enhancedWorldState) coord) $ \distanceToGhost -> do return $ 8 * (dist + 4 * max 0 (8 - fromMaybe distanceToGhost 8)) + (totalGhostDanger (fst enhancedWorldState) coord) getDistanceToBest_Scared = bindAp3 lam_getDistanceToBest_Scared lam_getOffset = function1 "lam_getOffset" "dir" $ \dir -> ifm (dir == kDirectionUp) (return $ pair 0 (-1)) (ifm (dir == kDirectionDown) (return $ pair 0 (1)) (ifm (dir == kDirectionLeft) (return $ pair (-1) 0) (return $ pair (1) 0) ) ) getOffset = bindAp1 lam_getOffset lam_addPosition = function2 "lam_addPosition" ("posA", "posB") $ \(posA, posB) -> with "diffX" (return $ (fst posA) + (fst posB)) $ \diffX -> do with "diffY" (return $ (snd posA) + (snd posB)) $ \diffY -> do return $ pair diffX diffY addPosition = bindAp2 lam_addPosition lam_makeDirsAndCoords = function2 "lam_makeDirsAndCoords" ("coord", "dir") $ \(coord, dir) -> with "offset" (return $ getOffset dir) $ \offset -> do return $ pair dir (addPosition coord offset) makeDirsAndCoords = bindAp2 lam_makeDirsAndCoords lam_canStep = function2 "lam_canStep" ("parsedState", "dirCoord") $ \(parsedState, dirCoord) -> do with "element" (return $ fastMapLookup parsedState (fst (snd dirCoord)) (snd (snd dirCoord)) ) $ \element -> do return $ element /= kCellSymWall lam_getGhostPos = function1 "lam_getGhostPos" ("ghost") $ \(ghost) -> do return $ getGhostPos ghost lam_getDistToNearestVisibleGhostPathfind :: TFunction ((Arg ParsedState, Arg WorldState, Arg MapPos) -> Maybe Int) lam_getDistToNearestVisibleGhostPathfind = function3 "lam_getDistToNearestVisibleGhostPathfind" ("parsedState", "worldState", "coord") $ \(parsedState, worldState, coord) -> do with "ghosts" (return $ getGhostState worldState) $ \ghosts-> with "visibleGhosts" (return $ filter (global lam_isGhostVisible) ghosts) $ \visibleGhosts -> ifm (null visibleGhosts) (return nothing) (with "visibleGhostsPositions" (return $ map (global lam_getGhostPos) visibleGhosts) $ \visibleGhostsPositions -> with "visibleGhostsApproxDistances" (return $ map (pAp2_1 (global lam_manhattanDistance) coord) visibleGhostsPositions) $ \visibleGhostsApproxDistances -> with "closestGhostPosDist" (return $ minimumOver (global lam_snd) (zip visibleGhostsPositions visibleGhostsApproxDistances)) $ \closestGhostPosDist -> ifm (snd closestGhostPosDist < 5) (return $ just $ pathfindDistance coord (fst closestGhostPosDist) parsedState) (return $ just $ snd closestGhostPosDist) ) {- lamPathfind <- block $ lam1 "otherCoord" $ \otherCoord -> do return $ pathfindDistance coord otherCoord parsedState with "visibleGhostsDistances" (return $ map lamPathfind visibleGhostsPositions) $ \visibleGhostsDistances -> do ifm (null visibleGhostsDistances) (return nothing) (return $ just $ minimum visibleGhostsDistances) -} getDistToNearestVisibleGhostPathfind = bindAp3 lam_getDistToNearestVisibleGhostPathfind lam_getPlayerDistToNearestGhost :: TFunction ((Arg ParsedState, Arg WorldState) -> Maybe Int) lam_getPlayerDistToNearestGhost = function2 "lam_getPlayerDistToNearestGhost" ("parsedState", "worldState") $ \(parsedState, worldState) -> do with "playerCoord" (return $ getLMPos $ getLMState $ worldState) $ \playerCoord -> do return $ getDistToNearestVisibleGhostPathfind parsedState worldState playerCoord getPlayerDistToNearestGhost = bindAp2 lam_getPlayerDistToNearestGhost lam_scoreCoord_killMode :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_scoreCoord_killMode = function3 "lam_scoreCoord_killMode" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do return $ fromJust $ getDistToNearestVisibleGhostPathfind parsedState (fst enhancedWorldState) coord scoreCoord_killMode = bindAp3 lam_scoreCoord_killMode lam_scoreCoord_safeMode :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_scoreCoord_safeMode = function3 "lam_scoreCoord_safeMode" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do return $ getDistanceToBest_Safe parsedState enhancedWorldState coord scoreCoord_safeMode = bindAp3 lam_scoreCoord_safeMode lam_scoreCoord_scaredMode :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_scoreCoord_scaredMode = function3 "lam_scoreCoord_scaredMode" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do with "playerDistToNearestGhost" (return $ fromJust $ getPlayerDistToNearestGhost parsedState (fst enhancedWorldState)) $ \playerDistToNearestGhost -> do with "bestDist" (return $ getDistanceToBest_Scared parsedState enhancedWorldState coord) $ \bestDist -> do with "distanceToVisibleGhost" (return $ fromJust $ getDistToNearestVisibleGhostPathfind parsedState (fst enhancedWorldState) coord) $ \distanceToVisibleGhost -> do ifm (distanceToVisibleGhost <= playerDistToNearestGhost) (return $ 50000 + bestDist) (return $ bestDist) scoreCoord_scaredMode = bindAp3 lam_scoreCoord_scaredMode lam_inFightMode = function1 "lam_inFightMode" ("worldState") $ \(worldState) -> do ifm (getLMVitality (getLMState worldState) > 0) (return $ toExpr True) (return $ toExpr False) inFightMode = bindAp1 lam_inFightMode -- if (frightModeRemaining > 4 * 127 && coordDistToGhost == 0 && distToPlayer < 6) lam_inKillMode :: TFunction ((Arg ParsedState, Arg WorldState) -> Bool) lam_inKillMode = function2 "lam_inKillMode" ("parsedState", "worldState") $ \(parsedState, worldState) -> do with "playerDistToNearestGhost" (return $ getPlayerDistToNearestGhost parsedState worldState) $ \playerDistToNearestGhost -> do ifm (isNothing playerDistToNearestGhost) (return $ toExpr False) (do with "lamdaManVitality" (return $ getLMVitality (getLMState worldState)) $ \lamdaManVitality -> do ifm (lamdaManVitality > (4 * 127) && (fromJust (playerDistToNearestGhost)) < 6) (return $ toExpr True) (return $ toExpr False) ) inKillMode = bindAp2 lam_inKillMode -- if (playerDistToGhost < 4) lam_inScaredMode :: TFunction ((Arg ParsedState, Arg WorldState) -> Bool) lam_inScaredMode = function2 "lam_inScaredMode" ("parsedState", "worldState") $ \(parsedState, worldState) -> do with "playerDistToNearestGhost" (return $ getPlayerDistToNearestGhost parsedState worldState) $ \playerDistToNearestGhost -> do ifm (isNothing playerDistToNearestGhost) (return $ toExpr False) (ifm (fromJust (playerDistToNearestGhost) < 4) (return $ toExpr True) (return $ toExpr False) ) inScaredMode = bindAp2 lam_inScaredMode lam_scoreCoord :: TFunction ((Arg ParsedState, Arg EnhancedWorldState, Arg MapPos) -> Int) lam_scoreCoord = function3 "lam_scoreCoord" ("parsedState", "enhancedWorldState", "coord") $ \(parsedState, enhancedWorldState, coord) -> do ifm (inFightMode $ fst enhancedWorldState) (ifm (inKillMode parsedState $ fst enhancedWorldState) (return $ scoreCoord_killMode parsedState enhancedWorldState coord) (return $ scoreCoord_safeMode parsedState enhancedWorldState coord) ) (ifm (inScaredMode parsedState $ fst enhancedWorldState) (return $ scoreCoord_scaredMode parsedState enhancedWorldState coord) (return $ scoreCoord_safeMode parsedState enhancedWorldState coord) ) scoreCoord = bindAp3 lam_scoreCoord lam_scoreNeighbor = function3 "lam_scoreNeighbor" ("parsedState", "enhancedWorldState", "neighbor") $ \(parsedState, enhancedWorldState, neighbor) -> do with "coord" (return $ snd neighbor) $ \coord -> do with "score" (return $ scoreCoord parsedState enhancedWorldState coord) $ \score -> do return $ pair neighbor score scoreNeighbor = bindAp3 lam_scoreNeighbor lam_aiHunter :: TFunction ((Arg AIState, Arg WorldState) -> Int) lam_aiHunter = function2 "lam_aiHunter" ("aiState", "worldState") $ \(aiState, worldState) -> do with "bestMapLocations" (return $ getInfoFromMap worldState) $ \bestMapLocations -> do with "playerCoord" (return $ getLMPos $ getLMState worldState) $ \playerCoord -> do with "dirs" (return $ cons 0 (cons 1 (cons 2 (cons 3 nil))) ) $ \dirs -> do with "dirsAndCoords" (return $ map (pAp2_1 (global lam_makeDirsAndCoords) playerCoord) dirs) $ \dirsAndCoords -> do with "validDirsAndCoords" (return $ filter (pAp2_1 (global lam_canStep) (getAIParsedState aiState)) dirsAndCoords) $ \validDirsAndCoords -> do lamScoreNeighbor <- block $ lam1 "neighbor" $ \neighbor -> do return $ scoreNeighbor (getAIParsedState aiState) (pair worldState bestMapLocations) neighbor with "scores" (return $ map lamScoreNeighbor validDirsAndCoords) $ \scores -> do ifm (null scores) (return kDirectionDown) (return $ (fst.fst) $ minimumOver (global lam_snd) scores) aiHunter = bindAp2 lam_aiHunter lam_aiSearch :: TFunction ((Arg AIState, Arg WorldState) -> Int) lam_aiSearch = function2 "lam_aiSearch" ("aiState", "worldState") $ \(aiState, worldState) -> do with "bestMapLocations" (return $ getInfoFromMap worldState) $ \_bestMapLocations -> do with "playerCoord" (return $ getLMPos $ getLMState worldState) $ \playerCoord -> do with "dirs" (return $ cons 0 (cons 1 (cons 2 (cons 3 nil))) ) $ \dirs -> do with "dirsAndCoords" (return $ map (pAp2_1 (global lam_makeDirsAndCoords) playerCoord) dirs) $ \dirsAndCoords -> do with "validDirsAndCoords" (return $ filter (pAp2_1 (global lam_canStep) (getAIParsedState aiState)) dirsAndCoords) $ \validDirsAndCoords -> do return $ debugTrace (fst $ head $ validDirsAndCoords) (fst $ head $ validDirsAndCoords) lam_aiBad :: TFunction ((Arg AIState, Arg WorldState) -> Int) lam_aiBad = function2 "lam_aiBad" ("aiState", "worldState") $ \(aiState, worldState) -> do with "bestMapLocations" (return $ getInfoFromMap worldState) $ \_bestMapLocations -> do with "playerCoord" (return $ getLMPos $ getLMState worldState) $ \playerCoord -> do with "dirs" (return $ cons 0 (cons 1 (cons 2 (cons 3 nil))) ) $ \dirs -> do with "dirsAndCoords" (return $ map (pAp2_1 (global lam_makeDirsAndCoords) playerCoord) dirs) $ \dirsAndCoords -> do with "validDirsAndCoords" (return $ filter (pAp2_1 (global lam_canStep) (getAIParsedState aiState)) dirsAndCoords) $ \validDirsAndCoords -> do return $ debugTrace (fst $ head $ validDirsAndCoords) (fst $ head $ validDirsAndCoords) aiBad = bindAp2 lam_aiBad lam_snd = function1 "lam_snd" "p" $ \p -> do return $ snd p ---------------------------------------- --- Program Loop ---------------------------------------- -- Main entry loop fLambdaManMain :: TFunction ((Arg WorldState, Arg () {-bogus-}) -> (AIState, (Arg AIState, Arg WorldState) -> (AIState, Int))) fLambdaManMain = function2 "lambdaManMain" ("worldState", "ghostAI") $ \(worldState, _ghostAI {-todo-} ) -> do (with "parsedState" (return (parseWorldState worldState)) (\parsedState -> return $ (pair (makeAIState parsedState) (global fLambdaManStep)))) -- Step function fLambdaManStep :: TFunction ((Arg AIState, Arg WorldState) -> (AIState, Int)) fLambdaManStep = function2 "lambdaMainStep" ("aiState", "worldState") $ \(aiState, worldState) -> do return $ pair aiState (aiHunter aiState worldState) -- Testing only. Shouldn't parse map state every step --(with "parsedState" (return (parseWorldState worldState)) (\_parsedState -> return $ -- pair aiState (lmDecideDirection (fst worldState) (getLMState worldState)))) {-ifv (getPlayerX parsedState > 20)-} {-(pair aiState kDirectionLeft)-} {-(pair aiState kDirectionRight)))-} lambdaMainStep = bindAp2 fLambdaManStep ---------------------------------------- -- Testing code ---------------------------------------- mainTest = do let mapState = toExpr [[0,5]] _gameState = pair mapState (pair 2 (pair 3 4)) putStrLn $ show $ parseMapState mapState 1 initParsedState putStrLn "\n\nMap Row" putStrLn $ show $ fParseMapRow putStrLn "\n\nMap State" putStrLn $ show $ fParseMapState {-putStrLn $ show $ ifv (null mapState) (toExpr True) (toExpr False)-} {-putStrLn $ show $ parseGameState gameState-} fTestParseMain :: TFunction (NoArgs -> ParsedState) fTestParseMain = function0 "testParseMain" $ do let mapState = [ [0,0,0,0], [0,0,5,0], [0,0,0,0] ] in return $ parseMapState (toExpr mapState) 0 initParsedState testParseProg :: LProgram testParseProg = mkProgram "lambdaManMain" -- "testParseMain" $ yeeModule >< jeffModule >< preludeModule >< pathfindModule yeeModule :: LModule yeeModule = newModule {-^^ fTestParseMain-} ^^ fNth ^^ fParseMapState ^^ fParseMapRow ^^ fParseWorldState ^^ fParseMapSize ^^ fMapLookup ^^ fFastMapLookup ^^ fLMDecideDirection ^^ fLambdaManMain ^^ fLambdaManStep ^^ fMap ^^ fAllocateQuadTree ^^ fReplaceQuadLeaf ^^ fFindQuadLeaf ^^ fRoundUpToPower2 jeffModule :: LModule jeffModule = newModule ^^ lam_subtractPos ^^ lam_absPos ^^ lam_manhattanDistance ^^ lam_selectMin ^^ lam_minimumOver ^^ lam_hasOneElement ^^ lam_foldr1 ^^ lam_zip ^^ lam_getDistanceToPowerPill ^^ lam_getDistanceToFruit ^^ lam_getDistanceToPill ^^ lam_identity ^^ lam_isGhostVisible ^^ lam_getDistanceToGhost ^^ lam_foldl ^^ lam_plus ^^ lam_sum ^^ lam_count ^^ lam_totalGhostDanger ^^ lam_calcGhostDangerAtPoint ^^ lam_max ^^ lam_getDistanceToBest_Scared ^^ lam_getOffset ^^ lam_addPosition ^^ lam_makeDirsAndCoords ^^ lam_canStep ^^ lam_scoreCoord ^^ lam_scoreNeighbor ^^ lam_scoreCoord_killMode ^^ lam_scoreCoord_safeMode ^^ lam_scoreCoord_scaredMode ^^ lam_inFightMode ^^ lam_inKillMode ^^ lam_inScaredMode ^^ lam_getPlayerDistToNearestGhost ^^ lam_getDistToNearestVisibleGhostPathfind ^^ lam_getDistanceToBest_Safe ^^ lam_getInfoFromMapRecursive ^^ lam_getInfoFromMap ^^ lam_makeMapInfo ^^ lam_closerLocation ^^ lam_tryImprovePowerPill ^^ lam_tryImprovePill ^^ lam_tryImproveFruit ^^ lam_tryImproveResults ^^ lam_filter ^^ lam_myAbs ^^ lam_aiHunter ^^ lam_aiBad ^^ lam_snd ^^ lam_pathfindDistance ^^ lam_getGhostPos testParse :: Either CompileError [LCInstr EnvAddr Address] testParse = compileAndLink $ testParseProg mainCompile = printAsm testParse main = mainCompile
ychin/icfp_2014_CannonBrawl
code/lambda_utils.hs
mit
40,684
334
56
7,770
11,276
5,899
5,377
-1
-1
module Main where import Data.List (minimumBy) import Data.Maybe import qualified Data.Map as Map import Text.Regex.Posix import System.IO import System.IO.Error import System.Environment type Time = Int type Node = Char data Street = Street { start :: Node, end :: Node, name :: String, times :: [Time] } type Path = [Street] type Graph = Map.Map Node [Street] instance Show Street where show s = concat [(name s), " (", (return $ start s), "->", (return $ end s), ")"] --streetTime t s = time at which you finish going down s if you start at t streetTime :: Time -> Street -> Time streetTime t street | 360 <= t && t < 600 = t + times street !! 0 | 600 <= t && t < 900 = t + times street !! 1 | 900 <= t && t < 1140 = t + times street !! 2 | 1140 <= t || t < 360 = t + times street !! 3 --pathTime t p = time at which you finish going down p if you start at t pathTime :: Time -> Path -> Time pathTime = foldl streetTime --next g t paths = path to next node in g under Djikstra's algorithm next :: Graph -> Time -> Map.Map Node Path -> Maybe Path next graph start_t node_paths = externals node_paths >>= return . map attach >>= earliest where externals = nullguard . filter is_external . concat . map (graph Map.!) . Map.keys nullguard [] = Nothing nullguard a = Just a is_external = flip Map.notMember node_paths . end attach st = node_paths Map.! start st ++ [st] earliest = return . minimumBy arrival arrival a b = compare (pathTime start_t a) (pathTime start_t b) --gives shortest distance to dest within graph if you start at t djikstra :: Graph -> Node -> Time -> Map.Map Node Path -> Maybe Path djikstra graph dest start_t node_paths = case Map.lookup dest node_paths of Just path -> Just path Nothing -> next graph start_t node_paths >>= return . updateMap >>= djikstra graph dest start_t where updateMap path = Map.insert (end $ last path) path node_paths --gives shortest path from a to b within g if you start at time t shortestPath :: Graph -> Node -> Node -> Time -> Maybe Path shortestPath graph a b time = djikstra graph b time (Map.singleton a []) --converts an input line to a Street lineToStreet :: String -> Maybe Street lineToStreet line = case listToMaybe (line =~ line_regex :: [[String]]) of Just (match:a:b:n:ts:[]) -> Just $ Street (head a) (head b) n (map read $ words ts) _ -> Nothing where line_regex = "(.) (.) \"([A-Za-z ]+)\" ([0-9 ]+)" --parses command line arguments to get (start, end, start_time) parseArgs :: [String] -> Maybe (Node, Node, Time) parseArgs ((a:as):(b:bs):t:[]) = Just (a, b, (*60) . (`div` 100) $ read t) parseArgs _ = (Nothing) --converts a list of streets to a graph. streetsToGraph :: [Street] -> Graph streetsToGraph = foldl insert_street Map.empty where insert_street m s = Map.insertWith (++) (start s) [s] . Map.insertWith (++) (start $ rev s) [rev s] $ m rev s = Street (end s) (start s) (name s) (times s) main = do args <- getArgs (a, b, t) <- case parseArgs args of Just tup -> return tup Nothing -> ioError $ userError "Invalid args" mapfile <- openFile "data.txt" ReadMode contents <- hGetContents mapfile let streets = mapMaybe lineToStreet . lines $ contents let g = streetsToGraph streets p <- case shortestPath g a b t of Just path -> return path Nothing -> ioError $ userError "No paths found" mapM_ (putStrLn . show) p putStrLn $ "Total time: " ++ show (pathTime t p - t) ++ " minutes."
devonhollowood/dailyprog
2015-01-14/shortest_path.hs
mit
3,874
0
15
1,141
1,319
675
644
76
3
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable #-} {- Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz, Luke Michael Brown <http://gsd.uwaterloo.ca> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -} -- | Intermediate representation (IR) of a Clafer model module Language.Clafer.Intermediate.Intclafer where import Language.Clafer.Front.AbsClafer import Control.Lens import Data.Aeson import Data.Aeson.TH import Data.Data import Data.Monoid import Data.Foldable import Prelude -- | unique identifier of a clafer type UID = String -- | clafer name as declared in the source model type CName = String -- | file:// ftp:// or http:// prefixed URL type URL = String -- | A "supertype" of all IR types data Ir = IRIModule IModule | IRIElement IElement | IRIType IType | IRClafer IClafer | IRIExp IExp | IRPExp PExp | IRIReference (Maybe IReference) | IRIQuant IQuant | IRIDecl IDecl | IRIGCard (Maybe IGCard) deriving (Eq, Show) data IType = TBoolean | TString | TInteger | TDouble | TReal | TClafer { _hi :: [UID] -- ^ [UID] represents an inheritance hierarchy obtained using @Common.findHierarchy } | TMap -- Represents a map from the src class to the target class { _so :: IType -- ^ must only be a TClass , _ta :: IType -- ^ must only be a TClass } | TUnion { _un :: [IType] -- ^ [IType] is a list of basic types (not union types) } deriving (Eq,Ord,Show,Data,Typeable) -- | each file contains exactly one mode. A module is a list of declarations data IModule = IModule { _mName :: String -- ^ always empty (no syntax for declaring modules) , _mDecls :: [IElement] -- ^ List of top-level elements } deriving (Eq,Ord,Show,Data,Typeable) -- | Clafer has a list of fields that specify its properties. Some fields, marked as (o) are for generating optimized code data IClafer = IClafer { _cinPos :: Span -- ^ the position of the syntax in source code , _isAbstract :: Bool -- ^ whether abstract or not (i.e., concrete) , _gcard :: Maybe IGCard -- ^ group cardinality , _ident :: CName -- ^ name declared in the model , _uid :: UID -- ^ a unique identifier , _parentUID :: UID -- ^ "root" if top-level concrete, "clafer" if top-level abstract, "" if unresolved or for root clafer, otherwise UID of the parent clafer , _super :: Maybe PExp -- ^ superclafer - only allowed PExp is IClaferId. Nothing = default super "clafer" , _reference :: Maybe IReference -- ^ reference type, bag or set , _card :: Maybe Interval -- ^ clafer cardinality , _glCard :: Interval -- ^ (o) global cardinality , _elements :: [IElement] -- ^ nested elements } deriving (Eq,Ord,Show,Data,Typeable) -- | Clafer's subelement is either a clafer, a constraint, or a goal (objective) -- This is a wrapper type needed to have polymorphic lists of elements data IElement = IEClafer { _iClafer :: IClafer -- ^ the actual clafer } | IEConstraint { _isHard :: Bool -- ^ whether hard constraint or assertion , _cpexp :: PExp -- ^ the container of the actual expression } -- | Goal (optimization objective) | IEGoal { _isMaximize :: Bool -- ^ whether maximize or minimize , _cpexp :: PExp -- ^ the expression } deriving (Eq,Ord,Show,Data,Typeable) -- | A type of reference. -- -> values unique (set) -- ->> values non-unique (bag) data IReference = IReference { _isSet :: Bool -- ^ whether set or bag , _ref :: PExp -- ^ the only allowed reference expressions are IClafer and set expr. (++, **, --s) } deriving (Eq,Ord,Show,Data,Typeable) -- | Group cardinality is specified as an interval. It may also be given by a keyword. -- xor 1..1 isKeyword = True -- 1..1 1..1 isKeyword = False data IGCard = IGCard { _isKeyword :: Bool -- ^ whether given by keyword: or, xor, mux , _interval :: Interval } deriving (Eq,Ord,Show,Data,Typeable) -- | (Min, Max) integer interval. -1 denotes * type Interval = (Integer, Integer) -- | This is expression container (parent). -- It has meta information about an actual expression 'exp' data PExp = PExp { _iType :: Maybe IType -- ^ the inferred type , _pid :: String -- ^ non-empty unique id for expressions with span, \"\" for noSpan , _inPos :: Span -- ^ position in the input Clafer file , _exp :: IExp -- ^ the actual expression } deriving (Eq,Ord,Show,Data,Typeable) -- | Embedes reference to a resolved Clafer type ClaferBinding = Maybe UID data IExp -- | quantified expression with declarations -- e.g., [ all x1; x2 : X | x1.ref != x2.ref ] = IDeclPExp { _quant :: IQuant , _oDecls :: [IDecl] , _bpexp :: PExp } -- | expression with a -- unary function, e.g., -1 -- binary function, e.g., 2 + 3 -- ternary function, e.g., if x then 4 else 5 | IFunExp { _op :: String , _exps :: [PExp] } -- | integer number | IInt { _iint :: Integer } -- | real number | IReal { _ireal :: Double } -- | double-precision floating point number | IDouble { _idouble :: Double } -- | string | IStr { _istr :: String } -- | a reference to a clafer name | IClaferId { _modName :: String -- ^ module name - currently not used and empty since we have no module system , _sident :: CName -- ^ name of the clafer being referred to , _isTop :: Bool -- ^ identifier refers to a top-level definition , _binding :: ClaferBinding -- ^ the UID of the bound IClafer, if resolved } deriving (Eq,Ord,Show,Data,Typeable) {- | For IFunExp standard set of operators includes: 1. Unary operators: ! - not (logical) # - set counting operator - - negation (arithmetic) max - maximum (created for goals and maximum of a set) min - minimum (created for goals and minimum of a set) 2. Binary operators: \<=\> - equivalence =\> - implication || - disjunction xor - exclusive or && - conjunction \< - less than \> - greater than = - equality \<= - less than or equal \>= - greater than or equal != - inequality in - belonging to a set/being a subset nin - not belonging to a set/not being a subset + - addition/string concatenation - - substraction * - multiplication / - division ++ - set union \-\- - set difference ** - set intersection \<: - domain restriction :\> - range restriction . - relational join 3. Ternary operators ifthenelse -- if then else -} -- | Local declaration -- disj x1; x2 : X ++ Y -- y1 : Y data IDecl = IDecl { _isDisj :: Bool -- ^ is disjunct , _decls :: [CName] -- ^ a list of local names , _body :: PExp -- ^ set to which local names refer to } deriving (Eq,Ord,Show,Data,Typeable) -- | quantifier data IQuant = INo -- ^ does not exist | ILone -- ^ less than one | IOne -- ^ exactly one | ISome -- ^ at least one (i.e., exists) | IAll -- ^ for all deriving (Eq,Ord,Show,Data,Typeable) type LineNo = Integer type ColNo = Integer {-Ir Traverse Functions-} ------------------------- -- | map over IR mapIR :: (Ir -> Ir) -> IModule -> IModule -- fmap/map for IModule mapIR f (IModule name decls') = unWrapIModule $ f $ IRIModule $ IModule name $ map (unWrapIElement . iMap f . IRIElement) decls' -- | foldMap over IR foldMapIR :: (Monoid m) => (Ir -> m) -> IModule -> m -- foldMap for IModule foldMapIR f i@(IModule _ decls') = (f $ IRIModule i) `mappend` foldMap (iFoldMap f . IRIElement) decls' -- | fold the IR foldIR :: (Ir -> a -> a) -> a -> IModule -> a -- a basic fold for IModule foldIR f e m = appEndo (foldMapIR (Endo . f) m) e {- Note: even though the above functions take an IModule, the functions they use take an Ir (wrapped version see top of module). Also the bellow functions are just helpers for the above, you may use them if you wish to start from somewhere other than IModule. -} iMap :: (Ir -> Ir) -> Ir -> Ir iMap f (IRIElement (IEClafer c)) = f $ IRIElement $ IEClafer $ unWrapIClafer $ iMap f $ IRClafer c iMap f (IRIElement (IEConstraint h pexp)) = f $ IRIElement $ IEConstraint h $ unWrapPExp $ iMap f $ IRPExp pexp iMap f (IRIElement (IEGoal m pexp)) = f $ IRIElement $ IEGoal m $ unWrapPExp $ iMap f $ IRPExp pexp iMap f (IRClafer (IClafer p a grc i u pu Nothing r c goc elems)) = f $ IRClafer $ IClafer p a (unWrapIGCard $ iMap f $ IRIGCard grc) i u pu Nothing (unWrapIReference $ iMap f $ IRIReference r) c goc $ map (unWrapIElement . iMap f . IRIElement) elems iMap f (IRClafer (IClafer p a grc i u pu (Just s) r c goc elems)) = f $ IRClafer $ IClafer p a (unWrapIGCard $ iMap f $ IRIGCard grc) i u pu (Just $ unWrapPExp $ iMap f $ IRPExp s) (unWrapIReference $ iMap f $ IRIReference r) c goc $ map (unWrapIElement . iMap f . IRIElement) elems iMap f (IRIExp (IDeclPExp q decs p)) = f $ IRIExp $ IDeclPExp (unWrapIQuant $ iMap f $ IRIQuant q) (map (unWrapIDecl . iMap f . IRIDecl) decs) $ unWrapPExp $ iMap f $ IRPExp p iMap f (IRIExp (IFunExp o pexps)) = f $ IRIExp $ IFunExp o $ map (unWrapPExp . iMap f . IRPExp) pexps iMap f (IRPExp (PExp (Just iType') pID p iExp)) = f $ IRPExp $ PExp (Just $ unWrapIType $ iMap f $ IRIType iType') pID p $ unWrapIExp $ iMap f $ IRIExp iExp iMap f (IRPExp (PExp Nothing pID p iExp)) = f $ IRPExp $ PExp Nothing pID p $ unWrapIExp $ iMap f $ IRIExp iExp iMap _ x@(IRIReference Nothing) = x iMap f (IRIReference (Just (IReference is ref))) = f $ IRIReference $ Just $ IReference is $ (unWrapPExp . iMap f . IRPExp) ref iMap f (IRIDecl (IDecl i d body')) = f $ IRIDecl $ IDecl i d $ unWrapPExp $ iMap f $ IRPExp body' iMap f i = f i iFoldMap :: (Monoid m) => (Ir -> m) -> Ir -> m iFoldMap f i@(IRIElement (IEConstraint _ pexp)) = f i `mappend` (iFoldMap f $ IRPExp pexp) iFoldMap f i@(IRIElement (IEGoal _ pexp)) = f i `mappend` (iFoldMap f $ IRPExp pexp) iFoldMap f i@(IRClafer (IClafer _ _ grc _ _ _ Nothing r _ _ elems)) = f i `mappend` (iFoldMap f $ IRIReference r) `mappend` (iFoldMap f $ IRIGCard grc) `mappend` foldMap (iFoldMap f . IRIElement) elems iFoldMap f i@(IRClafer (IClafer _ _ grc _ _ _ (Just s) r _ _ elems)) = f i `mappend` (iFoldMap f $ IRPExp s) `mappend` (iFoldMap f $ IRIReference r) `mappend` (iFoldMap f $ IRIGCard grc) `mappend` foldMap (iFoldMap f . IRIElement) elems iFoldMap f i@(IRIExp (IDeclPExp q decs p)) = f i `mappend` (iFoldMap f $ IRIQuant q) `mappend` (iFoldMap f $ IRPExp p) `mappend` foldMap (iFoldMap f . IRIDecl) decs iFoldMap f i@(IRIExp (IFunExp _ pexps)) = f i `mappend` foldMap (iFoldMap f . IRPExp) pexps iFoldMap f i@(IRPExp (PExp (Just iType') _ _ iExp)) = f i `mappend` (iFoldMap f $ IRIType iType') `mappend` (iFoldMap f $ IRIExp iExp) iFoldMap f i@(IRPExp (PExp Nothing _ _ iExp)) = f i `mappend` (iFoldMap f $ IRIExp iExp) iFoldMap f i@(IRIReference Nothing) = f i iFoldMap f i@(IRIReference (Just (IReference _ ref))) = f i `mappend` (iFoldMap f . IRPExp) ref iFoldMap f i@(IRIDecl (IDecl _ _ body')) = f i `mappend` (iFoldMap f $ IRPExp body') iFoldMap f (IRIElement (IEClafer c)) = iFoldMap f $ IRClafer c iFoldMap f i = f i iFold :: (Ir -> a -> a) -> a -> Ir -> a iFold f e m = appEndo (iFoldMap (Endo . f) m) e unWrapIModule :: Ir -> IModule unWrapIModule (IRIModule x) = x unWrapIModule x = error $ "Can't call unWarpIModule on " ++ show x unWrapIElement :: Ir -> IElement unWrapIElement (IRIElement x) = x unWrapIElement x = error $ "Can't call unWarpIElement on " ++ show x unWrapIType :: Ir -> IType unWrapIType (IRIType x) = x unWrapIType x = error $ "Can't call unWarpIType on " ++ show x unWrapIClafer :: Ir -> IClafer unWrapIClafer (IRClafer x) = x unWrapIClafer x = error $ "Can't call unWarpIClafer on " ++ show x unWrapIExp :: Ir -> IExp unWrapIExp (IRIExp x) = x unWrapIExp x = error $ "Can't call unWarpIExp on " ++ show x unWrapPExp :: Ir -> PExp unWrapPExp (IRPExp x) = x unWrapPExp x = error $ "Can't call unWarpPExp on " ++ show x unWrapIReference :: Ir -> Maybe IReference unWrapIReference (IRIReference x) = x unWrapIReference x = error $ "Can't call unWarpIReference on " ++ show x unWrapIQuant :: Ir -> IQuant unWrapIQuant (IRIQuant x) = x unWrapIQuant x = error $ "Can't call unWarpIQuant on " ++ show x unWrapIDecl :: Ir -> IDecl unWrapIDecl (IRIDecl x) = x unWrapIDecl x = error $ "Can't call unWarpIDecl on " ++ show x unWrapIGCard :: Ir -> Maybe IGCard unWrapIGCard (IRIGCard x) = x unWrapIGCard x = error $ "Can't call unWarpIGcard on " ++ show x instance Plated IModule instance Plated IClafer instance Plated PExp instance Plated IExp makeLenses ''IType makeLenses ''IModule makeLenses ''IClafer makeLenses ''IElement makeLenses ''IReference makeLenses ''IGCard makeLenses ''PExp makeLenses ''IExp makeLenses ''IDecl $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IType) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IModule) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IClafer) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IElement) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IReference) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IGCard) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''PExp) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IExp) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IDecl) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IQuant) instance ToJSON Span where toJSON _ = Null instance ToJSON Pos where toJSON _ = Null -- | Datatype used for JSON output. See Language.Clafer.gatherObjectivesAndAttributes data ObjectivesAndAttributes = ObjectivesAndAttributes { _qualities :: [String] , _attributes :: [String] } $(deriveToJSON defaultOptions{fieldLabelModifier = tail} ''ObjectivesAndAttributes)
juodaspaulius/clafer
src/Language/Clafer/Intermediate/Intclafer.hs
mit
15,702
0
15
3,806
3,865
2,063
1,802
245
1
{-# LANGUAGE NoMonomorphismRestriction #-} import Text.XML.HXT.Core import Text.HandsomeSoup import Network.HTTP.Conduit (simpleHttp) import Data.ByteString.Lazy.UTF8 (toString) import System.Environment import Data.Tree.NTree.TypeDefs base :: String base = "https://gist.github.com" main :: IO () main = getArgs >>= options options :: [String] -> IO () options ["-h" ] = help options ["--help"] = help options [user ] = run $ "/" ++ user options _ = help help :: IO () help = putStrLn "Usage: gists <username>" run :: String -> IO () run path = do bytes <- simpleHttp $ base ++ path let text = toString bytes doc = readString [withParseHTML yes, withWarnings no] text gists <- runX $ doc >>> getGists mapM_ (putStrLn . (base ++)) gists runX (doc >>> getNextPageLink) >>= mapM_ run . take 1 getNextPageLink, getGists, link, snippet, description :: ArrowXml cat => cat (NTree XNode) String getNextPageLink = css ".pagination a" >>> filterA (this //> hasText (elem "Older" . words)) ! "href" getGists = css ".gist-item" >>> (link <+> description <+> snippet) >. strip link = css ".creator a" >>. drop 1 >>> (getAttrValue "href" <+> deep getText) >. strip snippet = css ".line-data" >>> deep getText >. strip description = css ".description" >>> deep getText >. strip strip :: [String] -> String strip = unwords . words . unwords
sordina/gists
Gists.hs
mit
1,415
0
13
299
490
256
234
-1
-1
import Control.Concurrent import System.IO import Network blockSize :: Int blockSize = 500000 startServer = withSocketsDo $ do sock <- listenOn $ PortNumber 32101 sockHandler sock list where list :: [Int] list = [0, blockSize .. ] sockHandler :: Socket -> [Int] -> IO () sockHandler sock list = do (handle, hostname, port) <- accept sock hSetBuffering handle NoBuffering x <- hGetLine handle putStr ("Connected to: " ++ hostname ++ " at " ++ show port) forkIO $ handleRequest handle (list !! 0) (list !! (read x)) putStrLn (", Given " ++ show (list !! 0) ++ " to " ++ show (list !! (read x))) sockHandler sock $ drop (read x) list handleRequest handle l u = do hPutStrLn handle (lower ++ " " ++ upper) where lower = show l upper = show u main = startServer
Joss-Steward/Primality
server.hs
mit
893
0
14
274
325
162
163
24
1
-- Copyright 2015 Mitchell Kember. Subject to the MIT License. -- Project Euler: Problem 36 -- Double-base palindromes module Problem36 where import Common (isPalindrome, digits) import Data.Bits (unsafeShiftL, unsafeShiftR, (.&.), (.|.)) isBinPalindrome :: Int -> Bool isBinPalindrome n = odd n && binReverse n == n where binReverse = go 0 go r 0 = r go r n = go r' n' where r' = (r `unsafeShiftL` 1) .|. (n .&. 1) n' = n `unsafeShiftR` 1 solve :: Int solve = sum . filter works $ [1..999999] where works n = isBinPalindrome n && isPalindrome (digits n)
mk12/euler
haskell/Problem36.hs
mit
602
0
11
146
197
110
87
13
2
-- | A very simple implementation of the Levenshtein algorithm. module Data.Text.Levenshtein where import Algebra.Structure.Semiring import Data.Text (Text) import qualified Data.Text as T import qualified Data.Vector.Unboxed as VU import qualified Data.Vector.Align.Global.Linear2 as Align -- | Levenshtein distance. This function is marked @inline@. It should be bound -- where it is to be used, there marked @NoInline@. This allows enabling, say, -- @LLVM@, in the using module. -- -- This function is markedly worse than, say, the one in @text-metrics@. We -- internally hold the complete DP matrix to enable backtracing. -- -- TODO return the backtrace as well. levenshtein ∷ Text → Text → Int {-# Inline levenshtein #-} levenshtein xs ys = getMinPlus . fst $ Align.nwScoreForward (\x y → if x==y then 0 else 1) (const 1) (const 1) xv yv where !xv = VU.fromList $ T.unpack xs !yv = VU.fromList $ T.unpack ys
choener/AlignmentAlgorithms
Data/Text/Levenshtein.hs
gpl-3.0
960
0
10
184
177
105
72
-1
-1
{-# LANGUAGE ImplicitParams, FlexibleInstances, FlexibleContexts, ViewPatterns, RecordWildCards, NamedFieldPuns, ScopedTypeVariables, TypeSynonymInstances, NoMonomorphismRestriction, TupleSections, StandaloneDeriving, GeneralizedNewtypeDeriving #-} {-# OPTIONS -Wall -fno-warn-unused-imports #-} module Blender.Build where import Blender.Types import ToPython import Data.Vect.Double.Base import Blender.Blenderable import Data.Vect.Double.Util.Dim3 import MathUtil import Control.Exception import Control.Monad.IfElse import Blender.Mesh import Blender.ID import Control.Monad import Data.Vect.Double.Util.Projective(translateAfter4) contextObject :: Python () contextObject = py "context.object" newSphereObj :: ToPython r => PythonVar -> r -> Double -> Python () newSphereObj (var::PythonVar) loc radius = do methodCall1 (bpy_ops "surface") "primitive_nurbs_surface_sphere_add" (namedArg "location" loc) var .= contextObject var <.> "scale" .= (Vec3 radius radius radius) newCylinderObj :: (?sceneE::Python ()) => PythonVar -> Vec3 -> Vec3 -> BlenderUnits -> Python () newCylinderObj (var::PythonVar) from to radius = if normsqr (from &- to) <= 1E-14 then newEmptyObj var "Crushed newCylinderObj" else do methodCall (bpy_ops "surface") "primitive_nurbs_surface_cylinder_add" () var .= contextObject var <.> matrix_basis .= cylinderTransform from to radius newCylinderMeshObj :: PythonVar -> Vec3 -> Vec3 -> BlenderUnits -> Int -> Bool -> Python () newCylinderMeshObj (var::PythonVar) from to radius _nvertices smooth = do methodCall1 (bpy_ops "mesh") "primitive_cylinder_add" (namedArg "vertices" _nvertices) var .= contextObject var <.> matrix_basis .= cylinderTransform from to radius when smooth $ mesh_setSmooth (var <.> "data") cylinderTransform :: Vec3 -> Vec3 -> BlenderUnits -> Proj4 cylinderTransform from to radius = scaling (Vec3 radius radius (1/2)) .*. translation ((1/2) *& vec3Z) .*. linear (pointZTo (to &- from)) .*. translation from matrix_basis :: [Char] matrix_basis = "matrix_basis" newFlatTriangleObj :: (?sceneE::Python ()) => PythonVar -> MeshVertex -> MeshVertex -> MeshVertex -> String -> Python () newFlatTriangleObj var p0 p1 p2 name = let v1 = p1 &- p0 l1 = norm v1 u1 = v1&/l1 v2_0 = p2 &- p0 a = dotprod u1 v2_0 v2 = v2_0 &- a *& u1 l2 = norm v2 u2 = v2&/l2 in if l1==0 || l2==0 then -- fallback newMeshObj var (Mesh name [p0,p1,p2] [(0,1,2)] False [] []) else do -- use an orthogonal transformation so we get a nice local coordinate system newMeshObj var (Mesh name [ zero , l1*&vec3X , l2 *& vec3Y &+ (a *& vec3X) ] [(0,1,2)] False [] []) applyBlenderTransform var (BProj4 (translateAfter4 p0 (safeOrthogonal (Mat3 u1 u2 (crossprod u1 u2))))) safeOrthogonal :: Mat3 -> Proj4 safeOrthogonal m = assert (matrixApproxEq (m .*. transpose m) idmtx) $ assert (matrixApproxEq (transpose m .*. m) idmtx) $ linear m newTextObj :: (?sceneE::Python ()) => PythonVar -> TextCurve -> Python () newTextObj var txt = do let txtVar = pyv "txt" textCurve_init txtVar txt newObj var (blenderName txt) txtVar newCurveObj :: (?sceneE::Python ()) => PythonVar -> BlenderCurve -> Python () newCurveObj var (cu :: BlenderCurve) = do let curveVar = pyv "curve" curve_init curveVar cu newObj var (blenderName cu) curveVar applyBlenderTransform :: ToPython a => a -> BlenderTransform -> Python () applyBlenderTransform objVar tf = case tf of LocAndEulers loc (EulerAnglesXYZ x y z) -> do objVar <.> "rotation_euler" .= (x,y,z) objVar <.> "location" .= loc BProj4 m -> objVar <.> "matrix_basis" .= m bobj_applyTransform :: ToPython a => a -> BlenderObject a1 -> Python () bobj_applyTransform objVar = applyBlenderTransform objVar . bobj_transform newLampObj :: (?sceneE::Python ()) => PythonVar -> LampObj -> Python () newLampObj objVar BObj{..} = do lamp_init lampVar bobj_data newObj objVar (lamp_name bobj_data) lampVar applyBlenderTransform objVar bobj_transform where lampVar = pyv "lamp" -- | Creates a new object with the given name and data, links it to the scene, assigns it to the given var newObj :: (?sceneE::Python (), ToPython t) => PythonVar -> String -> t -> Python () newObj (var :: PythonVar) name objData = do var .= (methodCallExpr (bpy_dat "objects") "new" (str name,objData)) methodCall1 (?sceneE <.> "objects") "link" var newEmptyObj :: (?sceneE::Python ()) => PythonVar -> String -> Python () newEmptyObj var name = newObj var name none --linkObjToScene = grpLink :: BlenderGroup -> Python () -> Python () grpLink gr obj = methodCall1 (bgrp_objectsE gr) "link" obj newMeshObj :: (?sceneE::Python ()) => PythonVar -> Mesh -> Python () newMeshObj var m = do let _meshVar = pyv "decoConeMesh" mesh_init _meshVar m newObj var (meshName m) _meshVar setActiveObject ?sceneE var -- don't know how to determine whether we are in editmode already (seems to be determined at random for new objects...), so try/catch ln "try:" indent $ do normals_make_consistent ln "except RuntimeError:" indent $ do editmode_toggle normals_make_consistent editmode_toggle normals_make_consistent :: Python () normals_make_consistent = methodCall (bpy_ops "mesh") "normals_make_consistent" () originToGeometry :: Python () originToGeometry = do methodCall (bpy_ops "object") "origin_set" (SingleArg (namedArg "type" (str "ORIGIN_GEOMETRY"))) setActiveObject :: (ToPython r, ToPython a) => a -> r -> Python () setActiveObject scene obj = do scene <.> "objects.active" .= obj editmode_toggle :: Python () editmode_toggle = methodCall (bpy_ops "object") "editmode_toggle" () deselectAllStmt :: Python () deselectAllStmt = foreachStmt "o" (py "context.selected_objects") (\o -> o <.> "select" .= False) assignRenderSettingsProperties :: ToPython a => a -> RenderSettings -> Python () assignRenderSettingsProperties _sceneVar RS{..} = do _sceneVar <.> "render.resolution_x" .= render_resolution_x _sceneVar <.> "render.resolution_y" .= render_resolution_y awhen render_filepath (\fp -> _sceneVar <.> "render.filepath" .= str fp) setName :: ToPython a => String -> a -> Python () setName n obj = obj <.> "name" .= str n setMaterial :: (ToPython r, ToPython a) => r -> a -> Python () setMaterial m obj = obj <.> "active_material" .= m quit_blender :: Python () quit_blender = methodCall (bpy_ops "wm") "quit_blender" () newCamObj :: (?sceneE::Python ()) =>PythonVar -> BlenderObject BlenderCamData -> Python () newCamObj objVar BObj{..} = do let camVar = pyv "cam" blenderInit camVar (bobj_data :: BlenderCamData) newObj objVar bobj_name camVar applyBlenderTransform objVar bobj_transform
DanielSchuessler/hstri
Blender/Build.hs
gpl-3.0
7,446
0
20
1,867
2,215
1,107
1,108
160
2
{- mtlstats Copyright (C) 1984, 1985, 2019, 2020, 2021 Rhéal Lamothe <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. -} module HelpersSpec (spec) where import Test.Hspec (Spec, describe) import qualified Helpers.GoalieSpec as Goalie import qualified Helpers.PlayerSpec as Player import qualified Helpers.PositionSpec as Position spec :: Spec spec = describe "Helper" $ do Player.spec Goalie.spec Position.spec
mtlstats/mtlstats
test/HelpersSpec.hs
gpl-3.0
1,015
0
8
164
79
48
31
10
1
{-# LANGUAGE TupleSections, OverloadedStrings #-} module Handler.Home where import Import -- we import Yesod.Auth(maybeAuthId) because it doesn't seem to like being imported -- from the Import.hs file and we need it to display or hide the snip creation form -- in the Snips handler import Yesod.Auth (maybeAuthId,Route (LoginR)) -- For now just redirect the homepage. TODO make a nice homepage getHomeR :: Handler Html getHomeR = do redirect $ SnipsR -- The about page, pretty boring. getAboutR :: Handler Html getAboutR = do defaultLayout $ do setTitle "Snipp.IO: A pastebin sort of thingy" $(widgetFile "about") -- The form for inputting new snips. This is more interesting and -- shows the more complex FieldSettings way of implementing applicative -- form fields. We'd normally write areq textField "Title" Nothing, but -- easier CLI interaction snipForm :: Form (Snip) snipForm = renderBootstrap $ Snip <$> areq textField "Title" { fsName = Just "t" } Nothing <*> areq textareaField "Content" {fsName = Just "c"} Nothing <*> lift (liftIO getCurrentTime) -- the "created at" datestamp -- This is run when we receive a GET request for the snips page. -- Show the snipForm, and the most recent 10 snips getSnipsR :: Handler Html getSnipsR = do muser <- maybeAuthId snips <- runDB $ selectList [] [LimitTo 10, Desc SnipCreated] (formWidget, enctype) <- generateFormPost snipForm defaultLayout $ do setTitle "Snipp.IO: A pastebin sort of thingy" $(widgetFile "snips") -- The web based implementation of the form handling-code -- invoken when we make a POST request from the web. -- This won't work from the CLI as we receive a token id with -- the form. postSnipsR :: Handler () postSnipsR = do ((result, _), _) <- runFormPost snipForm (_) <- case result of FormSuccess snip -> do snipId <- runDB $ insert snip setMessage "Snip imported" redirect $ SnipR snipId _ -> do setMessage "Bad input of some description" redirect SnipsR return () -- Show a single snip from a GET request giving that snip's id -- or a 404 if the db doesn't hold the snip. getSnipR :: Key Snip -> Handler Html getSnipR snipid = do snip <- runDB $ get404 snipid defaultLayout $ do setTitle "Viewing snip" $(widgetFile "snip") -- Respond to CLI POST requests. Note that we use runFormPostNoToken -- meaning that we can accept input from places other than our form postSnipsPlainR :: Handler () postSnipsPlainR = do k <- lookupPostParam("k"::Text) key <- runDB $ count [UserApikey ==. k] if (key < 1) then do forbiddenPlain return () else do ((result, _), _) <- runFormPostNoToken snipForm (_) <- case result of FormSuccess snip -> do snipId <- runDB $ insert snip redirect $ SnipPlainR snipId _ -> do setMessage "Bad input of some description" redirect SnipsR return () -- Prints out the proper URL for the snip. Intended to be called when -- creating snips from the CLI. Because you don't necessarily want -- to see everything in your terminal straight away. getSnipPlainR :: Key Snip -> Handler Html getSnipPlainR snipid = do (_) <- runDB $ get404 snipid giveUrlRenderer [hamlet| @{SnipR snipid} \# |] -- \# gives us a trailing newline. cliUsage :: Widget cliUsage = $(widgetFile "cliUsage")
ciderpunx/snippio
Handler/Home.hs
agpl-3.0
3,454
0
18
815
692
344
348
-1
-1
-- Copyright (C) 2017 Red Hat, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE OverloadedStrings #-} module BDCS.RPM.Utils(splitFilename) where import Data.Bifunctor(first) import qualified Data.Text as T -- Turn an RPM filename in form of "NAME-[EPOCH:]VERSION-RELEASE.ARCH[.rpm] -- into a tuple of (name, epoch, version, release, and arch). splitFilename :: T.Text -> (T.Text, Maybe T.Text, T.Text, T.Text, T.Text) splitFilename rpm_ = let rpm = if ".rpm" `T.isSuffixOf` rpm_ then T.dropEnd 4 rpm_ else rpm_ (front, a) = T.breakOnEnd "." rpm (front2, r) = T.breakOnEnd "-" $ T.dropWhileEnd (== '.') front (n, ve) = first (T.dropWhileEnd (== '-')) $ T.breakOnEnd "-" $ T.dropWhileEnd (== '-') front2 (e, v) = first (T.dropWhileEnd (== ':')) $ T.breakOnEnd ":" ve in (n, if e == "" then Nothing else Just $ T.dropWhile (== ':') e, v, r, a)
dashea/bdcs
importer/BDCS/RPM/Utils.hs
lgpl-2.1
1,532
0
14
294
310
180
130
12
3
{-# OPTIONS_GHC -Wall #-} import Data.Char -- Credit card validator intToString :: Int -> String intToString n = (if d /= 0 then intToString d else "") ++ [intToDigit m] where (d, m) = n `divMod` 10 toDigits :: Integer -> [Integer] toDigits = map (toInteger . digitToInt) . intToString . fromIntegral toDigitsRev :: Integer -> [Integer] toDigitsRev = reverse . toDigits toStrings :: [Integer] -> [String] toStrings = map show doubleEveryOther :: [Integer] -> [Integer] doubleEveryOther = zipWith (*) (cycle [1,2]) toInteger_ :: String -> Integer toInteger_ = read sumDigits :: [Integer] -> Integer sumDigits = sum . toDigits . toInteger_ . concat . toStrings validate :: Integer -> Bool validate = (==0) . (`mod` 10) . sumDigits . doubleEveryOther . toDigitsRev eachLine :: (String -> String) -> (String -> String) eachLine f = unlines . map f . lines validator :: String -> String validator = show . validate . read main :: IO () main = interact (eachLine validator)
spanners/cis194
01-intro/01-intro.hs
unlicense
1,003
0
9
197
366
204
162
25
2
module Geometry.Cuboid ( volume , area ) where volume :: Float -> Float -> Float volume a b c = rectArea a b * c area :: Float -> Float -> Float area a b c = rectArea a b * 2 + rectArea a c * 2 + rectArea b c * 2 rectArea :: Float -> Float -> Float rectArea a b = a * b
alexliew/learn_you_a_haskell
code/Geometry/Cuboid.hs
unlicense
273
0
10
71
135
69
66
9
1
{-#LANGUAGE OverloadedStrings#-} module Data.P440.XML.Instances.Render.ZSO where import qualified Data.P440.Domain.ZSO as ZSO import Data.P440.Domain.ComplexTypes import Data.P440.XML.Render import qualified Data.P440.XML.Instances.Render.ComplexTypes as C instance ToNode ZSO.Файл where toNode (ZSO.Файл идЭС типИнф версПрог телОтпр должнОтпр фамОтпр версФорм запноостат) = complex "Файл" ["ИдЭС" =: идЭС ,"ТипИнф" =: типИнф ,"ВерсПрог" =: версПрог ,"ТелОтпр" =: телОтпр ,"ДолжнОтпр" =: должнОтпр ,"ФамОтпр" =: фамОтпр ,"ВерсФорм" =: версФорм ] [Sequence [запноостат]] instance ToNode ZSO.ЗАПНООСТАТ where toNode (ZSO.ЗАПНООСТАТ номЗапр идЗапр стНКРФ видЗапр основЗапр датаПодп свНО свБанкИлиСвУБР свПл поВсемИлиПоУказанным руководитель) = complex "ЗАПНООСТАТ" ["НомЗапр" =: номЗапр ,"ИдЗапр" =: идЗапр ,"СтНКРФ" =: стНКРФ ,"ВидЗапр" =: видЗапр ,"ОсновЗапр" =: основЗапр ,"ДатаПодп" =: датаПодп] [Sequence [C.свНО "СвНО" свНО] ,Sequence [свБанкИлиСвУБР] ,Sequence [свПл] ,Sequence [поВсемИлиПоУказанным] ,Sequence [C.рукНО "Руководитель" руководитель]] instance ToNode ZSO.СвПл where toNode свПл = complex "СвПл" [] [Sequence [child свПл]] where child (ZSO.ПлЮЛ' плЮЛ) = C.плЮЛ "ПлЮЛ" плЮЛ child (ZSO.ПлИП' плИП) = C.плИП "ПлИП" плИП child (ZSO.ПФЛ' пфл) = C.пфл "ПФЛ" пфл instance ToNode ZSO.СвБанкИлиСвУБР where toNode (ZSO.СвБанк банк) = C.банк "СвБанк" банк toNode (ZSO.СвУБР убр) = C.убр "СвУБР" убр instance ToNode ZSO.НаДатуИлиВПериод where toNode (ZSO.НаДату дата) = complex_ "НаДату" ["ДействПоСост" =: дата] toNode (ZSO.ВПериод датаНач датаКон) = complex_ "НаДату" ["ДатаНач" =: датаНач ,"ДатаКон" =: датаКон] instance ToNode ZSO.ПоВсем where toNode (ZSO.ПоВсем типЗапр остПоСост наДатуИлиЗаПериод) = complex "ПоВсем" ["ТипЗапр" =: типЗапр ,"ОстПоСост" =: остПоСост] [Sequence [toNode наДатуИлиЗаПериод]] instance ToNode ZSO.ИноеЛицо where toNode (ZSO.ИноеЛицоПлЮЛ плЮЛ) = C.плЮЛ "ПлЮЛ" плЮЛ toNode (ZSO.ИноеЛицоПлИП плИП) = C.плИП "ПлИП" плИП toNode (ZSO.ИноеЛицоПФЛ пфл) = C.пфл "ПФЛ" пфл instance ToNode ZSO.ВладСч where toNode (ZSO.УказЛицо' счЛица) = complex_ "УказЛицо" ["СчЛица" =: счЛица] toNode (ZSO.ИноеЛицо' пл) = complex "ИноеЛицо" [] [Sequence [пл]] instance ToNode ZSO.Счет where toNode (ZSO.Счет номСч владСч) = complex "Счет" ["НомСч" =: номСч] [Sequence [владСч]] instance ToNode ZSO.ПоВсемИлиПоУказанным where toNode (ZSO.ПоВсем' поВсем) = toNode поВсем toNode (ZSO.ПоУказанным' счет) = complex "ПоУказанным" [] [Sequence счет]
Macil-dev/p440
src/Data/P440/XML/Instances/Render/ZSO.hs
unlicense
4,410
0
11
1,191
2,252
1,130
1,122
83
0
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Data.CRF.Chain2.Tiers.Array ( -- * Array Array , mkArray , unArray , (!?) -- * Bounds , Bounds (..) ) where import Control.Applicative ((<$>), (<*>)) import Control.Arrow (first) import Data.Ix import Data.Int (Int16) import Data.Maybe (catMaybes) import Data.List (foldl1') import qualified Data.Vector.Unboxed as U import Data.Binary (Binary, get, put) import Data.Vector.Binary () -------------------------------- -- Array -------------------------------- -- | An unboxed array implemented in terms of an unboxed vector. data Array i a = Array { bounds :: (i, i) , array :: U.Vector a } instance (Binary i, Binary a, U.Unbox a) => Binary (Array i a) where put Array{..} = put bounds >> put array get = Array <$> get <*> get -- | Construct array with a default dummy value. mkArray :: (Bounds i, U.Unbox a) => a -> [(i, a)] -> Array i a mkArray dummy xs = Array { bounds = (p, q) , array = zeroed U.// map (first ix) xs } where p = foldl1' lower (map fst xs) q = foldl1' upper (map fst xs) ix = index (p, q) size = rangeSize (p, q) zeroed = U.replicate size dummy {-# INLINE mkArray #-} -- | Deconstruct the array. unArray :: (Bounds i, U.Unbox a) => Array i a -> [(i, a)] unArray ar = catMaybes [ (i,) <$> (ar !? i) | i <- range (bounds ar) ] {-# INLINE unArray #-} (!?) :: (Ix i, U.Unbox a) => Array i a -> i -> Maybe a Array{..} !? x = if inRange bounds x -- TODO: Use unsafe indexing. then Just (array U.! index bounds x) else Nothing {-# INLINE (!?) #-} -------------------------------- -- Bounds -------------------------------- -- | An extended Ix class. class Ix i => Bounds i where -- | A lower bound of two values. lower :: i -> i -> i -- | An upper bound of two values. upper :: i -> i -> i instance Bounds Int16 where lower x y = min x y upper x y = max x y instance Bounds i => Bounds (i, i) where lower (!x1, !y1) (!x2, !y2) = ( lower x1 x2 , lower y1 y2 ) upper (!x1, !y1) (!x2, !y2) = ( upper x1 x2 , upper y1 y2 ) instance Bounds i => Bounds (i, i, i) where lower (!x1, !y1, !z1) (!x2, !y2, !z2) = ( lower x1 x2 , lower y1 y2 , lower z1 z2 ) upper (!x1, !y1, !z1) (!x2, !y2, !z2) = ( upper x1 x2 , upper y1 y2 , upper z1 z2 )
kawu/crf-chain2-tiers
src/Data/CRF/Chain2/Tiers/Array.hs
bsd-2-clause
2,651
0
11
777
928
511
417
69
2
{-# LANGUAGE TemplateHaskell #-} module Model where import Data.ByteString import qualified Data.ByteString as BS import Data.List (find) import Data.Maybe (fromJust) import qualified Data.Text as T import Data.Text(Text) import Data.Text.Encoding (encodeUtf8,decodeUtf8) import Data.Typeable.Internal (Typeable) import Prelude import Yesod import qualified Data.Binary as B -- Data types import Tersus.DataTypes.TApplication import Tersus.DataTypes.User -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ type Id = Double type IdList = [Id] type ApplicationName = ByteString type UrlK = Text data WriteMode = Override | AppendToFile | Create | Delete deriving (Show, Eq, Enum) data ReadMode = FileMetadata | GetContent | Pagination deriving (Show, Eq, Enum) data FileType = File | Directory deriving Show {- TODO NOTE: THIS FILE SHOULD BE DELETED.... -}
kmels/tersus
Model.hs
bsd-2-clause
1,174
0
6
312
212
137
75
22
0
module Graphics.GL.Low.Depth where import Control.Monad.IO.Class import Graphics.GL -- | Enable the depth test. Attempting to render pixels with a depth value -- greater than the depth buffer at those pixels will have no effect. Otherwise -- the depth in the buffer will get updated to the new pixel's depth. enableDepthTest :: (MonadIO m) => m () enableDepthTest = glEnable GL_DEPTH_TEST -- | Disable the depth test and depth buffer updates. disableDepthTest :: (MonadIO m) => m () disableDepthTest = glDisable GL_DEPTH_TEST -- | Clear the depth buffer with the maximum depth value. clearDepthBuffer :: (MonadIO m) => m () clearDepthBuffer = glClear GL_DEPTH_BUFFER_BIT
sgraf812/lowgl
Graphics/GL/Low/Depth.hs
bsd-2-clause
675
0
7
107
106
61
45
9
1
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module CLaSH.GHC.GHC2Core ( GHC2CoreState , coreToTerm , coreToId , makeAllTyCons , emptyGHC2CoreState ) where -- External Modules import Control.Lens ((^.), (%~), (&), (%=)) import Control.Monad.State (State) import qualified Control.Monad.State.Lazy as State import Data.Hashable (Hashable (..)) import Data.HashMap.Lazy (HashMap) import qualified Data.HashMap.Lazy as HashMap import qualified Data.HashMap.Strict as HSM import Data.Maybe (fromMaybe) import Data.Text (isInfixOf,pack) import qualified Data.Traversable as T import Data.Typeable (Typeable) import Unbound.Generics.LocallyNameless (bind, embed, rebind, rec, runFreshM, string2Name, unbind, unembed) import qualified Unbound.Generics.LocallyNameless as Unbound -- GHC API import CLaSH.GHC.Compat.FastString (unpackFB, unpackFS) import CLaSH.GHC.Compat.Outputable (showPpr) import CLaSH.GHC.Compat.TyCon (isSuperKindTyCon) #if __GLASGOW_HASKELL__ < 710 import Coercion (Coercion(..), coercionType) #else import Coercion (coercionType) #endif import CoreFVs (exprSomeFreeVars) import CoreSyn (AltCon (..), Bind (..), CoreExpr, Expr (..), rhssOfAlts) import DataCon (DataCon, dataConExTyVars, dataConName, dataConRepArgTys, dataConTag, dataConTyCon, dataConUnivTyVars, dataConWorkId, dataConWrapId_maybe) import FamInstEnv (FamInst (..), FamInstEnvs, familyInstances) import Id (isDataConId_maybe) import IdInfo (IdDetails (..)) import Literal (Literal (..)) import Module (moduleName, moduleNameString) import Name (Name, nameModule_maybe, nameOccName, nameUnique) import OccName (occNameString) import TyCon (AlgTyConRhs (..), TyCon, algTyConRhs, isAlgTyCon, isFunTyCon, isNewTyCon, isPrimTyCon, isSynTyCon, isTupleTyCon, tcExpandTyCon_maybe, tyConArity, tyConDataCons, tyConKind, tyConName, tyConUnique) import Type (mkTopTvSubst, substTy, tcView) import TypeRep (TyLit (..), Type (..)) import Unique (Uniquable (..), Unique, getKey) import Var (Id, TyVar, Var, idDetails, isTyVar, varName, varType, varUnique) import VarSet (isEmptyVarSet) -- Local imports import qualified CLaSH.Core.DataCon as C import qualified CLaSH.Core.Literal as C import qualified CLaSH.Core.Term as C import qualified CLaSH.Core.TyCon as C import qualified CLaSH.Core.Type as C #if __GLASGOW_HASKELL__ < 710 import qualified CLaSH.Core.Util as C #endif import qualified CLaSH.Core.Var as C import CLaSH.Primitives.Types import CLaSH.Util instance Hashable Name where hashWithSalt s = hashWithSalt s . getKey . nameUnique data GHC2CoreState = GHC2CoreState { _tyConMap :: HashMap C.TyConName TyCon , _nameMap :: HashMap Name String } makeLenses ''GHC2CoreState emptyGHC2CoreState :: GHC2CoreState emptyGHC2CoreState = GHC2CoreState HSM.empty HSM.empty makeAllTyCons :: GHC2CoreState -> FamInstEnvs -> HashMap C.TyConName C.TyCon makeAllTyCons hm fiEnvs = go hm hm where go old new | HSM.null (new ^. tyConMap) = HSM.empty | otherwise = tcm `HSM.union` tcm' where (tcm,old') = State.runState (T.mapM (makeTyCon fiEnvs) (new ^. tyConMap)) old tcm' = go old' (old' & tyConMap %~ (`HSM.difference` (old ^. tyConMap))) makeTyCon :: FamInstEnvs -> TyCon -> State GHC2CoreState C.TyCon makeTyCon fiEnvs tc = tycon where tycon | isTupleTyCon tc = mkTupleTyCon | isAlgTyCon tc = mkAlgTyCon | isSynTyCon tc = mkFunTyCon | isPrimTyCon tc = mkPrimTyCon | isSuperKindTyCon tc = mkSuperKindTyCon | otherwise = mkVoidTyCon where tcArity = tyConArity tc mkAlgTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tcKind <- coreToType (tyConKind tc) tcRhsM <- makeAlgTyConRhs $ algTyConRhs tc case tcRhsM of Just tcRhs -> return C.AlgTyCon { C.tyConName = tcName , C.tyConKind = tcKind , C.tyConArity = tcArity , C.algTcRhs = tcRhs } Nothing -> return (C.PrimTyCon tcName tcKind tcArity) mkFunTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tcKind <- coreToType (tyConKind tc) let instances = familyInstances fiEnvs tc substs <- mapM famInstToSubst instances return C.FunTyCon { C.tyConName = tcName , C.tyConKind = tcKind , C.tyConArity = tcArity , C.tyConSubst = substs } mkTupleTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tcKind <- coreToType (tyConKind tc) tcDc <- fmap (C.DataTyCon . (:[])) . coreToDataCon False . head . tyConDataCons $ tc return C.AlgTyCon { C.tyConName = tcName , C.tyConKind = tcKind , C.tyConArity = tcArity , C.algTcRhs = tcDc } mkPrimTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tcKind <- coreToType (tyConKind tc) return C.PrimTyCon { C.tyConName = tcName , C.tyConKind = tcKind , C.tyConArity = tcArity } mkSuperKindTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc return C.SuperKindTyCon { C.tyConName = tcName } mkVoidTyCon = do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tcKind <- coreToType (tyConKind tc) return (C.PrimTyCon tcName tcKind tcArity) famInstToSubst :: FamInst -> State GHC2CoreState ([C.Type],C.Type) famInstToSubst fi = do tys <- mapM coreToType (fi_tys fi) ty <- coreToType (fi_rhs fi) return (tys,ty) makeAlgTyConRhs :: AlgTyConRhs -> State GHC2CoreState (Maybe C.AlgTyConRhs) makeAlgTyConRhs algTcRhs = case algTcRhs of DataTyCon dcs _ -> Just <$> C.DataTyCon <$> mapM (coreToDataCon False) dcs NewTyCon dc _ (rhsTvs,rhsEtad) _ -> Just <$> (C.NewTyCon <$> coreToDataCon False dc <*> ((,) <$> mapM coreToVar rhsTvs <*> coreToType rhsEtad ) ) AbstractTyCon _ -> return Nothing DataFamilyTyCon -> return Nothing coreToTerm :: PrimMap -> [Var] -> CoreExpr -> State GHC2CoreState C.Term coreToTerm primMap unlocs coreExpr = term coreExpr where term (Var x) = var x term (Lit l) = return $ C.Literal (coreToLiteral l) term (App eFun (Type tyArg)) = C.TyApp <$> term eFun <*> coreToType tyArg term (App eFun eArg) = C.App <$> term eFun <*> term eArg term (Lam x e) | isTyVar x = C.TyLam <$> (bind <$> coreToTyVar x <*> term e) | otherwise = C.Lam <$> (bind <$> coreToId x <*> term e) term (Let (NonRec x e1) e2) = do x' <- coreToId x e1' <- term e1 e2' <- term e2 return $ C.Letrec $ bind (rec [(x', embed e1')]) e2' term (Let (Rec xes) e) = do xes' <- mapM ( firstM coreToId <=< secondM ((return . embed) <=< term) ) xes e' <- term e return $ C.Letrec $ bind (rec xes') e' term (Case _ _ ty []) = C.Prim (pack "EmptyCase") <$> coreToType ty term (Case e b ty alts) = do let usesBndr = any ( not . isEmptyVarSet . exprSomeFreeVars (`elem` [b])) $ rhssOfAlts alts b' <- coreToId b e' <- term e ty' <- coreToType ty let caseTerm v = C.Case v ty' <$> mapM alt alts if usesBndr then do ct <- caseTerm (C.Var (unembed $ C.varType b') (C.varName b')) return $ C.Letrec $ bind (rec [(b',embed e')]) ct else caseTerm e' #if __GLASGOW_HASKELL__ < 710 term (Cast e co) = do e' <- term e case C.collectArgs e' of (C.Prim nm pTy, [Right _, Left errMsg]) | nm == (pack "Control.Exception.Base.irrefutPatError") -> case co of (UnivCo _ _ resTy) -> do resTy' <- coreToType resTy return (C.mkApps (C.Prim nm pTy) [Right resTy', Left errMsg]) _ -> error $ $(curLoc) ++ "irrefutPatError casted with an unknown coercion: " ++ showPpr co _ -> return e' #else term (Cast e _) = term e #endif term (Tick _ e) = term e term (Type t) = C.Prim (pack "_TY_") <$> coreToType t term (Coercion co) = C.Prim (pack "_CO_") <$> coreToType (coercionType co) var x = do xVar <- coreToVar x xPrim <- coreToPrimVar x let xNameS = pack $ Unbound.name2String xPrim xType <- coreToType (varType x) case isDataConId_maybe x of Just dc -> case HashMap.lookup xNameS primMap of Just _ -> return $ C.Prim xNameS xType Nothing -> C.Data <$> coreToDataCon (isDataConWrapId x && not (isNewTyCon (dataConTyCon dc))) dc Nothing -> case HashMap.lookup xNameS primMap of Just (Primitive f _) | f == pack "CLaSH.Signal.Internal.mapSignal#" -> return (mapSignalTerm xType) | f == pack "CLaSH.Signal.Internal.signal#" -> return (signalTerm xType) | f == pack "CLaSH.Signal.Internal.appSignal#" -> return (appSignalTerm xType) | f == pack "CLaSH.Signal.Internal.traverse#" -> return (traverseTerm xType) | f == pack "CLaSH.Signal.Bundle.vecBundle#" -> return (vecUnwrapTerm xType) | f == pack "GHC.Base.$" -> return (dollarTerm xType) | otherwise -> return (C.Prim xNameS xType) Just (BlackBox {}) -> return (C.Prim xNameS xType) Nothing | x `elem` unlocs -> return (C.Prim xNameS xType) | pack "$cshow" `isInfixOf` xNameS -> return (C.Prim xNameS xType) | otherwise -> return (C.Var xType xVar) alt (DEFAULT , _ , e) = bind C.DefaultPat <$> term e alt (LitAlt l , _ , e) = bind (C.LitPat . embed $ coreToLiteral l) <$> term e alt (DataAlt dc, xs, e) = case span isTyVar xs of (tyvs,tmvs) -> bind <$> (C.DataPat . embed <$> coreToDataCon False dc <*> (rebind <$> mapM coreToTyVar tyvs <*> mapM coreToId tmvs)) <*> term e coreToLiteral :: Literal -> C.Literal coreToLiteral l = case l of MachStr fs -> C.StringLiteral (unpackFB fs) MachChar c -> C.StringLiteral [c] MachInt i -> C.IntegerLiteral i MachInt64 i -> C.IntegerLiteral i MachWord i -> C.IntegerLiteral i MachWord64 i -> C.IntegerLiteral i LitInteger i _ -> C.IntegerLiteral i MachFloat r -> C.RationalLiteral r MachDouble r -> C.RationalLiteral r MachNullAddr -> C.StringLiteral [] _ -> error $ $(curLoc) ++ "Can't convert literal: " ++ showPpr l ++ " in expression: " ++ showPpr coreExpr coreToDataCon :: Bool -> DataCon -> State GHC2CoreState C.DataCon coreToDataCon mkWrap dc = do repTys <- mapM coreToType (dataConRepArgTys dc) dcTy <- if mkWrap then case dataConWrapId_maybe dc of Just wrapId -> coreToType (varType wrapId) Nothing -> error $ $(curLoc) ++ "DataCon Wrapper: " ++ showPpr dc ++ " not found" else coreToType (varType $ dataConWorkId dc) mkDc dcTy repTys where mkDc dcTy repTys = do nm <- coreToName dataConName getUnique qualfiedNameString dc uTvs <- mapM coreToVar (dataConUnivTyVars dc) eTvs <- mapM coreToVar (dataConExTyVars dc) return $ C.MkData { C.dcName = nm , C.dcTag = dataConTag dc , C.dcType = dcTy , C.dcArgTys = repTys , C.dcUnivTyVars = uTvs , C.dcExtTyVars = eTvs } coreToType :: Type -> State GHC2CoreState C.Type coreToType ty = coreToType' $ fromMaybe ty (tcView ty) coreToType' :: Type -> State GHC2CoreState C.Type coreToType' (TyVarTy tv) = C.VarTy <$> coreToType (varType tv) <*> (coreToVar tv) coreToType' (TyConApp tc args) | isFunTyCon tc = foldl C.AppTy (C.ConstTy C.Arrow) <$> mapM coreToType args | otherwise = case tcExpandTyCon_maybe tc args of Just (substs,synTy,remArgs) -> do let substs' = mkTopTvSubst substs synTy' = substTy substs' synTy foldl C.AppTy <$> coreToType synTy' <*> mapM coreToType remArgs _ -> do tcName <- coreToName tyConName tyConUnique qualfiedNameString tc tyConMap %= (HSM.insert tcName tc) C.mkTyConApp <$> (pure tcName) <*> mapM coreToType args coreToType' (FunTy ty1 ty2) = C.mkFunTy <$> coreToType ty1 <*> coreToType ty2 coreToType' (ForAllTy tv ty) = C.ForAllTy <$> (bind <$> coreToTyVar tv <*> coreToType ty) coreToType' (LitTy tyLit) = return $ C.LitTy (coreToTyLit tyLit) coreToType' (AppTy ty1 ty2) = C.AppTy <$> coreToType ty1 <*> coreToType' ty2 coreToTyLit :: TyLit -> C.LitTy coreToTyLit (NumTyLit i) = C.NumTy (fromInteger i) coreToTyLit (StrTyLit s) = C.SymTy (unpackFS s) coreToTyVar :: TyVar -> State GHC2CoreState C.TyVar coreToTyVar tv = C.TyVar <$> (coreToVar tv) <*> (embed <$> coreToType (varType tv)) coreToId :: Id -> State GHC2CoreState C.Id coreToId i = C.Id <$> (coreToVar i) <*> (embed <$> coreToType (varType i)) coreToVar :: Typeable a => Var -> State GHC2CoreState (Unbound.Name a) coreToVar = coreToName varName varUnique qualfiedNameStringM coreToPrimVar :: Var -> State GHC2CoreState (Unbound.Name C.Term) coreToPrimVar = coreToName varName varUnique qualfiedNameString coreToName :: Typeable a => (b -> Name) -> (b -> Unique) -> (Name -> State GHC2CoreState String) -> b -> State GHC2CoreState (Unbound.Name a) coreToName toName toUnique toString v = do ns <- toString (toName v) return (Unbound.makeName ns (toInteger . getKey . toUnique $ v)) qualfiedNameString :: Name -> State GHC2CoreState String qualfiedNameString n = makeCached n nameMap $ return (fromMaybe "_INTERNAL_" (modNameM n) ++ ('.':occName)) where occName = occNameString $ nameOccName n qualfiedNameStringM :: Name -> State GHC2CoreState String qualfiedNameStringM n = makeCached n nameMap $ return (maybe occName (\modName -> modName ++ ('.':occName)) (modNameM n)) where occName = occNameString $ nameOccName n modNameM :: Name -> Maybe String modNameM n = do module_ <- nameModule_maybe n let moduleNm = moduleName module_ return (moduleNameString moduleNm) -- | Given the type: -- -- @forall a. forall b. forall clk. (a -> b) -> Signal' clk a -> Signal' clk b@ -- -- Generate the term: -- -- @ -- /\(a:*)./\(b:*)./\(clk:Clock).\(f : (Signal' clk a -> Signal' clk b)). -- \(x : Signal' clk a).f x -- @ mapSignalTerm :: C.Type -> C.Term mapSignalTerm (C.ForAllTy tvATy) = C.TyLam (bind aTV ( C.TyLam (bind bTV ( C.TyLam (bind clkTV ( C.Lam (bind fId ( C.Lam (bind xId ( C.App (C.Var fTy fName) (C.Var aTy xName))))))))))) where (aTV,bTV,clkTV,funTy) = runFreshM $ do { (aTV',C.ForAllTy tvBTy) <- unbind tvATy ; (bTV',C.ForAllTy tvClkTy) <- unbind tvBTy ; (clkTV',funTy') <- unbind tvClkTy ; return (aTV',bTV',clkTV',funTy') } (C.FunTy _ funTy'') = C.tyView funTy (C.FunTy aTy bTy) = C.tyView funTy'' fName = string2Name "f" xName = string2Name "x" fTy = C.mkFunTy aTy bTy fId = C.Id fName (embed fTy) xId = C.Id xName (embed aTy) mapSignalTerm ty = error $ $(curLoc) ++ show ty -- | Given the type: -- -- @forall a. forall clk. a -> Signal' clk a@ -- -- Generate the term -- -- @/\(a:*)./\(clk:Clock).\(x:Signal' clk a).x@ signalTerm :: C.Type -> C.Term signalTerm (C.ForAllTy tvATy) = C.TyLam (bind aTV ( C.TyLam (bind clkTV ( C.Lam (bind xId ( C.Var aTy xName)))))) where (aTV,clkTV,funTy) = runFreshM $ do { (aTV', C.ForAllTy tvClkTy) <- unbind tvATy ; (clkTV', funTy') <- unbind tvClkTy ; return (aTV',clkTV',funTy') } (C.FunTy _ aTy) = C.tyView funTy xName = string2Name "x" xId = C.Id xName (embed aTy) signalTerm ty = error $ $(curLoc) ++ show ty -- | Given the type: -- -- @ -- forall clk. forall a. forall b. Signal' clk (a -> b) -> Signal' clk a -> -- Signal' clk b -- @ -- -- Generate the term: -- -- @ -- /\(clk:Clock)./\(a:*)./\(b:*).\(f : (Signal' clk a -> Signal' clk b)). -- \(x : Signal' clk a).f x -- @ appSignalTerm :: C.Type -> C.Term appSignalTerm (C.ForAllTy tvClkTy) = C.TyLam (bind clkTV ( C.TyLam (bind aTV ( C.TyLam (bind bTV ( C.Lam (bind fId ( C.Lam (bind xId ( C.App (C.Var fTy fName) (C.Var aTy xName))))))))))) where (clkTV,aTV,bTV,funTy) = runFreshM $ do { (clkTV',C.ForAllTy tvATy) <- unbind tvClkTy ; (aTV',C.ForAllTy tvBTy) <- unbind tvATy ; (bTV',funTy') <- unbind tvBTy ; return (clkTV',aTV',bTV',funTy') } (C.FunTy _ funTy'') = C.tyView funTy (C.FunTy aTy bTy) = C.tyView funTy'' fName = string2Name "f" xName = string2Name "x" fTy = C.mkFunTy aTy bTy fId = C.Id fName (embed fTy) xId = C.Id xName (embed aTy) appSignalTerm ty = error $ $(curLoc) ++ show ty -- | Given the type: -- -- @ -- forall t.forall n.forall a.SClock t -> Vec n (Signal' t a) -> -- Signal' t (Vec n a) -- @ -- -- Generate the term: -- -- @ -- /\(t:Clock)./\(n:Nat)./\(a:*).\(sclk:SClock t).\(vs:Signal' (Vec n a)).vs -- @ vecUnwrapTerm :: C.Type -> C.Term vecUnwrapTerm (C.ForAllTy tvTTy) = C.TyLam (bind tTV ( C.TyLam (bind nTV ( C.TyLam (bind aTV ( C.Lam (bind sclkId ( C.Lam (bind vsId ( C.Var vsTy vsName)))))))))) where (tTV,nTV,aTV,funTy) = runFreshM $ do { (tTV',C.ForAllTy tvNTy) <- unbind tvTTy ; (nTV',C.ForAllTy tvATy) <- unbind tvNTy ; (aTV',funTy') <- unbind tvATy ; return (tTV',nTV',aTV',funTy') } (C.FunTy sclkTy funTy'') = C.tyView funTy (C.FunTy _ vsTy) = C.tyView funTy'' sclkName = string2Name "sclk" vsName = string2Name "vs" sclkId = C.Id sclkName (embed sclkTy) vsId = C.Id vsName (embed vsTy) vecUnwrapTerm ty = error $ $(curLoc) ++ show ty -- | Given the type: -- -- @ -- forall f.forall a.forall b.forall clk.Applicative f => (a -> f b) -> -- CSignal clk a -> f (Signal' clk b) -- @ -- -- Generate the term: -- -- @ -- /\(f:* -> *)./\(a:*)./\(b:*)./\(clk:Clock).\(dict:Applicative f). -- \(g:a -> f b).\(x:Signal' clk a).g x -- @ traverseTerm :: C.Type -> C.Term traverseTerm (C.ForAllTy tvFTy) = C.TyLam (bind fTV ( C.TyLam (bind aTV ( C.TyLam (bind bTV ( C.TyLam (bind clkTV ( C.Lam (bind dictId ( C.Lam (bind gId ( C.Lam (bind xId ( C.App (C.Var gTy gName) (C.Var xTy xName))))))))))))))) where (fTV,aTV,bTV,clkTV,funTy) = runFreshM $ do { (fTV',C.ForAllTy tvATy) <- unbind tvFTy ; (aTV',C.ForAllTy tvBTy) <- unbind tvATy ; (bTV',C.ForAllTy tvClkTy) <- unbind tvBTy ; (clkTV',funTy') <- unbind tvClkTy ; return (fTV',aTV',bTV',clkTV',funTy') } (C.FunTy dictTy funTy1) = C.tyView funTy (C.FunTy gTy funTy2) = C.tyView funTy1 (C.FunTy xTy _) = C.tyView funTy2 dictName = string2Name "dict" gName = string2Name "g" xName = string2Name "x" dictId = C.Id dictName (embed dictTy) gId = C.Id gName (embed gTy) xId = C.Id xName (embed xTy) traverseTerm ty = error $ $(curLoc) ++ show ty -- | Given the type: -- -- @forall a. forall b. (a -> b) -> a -> b@ -- -- Generate the term: -- -- @/\(a:*)./\(b:*).\(f : (a -> b)).\(x : a).f x@ dollarTerm :: C.Type -> C.Term dollarTerm (C.ForAllTy tvATy) = C.TyLam (bind aTV ( C.TyLam (bind bTV ( C.Lam (bind fId ( C.Lam (bind xId ( C.App (C.Var fTy fName) (C.Var aTy xName))))))))) where (aTV,bTV,funTy) = runFreshM $ do { (aTV',C.ForAllTy tvBTy) <- unbind tvATy ; (bTV',funTy') <- unbind tvBTy ; return (aTV',bTV',funTy') } (C.FunTy fTy funTy'') = C.tyView funTy (C.FunTy aTy _) = C.tyView funTy'' fName = string2Name "f" xName = string2Name "x" fId = C.Id fName (embed fTy) xId = C.Id xName (embed aTy) dollarTerm ty = error $ $(curLoc) ++ show ty isDataConWrapId :: Id -> Bool isDataConWrapId v = case idDetails v of DataConWrapId {} -> True _ -> False
christiaanb/clash-compiler
clash-ghc/src-ghc/CLaSH/GHC/GHC2Core.hs
bsd-2-clause
23,669
0
36
8,500
7,025
3,600
3,425
479
32
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE EmptyDataDecls #-} -- todo: Go over everything in this file, make sure that everything is regular (this should mean that everything should be incredibly simple), so as to get stuff to actually work -- full disclosure: This file is basically a straight monadization of https://github.com/bos/aeson/blob/940449f4adc804fda4597cab4c25eae503e598ac/Data/Aeson/Types/Generic.hs (that being the most recent version that didn't scare me by doing crazy stuff with mutable vectors) and as such all credit for having actual programming skill goes straight to Bryan O. Sullivan and Bas Van Dijk. module Data.YamlObject.Generic where import GHC.Generics import Data.YamlObject.Types import Data.YamlObject.Support import Data.DList (DList, toList, singleton, empty) import Data.Monoid (mappend) import Control.Monad (return, liftM) import Data.Text (Text, pack, unpack) import Control.Monad.Trans (lift) import Control.Monad.Reader (ReaderT, ask) import Control.Monad.Error (throwError) import Control.Applicative ((<$>), (<*>), (<|>)) import Data.Map (Map) import qualified Data.Map as Map import Control.Monad.State (get, put) import Data.Dynamic import Control.Monad.Fix import Control.Arrow import Text.Libyaml (Position(..)) import Debug.Trace (trace) instance (ToYaml a) => GToYaml (K1 i a) where gToYaml (K1 x) = lift $ toYaml x {-# INLINE gToYaml #-} instance (GToYaml a) => GToYaml (M1 D c a) where gToYaml (M1 x) = gToYaml x {-# INLINE gToYaml #-} instance (GToYaml a) => GToYaml (M1 S c a) where gToYaml (M1 x) = gToYaml x {-# INLINE gToYaml #-} instance GToYaml U1 where gToYaml _ = toSequence [] {-# INLINE gToYaml #-} instance (GObject (M1 C c a), Constructor c, GToYaml a) => GToYaml (M1 C c a) where gToYaml = gObject instance (GProductToValues a, GProductToValues b) => GToYaml (a :*: b) where gToYaml x = do objs <- sequence . toList . gProductToValues $ x toSequence objs {-# INLINE gToYaml #-} instance (GObject a, GObject b) => GToYaml (a :+: b) where gToYaml (L1 x) = gObject x gToYaml (R1 x) = gObject x {-# INLINE gToYaml #-} --- class ConsToYaml f where consToYaml :: f a -> GToYamlAction a class ConsToYaml' b f where consToYaml' :: Tagged b (f a -> GToYamlAction a) newtype Tagged s b = Tagged {unTagged :: b} instance (IsRecord f b, ConsToYaml' b f) => ConsToYaml f where consToYaml = unTagged (consToYaml' :: Tagged b (f a -> GToYamlAction a)) -- {-# INLINE consToYaml #-} instance (GRecordToPairs f) => ConsToYaml' True f where consToYaml' = Tagged (\x -> do r <- gRecordToPairs x toMapping $ toList r) {-# INLINE consToYaml' #-} instance GToYaml f => ConsToYaml' False f where consToYaml' = Tagged gToYaml {-# INLINE consToYaml' #-} ---- class GRecordToPairs f where gRecordToPairs :: f a -> ReaderT (GToYamlDict a) ToYamlM (DList (Text, ToYamlObject)) instance (GRecordToPairs a, GRecordToPairs b) => GRecordToPairs (a :*: b) where gRecordToPairs (a :*: b) = do ra <- gRecordToPairs a rb <- gRecordToPairs b return (ra `mappend` rb) {-# INLINE gRecordToPairs #-} instance (Selector s, GToYaml a) => GRecordToPairs (S1 s a) where gRecordToPairs m1 = do obj <- gToYaml (unM1 m1) dict <- ask let name = pack $ selName m1 if excludeD dict (error "exclude evaluated its first argument") name then return empty else return $ singleton (translateFieldD dict undefined name, obj) {-# INLINE gRecordToPairs #-} ---- class GProductToValues f where gProductToValues :: f a -> DList (GToYamlAction a) instance (GProductToValues a, GProductToValues b) => GProductToValues (a :*: b) where gProductToValues (a :*: b) = gProductToValues a `mappend` gProductToValues b {-# INLINE gProductToValues #-} instance (GToYaml a) => GProductToValues a where gProductToValues = singleton . gToYaml {-# INLINE gProductToValues #-} --- class GObject f where gObject :: f a -> GToYamlAction a instance (GObject a, GObject b) => GObject (a :+: b) where gObject (L1 x) = gObject x gObject (R1 x) = gObject x {-# INLINE gObject #-} instance (Constructor c, GToYaml a, ConsToYaml a) => GObject (C1 c a) where gObject (M1 o) = do obj <- consToYaml o toMapping [(pack $ conName (undefined :: t c a p), obj)] {-# INLINE gObject #-} -- nullary constructors become strings instance (Constructor c) => GObject (C1 c U1) where gObject = toScalar . pack . conName {-# INLINE gObject #-} --- --- generic fromYaml instance (GFromYaml a) => GFromYaml (M1 i c a) where gFromYaml = fmap M1 . gFromYaml instance (FromYaml a) => GFromYaml (K1 i a) where gFromYaml x = do r <- lift $ fromYaml x return $ K1 r instance GFromYaml U1 where gFromYaml (Sequence _ []) = return U1 gFromYaml v = typeMismatch "unit constructor (U1)" v instance (ConsFromYaml a) => GFromYaml (C1 c a) where -- gFromYaml v | trace ("C1 instance: " ++ show v) False = undefined gFromYaml (Mapping ann [(key, value)]) = M1 `fmap` (consParseYaml $ value) -- todo: actually check the constructor name instance (GFromProduct a, GFromProduct b) => GFromYaml (a :*: b) where -- gFromYaml v | trace ("(:*:) instance: " ++ show v) False = undefined gFromYaml (Sequence ann xs) = gParseProduct xs gFromYaml v = typeMismatch "product (:*:)" v {-# INLINE gFromYaml #-} instance (GFromSum a, GFromSum b) => GFromYaml (a :+: b) where -- gFromYaml v | trace ("(:+:) instance: " ++ show v) False = undefined gFromYaml (Mapping ann ([keyVal@(constr, content)])) = gParseSum (unpack constr, content) gFromYaml (Scalar ann constr) = gParseSum (unpack constr, error "gFromYaml: tried to find value inside nullary constructor") gFromYaml v = typeMismatch "sum (:+:)" v {-# INLINE gFromYaml #-} --- class GFromRecord f where gParseRecord :: FromYamlObject -> GFromYamlM f a instance (GFromRecord a, GFromRecord b) => GFromRecord (a :*: b) where gParseRecord obj = (:*:) <$> gParseRecord obj <*> gParseRecord obj {-# INLINE gParseRecord #-} instance (Selector s, GFromYaml a) => GFromRecord (S1 s a) where gParseRecord (Mapping ann ps) = let tkey = pack key in ask >>= \dict -> case lookup (translateFieldD' dict undefined $ tkey) $ ps of Nothing -> if allowExclusionD dict undefined tkey then error "exclusion allowed and no value provided" else throwError $ MissingMapElement (fromYamlPosition ann) (unpack $ translateFieldD' dict undefined $ pack $ key) Just k -> gFromYaml k where key = selName (undefined :: t s a p) gParseRecord v = typeMismatch "field selector" v {-# INLINE gParseRecord #-} --- class GFromSum f where gParseSum :: (String, FromYamlObject) -> GFromYamlM f a instance (GFromSum a, GFromSum b) => GFromSum (a :+: b) where gParseSum keyVal = (L1 <$> gParseSum keyVal) <|> (R1 <$> gParseSum keyVal) {-# INLINE gParseSum #-} instance (Constructor c, GFromYaml a, ConsFromYaml a) => GFromSum (C1 c a) where gParseSum (key, value) | key == constructor = M1 `fmap` consParseYaml value | otherwise = throwError $ TypeMismatch (Position (-1) (-1) (-1) (-1) {-fromYamlPosition $ annotation value-}) (constructor ++ " (constructor)") key where constructor = conName (undefined :: t c a p) {-# INLINE gParseSum #-} instance (Constructor c) => GFromSum (C1 c U1) where gParseSum (key, _) | key == constructor = return $ M1 U1 | otherwise = fail "could not find constructor" -- todo: proper error reporting where constructor = conName (undefined :: t c U1 p) -- class ConsFromYaml f where consParseYaml :: FromYamlObject -> GFromYamlM f a class ConsFromYaml' b f where consParseYaml' :: Tagged b (FromYamlObject -> GFromYamlM f a) instance (IsRecord f b, ConsFromYaml' b f) => ConsFromYaml f where consParseYaml = unTagged (consParseYaml' :: Tagged b (FromYamlObject -> GFromYamlM f a)) {-# INLINE consParseYaml #-} instance (GFromRecord f) => ConsFromYaml' True f where consParseYaml' = Tagged gParseRecord where parseRecord o@(Mapping ann [(constr, obj)]) = gParseRecord obj parseRecord v = typeMismatch "record (:*:)" v {-# INLINE consParseYaml' #-} instance (GFromYaml f) => ConsFromYaml' False f where consParseYaml' = Tagged gFromYaml where go (Mapping ann [(constr, obj)]) = gFromYaml obj go v = typeMismatch "product (:*:)" v {-# INLINE consParseYaml' #-} -- class GFromProduct f where gParseProduct :: [FromYamlObject] -> GFromYamlM f a instance (GFromProduct a, GFromProduct b) => GFromProduct (a :*: b) where gParseProduct arr = (:*:) <$> gParseProduct arrL <*> gParseProduct arrR where (arrL, arrR) = splitAt (length arr `div` 2) arr {-# INLINE gParseProduct #-} instance (GFromYaml a) => GFromProduct a where gParseProduct ([v]) = gFromYaml v gParseProduct _ = throwError $ OtherException "Product too small" -- todo: Better error {-# INLINE gParseProduct #-} data True data False class IsRecord (f :: * -> *) b | f -> b instance (IsRecord f b) => IsRecord (f :*: g) b instance IsRecord (M1 S NoSelector f) False instance (IsRecord f b) => IsRecord (M1 S c f) b instance IsRecord (K1 i c) True instance IsRecord U1 False
arirahikkala/yaml-with-class
src/Data/YamlObject/Generic.hs
bsd-3-clause
9,886
0
20
2,247
2,943
1,544
1,399
-1
-1
module Beekeeper.Core.Declaration where import Beekeeper.Core.Identifiers (PythonTree, ModuleName, ImportSource) data Declaration = LocalVar {declarationName :: String} | Dereference {declarationName :: String} | FunctionDec {declarationName :: String} | ClassDec {declarationName :: String} | LambdaDec | GlobalVar {declarationName :: String} | NonlocalVar {declarationName :: String} | StarImport {source :: ImportSource} | ImportVar {source :: ImportSource, declarationName :: String} | ImportModule {source :: ImportSource, declarationName :: String} type DeclarationTree = PythonTree ModuleName Declaration
dsj36/beekeeper
src/Beekeeper/Core/Declaration.hs
bsd-3-clause
833
0
8
290
153
97
56
15
0
module Render (render_world, load_tiles) where import World import qualified Data.Map.Strict as Map import Graphics.Gloss import Data.Maybe import Data.Ratio load_tiles :: FilePath -> IO (Map.Map Tile Picture) load_tiles p = ((sequenceA . map sequenceA) (fmap (\x -> (fst x, loadBMP (toFileName x))) [(0, "$"), (1, "at"), (2, "b"), (3, "hero"), (4, "ll+"), (5, "lr+"), (6, "minus"), (7, "pipe"), (8, "plus"), (9, "skele"), (10, "ul+"), (11, "ur+")])) >>= (\x -> return (Map.fromList x)) where toFileName (_, b) = p ++ "/assets/" ++ b ++ ".bmp" render_world :: World -> Picture render_world w = Pictures [ if (curFloor w) >= length (floors w) then Blank else render_floor ((floors w) !! (curFloor w)) (tiles w), Color white $ Translate (-640) (-512) $ Scale 0.15 0.15 $ Text (curMessage w) ] obn :: [a] -> (Int -> a -> b) -> [b] obn l f = obn' l f 0 where obn' [] _ _ = [] obn' (x:xs) f n = [f n x] ++ obn' xs f (n + 1) obn2 :: [[a]] -> (Int -> Int -> a -> b) -> [b] obn2 l f = obn2' l f 0 where obn2' [] _ _ = [] obn2' (x:xs) f n = (obn x (\m -> (\x -> f n m x))) ++ (obn2' xs f (n + 1)) grid_to_x :: Int -> Float grid_to_x x = (16 * ((fromIntegral x) - ((fromIntegral floorWidth) - 1)/2)) grid_to_y :: Int -> Float grid_to_y y = (16 * ((fromIntegral y) - ((fromIntegral floorHeight) - 1)/2)) + 8 draw_tile_at :: Tile -> Map.Map Tile Picture -> Int -> Int -> Picture draw_tile_at t tm x y = maybe Blank (\t -> Translate (grid_to_x x) (grid_to_y y) t) (Map.lookup t tm) render_floor :: Floor -> (Map.Map Tile Picture) -> Picture render_floor f tm = Pictures $ (obn2 (terrainLayer f) (\m -> \n -> \x -> draw_tile_at x tm n m)) ++ map (\m -> draw_tile_at (monsterVariety m) tm (fst $ monsterPosition m) (snd $ monsterPosition m)) (monsterLayer f)
coddinkn/sns
app/Render.hs
bsd-3-clause
1,832
0
15
420
992
536
456
37
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ViewPatterns #-} module Stack.Setup.Installed ( getCompilerVersion , markInstalled , unmarkInstalled , listInstalled , Tool (..) , toolString , toolNameString , parseToolText , ExtraDirs (..) , extraDirs , installDir ) where import Control.Applicative import Control.Monad.Catch import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control import qualified Data.ByteString.Char8 as S8 import Data.List hiding (concat, elem, maximumBy) import Data.Maybe import Data.Monoid import Data.Text (Text) import qualified Data.Text as T import Distribution.System (Platform (..)) import qualified Distribution.System as Cabal import Path import Path.IO import Prelude hiding (concat, elem) -- Fix AMP warning import Stack.Types import qualified System.FilePath as FP import System.Process.Read data Tool = Tool PackageIdentifier -- ^ e.g. ghc-7.8.4, msys2-20150512 | ToolGhcjs CompilerVersion -- ^ e.g. ghcjs-0.1.0_ghc-7.10.2 toolString :: Tool -> String toolString (Tool ident) = packageIdentifierString ident toolString (ToolGhcjs cv) = compilerVersionString cv toolNameString :: Tool -> String toolNameString (Tool ident) = packageNameString $ packageIdentifierName ident toolNameString ToolGhcjs{} = "ghcjs" parseToolText :: Text -> Maybe Tool parseToolText (parseCompilerVersion -> Just (cv@GhcjsVersion{})) = Just (ToolGhcjs cv) parseToolText (parsePackageIdentifierFromString . T.unpack -> Just pkgId) = Just (Tool pkgId) parseToolText _ = Nothing markInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => Tool -> m () markInstalled tool = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ toolString tool ++ ".installed" liftIO $ writeFile (toFilePath $ dir </> fpRel) "installed" unmarkInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => Tool -> m () unmarkInstalled tool = do dir <- asks $ configLocalPrograms . getConfig fpRel <- parseRelFile $ toolString tool ++ ".installed" removeFileIfExists $ dir </> fpRel listInstalled :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m) => m [Tool] listInstalled = do dir <- asks $ configLocalPrograms . getConfig createTree dir (_, files) <- listDirectory dir return $ mapMaybe toTool files where toTool fp = do x <- T.stripSuffix ".installed" $ T.pack $ toFilePath $ filename fp parseToolText x getCompilerVersion :: (MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m) => EnvOverride -> WhichCompiler -> m CompilerVersion getCompilerVersion menv wc = case wc of Ghc -> do bs <- readProcessStdout Nothing menv "ghc" ["--numeric-version"] let (_, ghcVersion) = versionFromEnd bs GhcVersion <$> parseVersion ghcVersion Ghcjs -> do -- Output looks like -- -- The Glorious Glasgow Haskell Compilation System for JavaScript, version 0.1.0 (GHC 7.10.2) bs <- readProcessStdout Nothing menv "ghcjs" ["--version"] let (rest, ghcVersion) = versionFromEnd bs (_, ghcjsVersion) = versionFromEnd rest GhcjsVersion <$> parseVersion ghcjsVersion <*> parseVersion ghcVersion where versionFromEnd = S8.spanEnd isValid . fst . S8.breakEnd isValid isValid c = c == '.' || ('0' <= c && c <= '9') -- | Binary directories for the given installed package extraDirs :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => Tool -> m ExtraDirs extraDirs tool = do config <- asks getConfig dir <- installDir (configLocalPrograms config) tool case (configPlatform config, toolNameString tool) of (Platform _ Cabal.Windows, isGHC -> True) -> return mempty { edBins = goList [ dir </> $(mkRelDir "bin") , dir </> $(mkRelDir "mingw") </> $(mkRelDir "bin") ] } (Platform _ Cabal.Windows, "msys2") -> return mempty { edBins = goList [ dir </> $(mkRelDir "usr") </> $(mkRelDir "bin") ] , edInclude = goList [ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "include") , dir </> $(mkRelDir "mingw32") </> $(mkRelDir "include") ] , edLib = goList [ dir </> $(mkRelDir "mingw64") </> $(mkRelDir "lib") , dir </> $(mkRelDir "mingw32") </> $(mkRelDir "lib") ] } (_, isGHC -> True) -> return mempty { edBins = goList [ dir </> $(mkRelDir "bin") ] } (_, isGHCJS -> True) -> return mempty { edBins = goList [ dir </> $(mkRelDir "bin") ] } (Platform _ x, toolName) -> do $logWarn $ "binDirs: unexpected OS/tool combo: " <> T.pack (show (x, toolName)) return mempty where goList = map toFilePathNoTrailingSlash isGHC n = "ghc" == n || "ghc-" `isPrefixOf` n isGHCJS n = "ghcjs" == n data ExtraDirs = ExtraDirs { edBins :: ![FilePath] , edInclude :: ![FilePath] , edLib :: ![FilePath] } instance Monoid ExtraDirs where mempty = ExtraDirs [] [] [] mappend (ExtraDirs a b c) (ExtraDirs x y z) = ExtraDirs (a ++ x) (b ++ y) (c ++ z) installDir :: (MonadReader env m, HasConfig env, MonadThrow m, MonadLogger m) => Path Abs Dir -> Tool -> m (Path Abs Dir) installDir programsDir tool = do reldir <- parseRelDir $ toolString tool return $ programsDir </> reldir toFilePathNoTrailingSlash :: Path loc Dir -> FilePath toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath
meiersi-11ce/stack
src/Stack/Setup/Installed.hs
bsd-3-clause
6,288
0
19
1,850
1,777
924
853
145
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Stack.Options (BuildCommand(..) ,GlobalOptsContext(..) ,benchOptsParser ,buildOptsParser ,cleanOptsParser ,configCmdSetParser ,configOptsParser ,dockerOptsParser ,dockerCleanupOptsParser ,dotOptsParser ,execOptsParser ,evalOptsParser ,globalOptsParser ,initOptsParser ,newOptsParser ,nixOptsParser ,logLevelOptsParser ,ghciOptsParser ,solverOptsParser ,testOptsParser ,haddockOptsParser ,hpcReportOptsParser ,pvpBoundsOption ,globalOptsFromMonoid ,splitObjsWarning ) where import Control.Monad.Logger (LogLevel (..)) import Data.Char (isSpace, toLower, toUpper) import Data.List (intercalate) import Data.List.Split (splitOn) import qualified Data.Map as Map import Data.Map.Strict (Map) import qualified Data.Map.Strict as M import Data.Maybe import Data.Monoid.Extra import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Read (decimal) import Data.Version (showVersion) import Distribution.Version (anyVersion) import Options.Applicative import Options.Applicative.Args import Options.Applicative.Builder.Extra import Options.Applicative.Types (fromM, oneM, readerAsk) import Paths_stack as Meta import Stack.Build (splitObjsWarning) import Stack.Clean (CleanOpts (..)) import Stack.Config (packagesParser) import Stack.ConfigCmd import Stack.Constants import Stack.Coverage (HpcReportOpts (..)) import Stack.Docker import qualified Stack.Docker as Docker import Stack.Dot import Stack.Ghci (GhciOpts (..)) import Stack.Init import Stack.New import Stack.Nix import Stack.Types.FlagName import Stack.Types.PackageName import Stack.Types.Version import Stack.Types.Config import Stack.Types.Docker import Stack.Types.Nix import Stack.Types.Compiler import Stack.Types.TemplateName -- | Allows adjust global options depending on their context -- Note: This was being used to remove ambibuity between the local and global -- implementation of stack init --resolver option. Now that stack init has no -- local --resolver this is not being used anymore but the code is kept for any -- similar future use cases. data GlobalOptsContext = OuterGlobalOpts -- ^ Global options before subcommand name | OtherCmdGlobalOpts -- ^ Global options following any other subcommand | BuildCmdGlobalOpts deriving (Show, Eq) -- | Parser for bench arguments. -- FIXME hiding options benchOptsParser :: Bool -> Parser BenchmarkOptsMonoid benchOptsParser hide0 = BenchmarkOptsMonoid <$> optionalFirst (strOption (long "benchmark-arguments" <> metavar "BENCH_ARGS" <> help ("Forward BENCH_ARGS to the benchmark suite. " <> "Supports templates from `cabal bench`") <> hide)) <*> optionalFirst (switch (long "no-run-benchmarks" <> help "Disable running of benchmarks. (Benchmarks will still be built.)" <> hide)) where hide = hideMods hide0 -- | Parser for CLI-only build arguments buildOptsParser :: BuildCommand -> Parser BuildOptsCLI buildOptsParser cmd = BuildOptsCLI <$> many (textArgument (metavar "TARGET" <> help ("If none specified, use all packages. " <> "See https://docs.haskellstack.org/en/v" <> showVersion Meta.version <> "/build_command/#target-syntax for details."))) <*> switch (long "dry-run" <> help "Don't build anything, just prepare to") <*> ((\x y z -> concat [x, y, z]) <$> flag [] ["-Wall", "-Werror"] (long "pedantic" <> help "Turn on -Wall and -Werror") <*> flag [] ["-O0"] (long "fast" <> help "Turn off optimizations (-O0)") <*> many (textOption (long "ghc-options" <> metavar "OPTION" <> help "Additional options passed to GHC"))) <*> (Map.unionsWith Map.union <$> many (option readFlag (long "flag" <> metavar "PACKAGE:[-]FLAG" <> help ("Override flags set in stack.yaml " <> "(applies to local packages and extra-deps)")))) <*> (flag' BSOnlyDependencies (long "dependencies-only" <> help "A synonym for --only-dependencies") <|> flag' BSOnlySnapshot (long "only-snapshot" <> help "Only build packages for the snapshot database, not the local database") <|> flag' BSOnlyDependencies (long "only-dependencies" <> help "Only build packages that are dependencies of targets on the command line") <|> pure BSAll) <*> (flag' FileWatch (long "file-watch" <> help "Watch for changes in local files and automatically rebuild. Ignores files in VCS boring/ignore file") <|> flag' FileWatchPoll (long "file-watch-poll" <> help "Like --file-watch, but polling the filesystem instead of using events") <|> pure NoFileWatch) <*> many (cmdOption (long "exec" <> metavar "CMD [ARGS]" <> help "Command and arguments to run after a successful build")) <*> switch (long "only-configure" <> help "Only perform the configure step, not any builds. Intended for tool usage, may break when used on multiple packages at once!") <*> pure cmd -- | Parser for package:[-]flag readFlag :: ReadM (Map (Maybe PackageName) (Map FlagName Bool)) readFlag = do s <- readerAsk case break (== ':') s of (pn, ':':mflag) -> do pn' <- case parsePackageNameFromString pn of Nothing | pn == "*" -> return Nothing | otherwise -> readerError $ "Invalid package name: " ++ pn Just x -> return $ Just x let (b, flagS) = case mflag of '-':x -> (False, x) _ -> (True, mflag) flagN <- case parseFlagNameFromString flagS of Nothing -> readerError $ "Invalid flag name: " ++ flagS Just x -> return x return $ Map.singleton pn' $ Map.singleton flagN b _ -> readerError "Must have a colon" -- | Command-line parser for the clean command. cleanOptsParser :: Parser CleanOpts cleanOptsParser = CleanShallow <$> packages <|> doFullClean where packages = many (packageNameArgument (metavar "PACKAGE" <> help "If none specified, clean all local packages")) doFullClean = flag' CleanFull (long "full" <> help "Delete all work directories (.stack-work by default) in the project") -- | Command-line arguments parser for configuration. configOptsParser :: GlobalOptsContext -> Parser ConfigMonoid configOptsParser hide0 = (\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch ghcVariant jobs includes libs overrideGccPath skipGHCCheck skipMsys localBin modifyCodePage allowDifferentUser -> mempty { configMonoidStackRoot = stackRoot , configMonoidWorkDir = workDir , configMonoidBuildOpts = buildOpts , configMonoidDockerOpts = dockerOpts , configMonoidNixOpts = nixOpts , configMonoidSystemGHC = systemGHC , configMonoidInstallGHC = installGHC , configMonoidSkipGHCCheck = skipGHCCheck , configMonoidArch = arch , configMonoidGHCVariant = ghcVariant , configMonoidJobs = jobs , configMonoidExtraIncludeDirs = includes , configMonoidExtraLibDirs = libs , configMonoidOverrideGccPath = overrideGccPath , configMonoidSkipMsys = skipMsys , configMonoidLocalBinPath = localBin , configMonoidModifyCodePage = modifyCodePage , configMonoidAllowDifferentUser = allowDifferentUser }) <$> optionalFirst (absDirOption ( long stackRootOptionName <> metavar (map toUpper stackRootOptionName) <> help ("Absolute path to the global stack root directory " ++ "(Overrides any STACK_ROOT environment variable)") <> hide )) <*> optionalFirst (relDirOption ( long "work-dir" <> metavar "WORK-DIR" <> help "Override work directory (default: .stack-work)" <> hide )) <*> buildOptsMonoidParser (hide0 /= BuildCmdGlobalOpts) <*> dockerOptsParser True <*> nixOptsParser True <*> firstBoolFlags "system-ghc" "using the system installed GHC (on the PATH) if available and a matching version" hide <*> firstBoolFlags "install-ghc" "downloading and installing GHC if necessary (can be done manually with stack setup)" hide <*> optionalFirst (strOption ( long "arch" <> metavar "ARCH" <> help "System architecture, e.g. i386, x86_64" <> hide )) <*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (option auto ( long "jobs" <> short 'j' <> metavar "JOBS" <> help "Number of concurrent jobs to run" <> hide )) <*> fmap Set.fromList (many (absDirOption ( long "extra-include-dirs" <> metavar "DIR" <> help "Extra directories to check for C header files" <> hide ))) <*> fmap Set.fromList (many (absDirOption ( long "extra-lib-dirs" <> metavar "DIR" <> help "Extra directories to check for libraries" <> hide ))) <*> optionalFirst (absFileOption ( long "with-gcc" <> metavar "PATH-TO-GCC" <> help "Use gcc found at PATH-TO-GCC" <> hide )) <*> firstBoolFlags "skip-ghc-check" "skipping the GHC version and architecture check" hide <*> firstBoolFlags "skip-msys" "skipping the local MSYS installation (Windows only)" hide <*> optionalFirst (strOption ( long "local-bin-path" <> metavar "DIR" <> help "Install binaries to DIR" <> hide )) <*> firstBoolFlags "modify-code-page" "setting the codepage to support UTF-8 (Windows only)" hide <*> firstBoolFlags "allow-different-user" ("permission for users other than the owner of the stack root " ++ "directory to use a stack installation (POSIX only)") hide where hide = hideMods (hide0 /= OuterGlobalOpts) buildOptsMonoidParser :: Bool -> Parser BuildOptsMonoid buildOptsMonoidParser hide0 = transform <$> trace <*> profile <*> options where hide = hideMods hide0 transform tracing profiling = enable where enable opts | tracing || profiling = opts { buildMonoidLibProfile = First (Just True) , buildMonoidExeProfile = First (Just True) , buildMonoidBenchmarkOpts = bopts { beoMonoidAdditionalArgs = First (getFirst (beoMonoidAdditionalArgs bopts) <> Just (" " <> unwords additionalArgs)) } , buildMonoidTestOpts = topts { toMonoidAdditionalArgs = (toMonoidAdditionalArgs topts) <> additionalArgs } } | otherwise = opts where bopts = buildMonoidBenchmarkOpts opts topts = buildMonoidTestOpts opts additionalArgs = "+RTS" : catMaybes [trac, prof, Just "-RTS"] trac = if tracing then Just "-xc" else Nothing prof = if profiling then Just "-p" else Nothing profile = flag False True (long "profile" <> help "Enable profiling in libraries, executables, etc. \ \for all expressions and generate a profiling report\ \ in tests or benchmarks" <> hide) trace = flag False True (long "trace" <> help "Enable profiling in libraries, executables, etc. \ \for all expressions and generate a backtrace on \ \exception" <> hide) options = BuildOptsMonoid <$> libProfiling <*> exeProfiling <*> haddock <*> haddockOptsParser hide0 <*> openHaddocks <*> haddockDeps <*> copyBins <*> preFetch <*> keepGoing <*> forceDirty <*> tests <*> testOptsParser hide0 <*> benches <*> benchOptsParser hide0 <*> reconfigure <*> cabalVerbose <*> splitObjs libProfiling = firstBoolFlags "library-profiling" "library profiling for TARGETs and all its dependencies" hide exeProfiling = firstBoolFlags "executable-profiling" "executable profiling for TARGETs and all its dependencies" hide haddock = firstBoolFlags "haddock" "generating Haddocks the package(s) in this directory/configuration" hide openHaddocks = firstBoolFlags "open" "opening the local Haddock documentation in the browser" hide haddockDeps = firstBoolFlags "haddock-deps" "building Haddocks for dependencies" hide copyBins = firstBoolFlags "copy-bins" "copying binaries to the local-bin-path (see 'stack path')" hide keepGoing = firstBoolFlags "keep-going" "continue running after a step fails (default: false for build, true for test/bench)" hide preFetch = firstBoolFlags "prefetch" "Fetch packages necessary for the build immediately, useful with --dry-run" hide forceDirty = firstBoolFlags "force-dirty" "Force treating all local packages as having dirty files (useful for cases where stack can't detect a file change" hide tests = firstBoolFlags "test" "testing the package(s) in this directory/configuration" hide benches = firstBoolFlags "bench" "benchmarking the package(s) in this directory/configuration" hide reconfigure = firstBoolFlags "reconfigure" "Perform the configure step even if unnecessary. Useful in some corner cases with custom Setup.hs files" hide cabalVerbose = firstBoolFlags "cabal-verbose" "Ask Cabal to be verbose in its output" hide splitObjs = firstBoolFlags "split-objs" ("Enable split-objs, to reduce output size (at the cost of build time). " ++ splitObjsWarning) hide nixOptsParser :: Bool -> Parser NixOptsMonoid nixOptsParser hide0 = overrideActivation <$> (NixOptsMonoid <$> pure (Any False) <*> firstBoolFlags nixCmdName "use of a Nix-shell" hide <*> firstBoolFlags "nix-pure" "use of a pure Nix-shell" hide <*> optionalFirst (textArgsOption (long "nix-packages" <> metavar "NAMES" <> help "List of packages that should be available in the nix-shell (space separated)" <> hide)) <*> optionalFirst (option str (long "nix-shell-file" <> metavar "FILEPATH" <> help "Nix file to be used to launch a nix-shell (for regular Nix users)" <> hide)) <*> optionalFirst (textArgsOption (long "nix-shell-options" <> metavar "OPTIONS" <> help "Additional options passed to nix-shell" <> hide)) <*> optionalFirst (textArgsOption (long "nix-path" <> metavar "PATH_OPTIONS" <> help "Additional options to override NIX_PATH parts (notably 'nixpkgs')" <> hide)) <*> firstBoolFlags "nix-add-gc-roots" "addition of packages to the nix GC roots so nix-collect-garbage doesn't remove them" hide ) where hide = hideMods hide0 overrideActivation m = if m /= mempty then m { nixMonoidEnable = (First . Just . fromFirst True) (nixMonoidEnable m) } else m textArgsOption = fmap (map T.pack) . argsOption -- | Options parser configuration for Docker. dockerOptsParser :: Bool -> Parser DockerOptsMonoid dockerOptsParser hide0 = DockerOptsMonoid <$> pure (Any False) <*> firstBoolFlags dockerCmdName "using a Docker container" hide <*> fmap First ((Just . DockerMonoidRepo) <$> option str (long (dockerOptName dockerRepoArgName) <> hide <> metavar "NAME" <> help "Docker repository name") <|> (Just . DockerMonoidImage) <$> option str (long (dockerOptName dockerImageArgName) <> hide <> metavar "IMAGE" <> help "Exact Docker image ID (overrides docker-repo)") <|> pure Nothing) <*> firstBoolFlags (dockerOptName dockerRegistryLoginArgName) "registry requires login" hide <*> firstStrOption (long (dockerOptName dockerRegistryUsernameArgName) <> hide <> metavar "USERNAME" <> help "Docker registry username") <*> firstStrOption (long (dockerOptName dockerRegistryPasswordArgName) <> hide <> metavar "PASSWORD" <> help "Docker registry password") <*> firstBoolFlags (dockerOptName dockerAutoPullArgName) "automatic pulling latest version of image" hide <*> firstBoolFlags (dockerOptName dockerDetachArgName) "running a detached Docker container" hide <*> firstBoolFlags (dockerOptName dockerPersistArgName) "not deleting container after it exits" hide <*> firstStrOption (long (dockerOptName dockerContainerNameArgName) <> hide <> metavar "NAME" <> help "Docker container name") <*> argsOption (long (dockerOptName dockerRunArgsArgName) <> hide <> value [] <> metavar "'ARG1 [ARG2 ...]'" <> help "Additional options to pass to 'docker run'") <*> many (option auto (long (dockerOptName dockerMountArgName) <> hide <> metavar "(PATH | HOST-PATH:CONTAINER-PATH)" <> help ("Mount volumes from host in container " ++ "(may specify multiple times)"))) <*> many (option str (long (dockerOptName dockerEnvArgName) <> hide <> metavar "NAME=VALUE" <> help ("Set environment variable in container " ++ "(may specify multiple times)"))) <*> optionalFirst (absFileOption (long (dockerOptName dockerDatabasePathArgName) <> hide <> metavar "PATH" <> help "Location of image usage tracking database")) <*> optionalFirst (option (eitherReader' parseDockerStackExe) (long(dockerOptName dockerStackExeArgName) <> hide <> metavar (intercalate "|" [ dockerStackExeDownloadVal , dockerStackExeHostVal , dockerStackExeImageVal , "PATH" ]) <> help (concat [ "Location of " , stackProgName , " executable used in container" ]))) <*> firstBoolFlags (dockerOptName dockerSetUserArgName) "setting user in container to match host" hide <*> pure (IntersectingVersionRange anyVersion) where dockerOptName optName = dockerCmdName ++ "-" ++ T.unpack optName firstStrOption = optionalFirst . option str hide = hideMods hide0 -- | Parser for docker cleanup arguments. dockerCleanupOptsParser :: Parser Docker.CleanupOpts dockerCleanupOptsParser = Docker.CleanupOpts <$> (flag' Docker.CleanupInteractive (short 'i' <> long "interactive" <> help "Show cleanup plan in editor and allow changes (default)") <|> flag' Docker.CleanupImmediate (short 'y' <> long "immediate" <> help "Immediately execute cleanup plan") <|> flag' Docker.CleanupDryRun (short 'n' <> long "dry-run" <> help "Display cleanup plan but do not execute") <|> pure Docker.CleanupInteractive) <*> opt (Just 14) "known-images" "LAST-USED" <*> opt Nothing "unknown-images" "CREATED" <*> opt (Just 0) "dangling-images" "CREATED" <*> opt Nothing "stopped-containers" "CREATED" <*> opt Nothing "running-containers" "CREATED" where opt def' name mv = fmap Just (option auto (long name <> metavar (mv ++ "-DAYS-AGO") <> help ("Remove " ++ toDescr name ++ " " ++ map toLower (toDescr mv) ++ " N days ago" ++ case def' of Just n -> " (default " ++ show n ++ ")" Nothing -> ""))) <|> flag' Nothing (long ("no-" ++ name) <> help ("Do not remove " ++ toDescr name ++ case def' of Just _ -> "" Nothing -> " (default)")) <|> pure def' toDescr = map (\c -> if c == '-' then ' ' else c) -- | Parser for arguments to `stack dot` dotOptsParser :: Parser DotOpts dotOptsParser = DotOpts <$> includeExternal <*> includeBase <*> depthLimit <*> fmap (maybe Set.empty Set.fromList . fmap splitNames) prunedPkgs where includeExternal = boolFlags False "external" "inclusion of external dependencies" idm includeBase = boolFlags True "include-base" "inclusion of dependencies on base" idm depthLimit = optional (option auto (long "depth" <> metavar "DEPTH" <> help ("Limit the depth of dependency resolution " <> "(Default: No limit)"))) prunedPkgs = optional (strOption (long "prune" <> metavar "PACKAGES" <> help ("Prune each package name " <> "from the comma separated list " <> "of package names PACKAGES"))) splitNames :: String -> [String] splitNames = map (takeWhile (not . isSpace) . dropWhile isSpace) . splitOn "," ghciOptsParser :: Parser GhciOpts ghciOptsParser = GhciOpts <$> switch (long "no-build" <> help "Don't build before launching GHCi") <*> fmap concat (many (argsOption (long "ghci-options" <> metavar "OPTION" <> help "Additional options passed to GHCi"))) <*> optional (strOption (long "with-ghc" <> metavar "GHC" <> help "Use this GHC to run GHCi")) <*> (not <$> boolFlags True "load" "load modules on start-up" idm) <*> packagesParser <*> optional (textOption (long "main-is" <> metavar "TARGET" <> help "Specify which target should contain the main \ \module to load, such as for an executable for \ \test suite or benchmark.")) <*> switch (long "load-local-deps" <> help "Load all local dependencies of your targets") <*> switch (long "skip-intermediate-deps" <> help "Skip loading intermediate target dependencies") <*> boolFlags True "package-hiding" "package hiding" idm <*> buildOptsParser Build -- | Parser for exec command execOptsParser :: Maybe SpecialExecCmd -> Parser ExecOpts execOptsParser mcmd = ExecOpts <$> maybe eoCmdParser pure mcmd <*> eoArgsParser <*> execOptsExtraParser where eoCmdParser = ExecCmd <$> strArgument (metavar "CMD") eoArgsParser = many (strArgument (metavar "-- ARGS (e.g. stack ghc -- X.hs -o x)")) evalOptsParser :: String -- ^ metavar -> Parser EvalOpts evalOptsParser meta = EvalOpts <$> eoArgsParser <*> execOptsExtraParser where eoArgsParser :: Parser String eoArgsParser = strArgument (metavar meta) -- | Parser for extra options to exec command execOptsExtraParser :: Parser ExecOptsExtra execOptsExtraParser = eoPlainParser <|> ExecOptsEmbellished <$> eoEnvSettingsParser <*> eoPackagesParser where eoEnvSettingsParser :: Parser EnvSettings eoEnvSettingsParser = EnvSettings <$> pure True <*> boolFlags True "ghc-package-path" "setting the GHC_PACKAGE_PATH variable for the subprocess" idm <*> boolFlags True "stack-exe" "setting the STACK_EXE environment variable to the path for the stack executable" idm <*> pure False eoPackagesParser :: Parser [String] eoPackagesParser = many (strOption (long "package" <> help "Additional packages that must be installed")) eoPlainParser :: Parser ExecOptsExtra eoPlainParser = flag' ExecOptsPlain (long "plain" <> help "Use an unmodified environment (only useful with Docker)") -- | Parser for global command-line options. globalOptsParser :: GlobalOptsContext -> Maybe LogLevel -> Parser GlobalOptsMonoid globalOptsParser kind defLogLevel = GlobalOptsMonoid <$> optionalFirst (strOption (long Docker.reExecArgName <> hidden <> internal)) <*> optionalFirst (option auto (long dockerEntrypointArgName <> hidden <> internal)) <*> (First <$> logLevelOptsParser hide0 defLogLevel) <*> configOptsParser kind <*> optionalFirst (abstractResolverOptsParser hide0) <*> optionalFirst (compilerOptsParser hide0) <*> firstBoolFlags "terminal" "overriding terminal detection in the case of running in a false terminal" hide <*> optionalFirst (strOption (long "stack-yaml" <> metavar "STACK-YAML" <> help ("Override project stack.yaml file " <> "(overrides any STACK_YAML environment variable)") <> hide)) where hide = hideMods hide0 hide0 = kind /= OuterGlobalOpts -- | Create GlobalOpts from GlobalOptsMonoid. globalOptsFromMonoid :: Bool -> GlobalOptsMonoid -> GlobalOpts globalOptsFromMonoid defaultTerminal GlobalOptsMonoid{..} = GlobalOpts { globalReExecVersion = getFirst globalMonoidReExecVersion , globalDockerEntrypoint = getFirst globalMonoidDockerEntrypoint , globalLogLevel = fromFirst defaultLogLevel globalMonoidLogLevel , globalConfigMonoid = globalMonoidConfigMonoid , globalResolver = getFirst globalMonoidResolver , globalCompiler = getFirst globalMonoidCompiler , globalTerminal = fromFirst defaultTerminal globalMonoidTerminal , globalStackYaml = getFirst globalMonoidStackYaml } initOptsParser :: Parser InitOpts initOptsParser = InitOpts <$> searchDirs <*> solver <*> omitPackages <*> overwrite <*> fmap not ignoreSubDirs where searchDirs = many (textArgument (metavar "DIRS" <> help "Directories to include, default is current directory.")) ignoreSubDirs = switch (long "ignore-subdirs" <> help "Do not search for .cabal files in sub directories") overwrite = switch (long "force" <> help "Force overwriting an existing stack.yaml") omitPackages = switch (long "omit-packages" <> help "Exclude conflicting or incompatible user packages") solver = switch (long "solver" <> help "Use a dependency solver to determine extra dependencies") -- | Parser for a logging level. logLevelOptsParser :: Bool -> Maybe LogLevel -> Parser (Maybe LogLevel) logLevelOptsParser hide defLogLevel = fmap (Just . parse) (strOption (long "verbosity" <> metavar "VERBOSITY" <> help "Verbosity: silent, error, warn, info, debug" <> hideMods hide)) <|> flag' (Just verboseLevel) (short 'v' <> long "verbose" <> help ("Enable verbose mode: verbosity level \"" <> showLevel verboseLevel <> "\"") <> hideMods hide) <|> flag' (Just silentLevel) (long "silent" <> help ("Enable silent mode: verbosity level \"" <> showLevel silentLevel <> "\"") <> hideMods hide) <|> pure defLogLevel where verboseLevel = LevelDebug silentLevel = LevelOther "silent" showLevel l = case l of LevelDebug -> "debug" LevelInfo -> "info" LevelWarn -> "warn" LevelError -> "error" LevelOther x -> T.unpack x parse s = case s of "debug" -> LevelDebug "info" -> LevelInfo "warn" -> LevelWarn "error" -> LevelError _ -> LevelOther (T.pack s) -- | Parser for the resolver abstractResolverOptsParser :: Bool -> Parser AbstractResolver abstractResolverOptsParser hide = option readAbstractResolver (long "resolver" <> metavar "RESOLVER" <> help "Override resolver in project file" <> hideMods hide) readAbstractResolver :: ReadM AbstractResolver readAbstractResolver = do s <- readerAsk case s of "global" -> return ARGlobal "nightly" -> return ARLatestNightly "lts" -> return ARLatestLTS 'l':'t':'s':'-':x | Right (x', "") <- decimal $ T.pack x -> return $ ARLatestLTSMajor x' _ -> case parseResolverText $ T.pack s of Left e -> readerError $ show e Right x -> return $ ARResolver x compilerOptsParser :: Bool -> Parser CompilerVersion compilerOptsParser hide = option readCompilerVersion (long "compiler" <> metavar "COMPILER" <> help "Use the specified compiler" <> hideMods hide) readCompilerVersion :: ReadM CompilerVersion readCompilerVersion = do s <- readerAsk case parseCompilerVersion (T.pack s) of Nothing -> readerError $ "Failed to parse compiler: " ++ s Just x -> return x -- | GHC variant parser ghcVariantParser :: Bool -> Parser GHCVariant ghcVariantParser hide = option readGHCVariant (long "ghc-variant" <> metavar "VARIANT" <> help "Specialized GHC variant, e.g. integersimple (implies --no-system-ghc)" <> hideMods hide ) where readGHCVariant = do s <- readerAsk case parseGHCVariant s of Left e -> readerError (show e) Right v -> return v -- | Parser for @solverCmd@ solverOptsParser :: Parser Bool solverOptsParser = boolFlags False "update-config" "Automatically update stack.yaml with the solver's recommendations" idm -- | Parser for haddock arguments. haddockOptsParser :: Bool -> Parser HaddockOptsMonoid haddockOptsParser hide0 = HaddockOptsMonoid <$> fmap (fromMaybe []) (optional (argsOption (long "haddock-arguments" <> metavar "HADDOCK_ARGS" <> help "Arguments passed to the haddock program" <> hide))) where hide = hideMods hide0 -- | Parser for test arguments. -- FIXME hide args testOptsParser :: Bool -> Parser TestOptsMonoid testOptsParser hide0 = TestOptsMonoid <$> firstBoolFlags "rerun-tests" "running already successful tests" hide <*> fmap (fromMaybe []) (optional (argsOption (long "test-arguments" <> metavar "TEST_ARGS" <> help "Arguments passed in to the test suite program" <> hide))) <*> optionalFirst (switch (long "coverage" <> help "Generate a code coverage report" <> hide)) <*> optionalFirst (switch (long "no-run-tests" <> help "Disable running of tests. (Tests will still be built.)" <> hide)) where hide = hideMods hide0 -- | Parser for @stack new@. newOptsParser :: Parser (NewOpts,InitOpts) newOptsParser = (,) <$> newOpts <*> initOptsParser where newOpts = NewOpts <$> packageNameArgument (metavar "PACKAGE_NAME" <> help "A valid package name.") <*> switch (long "bare" <> help "Do not create a subdirectory for the project") <*> optional (templateNameArgument (metavar "TEMPLATE_NAME" <> help "Name of a template or a local template in a file or a URL.\ \ For example: foo or foo.hsfiles or ~/foo or\ \ https://example.com/foo.hsfiles")) <*> fmap M.fromList (many (templateParamArgument (short 'p' <> long "param" <> metavar "KEY:VALUE" <> help "Parameter for the template in the format key:value"))) -- | Parser for @stack hpc report@. hpcReportOptsParser :: Parser HpcReportOpts hpcReportOptsParser = HpcReportOpts <$> many (textArgument $ metavar "TARGET_OR_TIX") <*> switch (long "all" <> help "Use results from all packages and components") <*> optional (strOption (long "destdir" <> help "Output directy for HTML report")) pvpBoundsOption :: Parser PvpBounds pvpBoundsOption = option readPvpBounds (long "pvp-bounds" <> metavar "PVP-BOUNDS" <> help "How PVP version bounds should be added to .cabal file: none, lower, upper, both") where readPvpBounds = do s <- readerAsk case parsePvpBounds $ T.pack s of Left e -> readerError e Right v -> return v configCmdSetParser :: Parser ConfigCmdSet configCmdSetParser = fromM (do field <- oneM (strArgument (metavar "FIELD VALUE")) oneM (fieldToValParser field)) where fieldToValParser :: String -> Parser ConfigCmdSet fieldToValParser s = case s of "resolver" -> ConfigCmdSetResolver <$> argument readAbstractResolver idm _ -> error "parse stack config set field: only set resolver is implemented" -- | If argument is True, hides the option from usage and help hideMods :: Bool -> Mod f a hideMods hide = if hide then internal <> hidden else idm
AndrewRademacher/stack
src/Stack/Options.hs
bsd-3-clause
38,497
0
33
14,560
6,649
3,317
3,332
890
9
module LA ( module LA.Instances , module LA.Algebra , module LA.Epsilon , (~=) )where import qualified LA.Instances import LA.Epsilon import LA.Algebra (~=) :: (Additive a, Epsilon a) => a -> a -> Bool (~=) a b = closeToZero $ (a .- b)
chalmers-kandidat14/LA
LA.hs
bsd-3-clause
285
0
7
91
98
60
38
9
1
{-| FGL To Dot is an automatic translation and labeling of FGL graphs (see the 'Graph' class) to graphviz Dot format that can be written out to a file and displayed. @ let dot = showDot (fglToDot graph) writeFile \"file.dot\" dot system(\"dot -Tpng -ofile.png file.dot\") @ -} module Data.Graph.Inductive.Dot ( fglToDot, fglToDotString, fglToDotUnlabeled, fglToDotGeneric , showDot ) where import Control.Monad import Data.Graph.Inductive import Text.Dot -- |Generate a Dot graph using the show instances of the node and edge labels as displayed graph labels fglToDot :: (Show a, Show b, Graph gr) => gr a b -> Dot () fglToDot gr = fglToDotGeneric gr show show id -- |Generate a Dot graph using the Node and Edge strings as labels fglToDotString :: Graph gr => gr String String -> Dot () fglToDotString gr = fglToDotGeneric gr id id id -- |Generate a Dot graph without any edge or node labels fglToDotUnlabeled :: Graph gr => gr a b -> Dot () fglToDotUnlabeled gr = fglToDotGeneric gr undefined undefined (const []) -- |Generate a Dot graph using the provided functions to mutate the node labels, edge labels and list of attributes. fglToDotGeneric :: Graph gr => gr a b -> (a -> String) -> (b -> String) -> ([(String,String)] -> [(String,String)]) -> Dot () fglToDotGeneric gr nodeConv edgeConv attrConv = do let es = labEdges gr -- :: [(Int, Int, b)] ns = labNodes gr -- :: [(Int, a)] mapM_ (\(n,p) -> userNode (userNodeId n) (attrConv [("label", nodeConv p)])) ns mapM_ (\(a,b,p) -> edge (userNodeId a) (userNodeId b) (attrConv [("label", edgeConv p)])) es
TomMD/fgl-visualize
Data/Graph/Inductive/Dot.hs
bsd-3-clause
1,609
0
15
310
423
224
199
18
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Control.Lens import Control.Monad import Control.Monad.IO.Class (liftIO) import qualified Control.Exception as E import Data.Bool (bool) import Data.Either (isLeft) import qualified Data.Map as Map import Data.Maybe (catMaybes) import Data.Monoid ((<>)) import qualified Data.Text.Encoding as T import Reflex.Dom import Data.FileEmbed import qualified Data.Text as T import GHCJS.DOM.Types hiding (Event(..), Text(..)) import Data.String.QQ import AbsSyn import Interpreter import Parser import TypeChecker main :: IO () main = mainWidgetWithHead header $ divClass "content" $ do menu rec divClass "widget" $ do c <- codeBox ex fvgView c ex <- examplesPicker blank footer codeBox :: MonadWidget t m => Event t T.Text -> m (Dynamic t (Either E.SomeException Expr)) codeBox setText = divClass "code-box" $ do pb <- getPostBuild t <- fmap value $ textArea $ def & textAreaConfig_attributes .~ constDyn ("style" =: "width:500px;height:500px;") & textAreaConfig_setValue .~ setText & textAreaConfig_initialValue .~ code0 let evalTime = leftmost [tag (current t) pb, updated t] evals <- performEvent $ ffor evalTime $ \code -> liftJSM . liftIO . E.try . E.evaluate . runScript $ T.unpack code res <- holdDyn (Left $ E.SomeException (error "e" :: E.IOException)) evals divClass "error-message" $ dynText $ bool "" "There is a problem" . isLeft <$> res return res fvgView :: MonadWidget t m => Dynamic t (Either E.SomeException Expr) -> m () fvgView e = do srcdoc <- holdDyn "<h1>Waiting</h1>" (T.pack . show <$> fmapMaybe hush (updated e)) elDynAttr "iframe" (iframeAttrs <$> srcdoc) blank where iframeAttrs sd = "width" =: "500" <> "height" =: "500" <> "srcdoc" =: sd examplesPicker :: MonadWidget t m => m (Event t T.Text) examplesPicker = do dd <- dropdown "" (constDyn $ ("" =: "Examples") <> Map.fromList examples) def return $ _dropdown_change dd hush :: Either e a -> Maybe a hush (Left _) = Nothing hush (Right a) = Just a --Toggle the bool to work from an external stylesheet -- (much faster, if all you want to do is tweak the -- page style) header :: MonadWidget t m => m () header = if True then el "style" $ text (T.pack style) else elAttr "link" ("rel" =: "stylesheet" <> "href" =: "style.css" <> "type" =: "text/css" ) blank menu :: MonadWidget t m => m () menu = divClass "menu" $ do text "fvg" elAttr "a" ("href" =: "https://github.com/lemmih/fvg") -- (elAttr "img" ("src" =: "where's a link to octocat?") blank) (text "Github") footer :: MonadWidget t m => m () footer = blank examples :: [(T.Text, T.Text)] examples = filt $ $(embedDir "tests") where filt xs = do (fn, f) <- xs let ft = T.pack fn guard $ ".fvg" `T.isSuffixOf` ft return (T.decodeUtf8 f, ft) code0 :: T.Text code0 = T.unlines [ "data Bool = True | False" , "" ,"main : Int" ,"main =" ," case True of" ," True -> 1" ," False -> 0" ] style :: String style = [s| .menu { display: flex; flex-direction: row; justify-content: space-between; font-size: 16pt; padding-bottom: 20px; } .content { display: flex; flex-direction: column; padding: 10px; } .widget { display: flex; flex-direction: row; padding-bottom: 20px; } .code-box { position: relative; } .error-message { position: absolute; top: 20px; right: 20px; color: hsla(0, 50%, 50%, 1); } a { text-decoration: none; color: hsl(234, 35%, 53%); } html { width: 100%; height: 100%; padding: 0px; margin: 0px; } body { background-color: hsl(0,0%, 95%); font-family: Helvetica; display: flex; flex-direction: column; width: 100%; height: 100%; padding: 0px; margin: 0px; } textarea { /* background-color: rgba(0,0,0,0); */ background-color: hsl(0, 0%, 75%); color: hsl(240, 53%, 28%); border: none; resize: none; outline: none; font-family: "Lucida Console", Monaco, monospace; padding: 0px; padding-left: 10px; } iframe { border-style: solid; border: 0px; border-left: thick double rgba(0,0,0,0.25); } select { width: 400px; } |]
Lemmih/fvg
site/Main.hs
bsd-3-clause
4,954
0
17
1,576
1,081
558
523
102
2
----------------------------------------------------------------------------- -- | -- Module : Data.Pass.Trans -- Copyright : (C) 2012-2013 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : non-portable (GADTs, Rank2Types) -- ---------------------------------------------------------------------------- module Data.Pass.Trans ( Trans(..) ) where import Data.Typeable import Data.Monoid import Data.Binary -- import Data.Pass.Eval class Trans t where trans :: (Binary b, Monoid b, Typeable b) => k a b -> t k a b
ekmett/multipass
Data/Pass/Trans.hs
bsd-3-clause
645
0
9
105
94
57
37
7
0
module Graphics.UI.SDL.Event ( -- * Event Handling addEventWatch, delEventWatch, eventState, filterEvents, flushEvent, flushEvents, getEventFilter, getNumTouchDevices, getNumTouchFingers, getTouchDevice, getTouchFinger, hasEvent, hasEvents, loadDollarTemplates, peepEvents, pollEvent, pumpEvents, pushEvent, quitRequested, recordGesture, registerEvents, saveAllDollarTemplates, saveDollarTemplate, setEventFilter, waitEvent, waitEventTimeout, -- * Keyboard Support getKeyFromName, getKeyFromScancode, getKeyName, getKeyboardFocus, getKeyboardState, getModState, getScancodeFromKey, getScancodeFromName, getScancodeName, hasScreenKeyboardSupport, isScreenKeyboardShown, isTextInputActive, setModState, setTextInputRect, startTextInput, stopTextInput, -- * Mouse Support createColorCursor, createCursor, createSystemCursor, freeCursor, getCursor, getDefaultCursor, getMouseFocus, getMouseState, getRelativeMouseMode, getRelativeMouseState, setCursor, setRelativeMouseMode, showCursor, warpMouseInWindow, -- * Joystick Support joystickClose, joystickEventState, joystickGetAttached, joystickGetAxis, joystickGetBall, joystickGetButton, joystickGetDeviceGUID, joystickGetGUID, joystickGetGUIDFromString, joystickGetGUIDString, joystickGetHat, joystickInstanceID, joystickName, joystickNameForIndex, joystickNumAxes, joystickNumBalls, joystickNumButtons, joystickNumHats, joystickOpen, joystickUpdate, numJoysticks, -- * Game Controller Support gameControllerAddMapping, gameControllerAddMappingsFromFile, gameControllerAddMappingsFromRW, gameControllerClose, gameControllerEventState, gameControllerGetAttached, gameControllerGetAxis, gameControllerGetAxisFromString, gameControllerGetBindForAxis, gameControllerGetBindForButton, gameControllerGetButton, gameControllerGetButtonFromString, gameControllerGetJoystick, gameControllerGetStringForAxis, gameControllerGetStringForButton, gameControllerMapping, gameControllerMappingForGUID, gameControllerName, gameControllerNameForIndex, gameControllerOpen, gameControllerUpdate, isGameController ) where import Data.Int import Data.Word import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import Graphics.UI.SDL.Enum import Graphics.UI.SDL.Filesystem import Graphics.UI.SDL.Types foreign import ccall "SDL.h SDL_AddEventWatch" addEventWatch :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_DelEventWatch" delEventWatch :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_EventState" eventState :: Word32 -> CInt -> IO Word8 foreign import ccall "SDL.h SDL_FilterEvents" filterEvents :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_FlushEvent" flushEvent :: Word32 -> IO () foreign import ccall "SDL.h SDL_FlushEvents" flushEvents :: Word32 -> Word32 -> IO () foreign import ccall "SDL.h SDL_GetEventFilter" getEventFilter :: Ptr EventFilter -> Ptr (Ptr ()) -> IO Bool foreign import ccall "SDL.h SDL_GetNumTouchDevices" getNumTouchDevices :: IO CInt foreign import ccall "SDL.h SDL_GetNumTouchFingers" getNumTouchFingers :: TouchID -> IO CInt foreign import ccall "SDL.h SDL_GetTouchDevice" getTouchDevice :: CInt -> IO TouchID foreign import ccall "SDL.h SDL_GetTouchFinger" getTouchFinger :: TouchID -> CInt -> IO (Ptr Finger) foreign import ccall "SDL.h SDL_HasEvent" hasEvent :: Word32 -> IO Bool foreign import ccall "SDL.h SDL_HasEvents" hasEvents :: Word32 -> Word32 -> IO Bool foreign import ccall "SDL.h SDL_LoadDollarTemplates" loadDollarTemplates :: TouchID -> Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_PeepEvents" peepEvents :: Ptr Event -> CInt -> EventAction -> Word32 -> Word32 -> IO CInt foreign import ccall "SDL.h SDL_PollEvent" pollEvent :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_PumpEvents" pumpEvents :: IO () foreign import ccall "SDL.h SDL_PushEvent" pushEvent :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_RecordGesture" recordGesture :: TouchID -> IO CInt foreign import ccall "SDL.h SDL_RegisterEvents" registerEvents :: CInt -> IO Word32 foreign import ccall "SDL.h SDL_SaveAllDollarTemplates" saveAllDollarTemplates :: Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_SaveDollarTemplate" saveDollarTemplate :: GestureID -> Ptr RWops -> IO CInt foreign import ccall "SDL.h SDL_SetEventFilter" setEventFilter :: EventFilter -> Ptr () -> IO () foreign import ccall "SDL.h SDL_WaitEvent" waitEvent :: Ptr Event -> IO CInt foreign import ccall "SDL.h SDL_WaitEventTimeout" waitEventTimeout :: Ptr Event -> CInt -> IO CInt foreign import ccall "SDL.h SDL_GetKeyFromName" getKeyFromName :: CString -> IO Keycode foreign import ccall "SDL.h SDL_GetKeyFromScancode" getKeyFromScancode :: Scancode -> IO Keycode foreign import ccall "SDL.h SDL_GetKeyName" getKeyName :: Keycode -> IO CString foreign import ccall "SDL.h SDL_GetKeyboardFocus" getKeyboardFocus :: IO Window foreign import ccall "SDL.h SDL_GetKeyboardState" getKeyboardState :: Ptr CInt -> IO (Ptr Word8) foreign import ccall "SDL.h SDL_GetModState" getModState :: IO Keymod foreign import ccall "SDL.h SDL_GetScancodeFromKey" getScancodeFromKey :: Keycode -> IO Scancode foreign import ccall "SDL.h SDL_GetScancodeFromName" getScancodeFromName :: CString -> IO Scancode foreign import ccall "SDL.h SDL_GetScancodeName" getScancodeName :: Scancode -> IO CString foreign import ccall "SDL.h SDL_HasScreenKeyboardSupport" hasScreenKeyboardSupport :: IO Bool foreign import ccall "SDL.h SDL_IsScreenKeyboardShown" isScreenKeyboardShown :: Window -> IO Bool foreign import ccall "SDL.h SDL_IsTextInputActive" isTextInputActive :: IO Bool foreign import ccall "SDL.h SDL_SetModState" setModState :: Keymod -> IO () foreign import ccall "SDL.h SDL_SetTextInputRect" setTextInputRect :: Ptr Rect -> IO () foreign import ccall "SDL.h SDL_StartTextInput" startTextInput :: IO () foreign import ccall "SDL.h SDL_StopTextInput" stopTextInput :: IO () foreign import ccall "SDL.h SDL_CreateColorCursor" createColorCursor :: Ptr Surface -> CInt -> CInt -> IO Cursor foreign import ccall "SDL.h SDL_CreateCursor" createCursor :: Ptr Word8 -> Ptr Word8 -> CInt -> CInt -> CInt -> CInt -> IO Cursor foreign import ccall "SDL.h SDL_CreateSystemCursor" createSystemCursor :: SystemCursor -> IO Cursor foreign import ccall "SDL.h SDL_FreeCursor" freeCursor :: Cursor -> IO () foreign import ccall "SDL.h SDL_GetCursor" getCursor :: IO Cursor foreign import ccall "SDL.h SDL_GetDefaultCursor" getDefaultCursor :: IO Cursor foreign import ccall "SDL.h SDL_GetMouseFocus" getMouseFocus :: IO Window foreign import ccall "SDL.h SDL_GetMouseState" getMouseState :: Ptr CInt -> Ptr CInt -> IO Word32 foreign import ccall "SDL.h SDL_GetRelativeMouseMode" getRelativeMouseMode :: IO Bool foreign import ccall "SDL.h SDL_GetRelativeMouseState" getRelativeMouseState :: Ptr CInt -> Ptr CInt -> IO Word32 foreign import ccall "SDL.h SDL_SetCursor" setCursor :: Cursor -> IO () foreign import ccall "SDL.h SDL_SetRelativeMouseMode" setRelativeMouseMode :: Bool -> IO CInt foreign import ccall "SDL.h SDL_ShowCursor" showCursor :: CInt -> IO CInt foreign import ccall "SDL.h SDL_WarpMouseInWindow" warpMouseInWindow :: Window -> CInt -> CInt -> IO () foreign import ccall "SDL.h SDL_JoystickClose" joystickClose :: Joystick -> IO () foreign import ccall "SDL.h SDL_JoystickEventState" joystickEventState :: CInt -> IO CInt foreign import ccall "SDL.h SDL_JoystickGetAttached" joystickGetAttached :: Joystick -> IO Bool foreign import ccall "SDL.h SDL_JoystickGetAxis" joystickGetAxis :: Joystick -> CInt -> IO Int16 foreign import ccall "SDL.h SDL_JoystickGetBall" joystickGetBall :: Joystick -> CInt -> Ptr CInt -> Ptr CInt -> IO CInt foreign import ccall "SDL.h SDL_JoystickGetButton" joystickGetButton :: Joystick -> CInt -> IO Word8 foreign import ccall "sdlhelper.h SDLHelper_JoystickGetDeviceGUID" joystickGetDeviceGUID' :: CInt -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUID" joystickGetGUID' :: Joystick -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDFromString" joystickGetGUIDFromString' :: CString -> Ptr JoystickGUID -> IO () foreign import ccall "sdlhelper.h SDLHelper_JoystickGetGUIDString" joystickGetGUIDString' :: Ptr JoystickGUID -> CString -> CInt -> IO () foreign import ccall "SDL.h SDL_JoystickGetHat" joystickGetHat :: Joystick -> CInt -> IO Word8 foreign import ccall "SDL.h SDL_JoystickInstanceID" joystickInstanceID :: Joystick -> IO JoystickID foreign import ccall "SDL.h SDL_JoystickName" joystickName :: Joystick -> IO CString foreign import ccall "SDL.h SDL_JoystickNameForIndex" joystickNameForIndex :: CInt -> IO CString foreign import ccall "SDL.h SDL_JoystickNumAxes" joystickNumAxes :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumBalls" joystickNumBalls :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumButtons" joystickNumButtons :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickNumHats" joystickNumHats :: Joystick -> IO CInt foreign import ccall "SDL.h SDL_JoystickOpen" joystickOpen :: CInt -> IO Joystick foreign import ccall "SDL.h SDL_JoystickUpdate" joystickUpdate :: IO () foreign import ccall "SDL.h SDL_NumJoysticks" numJoysticks :: IO CInt foreign import ccall "SDL.h SDL_GameControllerAddMapping" gameControllerAddMapping :: CString -> IO CInt foreign import ccall "SDL.h SDL_GameControllerAddMappingsFromRW" gameControllerAddMappingsFromRW :: Ptr RWops -> CInt -> IO CInt foreign import ccall "SDL.h SDL_GameControllerClose" gameControllerClose :: GameController -> IO () foreign import ccall "SDL.h SDL_GameControllerEventState" gameControllerEventState :: CInt -> IO CInt foreign import ccall "SDL.h SDL_GameControllerGetAttached" gameControllerGetAttached :: GameController -> IO Bool foreign import ccall "SDL.h SDL_GameControllerGetAxis" gameControllerGetAxis :: GameController -> GameControllerAxis -> IO Int16 foreign import ccall "SDL.h SDL_GameControllerGetAxisFromString" gameControllerGetAxisFromString :: CString -> IO GameControllerAxis foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForAxis" gameControllerGetBindForAxis' :: GameController -> GameControllerAxis -> Ptr GameControllerButtonBind -> IO () foreign import ccall "sdlhelper.h SDLHelper_GameControllerGetBindForButton" gameControllerGetBindForButton' :: GameController -> GameControllerButton -> Ptr GameControllerButtonBind -> IO () foreign import ccall "SDL.h SDL_GameControllerGetButton" gameControllerGetButton :: GameController -> GameControllerButton -> IO Word8 foreign import ccall "SDL.h SDL_GameControllerGetButtonFromString" gameControllerGetButtonFromString :: CString -> IO GameControllerButton foreign import ccall "SDL.h SDL_GameControllerGetJoystick" gameControllerGetJoystick :: GameController -> IO Joystick foreign import ccall "SDL.h SDL_GameControllerGetStringForAxis" gameControllerGetStringForAxis :: GameControllerAxis -> IO CString foreign import ccall "SDL.h SDL_GameControllerGetStringForButton" gameControllerGetStringForButton :: GameControllerButton -> IO CString foreign import ccall "SDL.h SDL_GameControllerMapping" gameControllerMapping :: GameController -> IO CString foreign import ccall "sdlhelper.h SDLHelper_GameControllerMappingForGUID" gameControllerMappingForGUID' :: Ptr JoystickGUID -> IO CString foreign import ccall "SDL.h SDL_GameControllerName" gameControllerName :: GameController -> IO CString foreign import ccall "SDL.h SDL_GameControllerNameForIndex" gameControllerNameForIndex :: CInt -> IO CString foreign import ccall "SDL.h SDL_GameControllerOpen" gameControllerOpen :: CInt -> IO GameController foreign import ccall "SDL.h SDL_GameControllerUpdate" gameControllerUpdate :: IO () foreign import ccall "SDL.h SDL_IsGameController" isGameController :: CInt -> IO Bool quitRequested :: IO Bool quitRequested = do pumpEvents ev <- peepEvents nullPtr 0 SDL_PEEKEVENT SDL_QUIT SDL_QUIT return $ ev > 0 joystickGetDeviceGUID :: CInt -> IO JoystickGUID joystickGetDeviceGUID device_index = alloca $ \ptr -> do joystickGetDeviceGUID' device_index ptr peek ptr joystickGetGUID :: Joystick -> IO JoystickGUID joystickGetGUID joystick = alloca $ \ptr -> do joystickGetGUID' joystick ptr peek ptr joystickGetGUIDFromString :: CString -> IO JoystickGUID joystickGetGUIDFromString pchGUID = alloca $ \ptr -> do joystickGetGUIDFromString' pchGUID ptr peek ptr joystickGetGUIDString :: JoystickGUID -> CString -> CInt -> IO () joystickGetGUIDString guid pszGUID cbGUID = alloca $ \ptr -> do poke ptr guid joystickGetGUIDString' ptr pszGUID cbGUID gameControllerAddMappingsFromFile :: CString -> IO CInt gameControllerAddMappingsFromFile file = do rw <- withCString "rb" $ rwFromFile file gameControllerAddMappingsFromRW rw 1 gameControllerGetBindForAxis :: GameController -> GameControllerAxis -> IO GameControllerButtonBind gameControllerGetBindForAxis gamecontroller axis = alloca $ \ptr -> do gameControllerGetBindForAxis' gamecontroller axis ptr peek ptr gameControllerGetBindForButton :: GameController -> GameControllerButton -> IO GameControllerButtonBind gameControllerGetBindForButton gamecontroller button = alloca $ \ptr -> do gameControllerGetBindForButton' gamecontroller button ptr peek ptr gameControllerMappingForGUID :: JoystickGUID -> IO CString gameControllerMappingForGUID guid = alloca $ \ptr -> do poke ptr guid gameControllerMappingForGUID' ptr
ekmett/sdl2
Graphics/UI/SDL/Event.hs
bsd-3-clause
13,572
198
12
1,640
3,132
1,647
1,485
244
1
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveDataTypeable #-} #if __GLASGOW_HASKELL__ >= 707 {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE KindSignatures #-} #endif -- | Functions for building queries on cabal's setup-config an evaluating them. module Distribution.Client.Dynamic.Query ( Selector(), selector , Query(), query , LocalBuildInfo() , maybeDefault , (>>>=), (=<<<) , fmapS , fmapQ , on , runQuery , runRawQuery , getCabalVersion ) where import Control.Applicative import Control.Category import qualified Control.Exception as E import Control.Monad import Data.Version import Data.Void import qualified DynFlags import qualified GHC import qualified GHC.Paths import Language.Haskell.Exts.Syntax import Language.Haskell.Generate import qualified MonadUtils import Prelude hiding (id, (.)) import System.Directory import System.FilePath import System.IO.Error (isAlreadyExistsError) import Text.ParserCombinators.ReadP #if __GLASGOW_HASKELL__ >= 708 import Data.Dynamic hiding (Typeable1) #else import Data.Dynamic #endif #if __GLASGOW_HASKELL__ >= 707 type Typeable1 (f :: * -> *) = Typeable f #endif -- | This is just a dummy type representing a LocalBuildInfo. You don't have to use -- this type, it is just used to tag queries and make them more type-safe. data LocalBuildInfo = LocalBuildInfo Void deriving (Typeable, Read) -- | A selector is a generator for a function of type i -> o. newtype Selector i o = Selector (Version -> ExpG (i -> o)) instance Category Selector where id = Selector $ const id' Selector a . Selector b = Selector $ liftA2 (<>.) a b -- | Compose two selectors, monadically. (=<<<) :: Monad m => Selector b (m c) -> Selector a (m b) -> Selector a (m c) Selector s =<<< Selector t = Selector $ \v -> applyE (flip' <>$ bind') (s v) <>. t v -- | The same as (=<<<), but flipped. (>>>=) :: Monad m => Selector a (m b) -> Selector b (m c) -> Selector a (m c) (>>>=) = flip (=<<<) -- | Lift a selector to work on functorial inputs and outputs. fmapS :: Functor m => Selector a b -> Selector (m a) (m b) fmapS (Selector s) = Selector $ \v -> applyE fmap' (s v) -- | Zip together two selector that work on the same input. This is the equavilent of liftA2 (,) for selectors. zipSelector :: Selector i o -> Selector i p -> Selector i (o,p) zipSelector (Selector s) (Selector t) = Selector $ \v -> expr $ \i -> applyE2 tuple2 (s v <>$ i) (t v <>$ i) -- | A Selector to get something out of a Maybe if you supply a default value. maybeDefault :: (GenExpType a ~ a, GenExp a) => a -> Selector (Maybe a) a maybeDefault a = selector $ const $ applyE (flip' <>$ maybe' <>$ id') $ expr a -- | Build a selector. The expression the selector generates can depend on the cabal version. selector :: (Version -> ExpG (i -> o)) -> Selector i o selector = Selector -- | A query is like a Selector, but it cannot be composed any futher using a Category instance. -- It can have a Functor and Applicative instance though. -- To execute a query, you only need to run GHC once. data Query s a = forall i. Typeable i => Query (Selector s i) (i -> a) instance Functor (Query s) where fmap f (Query s x) = Query s $ f . x instance Applicative (Query s) where pure = Query (selector $ const $ const' <>$ tuple0) . const Query f getF <*> Query a getA = Query (zipSelector f a) $ \(fv, av) -> getF fv $ getA av -- | Build a query from a selector. query :: Typeable a => Selector s a -> Query s a query = flip Query id -- | Lift a query to work over functors. fmapQ :: (Functor f, Typeable1 f) => Query s a -> Query (f s) (f a) fmapQ (Query s f) = Query (fmapS s) (fmap f) -- | Use a selector to run a query in a bigger environment than it was defined in. on :: Selector i o -> Query o r -> Query i r on s (Query sq f) = Query (sq . s) f getRunDirectory :: IO FilePath getRunDirectory = getTemporaryDirectory >>= go 0 where go :: Integer -> FilePath -> IO FilePath go !c dir = do let cdir = dir </> "dynamic-cabal" <.> show c res <- E.try $ createDirectory cdir case res of Left e | isAlreadyExistsError e -> go (c + 1) dir | otherwise -> E.throwIO e Right () -> return cdir getCabalVersion :: FilePath -> IO Version getCabalVersion setupConfig = do versionString <- dropWhile (not . flip elem ['0'..'9']) . (!! 7) . words . head . lines <$> readFile setupConfig case filter (null . snd) $ readP_to_S parseVersion versionString of [(v,_)] -> return v _ -> E.throwIO $ userError "Couldn't parse version" data LeftoverTempDir e = LeftoverTempDir FilePath e deriving Typeable instance Show e => Show (LeftoverTempDir e) where show (LeftoverTempDir dir e) = "Left over temporary directory not removed: " ++ dir ++ "\n" ++ show e instance E.Exception e => E.Exception (LeftoverTempDir e) withTempWorkingDir :: IO a -> IO a withTempWorkingDir act = do pwd <- getCurrentDirectory tmp <- getRunDirectory setCurrentDirectory tmp res <- act `E.catch` \(E.SomeException e) -> setCurrentDirectory pwd >> E.throwIO (LeftoverTempDir tmp e) setCurrentDirectory pwd res <$ removeDirectoryRecursive tmp getConfigStateFile :: ExpG (FilePath -> IO LocalBuildInfo) getConfigStateFile = useValue "Distribution.Simple.Configure" $ Ident "getConfigStateFile" generateSource :: Selector LocalBuildInfo o -> String -> FilePath -> Version -> IO String generateSource (Selector s) modName setupConfig version = return $ flip generateModule modName $ do getLBI <- addDecl (Ident "getLBI") $ if version < Version [1,21] [] then applyE fmap' (read' <>. unlines' <>. applyE drop' 1 <>. lines' :: ExpG (String -> LocalBuildInfo)) <>$ applyE readFile' (expr setupConfig) else getConfigStateFile <>$ expr setupConfig result <- addDecl (Ident "result") $ applyE fmap' (s version) <>$ expr getLBI return $ Just [exportFun result] -- | Run a query. This will generate the source code for the query and then invoke GHC to run it. runQuery :: Query LocalBuildInfo a -> FilePath -> IO a runQuery (Query s post) setupConfig = do setupConfig' <- canonicalizePath setupConfig version <- getCabalVersion setupConfig' src<- generateSource s "DynamicCabalQuery" setupConfig' version runRawQuery' src setupConfig post -- | Run a raw query, getting the full source from the first parameter -- the module must be DynamicCabalQuery and it must have a result declaration runRawQuery :: Typeable a => String -> FilePath -> IO a runRawQuery s setupConfig = runRawQuery' s setupConfig id -- | Run a raw query, getting the full source from the first parameter. -- The module must be DynamicCabalQuery and it must have a result declaration. -- The third argument is a function to apply to the result of running the query. runRawQuery' :: Typeable i => String -> FilePath -> (i -> a) -> IO a runRawQuery' s setupConfig post = do setupConfig' <- canonicalizePath setupConfig withTempWorkingDir $ do version <- getCabalVersion setupConfig' writeFile "DynamicCabalQuery.hs" s GHC.runGhc (Just GHC.Paths.libdir) $ do dflags <- GHC.getSessionDynFlags let cabalPkg = "Cabal-" ++ showVersion version #if __GLASGOW_HASKELL__ >= 709 let cabalFlag = DynFlags.ExposePackage (DynFlags.PackageArg cabalPkg) (DynFlags.ModRenaming True []) #else let cabalFlag = DynFlags.ExposePackage cabalPkg #endif void $ GHC.setSessionDynFlags $ dflags { GHC.ghcLink = GHC.LinkInMemory , GHC.hscTarget = GHC.HscInterpreted , GHC.packageFlags = [cabalFlag] , GHC.ctxtStkDepth = 1000 } dflags' <- GHC.getSessionDynFlags GHC.defaultCleanupHandler dflags' $ do target <- GHC.guessTarget "DynamicCabalQuery.hs" Nothing GHC.setTargets [target] void $ GHC.load GHC.LoadAllTargets GHC.setContext [GHC.IIDecl $ GHC.simpleImportDecl $ GHC.mkModuleName "DynamicCabalQuery"] GHC.dynCompileExpr "result" >>= maybe (fail "dynamic-cabal: runQuery: Result expression has wrong type") (MonadUtils.liftIO . fmap post) . fromDynamic
bennofs/dynamic-cabal
src/Distribution/Client/Dynamic/Query.hs
bsd-3-clause
8,426
0
21
1,807
2,356
1,200
1,156
142
2
module B.Shake.Core.Action ( Action , apply , apply1 , actionOnException , actionFinally ) where import B.Shake.Core.Action.Internal (Action(..)) import B.Shake.Core.Rule.Internal (Rule, RuleKey(..)) import qualified B.Build as B apply :: (Rule key value) => [key] -> Action [value] apply keys = Action $ B.needs qs where qs = map RuleKey keys apply1 :: (Rule key value) => key -> Action value apply1 key = Action $ B.need (RuleKey key) actionOnException :: Action a -> IO b -> Action a actionOnException = error "Unimplemented: B.Shake.Action.actionOnException" actionFinally :: Action a -> IO b -> Action a actionFinally = error "Unimplemented: B.Shake.Action.actionFinally"
strager/b-shake
B/Shake/Core/Action.hs
bsd-3-clause
700
0
8
120
234
130
104
18
1
{-# LANGUAGE OverloadedStrings #-} module Test.Indices where import Test.Common import Test.Import import qualified Data.List as L import qualified Data.List.NonEmpty as NE import qualified Data.Map as M spec :: Spec spec = do describe "Index create/delete API" $ do it "creates and then deletes the requested index" $ withTestEnv $ do -- priming state. _ <- deleteExampleIndex resp <- createExampleIndex deleteResp <- deleteExampleIndex liftIO $ do validateStatus resp 200 validateStatus deleteResp 200 describe "Index aliases" $ do let aname = IndexAliasName (IndexName "bloodhound-tests-twitter-1-alias") let alias = IndexAlias (testIndex) aname let create = IndexAliasCreate Nothing Nothing let action = AddAlias alias create it "handles the simple case of aliasing an existing index" $ do withTestEnv $ do resetIndex resp <- updateIndexAliases (action :| []) liftIO $ validateStatus resp 200 let cleanup = withTestEnv (updateIndexAliases (RemoveAlias alias :| [])) (do aliases <- withTestEnv getIndexAliases let expected = IndexAliasSummary alias create case aliases of Right (IndexAliasesSummary summs) -> L.find ((== alias) . indexAliasSummaryAlias) summs `shouldBe` Just expected Left e -> expectationFailure ("Expected an IndexAliasesSummary but got " <> show e)) `finally` cleanup it "allows alias deletion" $ do aliases <- withTestEnv $ do resetIndex resp <- updateIndexAliases (action :| []) liftIO $ validateStatus resp 200 _ <- deleteIndexAlias aname getIndexAliases -- let expected = IndexAliasSummary alias create case aliases of Right (IndexAliasesSummary summs) -> L.find ( (== aname) . indexAlias . indexAliasSummaryAlias ) summs `shouldBe` Nothing Left e -> expectationFailure ("Expected an IndexAliasesSummary but got " <> show e) describe "Index Listing" $ do it "returns a list of index names" $ withTestEnv $ do _ <- createExampleIndex ixns <- listIndices liftIO (ixns `shouldContain` [testIndex]) describe "Index Settings" $ do it "persists settings" $ withTestEnv $ do _ <- deleteExampleIndex _ <- createExampleIndex let updates = BlocksWrite False :| [] updateResp <- updateIndexSettings updates testIndex liftIO $ validateStatus updateResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) (NE.toList updates)) it "allows total fields to be set" $ withTestEnv $ do _ <- deleteExampleIndex _ <- createExampleIndex let updates = MappingTotalFieldsLimit 2500 :| [] updateResp <- updateIndexSettings updates testIndex liftIO $ validateStatus updateResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) (NE.toList updates)) it "allows unassigned.node_left.delayed_timeout to be set" $ withTestEnv $ do _ <- deleteExampleIndex _ <- createExampleIndex let updates = UnassignedNodeLeftDelayedTimeout 10 :| [] updateResp <- updateIndexSettings updates testIndex liftIO $ validateStatus updateResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) (NE.toList updates)) it "accepts customer analyzers" $ withTestEnv $ do _ <- deleteExampleIndex let analysis = Analysis (M.singleton "ex_analyzer" ( AnalyzerDefinition (Just (Tokenizer "ex_tokenizer")) (map TokenFilter [ "ex_filter_lowercase","ex_filter_uppercase","ex_filter_apostrophe" , "ex_filter_reverse","ex_filter_snowball" , "ex_filter_shingle" ] ) (map CharFilter ["html_strip", "ex_mapping", "ex_pattern_replace"] ) ) ) (M.singleton "ex_tokenizer" ( TokenizerDefinitionNgram ( Ngram 3 4 [TokenLetter,TokenDigit]) ) ) (M.fromList [ ("ex_filter_lowercase",TokenFilterDefinitionLowercase (Just Greek)) , ("ex_filter_uppercase",TokenFilterDefinitionUppercase Nothing) , ("ex_filter_apostrophe",TokenFilterDefinitionApostrophe) , ("ex_filter_reverse",TokenFilterDefinitionReverse) , ("ex_filter_snowball",TokenFilterDefinitionSnowball English) , ("ex_filter_shingle",TokenFilterDefinitionShingle (Shingle 3 3 True False " " "_")) , ("ex_filter_stemmer",TokenFilterDefinitionStemmer German) , ("ex_filter_stop1", TokenFilterDefinitionStop (Left French)) , ("ex_filter_stop2", TokenFilterDefinitionStop (Right $ map StopWord ["a", "is", "the"])) ] ) (M.fromList [ ("ex_mapping", CharFilterDefinitionMapping (M.singleton "١" "1")) , ("ex_pattern_replace", CharFilterDefinitionPatternReplace "(\\d+)-(?=\\d)" "$1_" Nothing) ] ) updates = [AnalysisSetting analysis] createResp <- createIndexWith (updates ++ [NumberOfReplicas (ReplicaCount 0)]) 1 testIndex liftIO $ validateStatus createResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) updates ) it "accepts default compression codec" $ withTestEnv $ do _ <- deleteExampleIndex let updates = [CompressionSetting CompressionDefault] createResp <- createIndexWith (updates ++ [NumberOfReplicas (ReplicaCount 0)]) 1 testIndex liftIO $ validateStatus createResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) updates) it "accepts best compression codec" $ withTestEnv $ do _ <- deleteExampleIndex let updates = [CompressionSetting CompressionBest] createResp <- createIndexWith (updates ++ [NumberOfReplicas (ReplicaCount 0)]) 1 testIndex liftIO $ validateStatus createResp 200 getResp <- getIndexSettings testIndex liftIO $ getResp `shouldBe` Right (IndexSettingsSummary testIndex (IndexSettings (ShardCount 1) (ReplicaCount 0)) updates) describe "Index Optimization" $ do it "returns a successful response upon completion" $ withTestEnv $ do _ <- createExampleIndex resp <- forceMergeIndex (IndexList (testIndex :| [])) defaultForceMergeIndexSettings liftIO $ validateStatus resp 200 describe "Index flushing" $ do it "returns a successful response upon flushing" $ withTestEnv $ do _ <- createExampleIndex resp <- flushIndex testIndex liftIO $ validateStatus resp 200
bitemyapp/bloodhound
tests/Test/Indices.hs
bsd-3-clause
7,889
0
25
2,498
1,851
891
960
157
3
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UndecidableInstances #-} module FPNLA.Utils ( iif, mapPair, splitSlice, prevEnum, nextEnum, enumerate, ) where mapPair :: (a -> b) -> (c -> d)-> (a, c) -> (b, d) mapPair f g (a, c) = (f a, g c) -- inline if iif :: Bool -> a -> a -> a iif cond expTrue expFalse = if cond then expTrue else expFalse -- Parte la lista parametro en trozos de tamaño 'n'. El último puede ser mas pequeño si no existe k tal que length ls = k * n. splitSlice :: Int -> [a] -> [[a]] splitSlice 0 _ = error "El tamaño de n debe ser > 0" splitSlice _ [] = [] splitSlice n ls = sl : splitSlice n sls where (sl, sls) = splitAt n ls prevEnum :: (Eq a, Bounded a, Enum a) => a -> a prevEnum a | a == minBound = maxBound | otherwise = pred a nextEnum :: (Eq a, Bounded a, Enum a) => a -> a nextEnum a | a == maxBound = minBound | otherwise = succ a -- Devuelve una lista con los elementos de cualquier tipo que sea instancia de Enum y Bounded. enumerate :: forall a. (Enum a, Bounded a) => [a] enumerate = map toEnum [fromEnum (minBound :: a) .. fromEnum (maxBound :: a)]
mauroblanco/fpnla-examples
src/FPNLA/Utils.hs
bsd-3-clause
1,242
0
8
296
413
224
189
28
2
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-} module Development.Shake.Binary( BinaryWith(..), module Data.Binary ) where import Control.Monad import Data.Binary class BinaryWith ctx a where putWith :: ctx -> a -> Put getWith :: ctx -> Get a instance (BinaryWith ctx a, BinaryWith ctx b) => BinaryWith ctx (a,b) where putWith ctx (a,b) = putWith ctx a >> putWith ctx b getWith ctx = do a <- getWith ctx; b <- getWith ctx; return (a,b) instance BinaryWith ctx a => BinaryWith ctx [a] where putWith ctx xs = put (length xs) >> mapM_ (putWith ctx) xs getWith ctx = do n <- get; replicateM n $ getWith ctx instance BinaryWith ctx a => BinaryWith ctx (Maybe a) where putWith ctx Nothing = putWord8 0 putWith ctx (Just x) = putWord8 1 >> putWith ctx x getWith ctx = do i <- getWord8; if i == 0 then return Nothing else fmap Just $ getWith ctx
nh2/shake
Development/Shake/Binary.hs
bsd-3-clause
899
0
10
201
371
186
185
18
0
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeInType #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UnboxedTuples #-} {-# LANGUAGE UndecidableInstances #-} {- | Module : Numeric.PrimBytes Copyright : (c) Artem Chirkin License : BSD3 Facilities for converting Haskell data to and from raw bytes. The main purpose of this module is to support the implementation of the @DataFrame@ `Numeric.DataFrame.Internal.Backend.Backend`. However, it also comes very useful for writing FFI. To that end, the `PrimBytes` class is similar to the `Foreign.Storable.Storable` class: it provides means to write your data to and read from a raw memory area. Though, it is more flexible in that it can work with both, foreign pointers and primitive byte arrays, and it provides means to get data field offsets by their selector names. On top of that, a `PrimBytes` instance can be derived via the `GHC.Generics.Generic` machinery. A derived `PrimBytes` instance tries to pack the data as dense as possible, while respecting the alignment requirements. In all cases known to me, the resulting data layout coincides with a corresponding C struct, allowing to marshal the data without any boilerplate. However, this is not guaranteed, but you can write a `PrimBytes` instance manually if necessary (and report an issue plz). __Note about alignment, size, and padding of the data.__ There are two basic sanity assumptions about these, which are not checked in this module at all: * the alignment is always a power of 2; * the size is always rounded up to a multiple of the alignment. Generated instances of `PrimBytes` meet these assumptions if all components of a data meet these assumptions too. You are strongly advised to provide all byte offset arguments to the `PrimBytes` functions respecting the alignment of the data; otherwise, the data may be written or read incorrectly. -} module Numeric.PrimBytes ( -- * PrimBytes API PrimBytes (..) , bSizeOf, bAlignOf, bFieldOffsetOf -- * Storable API -- -- | -- `Foreign.Storable.Storable` can be defined in terms of `PrimBytes` -- by doing something like the following for your data type: -- -- @ -- instance PrimBytes a => Storable a where -- sizeOf = bSizeOf -- alignment = bAlignOf -- peekElemOff = bPeekElemOff -- pokeElemOff = bPokeElemOff -- peekByteOff = bPeekByteOff -- pokeByteOff = bPokeByteOff -- peek = bPeek -- poke = bPoke -- @ , bPeekElemOff, bPokeElemOff, bPeekByteOff, bPokeByteOff, bPeek, bPoke -- * Specialization tools , PrimTag (..), primTag ) where #include "MachDeps.h" import Data.Kind (Type) import Data.Proxy (Proxy (..)) import Data.Type.Equality ((:~:) (..)) import qualified Data.Type.List as L import Data.Type.Lits import Foreign.C.Types import GHC.Exts import GHC.Generics import GHC.Int import GHC.IO (IO (..)) import GHC.Stable import GHC.Word import Numeric.Dimensions import qualified Numeric.Tuple.Lazy as TL import qualified Numeric.Tuple.Strict as TS import Text.Read (readMaybe) {- | Defines how to read and write your data to and from Haskell unboxed byte arrays and plain pointers. Similarly to `Foreign.Storable.Storable`, this class provides functions to get the size and alignment of a data via phantom arguments. Thus, the size and alignment of the data must not depend on the data content (they depend only on the type of the data). In particular, this means that dynamically sized structures like Haskell lists or maps are not allowed. This module provides default implementations for all methods of this class via `GHC.Generics.Generic`. Hence, to make your data an instance of @PrimBytes@, it is sufficient to write the instance head: @ data MyData a b = ... deriving Generic instance (PrimBytes a, PrimBytes b) => PrimBytes (MyData a b) @ .. or use the @DeriveAnyClass@ extension to make it even shorter: @ data MyData a b = ... deriving (Generic, PrimBytes) @ The derived instance tries to pack the data as dense as possible, but sometimes it is better to write the instance by hand. If a derived type has more than one constructor, the derived instance puts a @Word32@ tag at the beginning of the byte representation. All fields of a constructor are packed in a C-like fashion next to each other, while respecting their alignments. -} class PrimTagged a => PrimBytes a where {- | List of field names. It is used to get field offsets using `byteFieldOffset` function. A Generic-derived instance has this list non-empty only if two obvious conditions are met: 1. The data has only one constructor. 2. The data uses record syntax to define its fields. -} type PrimFields a :: [Symbol] type PrimFields a = GPrimFields (Rep a) -- | Store content of a data type in a primitive byte array -- (should be used together with @byteOffset@ function). -- -- Note, the default implementation of this function returns a not pinned -- array, which is aligned to @SIZEOF_HSWORD@. -- Thus, it ignores the alignment of the underlying data type if it is larger. -- However, alignment calculation still makes sense for data types -- that are smaller than @SIZEOF_HSWORD@ bytes: they are packed more densely. getBytes :: a -> ByteArray# getBytes a = case runRW# ( \s0 -> case newByteArray# (byteSize a) s0 of (# s1, marr #) -> unsafeFreezeByteArray# marr (writeBytes marr 0# a s1) ) of (# _, r #) -> r {-# NOINLINE getBytes #-} -- | Store content of a data type in a primitive byte array -- (should be used together with @byteOffset@ function). -- -- In contrast to `getBytes`, this function returns a pinned byte array, -- aligned to the @byteAlign@ bytes of this data. -- -- Note, GC guarantees not to move the created array. -- While this is very useful sometimes, it incurs a certain performance penalty. getBytesPinned :: a -> ByteArray# getBytesPinned a = case runRW# ( \s0 -> case newAlignedPinnedByteArray# (byteSize a) (byteAlign a) s0 of (# s1, marr #) -> unsafeFreezeByteArray# marr (writeBytes marr 0# a s1) ) of (# _, r #) -> r {-# NOINLINE getBytesPinned #-} -- | Load content of a data type from a primitive byte array given an offset in bytes. fromBytes :: Int# -- ^ Offset in bytes -> ByteArray# -- ^ Source array -> a -- | Read data from a mutable byte array given an offset in bytes. readBytes :: MutableByteArray# s -- ^ Source array -> Int# -- ^ Byte offset in the source array -> State# s -> (# State# s, a #) -- | Write data into a mutable byte array at a given position (offset in bytes). writeBytes :: MutableByteArray# s -- ^ Destination array -> Int# -- ^ Byte offset in the destination array -> a -- ^ Data to write into the array -> State# s -> State# s -- | Read data from a specified address. readAddr :: Addr# -> State# s -> (# State# s, a #) -- | Write data to a specified address. writeAddr :: a -> Addr# -> State# s -> State# s -- | Size of a data type in bytes. -- It should be a multiple of @byteAlign@ for indexing functions to operate -- correctly. -- -- Implementation of this function must not inspect the argument value; -- a caller may provide @undefined@ in place of the argument. byteSize :: a -> Int# -- | Alignment of a data type in bytes. -- @byteOffset@ should be multiple of this value. -- -- Implementation of this function must not inspect the argument value; -- a caller may provide @undefined@ in place of the argument. byteAlign :: a -> Int# -- | Offset of the data in a byte array used to store the data, -- measured in bytes. -- Should be used together with @getBytes@ function. -- Unless in case of special data types represented by ByteArrays, -- it is equal to zero. -- -- Implementation of this function may inspect the argument value; -- a caller must not provide @undefined@ in place of the argument. byteOffset :: a -> Int# byteOffset _ = 0# {-# INLINE byteOffset #-} -- | Offset of a data record within the data type in bytes. -- -- Implementation of this function must not inspect the argument value; -- a caller may provide @undefined@ in place of the argument. -- -- The default (generic) implementation of this fucntion looks for the -- leftmost occurrence of a given field name (in case of multiple constructors). -- If a field with the given name is not found, it returns @-1@, -- but this is not possible thanks to @Elem name (PrimFields a)@ constraint. byteFieldOffset :: (Elem name (PrimFields a), KnownSymbol name) => Proxy# name -> a -> Int# -- | Index array given an element offset -- (which is @byteSize a@ and should be a multiple of @byteAlign a@). indexArray :: ByteArray# -> Int# -> a indexArray ba i = fromBytes (i *# byteSize @a undefined) ba {-# INLINE indexArray #-} -- | Read a mutable array given an element offset -- (which is @byteSize a@ and should be a multiple of @byteAlign a@). readArray :: MutableByteArray# s -> Int# -> State# s -> (# State# s, a #) readArray ba i = readBytes ba (i *# byteSize @a undefined) {-# INLINE readArray #-} -- | Write a mutable array given an element offset -- (which is @byteSize a@ and should be a multiple of @byteAlign a@). writeArray :: MutableByteArray# s -> Int# -> a -> State# s -> State# s writeArray ba i = writeBytes ba (i *# byteSize @a undefined) {-# INLINE writeArray #-} default fromBytes :: (Generic a, GPrimBytes (Rep a)) => Int# -> ByteArray# -> a fromBytes i arr = to (gfromBytes proxy# 0## 0# i arr) {-# INLINE fromBytes #-} default readBytes :: (Generic a, GPrimBytes (Rep a)) => MutableByteArray# s -> Int# -> State# s -> (# State# s, a #) readBytes mba i s = case greadBytes proxy# 0## 0# mba i s of (# s', x #) -> (# s', to x #) {-# INLINE readBytes #-} default writeBytes :: (Generic a, GPrimBytes (Rep a)) => MutableByteArray# s -> Int# -> a -> State# s -> State# s writeBytes mba i = gwriteBytes proxy# 0## 0# mba i . from {-# INLINE writeBytes #-} default readAddr :: (Generic a, GPrimBytes (Rep a)) => Addr# -> State# s -> (# State# s, a #) readAddr a s = case greadAddr proxy# 0## 0# a s of (# s', x #) -> (# s', to x #) {-# INLINE readAddr #-} default writeAddr :: (Generic a, GPrimBytes (Rep a)) => a -> Addr# -> State# s -> State# s writeAddr = gwriteAddr proxy# 0## 0# . from {-# INLINE writeAddr #-} default byteSize :: (Generic a, GPrimBytes (Rep a)) => a -> Int# byteSize a = gbyteSize proxy# 0## 0# (from a) `roundUpInt` byteAlign a {-# INLINE byteSize #-} default byteAlign :: (Generic a, GPrimBytes (Rep a)) => a -> Int# byteAlign a = gbyteAlign proxy# (from a) {-# INLINE byteAlign #-} default byteFieldOffset :: ( Generic a, GPrimBytes (Rep a) , KnownSymbol name) => Proxy# name -> a -> Int# byteFieldOffset p a = gbyteFieldOffset proxy# 0## 0# p (from a) {-# INLINE byteFieldOffset #-} -- | A wrapper on `byteSize` bSizeOf :: (PrimBytes a, Num b) => a -> b bSizeOf a = fromIntegral (I# (byteSize a)) -- | A wrapper on `byteAlign` bAlignOf :: (PrimBytes a, Num b) => a -> b bAlignOf a = fromIntegral (I# (byteAlign a)) -- | A wrapper on `byteFieldOffset`. bFieldOffsetOf :: forall (name :: Symbol) (a :: Type) (b :: Type) . ( PrimBytes a, Elem name (PrimFields a) , KnownSymbol name, Num b) => a -> b bFieldOffsetOf a = fromIntegral (I# (byteFieldOffset (proxy# :: Proxy# name) a)) -- | Same as `Foreign.Storable.peekElemOff`: peek an element @a@ by the offset -- measured in @byteSize a@. -- -- Note: the size of the element must be a multiple of its alignment for -- a correct operation of this function. bPeekElemOff :: forall (a :: Type) . PrimBytes a => Ptr a -> Int -> IO a bPeekElemOff (Ptr addr) (I# i) = IO (readAddr (plusAddr# addr (i *# byteSize @a undefined))) -- | Same as `Foreign.Storable.pokeElemOff`: poke an element @a@ by the offset -- measured in @byteSize a@. -- -- Note: the size of the element must be a multiple of its alignment for -- a correct operation of this function. bPokeElemOff :: forall (a :: Type) . PrimBytes a => Ptr a -> Int -> a -> IO () bPokeElemOff (Ptr addr) (I# i) a = IO (\s -> (# writeAddr a (plusAddr# addr (i *# byteSize a)) s, () #)) -- | Same as `Foreign.Storable.peekByteOff`: peek an element @a@ by the offset -- measured in bytes. -- -- Note: you'd better be sure the address is a multiple of -- the data alignment (`Foreign.Storable.peek`). bPeekByteOff :: forall (a :: Type) (b :: Type) . PrimBytes a => Ptr b -> Int -> IO a bPeekByteOff (Ptr addr) (I# i) = IO (readAddr (plusAddr# addr i)) -- | Same as `Foreign.Storable.pokeByteOff`: poke an element @a@ by the offset -- measured in bytes. -- -- Note: you'd better be sure the address is a multiple of -- the data alignment (`Foreign.Storable.peek`). bPokeByteOff :: forall (a :: Type) (b :: Type) . PrimBytes a => Ptr b -> Int -> a -> IO () bPokeByteOff (Ptr addr) (I# i) a = IO (\s -> (# writeAddr a (plusAddr# addr i) s, () #)) -- | Same as `Foreign.Storable.peek`: read a data from a pointer. -- -- Note: you'd better be sure the address is a multiple of -- the data alignment (`Foreign.Storable.peek`). bPeek :: forall (a :: Type) . PrimBytes a => Ptr a -> IO a bPeek (Ptr addr) = IO (readAddr addr) -- | Same as `Foreign.Storable.poke`: write a data to a pointer. -- -- Note: you'd better be sure the address is a multiple of -- the data alignment (`Foreign.Storable.peek`). bPoke :: forall (a :: Type) . PrimBytes a => Ptr a -> a -> IO () bPoke (Ptr addr) a = IO (\s -> (# writeAddr a addr s, () #)) -- | Derive a list of data selectors from the data representation @Rep a@. type family GPrimFields (rep :: Type -> Type) :: [Symbol] where GPrimFields (M1 D _ f) = GPrimFields f GPrimFields (M1 C _ f) = GPrimFields f GPrimFields (M1 S ('MetaSel ('Just n) _ _ _) _) = '[n] GPrimFields (f :*: g) = Concat (GPrimFields f) (GPrimFields g) GPrimFields _ = '[] {- | Deriving `PrimBytes` using generics This implementation relies on two assumptions, which are probably true in the GHC implementation of derived generics and __is not checked here__: 1. @Rep a@ is a sum-of-products. This means the struct offset is always @4@ for the parts of the sum type, and a constructor tag is always at position @0@ in the struct. 2. The @Rep a@ tree is balanced. Thus, I can implement a simple tag encoding: each bit in a tag corresponds to a nesting level. That is, maximum possible nesting level is 31 and minimum is 0. Therefore, the general logic for the sum type is summarized as follows: reserve 4 bytes for the tag and try to pack alternatives as good as possible. If a data type has only one constructor (@Rep a@ contains no @:+:@), then the tag is not added. Every function in @GPrimBytes@ has the first Proxy# argument; it is simply used to enforce type parameter and allows easy @coerce@ implementations for @Meta@ wrapper types. All functions except @gbyteAlign@ have the second and third arguments: tag mask (@Word#@) and current struct size (@Int#@); both start with zero at the top of the @Rep a@ hierarchy. The tag mask is used by the sum constructors to find out where to write a bit value to encode left or right branch. The current struct size is the size (in bytes) of all elements to the left of the current one (before alignment). -} class GPrimBytes f where gfromBytes :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> Int# -> ByteArray# -> f p greadBytes :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> MutableByteArray# s -> Int# -> State# s -> (# State# s, f p #) gwriteBytes :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> MutableByteArray# s -> Int# -> f p -> State# s -> State# s greadAddr :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> Addr# -> State# s -> (# State# s, f p #) gwriteAddr :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> f p -> Addr# -> State# s -> State# s -- | Cumulative size of a Rep structure gbyteSize :: Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> f p -> Int# gbyteAlign :: Proxy# p -> f p -> Int# -- | Gives an offset of the current piece of a Rep structure gbyteFieldOffset :: KnownSymbol name => Proxy# p -> Word# -- ^ Constructor tag position (mask) -> Int# -- ^ Left neighbour cumulative size (current offset before alignment) -> Proxy# name -> f p -> Int# gbyteFieldOffset _ _ _ _ _ = negateInt# 1# {-# INLINE gbyteFieldOffset #-} instance GPrimBytes V1 where gfromBytes _ _ _ _ _ = undefined greadBytes _ _ _ _ _ s = (# s, undefined #) gwriteBytes _ _ _ _ _ _ s = s greadAddr _ _ _ _ s = (# s, undefined #) gwriteAddr _ _ _ _ _ s = s gbyteSize _ _ ps _ = ps gbyteAlign _ _ = 1# instance GPrimBytes U1 where gfromBytes _ _ _ _ _ = U1 greadBytes _ _ _ _ _ s = (# s, U1 #) gwriteBytes _ _ _ _ _ _ s = s greadAddr _ _ _ _ s = (# s, U1 #) gwriteAddr _ _ _ _ _ s = s gbyteSize _ _ ps _ = ps gbyteAlign _ _ = 1# getGOff :: forall a . PrimBytes a => Int# -- parent cumulative size -> Int# -- original offset -> Int# -- new offset getGOff ps i = i +# roundUpInt ps (byteAlign @a undefined) instance PrimBytes a => GPrimBytes (K1 i a) where gfromBytes _ _ ps i ba = K1 (fromBytes (getGOff @a ps i) ba) greadBytes _ _ ps mba i = coerce (readBytes @a mba (getGOff @a ps i)) gwriteBytes _ _ ps mba i = coerce (writeBytes @a mba (getGOff @a ps i)) greadAddr _ _ ps addr = coerce (readAddr @a (plusAddr# addr (getGOff @a ps 0#))) gwriteAddr _ _ ps ka addr = writeAddr (unK1 ka) (plusAddr# addr (getGOff @a ps 0#)) gbyteSize _ _ ps ~(K1 a) = roundUpInt ps (byteAlign a) +# byteSize a gbyteAlign _ = coerce (byteAlign @a) instance {-# OVERLAPPING #-} (GPrimBytes f, KnownSymbol sn) => GPrimBytes (M1 S ('MetaSel ('Just sn) a b c) f) where gfromBytes p = coerce (gfromBytes @f p) greadBytes p = coerce (greadBytes @f p) gwriteBytes p = coerce (gwriteBytes @f p) greadAddr p = coerce (greadAddr @f p) gwriteAddr p = coerce (gwriteAddr @f p) gbyteSize p = coerce (gbyteSize @f p) gbyteAlign p = coerce (gbyteAlign @f p) gbyteFieldOffset p _ off (_ :: Proxy# n) ma | Just Refl <- sameSymbol (undefined :: Proxy n) (undefined :: Proxy sn) = off `roundUpInt` gbyteAlign p ma | otherwise = negateInt# 1# instance GPrimBytes f => GPrimBytes (M1 i c f) where gfromBytes p = coerce (gfromBytes @f p) greadBytes p = coerce (greadBytes @f p) gwriteBytes p = coerce (gwriteBytes @f p) greadAddr p = coerce (greadAddr @f p) gwriteAddr p = coerce (gwriteAddr @f p) gbyteSize p = coerce (gbyteSize @f p) gbyteAlign p = coerce (gbyteAlign @f p) gbyteFieldOffset p = coerce' (gbyteFieldOffset @f p) where coerce' :: (Word# -> Int# -> Proxy# name -> f p -> Int#) -> Word# -> Int# -> Proxy# name -> M1 i c f p -> Int# coerce' = coerce instance (GPrimBytes f, GPrimBytes g) => GPrimBytes (f :*: g) where gfromBytes p t ps i ba = x :*: y where x = gfromBytes p t ps i ba y = gfromBytes p t (gbyteSize p t ps x) i ba greadBytes p t ps mba i s0 | (# s1, x #) <- greadBytes p t ps mba i s0 , (# s2, y #) <- greadBytes p t (gbyteSize p t ps x) mba i s1 = (# s2, x :*: y #) gwriteBytes p t ps mba off (x :*: y) s0 | s1 <- gwriteBytes p t ps mba off x s0 , s2 <- gwriteBytes p t (gbyteSize p t ps x) mba off y s1 = s2 greadAddr p t ps addr s0 | (# s1, x #) <- greadAddr p t ps addr s0 , (# s2, y #) <- greadAddr p t (gbyteSize p t ps x) addr s1 = (# s2, x :*: y #) gwriteAddr p t ps (x :*: y) addr s0 | s1 <- gwriteAddr p t ps x addr s0 , s2 <- gwriteAddr p t (gbyteSize p t ps x) y addr s1 = s2 gbyteSize p t ps ~(x :*: y) = gbyteSize p t (gbyteSize p t ps x) y gbyteAlign p ~(x :*: y) = gbyteAlign p x `maxInt` gbyteAlign p y gbyteFieldOffset p t ps n ~(x :*: y) | offX <- gbyteFieldOffset p t ps n x , bsX <- gbyteSize p t ps x , offY <- gbyteFieldOffset p t bsX n y = if isTrue# (offX <# 0#) then offY else offX instance (GPrimBytes f, GPrimBytes g) => GPrimBytes (f :+: g) where gfromBytes p t _ off ba | c <- indexWord8ArrayAsWord32# ba off = if isTrue# (eqWord# (and# c t1) 0##) then L1 (gfromBytes p t1 4# off ba) else R1 (gfromBytes p t1 4# off ba) where t1 = upTag t greadBytes p t _ mba off s0 | (# s1, c #) <- readWord8ArrayAsWord32# mba off s0 = if isTrue# (eqWord# (and# c t1) 0##) then case greadBytes p t1 4# mba off s1 of (# s2, x #) -> (# s2, L1 x #) else case greadBytes p t1 4# mba off s1 of (# s2, y #) -> (# s2, R1 y #) where t1 = upTag t -- if this is the uppermost sum, overwrite the tag. gwriteBytes p 0## _ mba off (L1 x) s0 | s1 <- writeWord8ArrayAsWord32# mba off 0## s0 , s2 <- gwriteBytes p 1## 4# mba off x s1 = s2 gwriteBytes p 0## _ mba off (R1 y) s0 | s1 <- writeWord8ArrayAsWord32# mba off 1## s0 , s2 <- gwriteBytes p 1## 4# mba off y s1 = s2 -- here I know that I have written zero to the corresponding bit already gwriteBytes p t _ mba off (L1 x) s0 | s1 <- gwriteBytes p (upTag t) 4# mba off x s0 = s1 -- otherwise, carefully write a single corresponding bit gwriteBytes p t _ mba off (R1 y) s0 | (# s1, c #) <- readWord8ArrayAsWord32# mba off s0 , s2 <- writeWord8ArrayAsWord32# mba off (or# c t1) s1 , s3 <- gwriteBytes p t1 4# mba off y s2 = s3 where t1 = upTag t greadAddr p t _ addr s0 | (# s1, c #) <- readWord32OffAddr# addr 0# s0 = if isTrue# (eqWord# (and# c t1) 0##) then case greadAddr p t1 4# addr s1 of (# s2, x #) -> (# s2, L1 x #) else case greadAddr p t1 4# addr s1 of (# s2, y #) -> (# s2, R1 y #) where t1 = upTag t -- if this is the uppermost sum, overwrite the tag. gwriteAddr p 0## _ (L1 x) addr s0 | s1 <- writeWord32OffAddr# addr 0# 0## s0 , s2 <- gwriteAddr p 1## 4# x addr s1 = s2 gwriteAddr p 0## _ (R1 y) addr s0 | s1 <- writeWord32OffAddr# addr 0# 1## s0 , s2 <- gwriteAddr p 1## 4# y addr s1 = s2 -- here I know that I have written zero to the corresponding bit already gwriteAddr p t _ (L1 x) addr s0 | s1 <- gwriteAddr p (upTag t) 4# x addr s0 = s1 -- otherwise, carefully write a single corresponding bit gwriteAddr p t _ (R1 y) addr s0 | (# s1, c #) <- readWord32OffAddr# addr 0# s0 , s2 <- writeWord32OffAddr# addr 0# (or# c t1) s1 , s3 <- gwriteAddr p t1 4# y addr s2 = s3 where t1 = upTag t gbyteSize p 0## ps xy = maxInt (roundUpInt 4# (gbyteAlign p x) +# gbyteSize p 1## ps x) (roundUpInt 4# (gbyteAlign p y) +# gbyteSize p 1## ps y) where x = undef1 @f xy y = undef1 @g xy gbyteSize p t ps xy = maxInt (gbyteSize p (upTag t) ps (undef1 @f xy)) (gbyteSize p (upTag t) ps (undef1 @g xy)) gbyteAlign p xy = 4# `maxInt` maxInt (gbyteAlign p (undef1 @f xy)) (gbyteAlign p (undef1 @g xy)) -- check both branches if any of them contain the field. -- If there are more than one branches containing the field, the left one -- is preferred. gbyteFieldOffset p t ps n xy | offX <- gbyteFieldOffset p (upTag t) ps n (undef1 @f xy) , offY <- gbyteFieldOffset p (upTag t) ps n (undef1 @g xy) = if isTrue# (offX <# 0#) then offY else offX upTag :: Word# -> Word# upTag 0## = 1## upTag t = uncheckedShiftL# t 1# {-# INLINE upTag #-} maxInt :: Int# -> Int# -> Int# maxInt a b = if isTrue# (a ># b) then a else b {-# INLINE maxInt #-} -- | Round up the first numer to a multiple of the second. -- -- NB: this function is only used with alignment as the second number, -- which is always a power of 2. roundUpInt :: Int# -> Int# -> Int# roundUpInt a b = (a +# b -# 1#) `andI#` negateInt# b {-# INLINE roundUpInt #-} -- It's pity that the assertion would not work due to kind of the result -- not being Type. -- assert (isTrue# (eqWord# (popCnt# (int2Word# b)) 1##)) -- -- The version above is optimized for second number being power of two (align) -- The baseline implementation would be as follows: -- roundUpInt a b = case remInt# a b of -- 0# -> a -- q -> a +# b -# q undef1 :: forall p q a . q a -> p a undef1 = const undefined {-# INLINE undef1 #-} #if SIZEOF_HSWORD == 4 #define OFFSHIFT_W 2 #else #define OFFSHIFT_W 3 #endif instance GPrimBytes (URec Word) where gfromBytes _ _ ps off ba = UWord (indexWord8ArrayAsWord# ba (off +# roundUpInt ps ALIGNMENT_HSWORD#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsWord# mba (off +# roundUpInt ps ALIGNMENT_HSWORD#) s of (# s1, r #) -> (# s1, UWord r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsWord# mba (off +# roundUpInt ps ALIGNMENT_HSWORD#) (uWord# x) greadAddr _ _ ps a s = case readWordOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSWORD#)) 0# s of (# s', x #) -> (# s', UWord x #) gwriteAddr _ _ ps x a = writeWordOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSWORD#)) 0# (uWord# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSWORD# +# SIZEOF_HSWORD# gbyteAlign _ _ = ALIGNMENT_HSWORD# #if SIZEOF_HSINT == 4 #define OFFSHIFT_I 2 #else #define OFFSHIFT_I 3 #endif instance GPrimBytes (URec Int) where gfromBytes _ _ ps off ba = UInt (indexWord8ArrayAsInt# ba (off +# roundUpInt ps ALIGNMENT_HSINT#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsInt# mba (off +# roundUpInt ps ALIGNMENT_HSINT#) s of (# s1, r #) -> (# s1, UInt r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsInt# mba (off +# roundUpInt ps ALIGNMENT_HSINT#) (uInt# x) greadAddr _ _ ps a s = case readIntOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSINT#)) 0# s of (# s', x #) -> (# s', UInt x #) gwriteAddr _ _ ps x a = writeIntOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSINT#)) 0# (uInt# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSINT# +# SIZEOF_HSINT# gbyteAlign _ _ = ALIGNMENT_HSINT# #if SIZEOF_HSFLOAT == 4 #define OFFSHIFT_F 2 #else #define OFFSHIFT_F 3 #endif instance GPrimBytes (URec Float) where gfromBytes _ _ ps off ba = UFloat (indexWord8ArrayAsFloat# ba (off +# roundUpInt ps ALIGNMENT_HSFLOAT#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsFloat# mba (off +# roundUpInt ps ALIGNMENT_HSFLOAT#) s of (# s1, r #) -> (# s1, UFloat r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsFloat# mba (off +# roundUpInt ps ALIGNMENT_HSFLOAT#) (uFloat# x) greadAddr _ _ ps a s = case readFloatOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSFLOAT#)) 0# s of (# s', x #) -> (# s', UFloat x #) gwriteAddr _ _ ps x a = writeFloatOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSFLOAT#)) 0# (uFloat# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSFLOAT# +# SIZEOF_HSFLOAT# gbyteAlign _ _ = ALIGNMENT_HSFLOAT# #if SIZEOF_HSDOUBLE == 4 #define OFFSHIFT_D 2 #else #define OFFSHIFT_D 3 #endif instance GPrimBytes (URec Double) where gfromBytes _ _ ps off ba = UDouble (indexWord8ArrayAsDouble# ba (off +# roundUpInt ps ALIGNMENT_HSDOUBLE#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsDouble# mba (off +# roundUpInt ps ALIGNMENT_HSDOUBLE#) s of (# s1, r #) -> (# s1, UDouble r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsDouble# mba (off +# roundUpInt ps ALIGNMENT_HSDOUBLE#) (uDouble# x) greadAddr _ _ ps a s = case readDoubleOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSDOUBLE#)) 0# s of (# s', x #) -> (# s', UDouble x #) gwriteAddr _ _ ps x a = writeDoubleOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSDOUBLE#)) 0# (uDouble# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSDOUBLE# +# SIZEOF_HSDOUBLE# gbyteAlign _ _ = ALIGNMENT_HSDOUBLE# -- I believe Char is always 31 bit, but checking this does not hurt #if SIZEOF_HSCHAR == 2 #define OFFSHIFT_C 1 #elif SIZEOF_HSCHAR == 4 #define OFFSHIFT_C 2 #else #define OFFSHIFT_C 3 #endif instance GPrimBytes (URec Char) where gfromBytes _ _ ps off ba = UChar (indexWord8ArrayAsWideChar# ba (off +# roundUpInt ps ALIGNMENT_HSCHAR#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsWideChar# mba (off +# roundUpInt ps ALIGNMENT_HSCHAR#) s of (# s1, r #) -> (# s1, UChar r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsWideChar# mba (off +# roundUpInt ps ALIGNMENT_HSCHAR#) (uChar# x) greadAddr _ _ ps a s = case readWideCharOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSCHAR#)) 0# s of (# s', x #) -> (# s', UChar x #) gwriteAddr _ _ ps x a = writeWideCharOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSCHAR#)) 0# (uChar# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSCHAR# +# SIZEOF_HSCHAR# gbyteAlign _ _ = ALIGNMENT_HSCHAR# #if SIZEOF_HSPTR == 4 #define OFFSHIFT_P 2 #else #define OFFSHIFT_P 3 #endif instance GPrimBytes (URec (Ptr ())) where gfromBytes _ _ ps off ba = UAddr (indexWord8ArrayAsAddr# ba (off +# roundUpInt ps ALIGNMENT_HSPTR#)) greadBytes _ _ ps mba off s = case readWord8ArrayAsAddr# mba (off +# roundUpInt ps ALIGNMENT_HSPTR#) s of (# s1, r #) -> (# s1, UAddr r #) gwriteBytes _ _ ps mba off x = writeWord8ArrayAsAddr# mba (off +# roundUpInt ps ALIGNMENT_HSPTR#) (uAddr# x) greadAddr _ _ ps a s = case readAddrOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSPTR#)) 0# s of (# s', x #) -> (# s', UAddr x #) gwriteAddr _ _ ps x a = writeAddrOffAddr# (plusAddr# a (roundUpInt ps ALIGNMENT_HSPTR#)) 0# (uAddr# x) gbyteSize _ _ ps _ = roundUpInt ps ALIGNMENT_HSPTR# +# SIZEOF_HSPTR# gbyteAlign _ _ = ALIGNMENT_HSPTR# -------------------------------------------------------------------------------- -- Basic instances -------------------------------------------------------------------------------- instance PrimBytes Word where type PrimFields Word = '[] getBytes (W# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSWORD# s0 of (# s1, marr #) -> case writeWordArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = W# (indexWord8ArrayAsWord# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsWord# mba off s of (# s', r #) -> (# s', W# r #) {-# INLINE readBytes #-} writeBytes mba off (W# x) = writeWord8ArrayAsWord# mba off x {-# INLINE writeBytes #-} readAddr a s = case readWordOffAddr# a 0# s of (# s', x #) -> (# s', W# x #) {-# INLINE readAddr #-} writeAddr (W# x) a = writeWordOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSWORD# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSWORD# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = W# (indexWordArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWordArray# mba i s of (# s', x #) -> (# s', W# x #) {-# INLINE readArray #-} writeArray mba i (W# x) = writeWordArray# mba i x {-# INLINE writeArray #-} instance PrimBytes Int where type PrimFields Int = '[] getBytes (I# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSINT# s0 of (# s1, marr #) -> case writeIntArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = I# (indexWord8ArrayAsInt# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsInt# mba off s of (# s', r #) -> (# s', I# r #) {-# INLINE readBytes #-} writeBytes mba off (I# x) = writeWord8ArrayAsInt# mba off x {-# INLINE writeBytes #-} readAddr a s = case readIntOffAddr# a 0# s of (# s', x #) -> (# s', I# x #) {-# INLINE readAddr #-} writeAddr (I# x) a = writeIntOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSINT# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSINT# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = I# (indexIntArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readIntArray# mba i s of (# s', x #) -> (# s', I# x #) {-# INLINE readArray #-} writeArray mba i (I# x) = writeIntArray# mba i x {-# INLINE writeArray #-} instance PrimBytes Float where type PrimFields Float = '[] getBytes (F# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSFLOAT# s0 of (# s1, marr #) -> case writeFloatArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = F# (indexWord8ArrayAsFloat# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsFloat# mba off s of (# s', r #) -> (# s', F# r #) {-# INLINE readBytes #-} writeBytes mba off (F# x) = writeWord8ArrayAsFloat# mba off x {-# INLINE writeBytes #-} readAddr a s = case readFloatOffAddr# a 0# s of (# s', x #) -> (# s', F# x #) {-# INLINE readAddr #-} writeAddr (F# x) a = writeFloatOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSFLOAT# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSFLOAT# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = F# (indexFloatArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readFloatArray# mba i s of (# s', x #) -> (# s', F# x #) {-# INLINE readArray #-} writeArray mba i (F# x) = writeFloatArray# mba i x {-# INLINE writeArray #-} instance PrimBytes Double where type PrimFields Double = '[] getBytes (D# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSDOUBLE# s0 of (# s1, marr #) -> case writeDoubleArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = D# (indexWord8ArrayAsDouble# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsDouble# mba off s of (# s', r #) -> (# s', D# r #) {-# INLINE readBytes #-} writeBytes mba off (D# x) = writeWord8ArrayAsDouble# mba off x {-# INLINE writeBytes #-} readAddr a s = case readDoubleOffAddr# a 0# s of (# s', x #) -> (# s', D# x #) {-# INLINE readAddr #-} writeAddr (D# x) a = writeDoubleOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSDOUBLE# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSDOUBLE# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = D# (indexDoubleArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readDoubleArray# mba i s of (# s', x #) -> (# s', D# x #) {-# INLINE readArray #-} writeArray mba i (D# x) = writeDoubleArray# mba i x {-# INLINE writeArray #-} instance PrimBytes (Ptr a) where type PrimFields (Ptr a) = '[] getBytes (Ptr x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSPTR# s0 of (# s1, marr #) -> case writeAddrArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = Ptr (indexWord8ArrayAsAddr# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsAddr# mba off s of (# s', r #) -> (# s', Ptr r #) {-# INLINE readBytes #-} writeBytes mba off (Ptr x) = writeWord8ArrayAsAddr# mba off x {-# INLINE writeBytes #-} readAddr a s = case readAddrOffAddr# a 0# s of (# s', x #) -> (# s', Ptr x #) {-# INLINE readAddr #-} writeAddr (Ptr x) a = writeAddrOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSPTR# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSPTR# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = Ptr (indexAddrArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readAddrArray# mba i s of (# s', x #) -> (# s', Ptr x #) {-# INLINE readArray #-} writeArray mba i (Ptr x) = writeAddrArray# mba i x {-# INLINE writeArray #-} instance PrimBytes (FunPtr a) where type PrimFields (FunPtr a) = '[] getBytes (FunPtr x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSFUNPTR# s0 of (# s1, marr #) -> case writeAddrArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = FunPtr (indexWord8ArrayAsAddr# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsAddr# mba off s of (# s', r #) -> (# s', FunPtr r #) {-# INLINE readBytes #-} writeBytes mba off (FunPtr x) = writeWord8ArrayAsAddr# mba off x {-# INLINE writeBytes #-} readAddr a s = case readAddrOffAddr# a 0# s of (# s', x #) -> (# s', FunPtr x #) {-# INLINE readAddr #-} writeAddr (FunPtr x) a = writeAddrOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSFUNPTR# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSFUNPTR# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = FunPtr (indexAddrArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readAddrArray# mba i s of (# s', x #) -> (# s', FunPtr x #) {-# INLINE readArray #-} writeArray mba i (FunPtr x) = writeAddrArray# mba i x {-# INLINE writeArray #-} instance PrimBytes (StablePtr a) where type PrimFields (StablePtr a) = '[] getBytes (StablePtr x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSSTABLEPTR# s0 of (# s1, marr #) -> case writeStablePtrArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = StablePtr (indexWord8ArrayAsStablePtr# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsStablePtr# mba off s of (# s', r #) -> (# s', StablePtr r #) {-# INLINE readBytes #-} writeBytes mba off (StablePtr x) = writeWord8ArrayAsStablePtr# mba off x {-# INLINE writeBytes #-} readAddr a s = case readStablePtrOffAddr# a 0# s of (# s', x #) -> (# s', StablePtr x #) {-# INLINE readAddr #-} writeAddr (StablePtr x) a = writeStablePtrOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSSTABLEPTR# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSSTABLEPTR# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = StablePtr (indexStablePtrArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readStablePtrArray# mba i s of (# s', x #) -> (# s', StablePtr x #) {-# INLINE readArray #-} writeArray mba i (StablePtr x) = writeStablePtrArray# mba i x {-# INLINE writeArray #-} instance PrimBytes Int8 where type PrimFields Int8 = '[] getBytes (I8# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_INT8# s0 of (# s1, marr #) -> case writeInt8Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = indexArray ba off {-# INLINE fromBytes #-} readBytes = readArray {-# INLINE readBytes #-} writeBytes = writeArray {-# INLINE writeBytes #-} readAddr a s = case readInt8OffAddr# a 0# s of (# s', x #) -> (# s', I8# x #) {-# INLINE readAddr #-} writeAddr (I8# x) a = writeInt8OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_INT8# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_INT8# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = I8# (indexInt8Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readInt8Array# mba i s of (# s', x #) -> (# s', I8# x #) {-# INLINE readArray #-} writeArray mba i (I8# x) = writeInt8Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Int16 where type PrimFields Int16 = '[] getBytes (I16# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_INT16# s0 of (# s1, marr #) -> case writeInt16Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = I16# (indexWord8ArrayAsInt16# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsInt16# mba off s of (# s', r #) -> (# s', I16# r #) {-# INLINE readBytes #-} writeBytes mba off (I16# x) = writeWord8ArrayAsInt16# mba off x {-# INLINE writeBytes #-} readAddr a s = case readInt16OffAddr# a 0# s of (# s', x #) -> (# s', I16# x #) {-# INLINE readAddr #-} writeAddr (I16# x) a = writeInt16OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_INT16# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_INT16# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = I16# (indexInt16Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readInt16Array# mba i s of (# s', x #) -> (# s', I16# x #) {-# INLINE readArray #-} writeArray mba i (I16# x) = writeInt16Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Int32 where type PrimFields Int32 = '[] getBytes (I32# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_INT32# s0 of (# s1, marr #) -> case writeInt32Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = I32# (indexWord8ArrayAsInt32# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsInt32# mba off s of (# s', r #) -> (# s', I32# r #) {-# INLINE readBytes #-} writeBytes mba off (I32# x) = writeWord8ArrayAsInt32# mba off x {-# INLINE writeBytes #-} readAddr a s = case readInt32OffAddr# a 0# s of (# s', x #) -> (# s', I32# x #) {-# INLINE readAddr #-} writeAddr (I32# x) a = writeInt32OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_INT32# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_INT32# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = I32# (indexInt32Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readInt32Array# mba i s of (# s', x #) -> (# s', I32# x #) {-# INLINE readArray #-} writeArray mba i (I32# x) = writeInt32Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Int64 where type PrimFields Int64 = '[] getBytes (I64# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_INT64# s0 of (# s1, marr #) -> case writeInt64Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = I64# (indexWord8ArrayAsInt64# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsInt64# mba off s of (# s', r #) -> (# s', I64# r #) {-# INLINE readBytes #-} writeBytes mba off (I64# x) = writeWord8ArrayAsInt64# mba off x {-# INLINE writeBytes #-} readAddr a s = case readInt64OffAddr# a 0# s of (# s', x #) -> (# s', I64# x #) {-# INLINE readAddr #-} writeAddr (I64# x) a = writeInt64OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_INT64# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_INT64# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = I64# (indexInt64Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readInt64Array# mba i s of (# s', x #) -> (# s', I64# x #) {-# INLINE readArray #-} writeArray mba i (I64# x) = writeInt64Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Word8 where type PrimFields Word8 = '[] getBytes (W8# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_WORD8# s0 of (# s1, marr #) -> case writeWord8Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = indexArray ba off {-# INLINE fromBytes #-} readBytes = readArray {-# INLINE readBytes #-} writeBytes = writeArray {-# INLINE writeBytes #-} readAddr a s = case readWord8OffAddr# a 0# s of (# s', x #) -> (# s', W8# x #) {-# INLINE readAddr #-} writeAddr (W8# x) a = writeWord8OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_WORD8# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_WORD8# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = W8# (indexWord8Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWord8Array# mba i s of (# s', x #) -> (# s', W8# x #) {-# INLINE readArray #-} writeArray mba i (W8# x) = writeWord8Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Word16 where type PrimFields Word16 = '[] getBytes (W16# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_WORD16# s0 of (# s1, marr #) -> case writeWord16Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = W16# (indexWord8ArrayAsWord16# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsWord16# mba off s of (# s', r #) -> (# s', W16# r #) {-# INLINE readBytes #-} writeBytes mba off (W16# x) = writeWord8ArrayAsWord16# mba off x {-# INLINE writeBytes #-} readAddr a s = case readWord16OffAddr# a 0# s of (# s', x #) -> (# s', W16# x #) {-# INLINE readAddr #-} writeAddr (W16# x) a = writeWord16OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_WORD16# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_WORD16# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = W16# (indexWord16Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWord16Array# mba i s of (# s', x #) -> (# s', W16# x #) {-# INLINE readArray #-} writeArray mba i (W16# x) = writeWord16Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Word32 where type PrimFields Word32 = '[] getBytes (W32# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_WORD32# s0 of (# s1, marr #) -> case writeWord32Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = W32# (indexWord8ArrayAsWord32# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsWord32# mba off s of (# s', r #) -> (# s', W32# r #) {-# INLINE readBytes #-} writeBytes mba off (W32# x) = writeWord8ArrayAsWord32# mba off x {-# INLINE writeBytes #-} readAddr a s = case readWord32OffAddr# a 0# s of (# s', x #) -> (# s', W32# x #) {-# INLINE readAddr #-} writeAddr (W32# x) a = writeWord32OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_WORD32# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_WORD32# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = W32# (indexWord32Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWord32Array# mba i s of (# s', x #) -> (# s', W32# x #) {-# INLINE readArray #-} writeArray mba i (W32# x) = writeWord32Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Word64 where type PrimFields Word64 = '[] getBytes (W64# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_WORD64# s0 of (# s1, marr #) -> case writeWord64Array# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = W64# (indexWord8ArrayAsWord64# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsWord64# mba off s of (# s', r #) -> (# s', W64# r #) {-# INLINE readBytes #-} writeBytes mba off (W64# x) = writeWord8ArrayAsWord64# mba off x {-# INLINE writeBytes #-} readAddr a s = case readWord64OffAddr# a 0# s of (# s', x #) -> (# s', W64# x #) {-# INLINE readAddr #-} writeAddr (W64# x) a = writeWord64OffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_WORD64# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_WORD64# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = W64# (indexWord64Array# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWord64Array# mba i s of (# s', x #) -> (# s', W64# x #) {-# INLINE readArray #-} writeArray mba i (W64# x) = writeWord64Array# mba i x {-# INLINE writeArray #-} instance PrimBytes Char where type PrimFields Char = '[] getBytes (C# x) = case runRW# ( \s0 -> case newByteArray# SIZEOF_HSCHAR# s0 of (# s1, marr #) -> case writeWideCharArray# marr 0# x s1 of s2 -> unsafeFreezeByteArray# marr s2 ) of (# _, a #) -> a {-# NOINLINE getBytes #-} fromBytes off ba = C# (indexWord8ArrayAsWideChar# ba off) {-# INLINE fromBytes #-} readBytes mba off s = case readWord8ArrayAsWideChar# mba off s of (# s', r #) -> (# s', C# r #) {-# INLINE readBytes #-} writeBytes mba off (C# x) = writeWord8ArrayAsWideChar# mba off x {-# INLINE writeBytes #-} readAddr a s = case readWideCharOffAddr# a 0# s of (# s', x #) -> (# s', C# x #) {-# INLINE readAddr #-} writeAddr (C# x) a = writeWideCharOffAddr# a 0# x {-# INLINE writeAddr #-} byteSize _ = SIZEOF_HSCHAR# {-# INLINE byteSize #-} byteAlign _ = ALIGNMENT_HSCHAR# {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba i = C# (indexWideCharArray# ba i) {-# INLINE indexArray #-} readArray mba i s = case readWideCharArray# mba i s of (# s', x #) -> (# s', C# x #) {-# INLINE readArray #-} writeArray mba i (C# x) = writeWideCharArray# mba i x {-# INLINE writeArray #-} instance PrimBytes (Idx (x :: k)) where type PrimFields (Idx x) = '[] getBytes = unsafeCoerce# (getBytes @Word) {-# INLINE getBytes #-} fromBytes = unsafeCoerce# (fromBytes @Word) {-# INLINE fromBytes #-} readBytes = unsafeCoerce# (readBytes @Word) {-# INLINE readBytes #-} writeBytes = unsafeCoerce# (writeBytes @Word) {-# INLINE writeBytes #-} readAddr = unsafeCoerce# (readAddr @Word) {-# INLINE readAddr #-} writeAddr = unsafeCoerce# (writeAddr @Word) {-# INLINE writeAddr #-} byteSize = unsafeCoerce# (byteSize @Word) {-# INLINE byteSize #-} byteAlign = unsafeCoerce# (byteAlign @Word) {-# INLINE byteAlign #-} byteFieldOffset b = unsafeCoerce# (byteFieldOffset @Word b) {-# INLINE byteFieldOffset #-} indexArray = unsafeCoerce# (indexArray @Word) {-# INLINE indexArray #-} readArray = unsafeCoerce# (readArray @Word) {-# INLINE readArray #-} writeArray = unsafeCoerce# (writeArray @Word) {-# INLINE writeArray #-} deriving instance PrimBytes CChar deriving instance PrimBytes CSChar deriving instance PrimBytes CUChar deriving instance PrimBytes CShort deriving instance PrimBytes CUShort deriving instance PrimBytes CInt deriving instance PrimBytes CUInt deriving instance PrimBytes CLong deriving instance PrimBytes CULong deriving instance PrimBytes CPtrdiff deriving instance PrimBytes CSize deriving instance PrimBytes CWchar deriving instance PrimBytes CSigAtomic deriving instance PrimBytes CLLong deriving instance PrimBytes CULLong deriving instance PrimBytes CBool deriving instance PrimBytes CIntPtr deriving instance PrimBytes CUIntPtr deriving instance PrimBytes CIntMax deriving instance PrimBytes CUIntMax deriving instance PrimBytes CClock deriving instance PrimBytes CTime deriving instance PrimBytes CUSeconds deriving instance PrimBytes CSUSeconds deriving instance PrimBytes CFloat deriving instance PrimBytes CDouble anyList :: forall (k :: Type) (xs :: [k]) . RepresentableList xs => [Any] anyList = unsafeCoerce# (tList @xs) {-# INLINE anyList #-} instance RepresentableList xs => PrimBytes (Idxs (xs :: [k])) where type PrimFields (Idxs xs) = '[] fromBytes off ba = unsafeCoerce# (go off (anyList @_ @xs)) where go _ [] = [] go i (_ : ls) = W# (indexWord8ArrayAsWord# ba i) : go (i +# SIZEOF_HSWORD#) ls {-# INLINE fromBytes #-} readBytes mba = unsafeCoerce# (go (anyList @_ @xs)) where go [] _ s0 = (# s0, [] #) go (_ : ls) i s0 | (# s1, w #) <- readWord8ArrayAsWord# mba i s0 , (# s2, ws #) <- go ls (i +# SIZEOF_HSWORD#) s1 = (# s2, W# w : ws #) {-# INLINE readBytes #-} writeBytes mba off = go off . listIdxs where go _ [] s = s go i (W# x :xs) s = go (i +# SIZEOF_HSWORD#) xs (writeWord8ArrayAsWord# mba i x s) {-# INLINE writeBytes #-} readAddr addr = unsafeCoerce# (go addr (anyList @_ @xs)) where go :: forall s . Addr# -> [Any] -> State# s -> (# State# s, [Word] #) go _ [] s0 = (# s0, [] #) go i (_ : ls) s0 | (# s1, w #) <- readWordOffAddr# i 0# s0 , (# s2, xs #) <- go (plusAddr# i SIZEOF_HSWORD#) ls s1 = (# s2, W# w : xs #) {-# INLINE readAddr #-} writeAddr is addr = go addr (listIdxs is) where go :: forall s . Addr# -> [Word] -> State# s -> State# s go _ [] s = s go i (W# x :xs) s = go (plusAddr# i SIZEOF_HSWORD#) xs (writeWordOffAddr# i 0# x s) {-# INLINE writeAddr #-} byteSize _ = case dimVal (order' @xs) of W# n -> byteSize (undefined :: Idx x) *# word2Int# n {-# INLINE byteSize #-} byteAlign _ = byteAlign (undefined :: Idx x) {-# INLINE byteAlign #-} byteFieldOffset _ _ = negateInt# 1# {-# INLINE byteFieldOffset #-} indexArray ba off | n@(W# n#) <- dimVal (order' @xs) = unsafeCoerce# (go (off *# word2Int# n#) n) where go _ 0 = [] go i n = W# (indexWordArray# ba i) : go (i +# 1#) (n-1) {-# INLINE indexArray #-} readArray mba off s | n@(W# n#) <- dimVal (order' @xs) = unsafeCoerce# (go (off *# word2Int# n#) n s) where go _ 0 s0 = (# s0, [] #) go i n s0 | (# s1, w #) <- readWordArray# mba i s0 , (# s2, xs #) <- go (i +# 1#) (n-1) s1 = (# s2, W# w : xs #) {-# INLINE readArray #-} writeArray mba off is | W# n# <- dimVal (order' @xs) = go (off *# word2Int# n#) (listIdxs is) where go _ [] s = s go i (W# x :xs) s = go (i +# 1#) xs (writeWordArray# mba i x s) {-# INLINE writeArray #-} type family TupleFields (n :: Nat) (xs :: [Type]) :: [Symbol] where TupleFields _ '[] = '[] TupleFields n (_ ': xs) = ShowNat n ': TupleFields (n + 1) xs instance ( RepresentableList xs , L.All PrimBytes xs ) => PrimBytes (TL.Tuple xs) where type PrimFields (TL.Tuple xs) = TupleFields 1 xs getBytes = unsafeCoerce# (getBytes @(TS.Tuple xs)) {-# INLINE getBytes #-} fromBytes = unsafeCoerce# (fromBytes @(TS.Tuple xs)) {-# INLINE fromBytes #-} readBytes = unsafeCoerce# (readBytes @(TS.Tuple xs)) {-# INLINE readBytes #-} writeBytes = unsafeCoerce# (writeBytes @(TS.Tuple xs)) {-# INLINE writeBytes #-} readAddr = unsafeCoerce# (readAddr @(TS.Tuple xs)) {-# INLINE readAddr #-} writeAddr = unsafeCoerce# (writeAddr @(TS.Tuple xs)) {-# INLINE writeAddr #-} byteSize = unsafeCoerce# (byteSize @(TS.Tuple xs)) {-# INLINE byteSize #-} byteAlign = unsafeCoerce# (byteAlign @(TS.Tuple xs)) {-# INLINE byteAlign #-} byteFieldOffset p = unsafeCoerce# (byteFieldOffset @(TS.Tuple xs) p) {-# INLINE byteFieldOffset #-} indexArray = unsafeCoerce# (indexArray @(TS.Tuple xs)) {-# INLINE indexArray #-} readArray = unsafeCoerce# (readArray @(TS.Tuple xs)) {-# INLINE readArray #-} writeArray = unsafeCoerce# (writeArray @(TS.Tuple xs)) {-# INLINE writeArray #-} instance ( RepresentableList xs , L.All PrimBytes xs ) => PrimBytes (TS.Tuple xs) where type PrimFields (TS.Tuple xs) = TupleFields 1 xs fromBytes off ba = go 0# (tList @xs) where go :: L.All PrimBytes ds => Int# -> TypeList ds -> TS.Tuple ds go _ Empty = Empty go n (t :* ts@TypeList) | x <- undefP t , n' <- roundUpInt n (byteAlign x) = TS.Id (fromBytes (off +# n') ba) :* go (n' +# byteSize x) ts {-# INLINE fromBytes #-} readBytes mb off = go mb 0# (tList @xs) where go :: L.All PrimBytes ds => MutableByteArray# s -> Int# -> TypeList ds -> State# s -> (# State# s, TS.Tuple ds #) go _ _ Empty s0 = (# s0, Empty #) go mba n (t :* ts@TypeList) s0 | x <- undefP t , n' <- roundUpInt n (byteAlign x) = case readBytes mba (off +# n') s0 of (# s1, r #) -> case go mba (n' +# byteSize x) ts s1 of (# s2, rs #) -> (# s2, TS.Id r :* rs #) {-# INLINE readBytes #-} writeBytes mba off tup = go mba 0# tup (types tup) where go :: L.All PrimBytes ds => MutableByteArray# s -> Int# -> TS.Tuple ds -> TypeList ds -> State# s -> State# s go mb n (TS.Id x :* xs) (_ :* ts@TypeList) s | n' <- roundUpInt n (byteAlign x) = go mb (n' +# byteSize x) xs ts (writeBytes mb (off +# n') x s) go _ _ _ _ s = s {-# INLINE writeBytes #-} readAddr addr = go 0# (tList @xs) where go :: L.All PrimBytes ds => Int# -> TypeList ds -> State# s -> (# State# s, TS.Tuple ds #) go _ Empty s0 = (# s0, Empty #) go n (t :* ts@TypeList) s0 | x <- undefP t , n' <- roundUpInt n (byteAlign x) = case readAddr (plusAddr# addr n') s0 of (# s1, r #) -> case go (n' +# byteSize x) ts s1 of (# s2, rs #) -> (# s2, TS.Id r :* rs #) {-# INLINE readAddr #-} writeAddr tup addr = go 0# tup (types tup) where go :: L.All PrimBytes ds => Int# -> TS.Tuple ds -> TypeList ds -> State# s -> State# s go n (TS.Id x :* xs) (_ :* ts@TypeList) s | n' <- roundUpInt n (byteAlign x) = go (n' +# byteSize x) xs ts (writeAddr x (plusAddr# addr n') s) go _ _ _ s = s {-# INLINE writeAddr #-} byteSize _ = go 0# 1# (tList @xs) where go :: L.All PrimBytes ys => Int# -> Int# -> TypeList ys -> Int# go s a Empty = s `roundUpInt` a go s a (p :* ps) = let x = undefP p xa = byteAlign x in go ( roundUpInt s xa +# byteSize x) ( maxInt a xa ) ps {-# INLINE byteSize #-} byteAlign _ = go (tList @xs) where go :: L.All PrimBytes ys => TypeList ys -> Int# go Empty = 0# go (p :* ps) = maxInt (byteAlign (undefP p)) (go ps) {-# INLINE byteAlign #-} byteFieldOffset name _ | Just n <- readMaybe $ symbolVal' name = go (n-1) 0# (tList @xs) | otherwise = negateInt# 1# where go :: L.All PrimBytes ys => Word -> Int# -> TypeList ys -> Int# go 0 s (p :* _) = s `roundUpInt` byteAlign (undefP p) go n s (p :* ps) = let x = undefP p in go (n-1) ( roundUpInt s (byteAlign x) +# byteSize x) ps go _ _ Empty = negateInt# 1# {-# INLINE byteFieldOffset #-} undefP :: Proxy p -> p undefP = const undefined {-# INLINE undefP #-} instance PrimBytes () instance PrimBytes a => PrimBytes (Maybe a) instance ( PrimBytes a, PrimBytes b ) => PrimBytes (Either a b) instance ( PrimBytes a, PrimBytes b ) => PrimBytes (a, b) instance ( PrimBytes a, PrimBytes b, PrimBytes c ) => PrimBytes (a, b, c) instance ( PrimBytes a, PrimBytes b, PrimBytes c, PrimBytes d ) => PrimBytes (a, b, c, d) instance ( PrimBytes a, PrimBytes b, PrimBytes c, PrimBytes d, PrimBytes e ) => PrimBytes (a, b, c, d, e) instance ( PrimBytes a, PrimBytes b, PrimBytes c, PrimBytes d, PrimBytes e , PrimBytes f ) => PrimBytes (a, b, c, d, e, f) instance ( PrimBytes a, PrimBytes b, PrimBytes c, PrimBytes d, PrimBytes e , PrimBytes f, PrimBytes g ) => PrimBytes (a, b, c, d, e, f, g) -- | Find out which basic GHC type it is at runtime. -- It is used for @DataFrame@ backend specialization: -- by matching a @PrimTag a@ against its constructors, you can figure out -- a specific implementation of @Backend a ds@ -- (e.g. whether this is a specialized float array, or a generic polymorphic array). -- For non-basic types it defaults to `PTagOther`. data PrimTag a where PTagFloat :: PrimTag Float PTagDouble :: PrimTag Double PTagInt :: PrimTag Int PTagInt8 :: PrimTag Int8 PTagInt16 :: PrimTag Int16 PTagInt32 :: PrimTag Int32 PTagInt64 :: PrimTag Int64 PTagWord :: PrimTag Word PTagWord8 :: PrimTag Word8 PTagWord16 :: PrimTag Word16 PTagWord32 :: PrimTag Word32 PTagWord64 :: PrimTag Word64 PTagChar :: PrimTag Char PTagPtr :: PrimTag (Ptr a) PTagOther :: PrimTag a deriving instance Show (PrimTag a) -- | Find out which basic GHC type it is at runtime. class PrimTagged a where -- | This function allows to find out a type by comparing its tag primTag' :: a -> PrimTag a -- | This function allows to find out a type by comparing its tag. -- This is needed for backend specialization, to infer array instances. -- For non-basic types it defaults to `PTagOther`. primTag :: PrimBytes a => a -> PrimTag a primTag = primTag' {-# INLINE primTag #-} instance {-# OVERLAPPABLE #-} PrimTagged a where primTag' = const PTagOther {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Float where primTag' = const PTagFloat {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Double where primTag' = const PTagDouble {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Int where primTag' = const PTagInt {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Int8 where primTag' = const PTagInt8 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Int16 where primTag' = const PTagInt16 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Int32 where primTag' = const PTagInt32 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Int64 where primTag' = const PTagInt64 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Word where primTag' = const PTagWord {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Word8 where primTag' = const PTagWord8 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Word16 where primTag' = const PTagWord16 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Word32 where primTag' = const PTagWord32 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Word64 where primTag' = const PTagWord64 {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged Char where primTag' = const PTagChar {-# INLINE primTag' #-} instance {-# OVERLAPPING #-} PrimTagged (Ptr a) where primTag' = const PTagPtr {-# INLINE primTag' #-} #if !(MIN_VERSION_base(4,12,0)) -- these functions were introduced in base-4.12.0 writeWord8ArrayAsWideChar# :: MutableByteArray# d -> Int# -> Char# -> State# d -> State# d writeWord8ArrayAsWideChar# mba off = writeWideCharArray# mba (uncheckedIShiftRL# off OFFSHIFT_C#) {-# INLINE writeWord8ArrayAsWideChar# #-} writeWord8ArrayAsAddr# :: MutableByteArray# d -> Int# -> Addr# -> State# d -> State# d writeWord8ArrayAsAddr# mba off = writeAddrArray# mba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE writeWord8ArrayAsAddr# #-} writeWord8ArrayAsStablePtr# :: MutableByteArray# d -> Int# -> StablePtr# a -> State# d -> State# d writeWord8ArrayAsStablePtr# mba off = writeStablePtrArray# mba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE writeWord8ArrayAsStablePtr# #-} writeWord8ArrayAsFloat# :: MutableByteArray# d -> Int# -> Float# -> State# d -> State# d writeWord8ArrayAsFloat# mba off = writeFloatArray# mba (uncheckedIShiftRL# off OFFSHIFT_F#) {-# INLINE writeWord8ArrayAsFloat# #-} writeWord8ArrayAsDouble# :: MutableByteArray# d -> Int# -> Double# -> State# d -> State# d writeWord8ArrayAsDouble# mba off = writeDoubleArray# mba (uncheckedIShiftRL# off OFFSHIFT_D#) {-# INLINE writeWord8ArrayAsDouble# #-} writeWord8ArrayAsInt16# :: MutableByteArray# d -> Int# -> Int# -> State# d -> State# d writeWord8ArrayAsInt16# mba off = writeInt16Array# mba (uncheckedIShiftRL# off 1#) {-# INLINE writeWord8ArrayAsInt16# #-} writeWord8ArrayAsInt32# :: MutableByteArray# d -> Int# -> Int# -> State# d -> State# d writeWord8ArrayAsInt32# mba off = writeInt32Array# mba (uncheckedIShiftRL# off 2#) {-# INLINE writeWord8ArrayAsInt32# #-} writeWord8ArrayAsInt64# :: MutableByteArray# d -> Int# -> Int# -> State# d -> State# d writeWord8ArrayAsInt64# mba off = writeInt64Array# mba (uncheckedIShiftRL# off 3#) {-# INLINE writeWord8ArrayAsInt64# #-} writeWord8ArrayAsInt# :: MutableByteArray# d -> Int# -> Int# -> State# d -> State# d writeWord8ArrayAsInt# mba off = writeIntArray# mba (uncheckedIShiftRL# off OFFSHIFT_I#) {-# INLINE writeWord8ArrayAsInt# #-} writeWord8ArrayAsWord16# :: MutableByteArray# d -> Int# -> Word# -> State# d -> State# d writeWord8ArrayAsWord16# mba off = writeWord16Array# mba (uncheckedIShiftRL# off 1#) {-# INLINE writeWord8ArrayAsWord16# #-} writeWord8ArrayAsWord32# :: MutableByteArray# d -> Int# -> Word# -> State# d -> State# d writeWord8ArrayAsWord32# mba off = writeWord32Array# mba (uncheckedIShiftRL# off 2#) {-# INLINE writeWord8ArrayAsWord32# #-} writeWord8ArrayAsWord64# :: MutableByteArray# d -> Int# -> Word# -> State# d -> State# d writeWord8ArrayAsWord64# mba off = writeWord64Array# mba (uncheckedIShiftRL# off 3#) {-# INLINE writeWord8ArrayAsWord64# #-} writeWord8ArrayAsWord# :: MutableByteArray# d -> Int# -> Word# -> State# d -> State# d writeWord8ArrayAsWord# mba off = writeWordArray# mba (uncheckedIShiftRL# off OFFSHIFT_W#) {-# INLINE writeWord8ArrayAsWord# #-} readWord8ArrayAsWideChar# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Char# #) readWord8ArrayAsWideChar# mba off = readWideCharArray# mba (uncheckedIShiftRL# off OFFSHIFT_C#) {-# INLINE readWord8ArrayAsWideChar# #-} readWord8ArrayAsAddr# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Addr# #) readWord8ArrayAsAddr# mba off = readAddrArray# mba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE readWord8ArrayAsAddr# #-} readWord8ArrayAsStablePtr# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, StablePtr# a #) readWord8ArrayAsStablePtr# mba off = readStablePtrArray# mba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE readWord8ArrayAsStablePtr# #-} readWord8ArrayAsFloat# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Float# #) readWord8ArrayAsFloat# mba off = readFloatArray# mba (uncheckedIShiftRL# off OFFSHIFT_F#) {-# INLINE readWord8ArrayAsFloat# #-} readWord8ArrayAsDouble# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Double# #) readWord8ArrayAsDouble# mba off = readDoubleArray# mba (uncheckedIShiftRL# off OFFSHIFT_D#) {-# INLINE readWord8ArrayAsDouble# #-} readWord8ArrayAsInt16# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #) readWord8ArrayAsInt16# mba off = readInt16Array# mba (uncheckedIShiftRL# off 1#) {-# INLINE readWord8ArrayAsInt16# #-} readWord8ArrayAsInt32# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #) readWord8ArrayAsInt32# mba off = readInt32Array# mba (uncheckedIShiftRL# off 2#) {-# INLINE readWord8ArrayAsInt32# #-} readWord8ArrayAsInt64# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #) readWord8ArrayAsInt64# mba off = readInt64Array# mba (uncheckedIShiftRL# off 3#) {-# INLINE readWord8ArrayAsInt64# #-} readWord8ArrayAsInt# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Int# #) readWord8ArrayAsInt# mba off = readIntArray# mba (uncheckedIShiftRL# off OFFSHIFT_I#) {-# INLINE readWord8ArrayAsInt# #-} readWord8ArrayAsWord16# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Word# #) readWord8ArrayAsWord16# mba off = readWord16Array# mba (uncheckedIShiftRL# off 1#) {-# INLINE readWord8ArrayAsWord16# #-} readWord8ArrayAsWord32# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Word# #) readWord8ArrayAsWord32# mba off = readWord32Array# mba (uncheckedIShiftRL# off 2#) {-# INLINE readWord8ArrayAsWord32# #-} readWord8ArrayAsWord64# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Word# #) readWord8ArrayAsWord64# mba off = readWord64Array# mba (uncheckedIShiftRL# off 3#) {-# INLINE readWord8ArrayAsWord64# #-} readWord8ArrayAsWord# :: MutableByteArray# d -> Int# -> State# d -> (# State# d, Word# #) readWord8ArrayAsWord# mba off = readWordArray# mba (uncheckedIShiftRL# off OFFSHIFT_W#) {-# INLINE readWord8ArrayAsWord# #-} indexWord8ArrayAsWideChar# :: ByteArray# -> Int# -> Char# indexWord8ArrayAsWideChar# ba off = indexWideCharArray# ba (uncheckedIShiftRL# off OFFSHIFT_C#) {-# INLINE indexWord8ArrayAsWideChar# #-} indexWord8ArrayAsAddr# :: ByteArray# -> Int# -> Addr# indexWord8ArrayAsAddr# ba off = indexAddrArray# ba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE indexWord8ArrayAsAddr# #-} indexWord8ArrayAsStablePtr# :: ByteArray# -> Int# -> StablePtr# a indexWord8ArrayAsStablePtr# ba off = indexStablePtrArray# ba (uncheckedIShiftRL# off OFFSHIFT_P#) {-# INLINE indexWord8ArrayAsStablePtr# #-} indexWord8ArrayAsFloat# :: ByteArray# -> Int# -> Float# indexWord8ArrayAsFloat# ba off = indexFloatArray# ba (uncheckedIShiftRL# off OFFSHIFT_F#) {-# INLINE indexWord8ArrayAsFloat# #-} indexWord8ArrayAsDouble# :: ByteArray# -> Int# -> Double# indexWord8ArrayAsDouble# ba off = indexDoubleArray# ba (uncheckedIShiftRL# off OFFSHIFT_D#) {-# INLINE indexWord8ArrayAsDouble# #-} indexWord8ArrayAsInt16# :: ByteArray# -> Int# -> Int# indexWord8ArrayAsInt16# ba off = indexInt16Array# ba (uncheckedIShiftRL# off 1#) {-# INLINE indexWord8ArrayAsInt16# #-} indexWord8ArrayAsInt32# :: ByteArray# -> Int# -> Int# indexWord8ArrayAsInt32# ba off = indexInt32Array# ba (uncheckedIShiftRL# off 2#) {-# INLINE indexWord8ArrayAsInt32# #-} indexWord8ArrayAsInt64# :: ByteArray# -> Int# -> Int# indexWord8ArrayAsInt64# ba off = indexInt64Array# ba (uncheckedIShiftRL# off 3#) {-# INLINE indexWord8ArrayAsInt64# #-} indexWord8ArrayAsInt# :: ByteArray# -> Int# -> Int# indexWord8ArrayAsInt# ba off = indexIntArray# ba (uncheckedIShiftRL# off OFFSHIFT_I#) {-# INLINE indexWord8ArrayAsInt# #-} indexWord8ArrayAsWord16# :: ByteArray# -> Int# -> Word# indexWord8ArrayAsWord16# ba off = indexWord16Array# ba (uncheckedIShiftRL# off 1#) {-# INLINE indexWord8ArrayAsWord16# #-} indexWord8ArrayAsWord32# :: ByteArray# -> Int# -> Word# indexWord8ArrayAsWord32# ba off = indexWord32Array# ba (uncheckedIShiftRL# off 2#) {-# INLINE indexWord8ArrayAsWord32# #-} indexWord8ArrayAsWord64# :: ByteArray# -> Int# -> Word# indexWord8ArrayAsWord64# ba off = indexWord64Array# ba (uncheckedIShiftRL# off 3#) {-# INLINE indexWord8ArrayAsWord64# #-} indexWord8ArrayAsWord# :: ByteArray# -> Int# -> Word# indexWord8ArrayAsWord# ba off = indexWordArray# ba (uncheckedIShiftRL# off OFFSHIFT_W#) {-# INLINE indexWord8ArrayAsWord# #-} #endif
achirkin/easytensor
easytensor/src/Numeric/PrimBytes.hs
bsd-3-clause
76,161
0
18
20,096
20,278
10,332
9,946
1,432
2
{- | This modules defines `Builder`s, which are simple parsers on `Integer`. -} module Scat.Builder ( -- * Type Builder -- * Execution , runBuilder , evalBuilder , execBuilder -- * Primitives -- ** Numbers , lessThan , inRange -- ** Char , digit , letter , lower , upper , ascii , special -- * Combinators , useup , shuffle , oneOf , oneOfV ) where import Data.Char (ord, chr) import Data.Monoid import Control.Applicative import Control.Monad import Control.Arrow (second) import Data.Vector (Vector) import qualified Data.Vector as V import Scat.Utils.Permutation -- | Parser acting on an `Integer`. newtype Builder a = Builder { runBuilder :: Integer -> (Integer, a) -- ^ Runs the builder. } -- | Evaluates the builder. evalBuilder :: Builder a -> Integer -> a evalBuilder b n = snd $ runBuilder b n -- | Executes the builder. execBuilder :: Builder a -> Integer -> Integer execBuilder b n = fst $ runBuilder b n instance Functor Builder where fmap f (Builder g) = Builder $ second f . g instance Applicative Builder where pure x = Builder (\ n -> (n, x)) f <*> x = Builder $ \ n -> let (n', g) = runBuilder f n in g <$> runBuilder x n' instance Monad Builder where return = pure x >>= f = Builder $ \ n -> let (n', v) = runBuilder x n in runBuilder (f v) n' instance Monoid a => Monoid (Builder a) where mempty = return mempty mappend a b = mappend <$> a <*> b -- | Returns a positive integer less than `i`. lessThan :: Integral a => a -> Builder a lessThan i = Builder $ \ n -> second fromIntegral $ quotRem n $ fromIntegral i -- | Returns an integer between `a` and `b`, both inclusive. inRange :: Integral a => (a, a) -> Builder a inRange (a, b) = fmap (+ a) $ lessThan $ b + 1 - a -- | Returns a lower case letter. lower :: Builder Char lower = (chr . (+ ord 'a')) <$> lessThan 26 -- | Returns an upper case letter. upper :: Builder Char upper = (chr . (+ ord 'A')) <$> lessThan 26 -- | Returns an printable ascii char. ascii :: Builder Char ascii = chr <$> inRange (32, 126) -- | Returns a digit. digit :: Builder Char digit = chr <$> inRange (48, 57) -- | Returns a letter. letter :: Builder Char letter = join $ oneOf [upper, lower] -- | Returns a special character. special :: Builder Char special = oneOf "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" -- | Returns one element of the list. oneOf :: [a] -> Builder a oneOf [] = error "oneOf on empty list" oneOf xs = fmap (xs !!) $ lessThan $ length xs -- | Returns on element of the vector. oneOfV :: Vector a -> Builder a oneOfV vect = fmap (vect V.!) $ lessThan $ V.length vect {- | Returns the results of the input builder until the consummed integer is 0. -} useup :: Builder a -> Builder [a] useup b = Builder $ \ n -> if n == 0 then (0, []) else runBuilder ((:) <$> b <*> useup b) n -- | Shuffles the input list. shuffle :: [a] -> Builder [a] shuffle xs = fmap (perm xs) $ lessThan $ fact $ fromIntegral $ length xs where fact :: Integer -> Integer fact n = product [1 .. n]
rnhmjoj/scat
src/Scat/Builder.hs
bsd-3-clause
3,165
0
12
810
1,003
541
462
76
2
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell data TokenType = Foo | Char [lq| bar :: Char |] bar :: Char bar = undefined
spinda/liquidhaskell
tests/gsoc15/unknown/pos/TokenType.hs
bsd-3-clause
134
0
5
31
32
20
12
6
1
module Main where import Test.Tasty import Test.Tasty.HUnit -- import Test.Tasty.Runners.AntXML -- For cabal builds on Jenkins import Control.Applicative import Control.Monad.IO.Class import Prosper import Prosper.Monad import Prosper.MarketDataUser noteTestGroup :: ProsperState -> TestTree noteTestGroup ps = testGroup "Notes" [ testCase "parses at all" (runProsper ps parsesNoteAtAll) ] withMDUser :: (User -> Prosper a) -> Prosper a withMDUser f = mdUser <$> getMarketDataUser >>= f parsesNoteAtAll :: Prosper () parsesNoteAtAll = withMDUser $ \n -> liftIO $ notes n >>= print main :: IO () main = do ps <- initializeProsper "prosper.cfg" defaultMain $ testGroup "Tests" [ noteTestGroup ps ]
WraithM/notescript
test/RunTests.hs
bsd-3-clause
740
0
10
141
195
103
92
21
1
module Text.XML.SpreadsheetML.Builder where import Text.XML.SpreadsheetML.Types -- | Construct empty values emptyWorkbook :: Workbook emptyWorkbook = Workbook Nothing Nothing [] emptyDocumentProperties :: DocumentProperties emptyDocumentProperties = DocumentProperties Nothing Nothing Nothing Nothing Nothing Nothing Nothing emptyWorksheet :: Name -> Worksheet emptyWorksheet name = Worksheet Nothing name emptyTable :: Table emptyTable = Table [] [] Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing emptyColumn :: Column emptyColumn = Column Nothing Nothing Nothing Nothing Nothing Nothing Nothing emptyRow :: Row emptyRow = Row [] Nothing Nothing Nothing Nothing Nothing Nothing Nothing emptyCell :: Cell emptyCell = Cell Nothing Nothing Nothing Nothing Nothing Nothing formatCell :: StyleID -> Cell -> Cell formatCell s c = c { cellStyleID = Just s } -- | Convenience constructors number :: Double -> Cell number d = emptyCell { cellData = Just (Number d) } string :: String -> Cell string s = emptyCell { cellData = Just (StringType s) } bool :: Bool -> Cell bool b = emptyCell { cellData = Just (Boolean b) } -- | This function may change in future versions, if a real formula type is -- created. formula :: String -> Cell formula f = emptyCell { cellFormula = Just (Formula f) } mkWorkbook :: [Worksheet] -> Workbook mkWorkbook ws = Workbook Nothing Nothing ws mkStyles :: [Style] -> Styles mkStyles ss = Styles ss mkBorders :: [Border] -> Borders mkBorders bs = Borders bs mkStyle :: StyleID -> Style mkStyle id = Style id Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing mkWorksheet :: Name -> Table -> Worksheet mkWorksheet name table = Worksheet (Just table) name mkTable :: [Row] -> Table mkTable rs = emptyTable { tableRows = rs } mkRow :: [Cell] -> Row mkRow cs = emptyRow { rowCells = cs } -- | Most of the time this is the easiest way to make a table tableFromCells :: [[Cell]] -> Table tableFromCells cs = mkTable (map mkRow cs)
dagit/SpreadsheetML
src/Text/XML/SpreadsheetML/Builder.hs
bsd-3-clause
2,010
0
9
349
603
322
281
45
1
{-# LANGUAGE Arrows #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Main where import Data.Aeson import Data.Profunctor.Product import Data.Profunctor.Product.Default import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Scientific import Data.ByteString hiding (putStrLn) import Data.Text import Data.Time import Opaleye import Database.PostgreSQL.Simple import Database.PostgreSQL.Simple.FromField (Conversion, FromField (..), ResultError (..), returnError) import Control.Arrow import Prelude hiding (id) -- Tenant stuff newtype TenantId = TenantId Int deriving(Show) data TenantStatus = TenantStatusActive | TenantStatusInActive | TenantStatusNew deriving (Show) data TenantPoly key name fname lname email phone status b_domain = Tenant { tenant_id :: key , tenant_name :: name , tenant_firstname :: fname , tenant_lastname :: lname , tenant_email :: email , tenant_phone :: phone , tenant_status :: status , tenant_backofficedomain :: b_domain } deriving (Show) type Tenant = TenantPoly TenantId Text Text Text Text Text TenantStatus Text type TenantTableW = TenantPoly (Maybe (Column PGInt4)) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) type TenantTableR = TenantPoly (Column PGInt4) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) (Column PGText) -- Product stuff newtype ProductId = ProductId Int deriving (Show) data ProductType = ProductPhysical | ProductDigital deriving (Show) data ProductPoly id created_at updated_at tenant_id name description url_slug tags currency advertised_price comparison_price cost_price product_type is_published properties = Product { product_id :: id , product_created_at :: created_at , product_updated_at :: updated_at , product_tenant_id :: tenant_id , product_name :: name , product_description :: description , product_url_slug :: url_slug , product_tags :: tags , product_currency :: currency , product_advertised_price :: advertised_price , product_comparison_price :: comparison_price , product_cost_price :: cost_price , product_product_type :: product_type , product_is_published :: is_published , product_properties :: properties } deriving (Show) type Product = ProductPoly ProductId UTCTime UTCTime TenantId Text (Maybe Text) Text [Text] Text Scientific Scientific (Maybe Scientific) ProductType Bool Value type ProductTableW = ProductPoly (Maybe (Column PGInt4)) (Maybe (Column PGTimestamptz)) (Maybe (Column PGTimestamptz)) (Column PGInt4) (Column PGText) (Maybe (Column (Nullable PGText))) (Column PGText) (Column (PGArray PGText)) (Column PGText) (Column PGFloat8) (Column PGFloat8) (Maybe (Column (Nullable PGFloat8))) (Column PGText) (Column PGBool) (Column PGJsonb) type ProductTableR = ProductPoly (Column PGInt4) (Column PGTimestamptz) (Column PGTimestamptz) (Column PGInt4) (Column PGText) (Column (Nullable PGText)) (Column PGText) (Column (PGArray PGText)) (Column PGText) (Column PGFloat8) (Column PGFloat8) (Column (Nullable PGFloat8)) (Column PGText) (Column PGBool) (Column PGJsonb) -- Table defs $(makeAdaptorAndInstance "pTenant" ''TenantPoly) tenantTable :: Table TenantTableW TenantTableR tenantTable = Table "tenants" (pTenant Tenant { tenant_id = (optional "id"), tenant_name = (required "name"), tenant_firstname = (required "first_name"), tenant_lastname = (required "last_name"), tenant_email = (required "email"), tenant_phone = (required "phone"), tenant_status = (required "status"), tenant_backofficedomain = (required "backoffice_domain") } ) $(makeAdaptorAndInstance "pProduct" ''ProductPoly) productTable :: Table ProductTableW ProductTableR productTable = Table "products" (pProduct Product { product_id = (optional "id"), product_created_at = (optional "created_at"), product_updated_at = (optional "updated_at"), product_tenant_id = (required "tenant_id"), product_name = (required "name"), product_description = (optional "description"), product_url_slug = (required "url_slug"), product_tags = (required "tags"), product_currency = (required "currency"), product_advertised_price = (required "advertised_price"), product_comparison_price = (required "comparison_price"), product_cost_price = (optional "cost_price"), product_product_type = (required "type"), product_is_published = (required "is_published"), product_properties = (required "properties") }) -- Instance declarations for custom types -- For TenantStatus instance FromField TenantStatus where fromField field mb_bytestring = makeTenantStatus mb_bytestring where makeTenantStatus :: Maybe ByteString -> Conversion TenantStatus makeTenantStatus (Just "active") = return TenantStatusActive makeTenantStatus (Just "inactive") = return TenantStatusInActive makeTenantStatus (Just "new") = return TenantStatusNew makeTenantStatus (Just _) = returnError ConversionFailed field "Unrecognized tenant status" makeTenantStatus Nothing = returnError UnexpectedNull field "Empty tenant status" instance QueryRunnerColumnDefault PGText TenantStatus where queryRunnerColumnDefault = fieldQueryRunnerColumn -- For ProductType instance FromField ProductType where fromField field mb_bytestring = makeProductType mb_bytestring where makeProductType :: Maybe ByteString -> Conversion ProductType makeProductType (Just "physical") = return ProductPhysical makeProductType (Just "digital") = return ProductDigital makeProductType (Just _) = returnError ConversionFailed field "Unrecognized product type" makeTenantStatus Nothing = returnError UnexpectedNull field "Empty product type" instance QueryRunnerColumnDefault PGText ProductType where queryRunnerColumnDefault = fieldQueryRunnerColumn -- For productId instance FromField ProductId where fromField field mb_bytestring = ProductId <$> fromField field mb_bytestring instance QueryRunnerColumnDefault PGInt4 ProductId where queryRunnerColumnDefault = fieldQueryRunnerColumn -- For TenantId instance FromField TenantId where fromField field mb_bytestring = TenantId <$> fromField field mb_bytestring instance QueryRunnerColumnDefault PGInt4 TenantId where queryRunnerColumnDefault = fieldQueryRunnerColumn -- For Scientific we didn't have to implement instance of fromField -- because it is already defined in postgresql-simple instance QueryRunnerColumnDefault PGFloat8 Scientific where queryRunnerColumnDefault = fieldQueryRunnerColumn -- Default instance definitions for custom datatypes for converison to -- PG types while writing into tables -- For Tenant stuff instance Default Constant TenantStatus (Column PGText) where def = Constant def' where def' :: TenantStatus -> (Column PGText) def' TenantStatusActive = pgStrictText "active" def' TenantStatusInActive = pgStrictText "inactive" def' TenantStatusNew = pgStrictText "new" instance Default Constant TenantId (Maybe (Column PGInt4)) where def = Constant (\(TenantId x) -> Just $ pgInt4 x) -- For Product stuff instance Default Constant ProductType (Column PGText) where def = Constant def' where def' :: ProductType -> (Column PGText) def' ProductDigital = pgStrictText "digital" def' ProductPhysical = pgStrictText "physical" instance Default Constant ProductId (Maybe (Column PGInt4)) where def = Constant (\(ProductId x) -> Just $ constant x) instance Default Constant Scientific (Column PGFloat8) where def = Constant (pgDouble.toRealFloat) instance Default Constant Scientific (Column (Nullable PGFloat8)) where def = Constant (toNullable.constant) instance Default Constant Text (Column (Nullable PGText)) where def = Constant (toNullable.pgStrictText) instance Default Constant UTCTime (Maybe (Column PGTimestamptz)) where def = Constant ((Just).pgUTCTime) instance Default Constant TenantId (Column PGInt4) where def = Constant (\(TenantId x) -> constant x) getProducts :: IO [Product] getProducts = do conn <- connect defaultConnectInfo { connectDatabase = "scratch"} runQuery conn $ queryTable productTable getTenants :: IO [Tenant] getTenants = do conn <- connect defaultConnectInfo { connectDatabase = "scratch"} runQuery conn $ queryTable tenantTable insertTenant :: IO () insertTenant = do conn <- connect defaultConnectInfo { connectDatabase = "scratch"} runInsertManyReturning conn tenantTable [constant getTestTenant] (\x -> x) :: IO [Tenant] return () insertProduct :: IO () insertProduct = do conn <- connect defaultConnectInfo { connectDatabase = "scratch"} product <- getTestProduct runInsertManyReturning conn productTable [constant product] (\x -> x) :: IO [Product] return () getTestTenant :: TenantIncoming getTestTenant = Tenant { tenant_id = (), tenant_name = "Tenant Bob", tenant_firstname = "Bobby", tenant_lastname = "Bob", tenant_email = "[email protected]", tenant_phone = "2255", tenant_status = TenantStatusInActive, tenant_backofficedomain = "bob.com" } getTestProduct :: IO Product getTestProduct = do time <- getCurrentTime let (Just properties) = decode "{\"weight\": \"200gm\"}" :: Maybe Value return $ Product { product_id = (ProductId 5), product_created_at = time, product_updated_at = time, product_tenant_id = (TenantId 5), product_name = "snacks", product_description = Just "", product_url_slug = "", product_tags = ["tag1", "tag2"], product_currency = "INR", product_advertised_price = 30, product_comparison_price = 45, product_cost_price = Nothing, product_product_type = ProductPhysical, product_is_published = False, product_properties = properties } main :: IO () main = do insertTenant insertProduct tenants <- getTenants products <- getProducts putStrLn $ show tenants putStrLn $ show products -- Output -- -- [Tenant {tenant_id = TenantId 1, tenant_name = "Tenant John", tenant_firstname -- = "John", tenant_lastname = "Honai", tenant_email = "[email protected]", tenant_pho -- ne = "2255", tenant_status = TenantStatusInActive, tenant_backofficedomain = "j -- honhonai.com"}] -- [Product {product_id = ProductId 1, product_created_at = 2016-11-27 10:24:31.60 -- 0244 UTC, product_updated_at = 2016-11-27 10:24:31.600244 UTC, product_tenant_i -- d = TenantId 1, product_name = "Biscuits", product_description = Just "Biscuits -- , you know..", product_url_slug = "biscuits", product_tags = ["bakery","snacks" -- ], product_currency = "INR", product_advertised_price = 40.0, product_compariso -- n_price = 55.0, product_cost_price = Just 34.0, product_product_type = ProductP -- hysical, product_is_published = False, product_properties = Object (fromList [( -- "weight",String "200gm")])}]
meditans/haskell-webapps
doc/docs/opaleye/code/opaleye-tenants-and-products.hs
mit
11,687
0
11
2,399
2,640
1,437
1,203
248
1
-- Copyright (c) Microsoft. All rights reserved. -- Licensed under the MIT license. See LICENSE file in the project root for full license information. {-# LANGUAGE DeriveDataTypeable #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-cse #-} module Options ( getOptions , processOptions , Options(..) , ApplyOptions(..) ) where import Paths_bond (version) import Data.Version (showVersion) import System.Console.CmdArgs import System.Console.CmdArgs.Explicit (processValue) data ApplyOptions = Compact | Fast | Simple deriving (Show, Data, Typeable, Eq) data Options = Options | Cpp { files :: [FilePath] , import_dir :: [FilePath] , output_dir :: FilePath , using :: [String] , namespace :: [String] , header :: [String] , enum_header :: Bool , allocator :: Maybe String , apply :: [ApplyOptions] , export_attribute :: Maybe String , jobs :: Maybe Int , no_banner :: Bool , core_enabled :: Bool , comm_enabled :: Bool , grpc_enabled :: Bool , alloc_ctors_enabled :: Bool , type_aliases_enabled :: Bool , scoped_alloc_enabled :: Bool , service_inheritance_enabled :: Bool } | Cs { files :: [FilePath] , import_dir :: [FilePath] , output_dir :: FilePath , using :: [String] , namespace :: [String] , collection_interfaces :: Bool , readonly_properties :: Bool , fields :: Bool , jobs :: Maybe Int , no_banner :: Bool , structs_enabled :: Bool , comm_enabled :: Bool , grpc_enabled :: Bool , service_inheritance_enabled :: Bool } | Java { files :: [FilePath] , import_dir :: [FilePath] , output_dir :: FilePath , using :: [String] , namespace :: [String] , jobs :: Maybe Int , no_banner :: Bool } | Schema { files :: [FilePath] , import_dir :: [FilePath] , output_dir :: FilePath , jobs :: Maybe Int , runtime_schema :: Bool , service_inheritance_enabled :: Bool } deriving (Show, Data, Typeable) cpp :: Options cpp = Cpp { files = def &= typFile &= args , import_dir = def &= typDir &= name "i" &= help "Add the directory to import search path" , output_dir = "." &= typDir &= name "o" &= help "Output generated files into the specified directory" , using = def &= typ "MAPPING" &= name "u" &= help "Custom type alias mapping in the form alias=type" , namespace = def &= typ "MAPPING" &= name "n" &= help "Custom namespace mapping in the form bond_namespace=language_namespace" , header = def &= typ "HEADER" &= name "h" &= help "Emit #include HEADER into the generated files" , enum_header = def &= name "e" &= help "Generate enums into a separate header file" , allocator = def &= typ "ALLOCATOR" &= help "Generate types using the specified allocator" , apply = def &= typ "PROTOCOL" &= help "Generate Apply function overloads for the specified protocol only; supported protocols: compact, fast and simple" , export_attribute = def &= typ "ATTRIBUTE" &= explicit &= name "apply-attribute" &= name "export-attribute" &= help "Prefix declarations for library export with the specified C++ attribute/declspec. apply-attribute is a deprecated synonym." , jobs = def &= opt "0" &= typ "NUM" &= name "j" &= help "Run NUM jobs simultaneously (or '$ncpus' if no NUM is not given)" , no_banner = def &= help "Omit the banner at the top of generated files" , core_enabled = True &= explicit &= name "core" &= help "Generate core serialization definitions (true by default, --core=false to disable)" , comm_enabled = False &= explicit &= name "comm" &= help "Generate comm definitions" , grpc_enabled = False &= explicit &= name "grpc" &= help "Generate gRPC definitions" , alloc_ctors_enabled = False &= explicit &= name "alloc-ctors" &= help "Generate constructors with allocator argument" , type_aliases_enabled = False &= explicit &= name "type-aliases" &= help "Generate type aliases" , scoped_alloc_enabled = False &= explicit &= name "scoped-alloc" &= help "Use std::scoped_allocator_adaptor for strings and containers" , service_inheritance_enabled = False &= explicit &= name "enable-service-inheritance" &= help "Enable service inheritance syntax in IDL" } &= name "c++" &= help "Generate C++ code" cs :: Options cs = Cs { collection_interfaces = def &= name "c" &= help "Use interfaces rather than concrete collection types" , readonly_properties = def &= name "r" &= help "Generate private property setters" , fields = def &= name "f" &= help "Generate public fields rather than properties" , structs_enabled = True &= explicit &= name "structs" &= help "Generate C# types for Bond structs and enums (true by default, use \"--structs=false\" to disable)" , comm_enabled = False &= explicit &= name "comm" &= help "Generate C# services and proxies for Bond Comm" , grpc_enabled = False &= explicit &= name "grpc" &= help "Generate C# services and proxies for gRPC" } &= name "c#" &= help "Generate C# code" java :: Options java = Java { using = def &= typ "MAPPING" &= name "u" &= help "Currently unimplemented and ignored for Java" } &= name "java" &= help "Generate Java code" schema :: Options schema = Schema { runtime_schema = def &= help "Generate Simple JSON representation of runtime schema, aka SchemaDef" } &= name "schema" &= help "Output the JSON representation of the schema" mode :: Mode (CmdArgs Options) mode = cmdArgsMode $ modes [cpp, cs, java, schema] &= program "gbc" &= help "Compile Bond schema file(s) and generate specified output. The schema file(s) can be in one of two formats: Bond IDL or JSON representation of the schema abstract syntax tree as produced by `gbc schema`. Multiple schema files can be specified either directly on the command line or by listing them in a text file passed to gbc via @listfile syntax." &= summary ("Bond Compiler " ++ showVersion version ++ ", (C) Microsoft") getOptions :: IO Options getOptions = cmdArgsRun mode processOptions :: [String] -> Options processOptions = cmdArgsValue . processValue mode
gencer/bond
compiler/Options.hs
mit
6,426
0
14
1,583
1,328
732
596
126
1
module BasicIO (tests) where import Test.Hspec (Spec, describe, it) import Test.HUnit (assertBool, assertEqual) tests :: Spec tests = describe "BasicIO" $ do testReadingChar testReadingLine failIO :: String -> IO a failIO fnName = fail $ "\n\n\t\x1B[32;1mCheck documentation\x1B[0m of \x1B[33;1m" ++ fnName ++ "\x1B[0m on:\n\t" ++ "http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html" testReadingChar :: Spec testReadingChar = it "getChar" $ do putStrLn "Write: \"a\" to pass this test: " -- NOTE: replace 'failIO' with the actual function result <- failIO "getChar" assertEqual "" 'a' result testReadingLine :: Spec testReadingLine = it "getLine" $ do -- NOTE: replace 'failIO' with the actual function result <- failIO "getLine" assertEqual "Write: \"burrito\" to pass this test" "burrito" result
HaskVan/HaskellKoans
test/BasicIO.hs
mit
947
0
9
231
179
91
88
27
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonomorphismRestriction #-} module TAC.Data where import Autolib.Reader import Autolib.ToDoc import Autolib.FiniteMap import Autolib.Util.Zufall type Program = [ Statement ] data Statement = Constant Int Int | Add Int Int Int | Mul Int Int Int deriving ( Eq, Ord ) $(derives [makeReader, makeToDoc] [''Statement]) some :: Int -> IO Program some l = sequence $ replicate l $ do action <- eins [ some_constant , some_operation ] action some_constant = do i <- eins [ 0 .. 3 ] c <- eins [ 0 .. 1 ] return $ Constant i c some_operation = do i <- eins [ 0 .. 3 ] j <- eins [ 0 .. 3 ] k <- eins [ 0 .. 3 ] op <- eins [ Add, Mul ] return $ op i j k change_program [] = return [ Constant 0 1 ] change_program p = do i <- randomRIO ( 0, length p - 1 ) let ( pre , this : post ) = splitAt i p that <- change this return $ pre ++ that : post change s = case s of Constant i c -> do j <- randomRIO ( 0, i+1 ) d <- randomRIO ( 0, c+1 ) return $ Constant j d Add i j k -> change_operation i j k Mul i j k -> change_operation i j k change_operation i j k = do ii <- randomRIO ( max 0 $ i-1, i+1 ) jj <- randomRIO ( max 0 $ j-1, j+1 ) kk <- randomRIO ( max 0 $ k-1, k+1 ) op <- eins [ Mul, Add ] return $ op ii jj kk -- | costs on the Smallnums 1 model cost :: Statement -> Int cost s = case s of Constant i c -> patch i + patch c + 1 Add i j k -> 4 + sum [ patch i, patch j, patch k ] Mul i j k -> 4 + sum [ patch i, patch j, patch k ] patch i = max 1 $ 2*i-1 -- | the value that is left in x0 finally value :: Program -> Integer value stmts = let fm = foldl execute emptyFM stmts in access fm 0 access fm i = case lookupFM fm i of Just x -> x Nothing -> 0 execute state action = case action of Constant i c -> addToFM state i $ fromIntegral c Add i j k -> operation state (+) i j k Mul i j k -> operation state (*) i j k operation state op i j k = let x = access state j y = access state k in addToFM state i $ op x y -- local variables: -- mode: haskell -- end:
florianpilz/autotool
src/TAC/Data.hs
gpl-2.0
2,210
7
15
681
1,001
494
507
68
3
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.Redshift.DeleteHSMConfiguration -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified Amazon Redshift HSM configuration. -- -- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteHSMConfiguration.html AWS API Reference> for DeleteHSMConfiguration. module Network.AWS.Redshift.DeleteHSMConfiguration ( -- * Creating a Request deleteHSMConfiguration , DeleteHSMConfiguration -- * Request Lenses , dhcHSMConfigurationIdentifier -- * Destructuring the Response , deleteHSMConfigurationResponse , DeleteHSMConfigurationResponse ) where import Network.AWS.Prelude import Network.AWS.Redshift.Types import Network.AWS.Redshift.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'deleteHSMConfiguration' smart constructor. newtype DeleteHSMConfiguration = DeleteHSMConfiguration' { _dhcHSMConfigurationIdentifier :: Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteHSMConfiguration' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'dhcHSMConfigurationIdentifier' deleteHSMConfiguration :: Text -- ^ 'dhcHSMConfigurationIdentifier' -> DeleteHSMConfiguration deleteHSMConfiguration pHSMConfigurationIdentifier_ = DeleteHSMConfiguration' { _dhcHSMConfigurationIdentifier = pHSMConfigurationIdentifier_ } -- | The identifier of the Amazon Redshift HSM configuration to be deleted. dhcHSMConfigurationIdentifier :: Lens' DeleteHSMConfiguration Text dhcHSMConfigurationIdentifier = lens _dhcHSMConfigurationIdentifier (\ s a -> s{_dhcHSMConfigurationIdentifier = a}); instance AWSRequest DeleteHSMConfiguration where type Rs DeleteHSMConfiguration = DeleteHSMConfigurationResponse request = postQuery redshift response = receiveNull DeleteHSMConfigurationResponse' instance ToHeaders DeleteHSMConfiguration where toHeaders = const mempty instance ToPath DeleteHSMConfiguration where toPath = const "/" instance ToQuery DeleteHSMConfiguration where toQuery DeleteHSMConfiguration'{..} = mconcat ["Action" =: ("DeleteHsmConfiguration" :: ByteString), "Version" =: ("2012-12-01" :: ByteString), "HsmConfigurationIdentifier" =: _dhcHSMConfigurationIdentifier] -- | /See:/ 'deleteHSMConfigurationResponse' smart constructor. data DeleteHSMConfigurationResponse = DeleteHSMConfigurationResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'DeleteHSMConfigurationResponse' with the minimum fields required to make a request. -- deleteHSMConfigurationResponse :: DeleteHSMConfigurationResponse deleteHSMConfigurationResponse = DeleteHSMConfigurationResponse'
olorin/amazonka
amazonka-redshift/gen/Network/AWS/Redshift/DeleteHSMConfiguration.hs
mpl-2.0
3,565
0
9
659
365
224
141
55
1
module Hailstorm.Logging ( initializeLogging ) where import System.IO import System.Log.Formatter import System.Log.Logger import System.Log.Handler (setFormatter) import System.Log.Handler.Simple initializeLogging :: IO () initializeLogging = do hdlr <- streamHandler stderr INFO let fmtr = simpleLogFormatter "[$loggername $prio] $msg" updateGlobalLogger rootLoggerName $ setLevel INFO . setHandlers [setFormatter hdlr fmtr]
hailstorm-hs/hailstorm
src/Hailstorm/Logging.hs
apache-2.0
449
0
10
68
113
60
53
13
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE DeriveFunctor #-} ----------------------------------------------------------------------------- -- | -- Module : Text.ParserCombinators.ReadP -- Copyright : (c) The University of Glasgow 2002 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : non-portable (local universal quantification) -- -- This is a library of parser combinators, originally written by Koen Claessen. -- It parses all alternatives in parallel, so it never keeps hold of -- the beginning of the input string, a common source of space leaks with -- other parsers. The @('+++')@ choice combinator is genuinely commutative; -- it makes no difference which branch is \"shorter\". ----------------------------------------------------------------------------- module Text.ParserCombinators.ReadP ( -- * The 'ReadP' type ReadP, -- * Primitive operations get, look, (+++), (<++), gather, -- * Other operations pfail, eof, satisfy, char, string, munch, munch1, skipSpaces, choice, count, between, option, optional, many, many1, skipMany, skipMany1, sepBy, sepBy1, endBy, endBy1, chainr, chainl, chainl1, chainr1, manyTill, -- * Running a parser ReadS, readP_to_S, readS_to_P, -- * Properties -- $properties ) where import GHC.Unicode ( isSpace ) import GHC.List ( replicate, null ) import GHC.Base hiding ( many ) import Control.Monad.Fail infixr 5 +++, <++ ------------------------------------------------------------------------ -- ReadS -- | A parser for a type @a@, represented as a function that takes a -- 'String' and returns a list of possible parses as @(a,'String')@ pairs. -- -- Note that this kind of backtracking parser is very inefficient; -- reading a large structure may be quite slow (cf 'ReadP'). type ReadS a = String -> [(a,String)] -- --------------------------------------------------------------------------- -- The P type -- is representation type -- should be kept abstract data P a = Get (Char -> P a) | Look (String -> P a) | Fail | Result a (P a) | Final (NonEmpty (a,String)) deriving Functor -- ^ @since 4.8.0.0 -- Monad, MonadPlus -- | @since 4.5.0.0 instance Applicative P where pure x = Result x Fail (<*>) = ap -- | @since 2.01 instance MonadPlus P -- | @since 2.01 instance Monad P where (Get f) >>= k = Get (\c -> f c >>= k) (Look f) >>= k = Look (\s -> f s >>= k) Fail >>= _ = Fail (Result x p) >>= k = k x <|> (p >>= k) (Final (r:|rs)) >>= k = final [ys' | (x,s) <- (r:rs), ys' <- run (k x) s] -- | @since 4.9.0.0 instance MonadFail P where fail _ = Fail -- | @since 4.5.0.0 instance Alternative P where empty = Fail -- most common case: two gets are combined Get f1 <|> Get f2 = Get (\c -> f1 c <|> f2 c) -- results are delivered as soon as possible Result x p <|> q = Result x (p <|> q) p <|> Result x q = Result x (p <|> q) -- fail disappears Fail <|> p = p p <|> Fail = p -- two finals are combined -- final + look becomes one look and one final (=optimization) -- final + sthg else becomes one look and one final Final r <|> Final t = Final (r <> t) Final (r:|rs) <|> Look f = Look (\s -> Final (r:|(rs ++ run (f s) s))) Final (r:|rs) <|> p = Look (\s -> Final (r:|(rs ++ run p s))) Look f <|> Final r = Look (\s -> Final (case run (f s) s of [] -> r (x:xs) -> (x:|xs) <> r)) p <|> Final r = Look (\s -> Final (case run p s of [] -> r (x:xs) -> (x:|xs) <> r)) -- two looks are combined (=optimization) -- look + sthg else floats upwards Look f <|> Look g = Look (\s -> f s <|> g s) Look f <|> p = Look (\s -> f s <|> p) p <|> Look f = Look (\s -> p <|> f s) -- --------------------------------------------------------------------------- -- The ReadP type newtype ReadP a = R (forall b . (a -> P b) -> P b) -- | @since 2.01 instance Functor ReadP where fmap h (R f) = R (\k -> f (k . h)) -- | @since 4.6.0.0 instance Applicative ReadP where pure x = R (\k -> k x) (<*>) = ap -- liftA2 = liftM2 -- | @since 2.01 instance Monad ReadP where R m >>= f = R (\k -> m (\a -> let R m' = f a in m' k)) -- | @since 4.9.0.0 instance MonadFail ReadP where fail _ = R (\_ -> Fail) -- | @since 4.6.0.0 instance Alternative ReadP where empty = pfail (<|>) = (+++) -- | @since 2.01 instance MonadPlus ReadP -- --------------------------------------------------------------------------- -- Operations over P final :: [(a,String)] -> P a final [] = Fail final (r:rs) = Final (r:|rs) run :: P a -> ReadS a run (Get f) (c:s) = run (f c) s run (Look f) s = run (f s) s run (Result x p) s = (x,s) : run p s run (Final (r:|rs)) _ = (r:rs) run _ _ = [] -- --------------------------------------------------------------------------- -- Operations over ReadP get :: ReadP Char -- ^ Consumes and returns the next character. -- Fails if there is no input left. get = R Get look :: ReadP String -- ^ Look-ahead: returns the part of the input that is left, without -- consuming it. look = R Look pfail :: ReadP a -- ^ Always fails. pfail = R (\_ -> Fail) (+++) :: ReadP a -> ReadP a -> ReadP a -- ^ Symmetric choice. R f1 +++ R f2 = R (\k -> f1 k <|> f2 k) (<++) :: ReadP a -> ReadP a -> ReadP a -- ^ Local, exclusive, left-biased choice: If left parser -- locally produces any result at all, then right parser is -- not used. R f0 <++ q = do s <- look probe (f0 return) s 0# where probe (Get f) (c:s) n = probe (f c) s (n+#1#) probe (Look f) s n = probe (f s) s n probe p@(Result _ _) _ n = discard n >> R (p >>=) probe (Final r) _ _ = R (Final r >>=) probe _ _ _ = q discard 0# = return () discard n = get >> discard (n-#1#) gather :: ReadP a -> ReadP (String, a) -- ^ Transforms a parser into one that does the same, but -- in addition returns the exact characters read. -- IMPORTANT NOTE: 'gather' gives a runtime error if its first argument -- is built using any occurrences of readS_to_P. gather (R m) = R (\k -> gath id (m (\a -> return (\s -> k (s,a))))) where gath :: (String -> String) -> P (String -> P b) -> P b gath l (Get f) = Get (\c -> gath (l.(c:)) (f c)) gath _ Fail = Fail gath l (Look f) = Look (\s -> gath l (f s)) gath l (Result k p) = k (l []) <|> gath l p gath _ (Final _) = errorWithoutStackTrace "do not use readS_to_P in gather!" -- --------------------------------------------------------------------------- -- Derived operations satisfy :: (Char -> Bool) -> ReadP Char -- ^ Consumes and returns the next character, if it satisfies the -- specified predicate. satisfy p = do c <- get; if p c then return c else pfail char :: Char -> ReadP Char -- ^ Parses and returns the specified character. char c = satisfy (c ==) eof :: ReadP () -- ^ Succeeds iff we are at the end of input eof = do { s <- look ; if null s then return () else pfail } string :: String -> ReadP String -- ^ Parses and returns the specified string. string this = do s <- look; scan this s where scan [] _ = do return this scan (x:xs) (y:ys) | x == y = do _ <- get; scan xs ys scan _ _ = do pfail munch :: (Char -> Bool) -> ReadP String -- ^ Parses the first zero or more characters satisfying the predicate. -- Always succeeds, exactly once having consumed all the characters -- Hence NOT the same as (many (satisfy p)) munch p = do s <- look scan s where scan (c:cs) | p c = do _ <- get; s <- scan cs; return (c:s) scan _ = do return "" munch1 :: (Char -> Bool) -> ReadP String -- ^ Parses the first one or more characters satisfying the predicate. -- Fails if none, else succeeds exactly once having consumed all the characters -- Hence NOT the same as (many1 (satisfy p)) munch1 p = do c <- get if p c then do s <- munch p; return (c:s) else pfail choice :: [ReadP a] -> ReadP a -- ^ Combines all parsers in the specified list. choice [] = pfail choice [p] = p choice (p:ps) = p +++ choice ps skipSpaces :: ReadP () -- ^ Skips all whitespace. skipSpaces = do s <- look skip s where skip (c:s) | isSpace c = do _ <- get; skip s skip _ = do return () count :: Int -> ReadP a -> ReadP [a] -- ^ @count n p@ parses @n@ occurrences of @p@ in sequence. A list of -- results is returned. count n p = sequence (replicate n p) between :: ReadP open -> ReadP close -> ReadP a -> ReadP a -- ^ @between open close p@ parses @open@, followed by @p@ and finally -- @close@. Only the value of @p@ is returned. between open close p = do _ <- open x <- p _ <- close return x option :: a -> ReadP a -> ReadP a -- ^ @option x p@ will either parse @p@ or return @x@ without consuming -- any input. option x p = p +++ return x optional :: ReadP a -> ReadP () -- ^ @optional p@ optionally parses @p@ and always returns @()@. optional p = (p >> return ()) +++ return () many :: ReadP a -> ReadP [a] -- ^ Parses zero or more occurrences of the given parser. many p = return [] +++ many1 p many1 :: ReadP a -> ReadP [a] -- ^ Parses one or more occurrences of the given parser. many1 p = liftM2 (:) p (many p) skipMany :: ReadP a -> ReadP () -- ^ Like 'many', but discards the result. skipMany p = many p >> return () skipMany1 :: ReadP a -> ReadP () -- ^ Like 'many1', but discards the result. skipMany1 p = p >> skipMany p sepBy :: ReadP a -> ReadP sep -> ReadP [a] -- ^ @sepBy p sep@ parses zero or more occurrences of @p@, separated by @sep@. -- Returns a list of values returned by @p@. sepBy p sep = sepBy1 p sep +++ return [] sepBy1 :: ReadP a -> ReadP sep -> ReadP [a] -- ^ @sepBy1 p sep@ parses one or more occurrences of @p@, separated by @sep@. -- Returns a list of values returned by @p@. sepBy1 p sep = liftM2 (:) p (many (sep >> p)) endBy :: ReadP a -> ReadP sep -> ReadP [a] -- ^ @endBy p sep@ parses zero or more occurrences of @p@, separated and ended -- by @sep@. endBy p sep = many (do x <- p ; _ <- sep ; return x) endBy1 :: ReadP a -> ReadP sep -> ReadP [a] -- ^ @endBy p sep@ parses one or more occurrences of @p@, separated and ended -- by @sep@. endBy1 p sep = many1 (do x <- p ; _ <- sep ; return x) chainr :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a -- ^ @chainr p op x@ parses zero or more occurrences of @p@, separated by @op@. -- Returns a value produced by a /right/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainr p op x = chainr1 p op +++ return x chainl :: ReadP a -> ReadP (a -> a -> a) -> a -> ReadP a -- ^ @chainl p op x@ parses zero or more occurrences of @p@, separated by @op@. -- Returns a value produced by a /left/ associative application of all -- functions returned by @op@. If there are no occurrences of @p@, @x@ is -- returned. chainl p op x = chainl1 p op +++ return x chainr1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a -- ^ Like 'chainr', but parses one or more occurrences of @p@. chainr1 p op = scan where scan = p >>= rest rest x = do f <- op y <- scan return (f x y) +++ return x chainl1 :: ReadP a -> ReadP (a -> a -> a) -> ReadP a -- ^ Like 'chainl', but parses one or more occurrences of @p@. chainl1 p op = p >>= rest where rest x = do f <- op y <- p rest (f x y) +++ return x manyTill :: ReadP a -> ReadP end -> ReadP [a] -- ^ @manyTill p end@ parses zero or more occurrences of @p@, until @end@ -- succeeds. Returns a list of values returned by @p@. manyTill p end = scan where scan = (end >> return []) <++ (liftM2 (:) p scan) -- --------------------------------------------------------------------------- -- Converting between ReadP and Read readP_to_S :: ReadP a -> ReadS a -- ^ Converts a parser into a Haskell ReadS-style function. -- This is the main way in which you can \"run\" a 'ReadP' parser: -- the expanded type is -- @ readP_to_S :: ReadP a -> String -> [(a,String)] @ readP_to_S (R f) = run (f return) readS_to_P :: ReadS a -> ReadP a -- ^ Converts a Haskell ReadS-style function into a parser. -- Warning: This introduces local backtracking in the resulting -- parser, and therefore a possible inefficiency. readS_to_P r = R (\k -> Look (\s -> final [bs'' | (a,s') <- r s, bs'' <- run (k a) s'])) -- --------------------------------------------------------------------------- -- QuickCheck properties that hold for the combinators {- $properties The following are QuickCheck specifications of what the combinators do. These can be seen as formal specifications of the behavior of the combinators. For some values, we only care about the lists contents, not their order, > (=~) :: Ord a => [a] -> [a] -> Bool > xs =~ ys = sort xs == sort ys Here follow the properties: >>> readP_to_S get [] [] prop> \c str -> readP_to_S get (c:str) == [(c, str)] prop> \str -> readP_to_S look str == [(str, str)] prop> \str -> readP_to_S pfail str == [] prop> \x str -> readP_to_S (return x) s == [(x,s)] > prop_Bind p k s = > readP_to_S (p >>= k) s =~ > [ ys'' > | (x,s') <- readP_to_S p s > , ys'' <- readP_to_S (k (x::Int)) s' > ] > prop_Plus p q s = > readP_to_S (p +++ q) s =~ > (readP_to_S p s ++ readP_to_S q s) > prop_LeftPlus p q s = > readP_to_S (p <++ q) s =~ > (readP_to_S p s +<+ readP_to_S q s) > where > [] +<+ ys = ys > xs +<+ _ = xs > prop_Gather s = > forAll readPWithoutReadS $ \p -> > readP_to_S (gather p) s =~ > [ ((pre,x::Int),s') > | (x,s') <- readP_to_S p s > , let pre = take (length s - length s') s > ] prop> \this str -> readP_to_S (string this) (this ++ str) == [(this,str)] > prop_String_Maybe this s = > readP_to_S (string this) s =~ > [(this, drop (length this) s) | this `isPrefixOf` s] > prop_Munch p s = > readP_to_S (munch p) s =~ > [(takeWhile p s, dropWhile p s)] > prop_Munch1 p s = > readP_to_S (munch1 p) s =~ > [(res,s') | let (res,s') = (takeWhile p s, dropWhile p s), not (null res)] > prop_Choice ps s = > readP_to_S (choice ps) s =~ > readP_to_S (foldr (+++) pfail ps) s > prop_ReadS r s = > readP_to_S (readS_to_P r) s =~ r s -}
sdiehl/ghc
libraries/base/Text/ParserCombinators/ReadP.hs
bsd-3-clause
14,956
1
17
3,998
3,905
2,018
1,887
223
6
-- Copyright (c) 2014 Eric McCorkle. All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- -- 3. Neither the name of the author nor the names of any contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -- TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A -- PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS -- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF -- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT -- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -- SUCH DAMAGE. module Tests.Text(tests) where import Test.HUnitPlus.Base import qualified Tests.Text.Numbers as Numbers tests :: Test tests = "Text" ~: [Numbers.tests]
saltlang/compiler-toolbox
test/Tests/Text.hs
bsd-3-clause
1,713
0
7
289
74
58
16
5
1
--------------------------------------------------------- -- The main program for the hpc-markup tool, part of HPC. -- Andy Gill and Colin Runciman, June 2006 --------------------------------------------------------- module HpcMarkup (markup_plugin) where import Trace.Hpc.Mix import Trace.Hpc.Tix import Trace.Hpc.Util import HpcFlags import HpcUtils import System.Directory import Data.List import Data.Maybe(fromJust) import Data.Array import Data.Monoid import Control.Monad import qualified Data.Set as Set ------------------------------------------------------------------------------ markup_options :: FlagOptSeq markup_options = excludeOpt . includeOpt . srcDirOpt . hpcDirOpt . funTotalsOpt . altHighlightOpt . destDirOpt markup_plugin :: Plugin markup_plugin = Plugin { name = "markup" , usage = "[OPTION] .. <TIX_FILE> [<MODULE> [<MODULE> ..]]" , options = markup_options , summary = "Markup Haskell source with program coverage" , implementation = markup_main , init_flags = default_flags , final_flags = default_final_flags } ------------------------------------------------------------------------------ markup_main :: Flags -> [String] -> IO () markup_main flags (prog:modNames) = do let hpcflags1 = flags { includeMods = Set.fromList modNames `Set.union` includeMods flags } let Flags { funTotals = theFunTotals , altHighlight = invertOutput , destDir = dest_dir } = hpcflags1 mtix <- readTix (getTixFileName prog) Tix tixs <- case mtix of Nothing -> hpcError markup_plugin $ "unable to find tix file for: " ++ prog Just a -> return a mods <- sequence [ genHtmlFromMod dest_dir hpcflags1 tix theFunTotals invertOutput | tix <- tixs , allowModule hpcflags1 (tixModuleName tix) ] let index_name = "hpc_index" index_fun = "hpc_index_fun" index_alt = "hpc_index_alt" index_exp = "hpc_index_exp" let writeSummary filename cmp = do let mods' = sortBy cmp mods putStrLn $ "Writing: " ++ (filename ++ ".html") writeFileUsing (dest_dir ++ "/" ++ filename ++ ".html") $ "<html>" ++ "<style type=\"text/css\">" ++ "table.bar { background-color: #f25913; }\n" ++ "td.bar { background-color: #60de51; }\n" ++ "td.invbar { background-color: #f25913; }\n" ++ "table.dashboard { border-collapse: collapse ; border: solid 1px black }\n" ++ ".dashboard td { border: solid 1px black }\n" ++ ".dashboard th { border: solid 1px black }\n" ++ "</style>\n" ++ "<table class=\"dashboard\" width=\"100%\" border=1>\n" ++ "<tr>" ++ "<th rowspan=2><a href=\"" ++ index_name ++ ".html\">module</a></th>" ++ "<th colspan=3><a href=\"" ++ index_fun ++ ".html\">Top Level Definitions</a></th>" ++ "<th colspan=3><a href=\"" ++ index_alt ++ ".html\">Alternatives</a></th>" ++ "<th colspan=3><a href=\"" ++ index_exp ++ ".html\">Expressions</a></th>" ++ "</tr>" ++ "<tr>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "<th>%</th>" ++ "<th colspan=2>covered / total</th>" ++ "</tr>" ++ concat [ showModuleSummary (modName,fileName,modSummary) | (modName,fileName,modSummary) <- mods' ] ++ "<tr></tr>" ++ showTotalSummary (mconcat [ modSummary | (_,_,modSummary) <- mods' ]) ++ "</table></html>\n" writeSummary index_name $ \ (n1,_,_) (n2,_,_) -> compare n1 n2 writeSummary index_fun $ \ (_,_,s1) (_,_,s2) -> compare (percent (topFunTicked s2) (topFunTotal s2)) (percent (topFunTicked s1) (topFunTotal s1)) writeSummary index_alt $ \ (_,_,s1) (_,_,s2) -> compare (percent (altTicked s2) (altTotal s2)) (percent (altTicked s1) (altTotal s1)) writeSummary index_exp $ \ (_,_,s1) (_,_,s2) -> compare (percent (expTicked s2) (expTotal s2)) (percent (expTicked s1) (expTotal s1)) markup_main _ [] = hpcError markup_plugin $ "no .tix file or executable name specified" genHtmlFromMod :: String -> Flags -> TixModule -> Bool -> Bool -> IO (String, [Char], ModuleSummary) genHtmlFromMod dest_dir flags tix theFunTotals invertOutput = do let theHsPath = srcDirs flags let modName0 = tixModuleName tix (Mix origFile _ _ tabStop mix') <- readMixWithFlags flags (Right tix) let arr_tix :: Array Int Integer arr_tix = listArray (0,length (tixModuleTixs tix) - 1) $ tixModuleTixs tix let tickedWith :: Int -> Integer tickedWith n = arr_tix ! n isTicked n = tickedWith n /= 0 let info = [ (pos,theMarkup) | (gid,(pos,boxLabel)) <- zip [0 ..] mix' , let binBox = case (isTicked gid,isTicked (gid+1)) of (False,False) -> [] (True,False) -> [TickedOnlyTrue] (False,True) -> [TickedOnlyFalse] (True,True) -> [] , let tickBox = if isTicked gid then [IsTicked] else [NotTicked] , theMarkup <- case boxLabel of ExpBox {} -> tickBox TopLevelBox {} -> TopLevelDecl theFunTotals (tickedWith gid) : tickBox LocalBox {} -> tickBox BinBox _ True -> binBox _ -> [] ] let modSummary = foldr (.) id [ \ st -> case boxLabel of ExpBox False -> st { expTicked = ticked (expTicked st) , expTotal = succ (expTotal st) } ExpBox True -> st { expTicked = ticked (expTicked st) , expTotal = succ (expTotal st) , altTicked = ticked (altTicked st) , altTotal = succ (altTotal st) } TopLevelBox _ -> st { topFunTicked = ticked (topFunTicked st) , topFunTotal = succ (topFunTotal st) } _ -> st | (gid,(_pos,boxLabel)) <- zip [0 ..] mix' , let ticked = if isTicked gid then succ else id ] $ mempty -- add prefix to modName argument content <- readFileFromPath (hpcError markup_plugin) origFile theHsPath let content' = markup tabStop info content let show' = reverse . take 5 . (++ " ") . reverse . show let addLine n xs = "<span class=\"lineno\">" ++ show' n ++ " </span>" ++ xs let addLines = unlines . map (uncurry addLine) . zip [1 :: Int ..] . lines let fileName = modName0 ++ ".hs.html" putStrLn $ "Writing: " ++ fileName writeFileUsing (dest_dir ++ "/" ++ fileName) $ unlines [ "<html><style type=\"text/css\">", "span.lineno { color: white; background: #aaaaaa; border-right: solid white 12px }", if invertOutput then "span.nottickedoff { color: #404040; background: white; font-style: oblique }" else "span.nottickedoff { background: " ++ yellow ++ "}", if invertOutput then "span.istickedoff { color: black; background: #d0c0ff; font-style: normal; }" else "span.istickedoff { background: white }", "span.tickonlyfalse { margin: -1px; border: 1px solid " ++ red ++ "; background: " ++ red ++ " }", "span.tickonlytrue { margin: -1px; border: 1px solid " ++ green ++ "; background: " ++ green ++ " }", "span.funcount { font-size: small; color: orange; z-index: 2; position: absolute; right: 20 }", if invertOutput then "span.decl { font-weight: bold; background: #d0c0ff }" else "span.decl { font-weight: bold }", "span.spaces { background: white }", "</style>", "<pre>"] ++ addLines content' ++ "\n</pre>\n</html>\n"; modSummary `seq` return (modName0,fileName,modSummary) data Loc = Loc !Int !Int deriving (Eq,Ord,Show) data Markup = NotTicked | TickedOnlyTrue | TickedOnlyFalse | IsTicked | TopLevelDecl Bool -- display entry totals Integer deriving (Eq,Show) markup :: Int -- ^tabStop -> [(HpcPos,Markup)] -- random list of tick location pairs -> String -- text to mark up -> String markup tabStop mix str = addMarkup tabStop str (Loc 1 1) [] sortedTickLocs where tickLocs = [ (Loc ln1 c1,Loc ln2 c2,mark) | (pos,mark) <- mix , let (ln1,c1,ln2,c2) = fromHpcPos pos ] sortedTickLocs = sortBy (\(locA1,locZ1,_) (locA2,locZ2,_) -> (locA1,locZ2) `compare` (locA2,locZ1)) tickLocs addMarkup :: Int -- tabStop -> String -- text to mark up -> Loc -- current location -> [(Loc,Markup)] -- stack of open ticks, with closing location -> [(Loc,Loc,Markup)] -- sorted list of tick location pairs -> String -- check the pre-condition. --addMarkup tabStop cs loc os ticks -- | not (isSorted (map fst os)) = error $ "addMarkup: bad closing ordering: " ++ show os --addMarkup tabStop cs loc os@(_:_) ticks -- | trace (show (loc,os,take 10 ticks)) False = undefined -- close all open ticks, if we have reached the end addMarkup _ [] _loc os [] = concatMap (const closeTick) os addMarkup tabStop cs loc ((o,_):os) ticks | loc > o = closeTick ++ addMarkup tabStop cs loc os ticks --addMarkup tabStop cs loc os ((t1,t2,tik@(TopLevelDecl {})):ticks) | loc == t1 = -- openTick tik ++ closeTick ++ addMarkup tabStop cs loc os ticks addMarkup tabStop cs loc os ((t1,t2,tik0):ticks) | loc == t1 = case os of ((_,tik'):_) | not (allowNesting tik0 tik') -> addMarkup tabStop cs loc os ticks -- already marked or bool within marked bool _ -> openTick tik0 ++ addMarkup tabStop cs loc (addTo (t2,tik0) os) ticks where addTo (t,tik) [] = [(t,tik)] addTo (t,tik) ((t',tik'):xs) | t <= t' = (t,tik):(t',tik'):xs | otherwise = (t',tik):(t',tik'):xs addMarkup tabStop0 cs loc os ((t1,_t2,_tik):ticks) | loc > t1 = -- throw away this tick, because it is from a previous place ?? addMarkup tabStop0 cs loc os ticks addMarkup tabStop0 ('\n':cs) loc@(Loc ln col) os@((Loc ln2 col2,_):_) ticks | ln == ln2 && col < col2 = addMarkup tabStop0 (' ':'\n':cs) loc os ticks addMarkup tabStop0 (c0:cs) loc@(Loc _ p) os ticks = if c0=='\n' && os/=[] then concatMap (const closeTick) (downToTopLevel os) ++ c0 : "<span class=\"spaces\">" ++ expand 1 w ++ "</span>" ++ concatMap (openTick.snd) (reverse (downToTopLevel os)) ++ addMarkup tabStop0 cs' loc' os ticks else if c0=='\t' then expand p "\t" ++ addMarkup tabStop0 cs (incBy c0 loc) os ticks else escape c0 ++ addMarkup tabStop0 cs (incBy c0 loc) os ticks where (w,cs') = span (`elem` " \t") cs loc' = foldl (flip incBy) loc (c0:w) escape '>' = "&gt;" escape '<' = "&lt;" escape '"' = "&quot;" escape '&' = "&amp;" escape c = [c] expand :: Int -> String -> String expand _ "" = "" expand c ('\t':s) = replicate (c' - c) ' ' ++ expand c' s where c' = tabStopAfter 8 c expand c (' ':s) = ' ' : expand (c+1) s expand _ _ = error "bad character in string for expansion" incBy :: Char -> Loc -> Loc incBy '\n' (Loc ln _c) = Loc (succ ln) 1 incBy '\t' (Loc ln c) = Loc ln (tabStopAfter tabStop0 c) incBy _ (Loc ln c) = Loc ln (succ c) tabStopAfter :: Int -> Int -> Int tabStopAfter tabStop c = fromJust (find (>c) [1,(tabStop + 1)..]) addMarkup tabStop cs loc os ticks = "ERROR: " ++ show (take 10 cs,tabStop,loc,take 10 os,take 10 ticks) openTick :: Markup -> String openTick NotTicked = "<span class=\"nottickedoff\">" openTick IsTicked = "<span class=\"istickedoff\">" openTick TickedOnlyTrue = "<span class=\"tickonlytrue\">" openTick TickedOnlyFalse = "<span class=\"tickonlyfalse\">" openTick (TopLevelDecl False _) = openTopDecl openTick (TopLevelDecl True 0) = "<span class=\"funcount\">-- never entered</span>" ++ openTopDecl openTick (TopLevelDecl True 1) = "<span class=\"funcount\">-- entered once</span>" ++ openTopDecl openTick (TopLevelDecl True n0) = "<span class=\"funcount\">-- entered " ++ showBigNum n0 ++ " times</span>" ++ openTopDecl where showBigNum n | n <= 9999 = show n | otherwise = showBigNum' (n `div` 1000) ++ "," ++ showWith (n `mod` 1000) showBigNum' n | n <= 999 = show n | otherwise = showBigNum' (n `div` 1000) ++ "," ++ showWith (n `mod` 1000) showWith n = take 3 $ reverse $ ("000" ++) $ reverse $ show n closeTick :: String closeTick = "</span>" openTopDecl :: String openTopDecl = "<span class=\"decl\">" downToTopLevel :: [(Loc,Markup)] -> [(Loc,Markup)] downToTopLevel ((_,TopLevelDecl {}):_) = [] downToTopLevel (o : os) = o : downToTopLevel os downToTopLevel [] = [] -- build in logic for nesting bin boxes allowNesting :: Markup -- innermost -> Markup -- outermost -> Bool allowNesting n m | n == m = False -- no need to double nest allowNesting IsTicked TickedOnlyFalse = False allowNesting IsTicked TickedOnlyTrue = False allowNesting _ _ = True ------------------------------------------------------------------------------ data ModuleSummary = ModuleSummary { expTicked :: !Int , expTotal :: !Int , topFunTicked :: !Int , topFunTotal :: !Int , altTicked :: !Int , altTotal :: !Int } deriving (Show) showModuleSummary :: (String, String, ModuleSummary) -> String showModuleSummary (modName,fileName,modSummary) = "<tr>\n" ++ "<td>&nbsp;&nbsp;<tt>module <a href=\"" ++ fileName ++ "\">" ++ modName ++ "</a></tt></td>\n" ++ showSummary (topFunTicked modSummary) (topFunTotal modSummary) ++ showSummary (altTicked modSummary) (altTotal modSummary) ++ showSummary (expTicked modSummary) (expTotal modSummary) ++ "</tr>\n" showTotalSummary :: ModuleSummary -> String showTotalSummary modSummary = "<tr style=\"background: #e0e0e0\">\n" ++ "<th align=left>&nbsp;&nbsp;Program Coverage Total</tt></th>\n" ++ showSummary (topFunTicked modSummary) (topFunTotal modSummary) ++ showSummary (altTicked modSummary) (altTotal modSummary) ++ showSummary (expTicked modSummary) (expTotal modSummary) ++ "</tr>\n" showSummary :: (Integral t, Show t) => t -> t -> String showSummary ticked total = "<td align=\"right\">" ++ showP (percent ticked total) ++ "</td>" ++ "<td>" ++ show ticked ++ "/" ++ show total ++ "</td>" ++ "<td width=100>" ++ (case percent ticked total of Nothing -> "&nbsp;" Just w -> bar w "bar" ) ++ "</td>" where showP Nothing = "-&nbsp;" showP (Just x) = show x ++ "%" bar 0 _ = bar 100 "invbar" bar w inner = "<table cellpadding=0 cellspacing=0 width=\"100\" class=\"bar\">" ++ "<tr><td><table cellpadding=0 cellspacing=0 width=\"" ++ show w ++ "%\">" ++ "<tr><td height=12 class=" ++ show inner ++ "></td></tr>" ++ "</table></td></tr></table>" percent :: (Integral a) => a -> a -> Maybe a percent ticked total = if total == 0 then Nothing else Just (ticked * 100 `div` total) instance Monoid ModuleSummary where mempty = ModuleSummary { expTicked = 0 , expTotal = 0 , topFunTicked = 0 , topFunTotal = 0 , altTicked = 0 , altTotal = 0 } mappend (ModuleSummary eTik1 eTot1 tTik1 tTot1 aTik1 aTot1) (ModuleSummary eTik2 eTot2 tTik2 tTot2 aTik2 aTot2) = ModuleSummary (eTik1 + eTik2) (eTot1 + eTot2) (tTik1 + tTik2) (tTot1 + tTot2) (aTik1 + aTik2) (aTot1 + aTot2) ------------------------------------------------------------------------------ writeFileUsing :: String -> String -> IO () writeFileUsing filename text = do let dest_dir = reverse . dropWhile (\ x -> x /= '/') . reverse $ filename -- We need to check for the dest_dir each time, because we use sub-dirs for -- packages, and a single .tix file might contain information about -- many package. -- create the dest_dir if needed when (not (null dest_dir)) $ createDirectoryIfMissing True dest_dir writeFile filename text ------------------------------------------------------------------------------ -- global color pallete red,green,yellow :: String red = "#f20913" green = "#60de51" yellow = "yellow"
mcmaniac/ghc
utils/hpc/HpcMarkup.hs
bsd-3-clause
18,210
0
52
5,952
4,677
2,458
2,219
369
16
----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Install -- Copyright : Isaac Jones 2003-2004 -- License : BSD3 -- -- Maintainer : [email protected] -- Portability : portable -- -- This is the entry point into installing a built package. Performs the -- \"@.\/setup install@\" and \"@.\/setup copy@\" actions. It moves files into -- place based on the prefix argument. It does the generic bits and then calls -- compiler-specific functions to do the rest. module Distribution.Simple.Install ( install, ) where import Distribution.PackageDescription import Distribution.Package (Package(..)) import Distribution.Simple.LocalBuildInfo import Distribution.Simple.BuildPaths (haddockName, haddockPref) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose , installDirectoryContents, installOrdinaryFile, isInSearchPath , die, info, notice, warn, matchDirFileGlob ) import Distribution.Simple.Compiler ( CompilerFlavor(..), compilerFlavor ) import Distribution.Simple.Setup (CopyFlags(..), fromFlag) import Distribution.Simple.BuildTarget import qualified Distribution.Simple.GHC as GHC import qualified Distribution.Simple.GHCJS as GHCJS import qualified Distribution.Simple.JHC as JHC import qualified Distribution.Simple.LHC as LHC import qualified Distribution.Simple.UHC as UHC import qualified Distribution.Simple.HaskellSuite as HaskellSuite import Control.Monad (when, unless) import System.Directory ( doesDirectoryExist, doesFileExist ) import System.FilePath ( takeFileName, takeDirectory, (</>), isAbsolute ) import Distribution.Verbosity import Distribution.Text ( display ) -- |Perform the \"@.\/setup install@\" and \"@.\/setup copy@\" -- actions. Move files into place based on the prefix argument. -- -- This does NOT register libraries, you should call 'register' -- to do that. install :: PackageDescription -- ^information from the .cabal file -> LocalBuildInfo -- ^information from the configure step -> CopyFlags -- ^flags sent to copy or install -> IO () install pkg_descr lbi flags | fromFlag (copyAssumeDepsUpToDate flags) = do checkHasLibsOrExes targets <- readBuildTargets pkg_descr (copyArgs flags) targets' <- checkBuildTargets verbosity pkg_descr targets case targets' of _ | null (copyArgs flags) -> copyPackage verbosity pkg_descr lbi distPref copydest [(cname, _)] -> let clbi = getComponentLocalBuildInfo lbi cname comp = getComponent pkg_descr cname in copyComponent verbosity pkg_descr lbi comp clbi copydest _ -> die "In --assume-deps-up-to-date mode you can only copy a single target" | otherwise = do checkHasLibsOrExes targets <- readBuildTargets pkg_descr (copyArgs flags) targets' <- checkBuildTargets verbosity pkg_descr targets copyPackage verbosity pkg_descr lbi distPref copydest -- It's not necessary to do these in build-order, but it's harmless withComponentsInBuildOrder pkg_descr lbi (map fst targets') $ \comp clbi -> copyComponent verbosity pkg_descr lbi comp clbi copydest where distPref = fromFlag (copyDistPref flags) verbosity = fromFlag (copyVerbosity flags) copydest = fromFlag (copyDest flags) checkHasLibsOrExes = unless (hasLibs pkg_descr || hasExes pkg_descr) $ die "No executables and no library found. Nothing to do." -- | Copy package global files. copyPackage :: Verbosity -> PackageDescription -> LocalBuildInfo -> FilePath -> CopyDest -> IO () copyPackage verbosity pkg_descr lbi distPref copydest = do let -- This is a bit of a hack, to handle files which are not -- per-component (data files and Haddock files.) InstallDirs { datadir = dataPref, -- NB: The situation with Haddock is a bit delicate. On the -- one hand, the easiest to understand Haddock documentation -- path is pkgname-0.1, which means it's per-package (not -- per-component). But this means that it's impossible to -- install Haddock documentation for internal libraries. We'll -- keep this constraint for now; this means you can't use -- Cabal to Haddock internal libraries. This does not seem -- like a big problem. docdir = docPref, htmldir = htmlPref, haddockdir = interfacePref} -- Notice use of 'absoluteInstallDirs' (not the -- per-component variant). This means for non-library -- packages we'll just pick a nondescriptive foo-0.1 = absoluteInstallDirs pkg_descr lbi copydest -- Install (package-global) data files installDataFiles verbosity pkg_descr dataPref -- Install (package-global) Haddock files -- TODO: these should be done per-library docExists <- doesDirectoryExist $ haddockPref distPref pkg_descr info verbosity ("directory " ++ haddockPref distPref pkg_descr ++ " does exist: " ++ show docExists) -- TODO: this is a bit questionable, Haddock files really should -- be per library (when there are convenience libraries.) when docExists $ do createDirectoryIfMissingVerbose verbosity True htmlPref installDirectoryContents verbosity (haddockPref distPref pkg_descr) htmlPref -- setPermissionsRecursive [Read] htmlPref -- The haddock interface file actually already got installed -- in the recursive copy, but now we install it where we actually -- want it to be (normally the same place). We could remove the -- copy in htmlPref first. let haddockInterfaceFileSrc = haddockPref distPref pkg_descr </> haddockName pkg_descr haddockInterfaceFileDest = interfacePref </> haddockName pkg_descr -- We only generate the haddock interface file for libs, So if the -- package consists only of executables there will not be one: exists <- doesFileExist haddockInterfaceFileSrc when exists $ do createDirectoryIfMissingVerbose verbosity True interfacePref installOrdinaryFile verbosity haddockInterfaceFileSrc haddockInterfaceFileDest let lfiles = licenseFiles pkg_descr unless (null lfiles) $ do createDirectoryIfMissingVerbose verbosity True docPref sequence_ [ installOrdinaryFile verbosity lfile (docPref </> takeFileName lfile) | lfile <- lfiles ] -- | Copy files associated with a component. copyComponent :: Verbosity -> PackageDescription -> LocalBuildInfo -> Component -> ComponentLocalBuildInfo -> CopyDest -> IO () copyComponent verbosity pkg_descr lbi (CLib lib) clbi copydest = do let InstallDirs{ libdir = libPref, includedir = incPref } = absoluteComponentInstallDirs pkg_descr lbi (componentUnitId clbi) copydest buildPref = componentBuildDir lbi clbi -- TODO: decide if we need the user to be able to control the libdir -- for shared libs independently of the one for static libs. If so -- it should also have a flag in the command line UI -- For the moment use dynlibdir = libdir dynlibPref = libPref if componentUnitId clbi == localUnitId lbi then notice verbosity ("Installing library in " ++ libPref) else notice verbosity ("Installing internal library " ++ libName lib ++ " in " ++ libPref) -- install include files for all compilers - they may be needed to compile -- haskell files (using the CPP extension) installIncludeFiles verbosity lib incPref case compilerFlavor (compiler lbi) of GHC -> GHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi GHCJS -> GHCJS.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi LHC -> LHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi JHC -> JHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi UHC -> UHC.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi HaskellSuite _ -> HaskellSuite.installLib verbosity lbi libPref dynlibPref buildPref pkg_descr lib clbi _ -> die $ "installing with " ++ display (compilerFlavor (compiler lbi)) ++ " is not implemented" copyComponent verbosity pkg_descr lbi (CExe exe) clbi copydest = do let installDirs@InstallDirs { bindir = binPref } = absoluteComponentInstallDirs pkg_descr lbi (componentUnitId clbi) copydest -- the installers know how to find the actual location of the -- binaries buildPref = buildDir lbi uid = componentUnitId clbi progPrefixPref = substPathTemplate (packageId pkg_descr) lbi uid (progPrefix lbi) progSuffixPref = substPathTemplate (packageId pkg_descr) lbi uid (progSuffix lbi) notice verbosity ("Installing executable " ++ exeName exe ++ " in " ++ binPref) inPath <- isInSearchPath binPref when (not inPath) $ warn verbosity ("The directory " ++ binPref ++ " is not in the system search path.") case compilerFlavor (compiler lbi) of GHC -> GHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr exe GHCJS -> GHCJS.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr exe LHC -> LHC.installExe verbosity lbi installDirs buildPref (progPrefixPref, progSuffixPref) pkg_descr exe JHC -> JHC.installExe verbosity binPref buildPref (progPrefixPref, progSuffixPref) pkg_descr exe UHC -> return () HaskellSuite {} -> return () _ -> die $ "installing with " ++ display (compilerFlavor (compiler lbi)) ++ " is not implemented" -- Nothing to do for benchmark/testsuite copyComponent _ _ _ _ _ _ = return () -- | Install the files listed in data-files -- installDataFiles :: Verbosity -> PackageDescription -> FilePath -> IO () installDataFiles verbosity pkg_descr destDataDir = flip mapM_ (dataFiles pkg_descr) $ \ file -> do let srcDataDir = dataDir pkg_descr files <- matchDirFileGlob srcDataDir file let dir = takeDirectory file createDirectoryIfMissingVerbose verbosity True (destDataDir </> dir) sequence_ [ installOrdinaryFile verbosity (srcDataDir </> file') (destDataDir </> file') | file' <- files ] -- | Install the files listed in install-includes for a library -- installIncludeFiles :: Verbosity -> Library -> FilePath -> IO () installIncludeFiles verbosity lib destIncludeDir = do let relincdirs = "." : filter (not.isAbsolute) (includeDirs lbi) lbi = libBuildInfo lib incs <- mapM (findInc relincdirs) (installIncludes lbi) sequence_ [ do createDirectoryIfMissingVerbose verbosity True destDir installOrdinaryFile verbosity srcFile destFile | (relFile, srcFile) <- incs , let destFile = destIncludeDir </> relFile destDir = takeDirectory destFile ] where findInc [] file = die ("can't find include file " ++ file) findInc (dir:dirs) file = do let path = dir </> file exists <- doesFileExist path if exists then return (file, path) else findInc dirs file
bennofs/cabal
Cabal/Distribution/Simple/Install.hs
bsd-3-clause
11,550
0
16
2,732
2,179
1,119
1,060
166
14
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching constructors -} {-# LANGUAGE CPP #-} {-# LANGUAGE TypeFamilies #-} module MatchCon ( matchConFamily, matchPatSyn ) where #include "HsVersions.h" import GhcPrelude import {-# SOURCE #-} Match ( match ) import HsSyn import DsBinds import ConLike import TcType import DsMonad import DsUtils import MkCore ( mkCoreLets ) import Util import Id import NameEnv import FieldLabel ( flSelector ) import SrcLoc import DynFlags import Outputable import Control.Monad(liftM) import Data.List (groupBy) {- We are confronted with the first column of patterns in a set of equations, all beginning with constructors from one ``family'' (e.g., @[]@ and @:@ make up the @List@ ``family''). We want to generate the alternatives for a @Case@ expression. There are several choices: \begin{enumerate} \item Generate an alternative for every constructor in the family, whether they are used in this set of equations or not; this is what the Wadler chapter does. \begin{description} \item[Advantages:] (a)~Simple. (b)~It may also be that large sparsely-used constructor families are mainly handled by the code for literals. \item[Disadvantages:] (a)~Not practical for large sparsely-used constructor families, e.g., the ASCII character set. (b)~Have to look up a list of what constructors make up the whole family. \end{description} \item Generate an alternative for each constructor used, then add a default alternative in case some constructors in the family weren't used. \begin{description} \item[Advantages:] (a)~Alternatives aren't generated for unused constructors. (b)~The STG is quite happy with defaults. (c)~No lookup in an environment needed. \item[Disadvantages:] (a)~A spurious default alternative may be generated. \end{description} \item ``Do it right:'' generate an alternative for each constructor used, and add a default alternative if all constructors in the family weren't used. \begin{description} \item[Advantages:] (a)~You will get cases with only one alternative (and no default), which should be amenable to optimisation. Tuples are a common example. \item[Disadvantages:] (b)~Have to look up constructor families in TDE (as above). \end{description} \end{enumerate} We are implementing the ``do-it-right'' option for now. The arguments to @matchConFamily@ are the same as to @match@; the extra @Int@ returned is the number of constructors in the family. The function @matchConFamily@ is concerned with this have-we-used-all-the-constructors? question; the local function @match_cons_used@ does all the real work. -} matchConFamily :: [Id] -> Type -> [[EquationInfo]] -> DsM MatchResult -- Each group of eqns is for a single constructor matchConFamily (var:vars) ty groups = do dflags <- getDynFlags alts <- mapM (fmap toRealAlt . matchOneConLike vars ty) groups return (mkCoAlgCaseMatchResult dflags var ty alts) where toRealAlt alt = case alt_pat alt of RealDataCon dcon -> alt{ alt_pat = dcon } _ -> panic "matchConFamily: not RealDataCon" matchConFamily [] _ _ = panic "matchConFamily []" matchPatSyn :: [Id] -> Type -> [EquationInfo] -> DsM MatchResult matchPatSyn (var:vars) ty eqns = do alt <- fmap toSynAlt $ matchOneConLike vars ty eqns return (mkCoSynCaseMatchResult var ty alt) where toSynAlt alt = case alt_pat alt of PatSynCon psyn -> alt{ alt_pat = psyn } _ -> panic "matchPatSyn: not PatSynCon" matchPatSyn _ _ _ = panic "matchPatSyn []" type ConArgPats = HsConDetails (LPat GhcTc) (HsRecFields GhcTc (LPat GhcTc)) matchOneConLike :: [Id] -> Type -> [EquationInfo] -> DsM (CaseAlt ConLike) matchOneConLike vars ty (eqn1 : eqns) -- All eqns for a single constructor = do { let inst_tys = ASSERT( tvs1 `equalLength` ex_tvs ) arg_tys ++ mkTyVarTys tvs1 val_arg_tys = conLikeInstOrigArgTys con1 inst_tys -- dataConInstOrigArgTys takes the univ and existential tyvars -- and returns the types of the *value* args, which is what we want match_group :: [Id] -> [(ConArgPats, EquationInfo)] -> DsM MatchResult -- All members of the group have compatible ConArgPats match_group arg_vars arg_eqn_prs = ASSERT( notNull arg_eqn_prs ) do { (wraps, eqns') <- liftM unzip (mapM shift arg_eqn_prs) ; let group_arg_vars = select_arg_vars arg_vars arg_eqn_prs ; match_result <- match (group_arg_vars ++ vars) ty eqns' ; return (adjustMatchResult (foldr1 (.) wraps) match_result) } shift (_, eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_tvs = tvs, pat_dicts = ds, pat_binds = bind, pat_args = args } : pats })) = do ds_bind <- dsTcEvBinds bind return ( wrapBinds (tvs `zip` tvs1) . wrapBinds (ds `zip` dicts1) . mkCoreLets ds_bind , eqn { eqn_pats = conArgPats val_arg_tys args ++ pats } ) shift (_, (EqnInfo { eqn_pats = ps })) = pprPanic "matchOneCon/shift" (ppr ps) ; arg_vars <- selectConMatchVars val_arg_tys args1 -- Use the first equation as a source of -- suggestions for the new variables -- Divide into sub-groups; see Note [Record patterns] ; let groups :: [[(ConArgPats, EquationInfo)]] groups = groupBy compatible_pats [ (pat_args (firstPat eqn), eqn) | eqn <- eqn1:eqns ] ; match_results <- mapM (match_group arg_vars) groups ; return $ MkCaseAlt{ alt_pat = con1, alt_bndrs = tvs1 ++ dicts1 ++ arg_vars, alt_wrapper = wrapper1, alt_result = foldr1 combineMatchResults match_results } } where ConPatOut { pat_con = L _ con1, pat_arg_tys = arg_tys, pat_wrap = wrapper1, pat_tvs = tvs1, pat_dicts = dicts1, pat_args = args1 } = firstPat eqn1 fields1 = map flSelector (conLikeFieldLabels con1) ex_tvs = conLikeExTyVars con1 -- Choose the right arg_vars in the right order for this group -- Note [Record patterns] select_arg_vars :: [Id] -> [(ConArgPats, EquationInfo)] -> [Id] select_arg_vars arg_vars ((arg_pats, _) : _) | RecCon flds <- arg_pats , let rpats = rec_flds flds , not (null rpats) -- Treated specially; cf conArgPats = ASSERT2( fields1 `equalLength` arg_vars, ppr con1 $$ ppr fields1 $$ ppr arg_vars ) map lookup_fld rpats | otherwise = arg_vars where fld_var_env = mkNameEnv $ zipEqual "get_arg_vars" fields1 arg_vars lookup_fld (L _ rpat) = lookupNameEnv_NF fld_var_env (idName (unLoc (hsRecFieldId rpat))) select_arg_vars _ [] = panic "matchOneCon/select_arg_vars []" matchOneConLike _ _ [] = panic "matchOneCon []" ----------------- compatible_pats :: (ConArgPats,a) -> (ConArgPats,a) -> Bool -- Two constructors have compatible argument patterns if the number -- and order of sub-matches is the same in both cases compatible_pats (RecCon flds1, _) (RecCon flds2, _) = same_fields flds1 flds2 compatible_pats (RecCon flds1, _) _ = null (rec_flds flds1) compatible_pats _ (RecCon flds2, _) = null (rec_flds flds2) compatible_pats _ _ = True -- Prefix or infix con same_fields :: HsRecFields GhcTc (LPat GhcTc) -> HsRecFields GhcTc (LPat GhcTc) -> Bool same_fields flds1 flds2 = all2 (\(L _ f1) (L _ f2) -> unLoc (hsRecFieldId f1) == unLoc (hsRecFieldId f2)) (rec_flds flds1) (rec_flds flds2) ----------------- selectConMatchVars :: [Type] -> ConArgPats -> DsM [Id] selectConMatchVars arg_tys (RecCon {}) = newSysLocalsDsNoLP arg_tys selectConMatchVars _ (PrefixCon ps) = selectMatchVars (map unLoc ps) selectConMatchVars _ (InfixCon p1 p2) = selectMatchVars [unLoc p1, unLoc p2] conArgPats :: [Type] -- Instantiated argument types -- Used only to fill in the types of WildPats, which -- are probably never looked at anyway -> ConArgPats -> [Pat GhcTc] conArgPats _arg_tys (PrefixCon ps) = map unLoc ps conArgPats _arg_tys (InfixCon p1 p2) = [unLoc p1, unLoc p2] conArgPats arg_tys (RecCon (HsRecFields { rec_flds = rpats })) | null rpats = map WildPat arg_tys -- Important special case for C {}, which can be used for a -- datacon that isn't declared to have fields at all | otherwise = map (unLoc . hsRecFieldArg . unLoc) rpats {- Note [Record patterns] ~~~~~~~~~~~~~~~~~~~~~~ Consider data T = T { x,y,z :: Bool } f (T { y=True, x=False }) = ... We must match the patterns IN THE ORDER GIVEN, thus for the first one we match y=True before x=False. See Trac #246; or imagine matching against (T { y=False, x=undefined }): should fail without touching the undefined. Now consider: f (T { y=True, x=False }) = ... f (T { x=True, y= False}) = ... In the first we must test y first; in the second we must test x first. So we must divide even the equations for a single constructor T into sub-goups, based on whether they match the same field in the same order. That's what the (groupBy compatible_pats) grouping. All non-record patterns are "compatible" in this sense, because the positional patterns (T a b) and (a `T` b) all match the arguments in order. Also T {} is special because it's equivalent to (T _ _). Hence the (null rpats) checks here and there. Note [Existentials in shift_con_pat] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data T = forall a. Ord a => T a (a->Int) f (T x f) True = ...expr1... f (T y g) False = ...expr2.. When we put in the tyvars etc we get f (T a (d::Ord a) (x::a) (f::a->Int)) True = ...expr1... f (T b (e::Ord b) (y::a) (g::a->Int)) True = ...expr2... After desugaring etc we'll get a single case: f = \t::T b::Bool -> case t of T a (d::Ord a) (x::a) (f::a->Int)) -> case b of True -> ...expr1... False -> ...expr2... *** We have to substitute [a/b, d/e] in expr2! ** Hence False -> ....((/\b\(e:Ord b).expr2) a d).... Originally I tried to use (\b -> let e = d in expr2) a to do this substitution. While this is "correct" in a way, it fails Lint, because e::Ord b but d::Ord a. -}
ezyang/ghc
compiler/deSugar/MatchCon.hs
bsd-3-clause
11,069
0
20
3,096
1,781
939
842
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} module Stack.Options.ConfigParser where import Data.Char import qualified Data.Set as Set import Options.Applicative import Options.Applicative.Builder.Extra import Path import Stack.Constants import Stack.Options.BuildMonoidParser import Stack.Options.DockerParser import Stack.Options.GhcBuildParser import Stack.Options.GhcVariantParser import Stack.Options.NixParser import Stack.Options.Utils import Stack.Prelude import Stack.Types.Config import qualified System.FilePath as FilePath -- | Command-line arguments parser for configuration. configOptsParser :: FilePath -> GlobalOptsContext -> Parser ConfigMonoid configOptsParser currentDir hide0 = (\stackRoot workDir buildOpts dockerOpts nixOpts systemGHC installGHC arch ghcVariant ghcBuild jobs includes libs overrideGccPath overrideHpack skipGHCCheck skipMsys localBin modifyCodePage allowDifferentUser dumpLogs -> mempty { configMonoidStackRoot = stackRoot , configMonoidWorkDir = workDir , configMonoidBuildOpts = buildOpts , configMonoidDockerOpts = dockerOpts , configMonoidNixOpts = nixOpts , configMonoidSystemGHC = systemGHC , configMonoidInstallGHC = installGHC , configMonoidSkipGHCCheck = skipGHCCheck , configMonoidArch = arch , configMonoidGHCVariant = ghcVariant , configMonoidGHCBuild = ghcBuild , configMonoidJobs = jobs , configMonoidExtraIncludeDirs = includes , configMonoidExtraLibDirs = libs , configMonoidOverrideGccPath = overrideGccPath , configMonoidOverrideHpack = overrideHpack , configMonoidSkipMsys = skipMsys , configMonoidLocalBinPath = localBin , configMonoidModifyCodePage = modifyCodePage , configMonoidAllowDifferentUser = allowDifferentUser , configMonoidDumpLogs = dumpLogs }) <$> optionalFirst (absDirOption ( long stackRootOptionName <> metavar (map toUpper stackRootOptionName) <> help ("Absolute path to the global stack root directory " ++ "(Overrides any STACK_ROOT environment variable)") <> hide )) <*> optionalFirst (option (eitherReader (mapLeft showWorkDirError . parseRelDir)) ( long "work-dir" <> metavar "WORK-DIR" <> completer (pathCompleterWith (defaultPathCompleterOpts { pcoAbsolute = False, pcoFileFilter = const False })) <> help ("Relative path of work directory " ++ "(Overrides any STACK_WORK environment variable, default is '.stack-work')") <> hide )) <*> buildOptsMonoidParser hide0 <*> dockerOptsParser True <*> nixOptsParser True <*> firstBoolFlags "system-ghc" "using the system installed GHC (on the PATH) if available and a matching version. Disabled by default." hide <*> firstBoolFlags "install-ghc" "downloading and installing GHC if necessary (can be done manually with stack setup)" hide <*> optionalFirst (strOption ( long "arch" <> metavar "ARCH" <> help "System architecture, e.g. i386, x86_64" <> hide )) <*> optionalFirst (ghcVariantParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (ghcBuildParser (hide0 /= OuterGlobalOpts)) <*> optionalFirst (option auto ( long "jobs" <> short 'j' <> metavar "JOBS" <> help "Number of concurrent jobs to run" <> hide )) <*> fmap Set.fromList (many ((currentDir FilePath.</>) <$> strOption ( long "extra-include-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for C header files" <> hide ))) <*> fmap Set.fromList (many ((currentDir FilePath.</>) <$> strOption ( long "extra-lib-dirs" <> metavar "DIR" <> completer dirCompleter <> help "Extra directories to check for libraries" <> hide ))) <*> optionalFirst (absFileOption ( long "with-gcc" <> metavar "PATH-TO-GCC" <> help "Use gcc found at PATH-TO-GCC" <> hide )) <*> optionalFirst (strOption ( long "with-hpack" <> metavar "HPACK" <> help "Use HPACK executable (overrides bundled Hpack)" <> hide )) <*> firstBoolFlags "skip-ghc-check" "skipping the GHC version and architecture check" hide <*> firstBoolFlags "skip-msys" "skipping the local MSYS installation (Windows only)" hide <*> optionalFirst (strOption ( long "local-bin-path" <> metavar "DIR" <> completer dirCompleter <> help "Install binaries to DIR" <> hide )) <*> firstBoolFlags "modify-code-page" "setting the codepage to support UTF-8 (Windows only)" hide <*> firstBoolFlags "allow-different-user" ("permission for users other than the owner of the stack root " ++ "directory to use a stack installation (POSIX only)") hide <*> fmap toDumpLogs (firstBoolFlags "dump-logs" "dump the build output logs for local packages to the console" hide) where hide = hideMods (hide0 /= OuterGlobalOpts) toDumpLogs (First (Just True)) = First (Just DumpAllLogs) toDumpLogs (First (Just False)) = First (Just DumpNoLogs) toDumpLogs (First Nothing) = First Nothing showWorkDirError err = show err ++ "\nNote that --work-dir must be a relative child directory, because work-dirs outside of the package are not supported by Cabal." ++ "\nSee https://github.com/commercialhaskell/stack/issues/2954"
MichielDerhaeg/stack
src/Stack/Options/ConfigParser.hs
bsd-3-clause
6,219
0
38
1,977
1,039
542
497
135
3
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- module Thrift.Protocol.Binary ( module Thrift.Protocol , BinaryProtocol(..) ) where import Control.Exception ( throw ) import Data.Bits import Data.Int import Data.List ( foldl' ) import GHC.Exts import GHC.Word import Thrift.Protocol import Thrift.Transport version_mask = 0xffff0000 version_1 = 0x80010000 data BinaryProtocol a = Transport a => BinaryProtocol a instance Protocol BinaryProtocol where getTransport (BinaryProtocol t) = t writeMessageBegin p (n, t, s) = do writeI32 p (version_1 .|. (fromEnum t)) writeString p n writeI32 p s writeMessageEnd _ = return () writeStructBegin _ _ = return () writeStructEnd _ = return () writeFieldBegin p (_, t, i) = writeType p t >> writeI16 p i writeFieldEnd _ = return () writeFieldStop p = writeType p T_STOP writeMapBegin p (k, v, n) = writeType p k >> writeType p v >> writeI32 p n writeMapEnd p = return () writeListBegin p (t, n) = writeType p t >> writeI32 p n writeListEnd _ = return () writeSetBegin p (t, n) = writeType p t >> writeI32 p n writeSetEnd _ = return () writeBool p b = tWrite (getTransport p) [toEnum $ if b then 1 else 0] writeByte p b = tWrite (getTransport p) (getBytes b 1) writeI16 p b = tWrite (getTransport p) (getBytes b 2) writeI32 p b = tWrite (getTransport p) (getBytes b 4) writeI64 p b = tWrite (getTransport p) (getBytes b 8) writeDouble p d = writeI64 p (fromIntegral $ floatBits d) writeString p s = writeI32 p (length s) >> tWrite (getTransport p) s writeBinary = writeString readMessageBegin p = do ver <- readI32 p if (ver .&. version_mask /= version_1) then throw $ ProtocolExn PE_BAD_VERSION "Missing version identifier" else do s <- readString p sz <- readI32 p return (s, toEnum $ ver .&. 0xFF, sz) readMessageEnd _ = return () readStructBegin _ = return "" readStructEnd _ = return () readFieldBegin p = do t <- readType p n <- if t /= T_STOP then readI16 p else return 0 return ("", t, n) readFieldEnd _ = return () readMapBegin p = do kt <- readType p vt <- readType p n <- readI32 p return (kt, vt, n) readMapEnd _ = return () readListBegin p = do t <- readType p n <- readI32 p return (t, n) readListEnd _ = return () readSetBegin p = do t <- readType p n <- readI32 p return (t, n) readSetEnd _ = return () readBool p = (== 1) `fmap` readByte p readByte p = do bs <- tReadAll (getTransport p) 1 return $ fromIntegral (composeBytes bs :: Int8) readI16 p = do bs <- tReadAll (getTransport p) 2 return $ fromIntegral (composeBytes bs :: Int16) readI32 p = composeBytes `fmap` tReadAll (getTransport p) 4 readI64 p = composeBytes `fmap` tReadAll (getTransport p) 8 readDouble p = do bs <- readI64 p return $ floatOfBits $ fromIntegral bs readString p = readI32 p >>= tReadAll (getTransport p) readBinary = readString -- | Write a type as a byte writeType :: (Protocol p, Transport t) => p t -> ThriftType -> IO () writeType p t = writeByte p (fromEnum t) -- | Read a byte as though it were a ThriftType readType :: (Protocol p, Transport t) => p t -> IO ThriftType readType p = toEnum `fmap` readByte p composeBytes :: (Bits b, Enum t) => [t] -> b composeBytes = (foldl' fn 0) . (map $ fromIntegral . fromEnum) where fn acc b = (acc `shiftL` 8) .|. b getByte :: Bits a => a -> Int -> a getByte i n = 255 .&. (i `shiftR` (8 * n)) getBytes :: (Bits a, Integral a) => a -> Int -> String getBytes i 0 = [] getBytes i n = (toEnum $ fromIntegral $ getByte i (n-1)):(getBytes i (n-1)) floatBits :: Double -> Word64 floatBits (D# d#) = W64# (unsafeCoerce# d#) floatOfBits :: Word64 -> Double floatOfBits (W64# b#) = D# (unsafeCoerce# b#)
xJom/mbunit-v3
tools/Thrift/src/lib/hs/src/Thrift/Protocol/Binary.hs
apache-2.0
4,800
0
14
1,253
1,640
826
814
-1
-1
import Control.Monad (unless) import Test.HUnit import Metrics assertAlmostEqual :: String -> Double -> Double -> Double -> Assertion assertAlmostEqual preface delta expected actual = unless (abs (expected - actual) < delta) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "expected: " ++ show expected ++ "\n but got: " ++ show actual delta = 1**(-10) infinity = -(log 0) -- should be a better way to do this testEqual label val1 val2 = TestLabel label (TestCase (assertEqual label val1 val2)) testAlmostEqual label val1 val2 = TestLabel label (TestCase (assertAlmostEqual label delta val1 val2)) aeTests = TestList [ testEqual "ae1" 0.0 (ae 3.4 3.4) , testAlmostEqual "ae2" 1.0 (ae 3.4 4.4) , testEqual "ae3" 2 (ae 9 11 ) ] apkTests = TestList [ testEqual "apk1" 0.25 (apk 2 [1..5] [6, 4, 7, 1, 2]) , testEqual "apk2" 0.2 (apk 5 [1..5] [1, 1, 1, 1, 1]) , testEqual "apk3" 1.0 (apk 20 [1..100] ([1..20]++[200..600])) , testAlmostEqual "apk4" (5/6) (apk 3 [1,3] [1..5]) , testEqual "apk5" (1/3) (apk 3 [1..3] [1,1,1]) , testEqual "apk6" (2/3) (apk 3 [1..3] [1,2,1]) ] aucTests = TestList [ testEqual "auc1" (1/3) (auc [1,0,1,1] [0.32,0.52,0.26,0.86]) , testAlmostEqual "auc2" 1 (auc [1,0,1,0,1] [0.9,0.1,0.8,0.1,0.7]) , testEqual "auc3" (1/4) (auc [0,1,1,0] [0.2,0.1,0.3,0.4]) , testEqual "auc4" 0.5 (auc [1,1,1,1,0,0,0,0,0,0] [1,1,1,1,1,1,1,1,1,1]) ] ceTests = TestList [ testEqual "ce1" 0.0 (ce [1,1,1,0,0,0] [1,1,1,0,0,0]) , testEqual "ce2" (1/6) (ce [1,1,1,0,0,0] [1,1,1,1,0,0]) , testEqual "ce3" (1/4) (ce [1,2,3,4] [1,2,3,3]) , testEqual "ce4" (1/3) (ce ["cat","dog","bird"] ["cat","dog","fish"]) , testEqual "ce5" 1 (ce ["cat","dog","bird"] ["caat","doog","biird"]) ] levenshteinTests = TestList [ testEqual "levenshtein1" 5 (levenshtein "intention" "execution") , testEqual "levenshtein2" 3 (levenshtein "sitting" "kitten") , testEqual "levenshtein3" 3 (levenshtein "Saturday" "Sunday") , testEqual "levenshtein4" 7 (levenshtein "sitting" "") , testEqual "levenshtein5" 3 (levenshtein "" "Ben") , testEqual "levenshtein6" 0 (levenshtein "cat" "cat") , testEqual "levenshtein7" 1 (levenshtein "hat" "cat") , testEqual "levenshtein8" 1 (levenshtein "at" "cat") , testEqual "levenshtein9" 1 (levenshtein "" "a") , testEqual "levenshtein10" 1 (levenshtein "a" "") , testEqual "levenshtein11" 0 (levenshtein "" "") , testEqual "levenshtein12" 1 (levenshtein "ant" "aunt") , testEqual "levenshtein13" 5 (levenshtein "Samantha" "Sam") , testEqual "levenshtein14" 3 (levenshtein "Flomax" "Volmax") , testEqual "levenshtein15" 0 (levenshtein [1] [1]) , testEqual "levenshtein16" 1 (levenshtein [1] [1,2]) , testEqual "levenshtein17" 1 (levenshtein [1] [1,10]) , testEqual "levenshtein18" 2 (levenshtein [1,2] [10,20]) , testEqual "levenshtein19" 3 (levenshtein [1,2] [10,20,30]) , testEqual "levenshtein20" 3 (levenshtein [3,3,4] [4,1,4,3]) ] llTests = TestList [ testEqual "ll1" 0.0 (ll 1 1) , testEqual "ll2" infinity (ll 1 0) , testEqual "ll3" infinity (ll 0 1) , testEqual "ll4" (- (log 0.5)) (ll 0 0.5) ] logLossTests = TestList [ testEqual "logLoss1" 0.0 (logLoss [1, 1, 0, 0] [1, 1, 0, 0]) , testEqual "logLoss2" infinity (logLoss [1, 1, 0, 0] [1, 1, 1, 0]) , testEqual "logLoss3" 1.881797068998267 (logLoss [1, 1, 1, 0, 0, 0] [0.5, 0.1, 0.01, 0.9, 0.75, 0.001]) ] maeTests = TestList [ testEqual "mae1" 1.0 (mae [0..10] [1..11]) , testEqual "mae2" 0.0 (mae [0,0.5..2] [0,0.5..2]) , testEqual "mae3" 0.25 (mae [1,2,3,4] [1,2,3,5]) ] mapkTests = TestList [ testAlmostEqual "mapk1" (5/6) (mapk 10 [[1..5],[1..3]] [[1..10],[1,2]++[4..11]++[3]]) , testEqual "mapk2" 1.0 (mapk 3 [[1..4]] [[1..4]]) , testAlmostEqual "mapk3" 0.685185185185185 (mapk 3 [[1,3,4],[1,2,4],[1,3]] [[1..5],[1..5],[1..5]]) , testEqual "mapk4" 0.26 (mapk 5 [[1..5],[1..5]] [[6,4,7,1,2],[1,1,1,1,1]]) , testAlmostEqual "mapk5" (11/18) (mapk 3 [[1,3],[1..3],[1..3]] [[1..5],[1,1,1],[1,2,1]]) ] mseTests = TestList [ testEqual "mse1" 1.0 (mse [0..10] [1..11]) , testEqual "mse2" 0.0 (mse [0,0.5..2] [0,0.5..2]) , testEqual "mse3" 1.0 (mse [1,2,3,4] [1,2,3,6]) ] msleTests = TestList [ testEqual "msle1" 1.0 (msle [(exp 2)-1] [exp(1)-1]) , testEqual "msle2" 0.0 (msle [0,0.5..2] [0,0.5..2]) , testEqual "msle3" 0.25 (msle [1,2,3,((exp 1)-1)] [1,2,3,((exp 2)-1)]) ] rmseTests = TestList [ testEqual "rmse1" 1.0 (rmse [0..10] [1..11]) , testEqual "rmse2" 0.0 (rmse [0,0.5..2] [0,0.5..2]) , testEqual "rmse3" 0.5 (rmse [1,2,3,4] [1,2,3,5]) ] rmsleTests = TestList [ testEqual "rmsle1" 1.0 (rmsle [(exp 2)-1] [exp(1)-1]) , testEqual "rmsle2" 0.0 (rmsle [0,0.5..2] [0,0.5..2]) , testEqual "rmsle3" 0.5 (rmsle [1,2,3,((exp 1)-1)] [1,2,3,((exp 2)-1)]) ] seTests = TestList [ testEqual "se1" 0.0 (se 3.4 3.4) , testAlmostEqual "se2" 1.0 (se 3.4 4.4) , testEqual "se3" 4 (se 9 11 ) ] sleTests = TestList [ testEqual "sle1" 0.0 (sle 3.4 3.4) , testAlmostEqual "sle2" 1.0 (sle ((exp 2)-1) ((exp 1)-1)) ] allTests = TestList [ aeTests , apkTests , aucTests , ceTests , levenshteinTests , llTests , logLossTests , maeTests , mapkTests , mseTests , msleTests , rmseTests , rmsleTests , seTests , sleTests ] main = runTestTT allTests
AaronRanAn/Metrics
Haskell/testMetrics.hs
bsd-2-clause
7,274
0
14
2,891
2,888
1,615
1,273
98
2
module Expression.Type where import Context.Type import Way.Type import Builder import qualified Hadrian.Expression as H -- | @Expr a@ is a computation that produces a value of type @Action a@ and can -- read parameters of the current build 'Target'. type Expr a = H.Expr Context Builder a -- | The following expressions are used throughout the build system for -- specifying conditions ('Predicate'), lists of arguments ('Args'), 'Ways' -- and 'Packages'. type Predicate = H.Predicate Context Builder type Args = H.Args Context Builder type Ways = Expr [Way]
snowleopard/hadrian
src/Expression/Type.hs
mit
579
0
6
107
86
53
33
9
0
module Main where import P main = print p
themoritz/cabal
cabal-testsuite/PackageTests/NewBuild/T3827/q/Main.hs
bsd-3-clause
42
0
5
9
15
9
6
3
1
{-# LANGUAGE RankNTypes, ScopedTypeVariables #-} -- Trac #2494, should compile ok module Foo where foo :: (forall m. Monad m => Maybe (m a) -> Maybe (m a)) -> Maybe a -> Maybe a {-# NOINLINE [1] foo #-} foo _ x = x {-# RULES "foo/foo" forall (f :: forall m. Monad m => Maybe (m a) -> Maybe (m a)) (g :: forall m. Monad m => Maybe (m a) -> Maybe (m a)) x. foo f (foo g x) = foo (f . g) x #-}
ghc-android/ghc
testsuite/tests/typecheck/should_compile/T2494-2.hs
bsd-3-clause
410
0
12
108
74
39
35
10
1
module Control.Disruptor.SequenceBarrier where import Control.Disruptor.Sequence import qualified Data.Foldable as F import Data.IORef -- TODO figure out if we need this at all data AlertException = AlertException alertException = AlertException data WaitResult = Alert AlertException | Interrupted | Timeout data SequenceBarrier c = SequenceBarrier { waitFor :: SequenceId c -> IO (Either WaitResult (SequenceId c)) , getCursor :: IO (SequenceId c) , alert :: IO () , clearAlert :: IO () -- no need for isAlert because we have Maybe , checkAlert :: IO (Maybe AlertException) }
iand675/disruptor
src/Control/Disruptor/SequenceBarrier.hs
mit
648
0
14
156
147
85
62
15
1
import Control.Monad import qualified Data.Vector as V readNumbers :: String -> [Int] readNumbers = map read . words readInput [a, b] = (a, b) minVehicle lanes (i, j) = V.minimum s where s = V.slice i (j - i + 1) lanes main :: IO () main = do input <- getLine let (n, t) = readInput (readNumbers input) input <- getLine let lanes = V.fromList (readNumbers input) -- print lanes testsInput <- replicateM t getLine let tests = map (readInput . readNumbers) testsInput -- print tests let ans = map (minVehicle lanes) tests mapM_ print ans
mgrebenets/hackerrank
alg/warmup/service-lane.hs
mit
592
0
12
153
243
123
120
17
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Shiva.HTML ( -- * Pages feedPage, mainPage, articlePage, errorPage, -- * Helpers htmlFromEither ) where import Shiva.Config (Source (..), titleCode) import Shiva.Feeds import Shiva.Sources (sources) import Shiva.Translation import Control.Monad (forM_, unless) import Data.Monoid ((<>)) import Lucid.Base import Lucid.Html5 import Microsoft.Translator import Shiva.Table.ArticleContent (ArticleContent) import qualified Shiva.Table.ArticleContent as Article ---- Html Infra ---- bodyTemplate :: String -> Html () -> Html () bodyTemplate title bod = doctypehtml_ $ do head_ $ do meta_ [charset_ "utf-8"] title_ (toHtml title) link_ [ href_ "/css/style.css" , rel_ "stylesheet" , type_ "text/css" ] body_ $ do h1_ (toHtml title) bod errorPage :: String -> Html () errorPage msg = bodyTemplate "Shiva" $ div_ [class_ "warning"] $ do b_ "Error: " p_ $ toHtml msg htmlFromEither :: (a -> Html ()) -> Either String a -> Html () htmlFromEither f (Right x) = f x htmlFromEither _ (Left str) = errorPage str ---- Main page ---- mainPage :: [ArticleContent] -> Html () mainPage xs = bodyTemplate "Shiva" $ do h2_ "Feed Sources" div_ [class_ "contentarea"] $ do h3_ "Dagens Nyheter" ul_ $ mapM_ sourceItem sources h2_ "Recently viewed" div_ [class_ "contentarea"] . ul_ . forM_ xs $ \meta -> li_ . a_ [href_ $ "/content/dn/" <> Article.urlFrag meta] . toHtml $ Article.urlFrag meta sourceItem :: Source -> Html () sourceItem i = li_ $ a_ [href_ $ "sources/" <> titleCode i] . toHtml $ sourceTitle i ---- Feed listing pages ---- dnTitle :: String dnTitle = "Dagens Nyheter" feedPage :: FeedData -> Html () feedPage (FeedData xs errs) = bodyTemplate dnTitle $ do unless (null errs) . div_ [class_ "warning"] $ do p_ "Errors were encountered for feed items: " ul_ $ mapM_ (li_ . toHtml) errs mapM_ renderFeedItem xs renderFeedItem :: FeedItem -> Html () renderFeedItem d = do div_ [class_ "feedmetadata"] $ table_ [width_ "100%"] $ tr_ $ do td_ $ toHtml $ showTime (itemTime d) td_ [makeAttribute "align" "right"] $ do "Original content: " a_ [href_ $ urlFull d] "Link" div_ [class_ "svenska"] $ a_ [href_ $ "/content/dn/" <> urlFrag d] (toHtml $ svTitle d) div_ [class_ "engelska"] (toHtml $ enTitle d) br_ [] br_ [] ---- Article content pages ---- articlePage :: TransArticle -> Html () articlePage TransArticle {..} = bodyTemplate "Shiva" $ do h2_ $ toHtml thetitle p_ $ do "Translated from " a_ [href_ origUrl] "the original." forM_ imageUrl $ \url -> do img_ [src_ url, class_ "articleImg"] br_ [] br_ [] mapM_ renderPair bodyResult renderPair :: Sentence -> Html () renderPair s = do div_ [class_ "svenska"] (toHtml $ fromText s) div_ [class_ "engelska"] (toHtml $ toText s) br_ [] br_ []
BlackBrane/shiva
src/Shiva/HTML.hs
mit
3,335
0
17
1,021
1,093
524
569
92
1
module TestBallots ( tests ) where -- local imports import Control.Consensus.Paxos import Control.Consensus.Paxos.Protocol.Courier import Control.Consensus.Paxos.Storage.Memory import Network.Transport.Memory import SimpleDecree -- external imports import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM import Control.Exception import qualified Data.Map as M import qualified Data.Set as S import Debug.Trace import Network.Endpoints import System.Timeout import Test.Framework import Test.HUnit import Test.Framework.Providers.HUnit -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- tests :: [Test.Framework.Test] tests = [ testCase "1-ballot" test1Ballot ] test1Ballot :: Assertion test1Ballot = do let instId = InstanceId 1 mid1 = MemberId 1 mid2 = MemberId 2 mid3 = MemberId 3 members = S.fromList [mid1, mid2, mid3] memberNames = M.fromSet (Name . show) members decree = Decree { decreeInstanceId = instId, decreeMemberId = mid1, decreeable = SetValue 1 } inst1 <- newInstance instId members mid1 inst2 <- newInstance instId members mid2 inst3 <- newInstance instId members mid3 rv <- rendezvous 4 -- 1 leader + 3 followers endpoint1 <- newEndpoint endpoint2 <- newEndpoint endpoint3 <- newEndpoint timeBound maxTestRun $ withTransport newMemoryTransport $ \transport -> withAsync (runFollower1Ballot rv transport endpoint1 inst1 memberNames) $ \async1 -> withAsync (runFollower1Ballot rv transport endpoint2 inst2 memberNames) $ \async2 -> withAsync (runFollower1Ballot rv transport endpoint3 inst3 memberNames) $ \async3 -> withConnection3 transport endpoint1 (Name $ show mid1) (Name $ show mid2) (Name $ show mid3) $ do threadDelay (500 * 1000 :: Int) leader1 <- runLeader1Ballot rv endpoint1 inst1 memberNames decree follower1 <- wait async1 (follower2,follower3) <- waitBoth async2 async3 assertBool "expected leader decree" $ leader1 == Just decree assertBool "expected follower2 decree" $ leader1 == follower1 assertBool "expected follower2 decree" $ follower1 == follower2 assertBool "expected follower3 decree" $ follower2 == follower3 runFollower1Ballot :: (Decreeable d) => Rendezvous -> Transport -> Endpoint -> Instance d -> MemberNames -> IO (Maybe (Decree d)) runFollower1Ballot rv transport endpoint inst memberNames = catch (do let name = memberName inst memberNames withEndpoint transport endpoint $ withBinding transport endpoint name $ do let p = protocol defaultTimeouts endpoint memberNames name s <- storage meet rv r <- paxos inst $ followBasicPaxosBallot p s leave rv return r) (\e -> do traceIO $ "follower error: " ++ show (e :: SomeException) return Nothing) runLeader1Ballot :: (Decreeable d) => Rendezvous -> Endpoint -> Instance d -> MemberNames -> Decree d -> IO (Maybe (Decree d)) runLeader1Ballot rv endpoint inst memberNames decree = catch (do let name = memberName inst memberNames let p = protocol defaultTimeouts endpoint memberNames name s <- storage meet rv r <- paxos inst $ leadBasicPaxosBallot p s decree leave rv return r) (\e -> do traceIO $ "leader error: " ++ show (e :: SomeException) return Nothing) timeBound :: Int -> IO () -> IO () timeBound delay action = do outcome <- timeout delay action assertBool "Test should not block" $ outcome == Just () maxTestRun :: Int maxTestRun = 5000 * 1000 -- 5 sec data Rendezvous = Rendezvous { meet :: IO (), leave :: IO () } rendezvous :: Integer -> IO Rendezvous rendezvous count = atomically $ do m <- newTVar count l <- newTVar count return Rendezvous { meet = join m, leave = join l } join :: TVar Integer -> IO () join rv = do atomically $ modifyTVar rv $ \count -> count - 1 atomically $ do count <- readTVar rv if count > 0 then retry else return ()
hargettp/paxos
tests/TestBallots.hs
mit
4,225
0
20
974
1,255
622
633
105
2
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. -- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? -- smallest positive number that is evenly divisible by all of the numbers from 1 to n -- lcm [1 to n] lcm' = foldl (lcm) 1 myList :: Int -> [Int] myList n = [2 .. n] smallestMul :: Int -> Int smallestMul n = lcm' (myList n)
sravan-s/euler
euler-0005/smallestMultiple.hs
mit
441
0
7
96
70
39
31
5
1
module Nix.Spec.OperatorsSpec (main, spec) where import Nix.Common import Nix.Atoms import Nix.Eval import Nix.Expr import Nix.Evaluator import Nix.Spec.Lib import Nix.Values import Nix.Values.NativeConversion import Test.Hspec import Test.QuickCheck main :: IO () main = hspec spec spec :: Spec spec = do divisionSpec binopsSpec unopsSpec divisionSpec :: Spec divisionSpec = describe "division" $ do let div_ = toNative2 binop_div let mkInt = pure . intV it "should divide numbers" $ do res <- runNativeStrictL1 $ applyNative2 div_ (mkInt 6) (mkInt 3) res `shouldBe` Right (intV 2) it "should not divide by zero" $ property $ \i -> do res <- runNativeStrictL1 $ applyNative2 div_ (mkInt i) (mkInt 0) res `shouldBe` Left DivideByZero binopsSpec :: Spec binopsSpec = describe "binary operators" $ do describe "numerical stuff" $ do it "should evaluate +" $ property $ \i j -> mkInt i $+ mkInt j `shouldEvalTo` intV (i + j) it "should evaluate -" $ property $ \i j -> mkInt i $- mkInt j `shouldEvalTo` intV (i - j) it "should evaluate *" $ property $ \i j -> mkInt i $* mkInt j `shouldEvalTo` intV (i * j) describe "comparison" $ do it "should evaluate <" $ property $ \i j -> do mkInt i $< mkInt j `shouldEvalTo` convert (i < j) it "should evaluate <=" $ property $ \i j -> do mkInt i $<= mkInt j `shouldEvalTo` convert (i <= j) it "should evaluate >" $ property $ \i j -> do mkInt i $> mkInt j `shouldEvalTo` convert (i > j) it "should evaluate >=" $ property $ \i j -> do mkInt i $>= mkInt j `shouldEvalTo` convert (i >= j) describe "logic" $ do it "should evaluate &&" $ property $ \b1 b2 -> mkBool b1 $&& mkBool b2 `shouldEvalTo` boolV (b1 && b2) it "should evaluate ||" $ property $ \b1 b2 -> mkBool b1 $|| mkBool b2 `shouldEvalTo` boolV (b1 || b2) it "should evaluate ->" $ property $ \b1 b2 -> mkBool b1 $-> mkBool b2 `shouldEvalTo` boolV (if b1 then b2 else True) describe "data structures" $ do it "should evaluate ++" $ property $ \list1 list2 -> do fromAtoms list1 $++ fromAtoms list2 `shouldEvalTo` fromAtoms (list1 <> list2) it "should evaluate //" $ property $ \set1 set2 -> do fromAtomSet set1 $// fromAtomSet set2 `shouldEvalTo` fromAtomSet (set2 <> set1) it "should evaluate + for strings" $ property $ \s1 s2 -> do mkStr s1 $+ mkStr s2 `shouldEvalTo` strV (s1 <> s2) describe "equality" $ do it "equal things are equal" $ property $ \constant -> do fromAtom constant $== fromAtom constant `shouldEvalTo` convert True it "equal things are not unequal" $ property $ \constant -> do fromAtom constant $!= fromAtom constant `shouldEvalTo` convert False it "unequal things are unequal" $ property $ \const1 const2 -> do fromAtom const1 $== fromAtom const2 `shouldEvalTo` convert (const1 == const2) it "unequal things are not equal" $ property $ \const1 const2 -> do fromAtom const1 $!= fromAtom const2 `shouldEvalTo` convert (const1 /= const2) unopsSpec :: Spec unopsSpec = describe "unary operators" $ do describe "numeric negation" $ do it "should work once" $ property $ \num -> do -(mkInt num) `shouldEvalTo` convert (-num) it "should work twice" $ property $ \num -> do -(-(mkInt num)) `shouldEvalTo` convert num describe "logical negation" $ do it "should work once" $ property $ \bool -> do mkNot (mkBool bool) `shouldEvalTo` convert (not bool) it "should work twice" $ property $ \bool -> do mkNot (mkNot (mkBool bool)) `shouldEvalTo` convert bool
adnelson/nix-eval
tests/Nix/Spec/OperatorsSpec.hs
mit
3,700
0
21
913
1,367
665
702
88
2
module Gaia.UserPreferences ( getXCacheRoot, getFSRootsListingFilePath ) where import Gaia.Types import System.Directory as Dir import System.Environment (getEnv) import System.FilePath (normalise, (</>)) import System.IO.Error (catchIOError, isDoesNotExistError) xcacheRepositoryLegacyFolderPath :: FolderPath xcacheRepositoryLegacyFolderPath = "/x-space/xcache-v2" ensureFolderPath :: FolderPath -> IO () ensureFolderPath = Dir.createDirectoryIfMissing True getEnvFailback :: String -> String -> IO String getEnvFailback env failback = catchIOError (getEnv env) (\e -> if isDoesNotExistError e then return failback else ioError e) getXCacheRoot :: IO String getXCacheRoot = getEnvFailback "GAIAXCACHEROOT" xcacheRepositoryLegacyFolderPath getFSRootsListingFilePath :: IO String getFSRootsListingFilePath = do folderpath <- Dir.getAppUserDataDirectory "gaia" ensureFolderPath folderpath return $ normalise $ folderpath </> "FSRootsListing.txt"
shtukas/Gaia
src/Gaia/UserPreferences.hs
mit
1,026
0
9
176
225
121
104
22
2
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Compiler.Test (htf_thisModulesTests) where import Test.Framework import Test.HUnit (Assertion) import Compiler import Types {- compilerTest :: [Declaration] -> [Deployment] -> Assertion compilerTest dc dp = assertEqual dp $ compile dc test_compiler_empty = compilerTest [] [] test_compiler_single_deploy = compilerTest [Deploy "bashrc" ".bashrc" LinkDeployment] [Link "bashrc" ".bashrc"] --test_compiler_single_spark = compilerTest test_compiler_single_into = compilerTest [IntoDir "~/.xmonad"] [] test_compiler_single_outof = compilerTest [OutofDir "bash"] [] test_compiler_into = compilerTest [IntoDir "~" ,Deploy "bashrc" ".bashrc" LinkDeployment ,IntoDir "~/.xmonad" ,Deploy "xmonad.hs" "xmonad.hs" LinkDeployment] [Link "bashrc" "~/.bashrc", Link "xmonad.hs" "~/.xmonad/xmonad.hs"] test_compiler_outof = compilerTest [OutofDir "bash" ,Deploy "bashrc" "~/.bashrc" LinkDeployment] [Link "bash/bashrc" "~/.bashrc"] test_compiler_both = compilerTest [IntoDir "~/.xmonad" ,OutofDir "xmonad" ,Deploy "xmonad.hs" "xmonad.hs" LinkDeployment] [Link "xmonad/xmonad.hs" "~/.xmonad/xmonad.hs"] -}
plietar/super-user-spark
test/Compiler/Test.hs
mit
1,263
0
5
245
34
22
12
6
0
import qualified Data.List as List compartments = 4 main = do weights <- map read <$> lines <$> getContents let capacity = sum weights `div` compartments let compartments = filter ((== capacity) . sum) $ distribute weights let passengerCompartmentPackageCount = minimum $ map length compartments let passengerCompartments = filter (\pc -> length pc == passengerCompartmentPackageCount) compartments let quantumEntanglements = map product passengerCompartments let quantumEntanglement = minimum quantumEntanglements print quantumEntanglement distribute :: [Int] -> [[Int]] distribute weights = concatMap (\i -> combinations i weights) [0 .. (length weights `div` compartments)] where sortedWeights = List.sortBy (flip compare) weights combinations :: Int -> [a] -> [[a]] combinations 0 _ = [[]] combinations n list = [x : xs | x : ts <- List.tails list, xs <- combinations (n - 1) ts]
SamirTalwar/advent-of-code
2015/AOC_24_2.hs
mit
910
0
14
155
337
172
165
17
1
module Hello ( sayHello ) where sayHello :: String -> IO () sayHello name = do putStrLn ("Hi " ++ name ++ "!")
brodyberg/Notes
hello/src/Hello.hs
mit
119
0
10
31
48
25
23
5
1
{-# LANGUAGE GeneralizedNewtypeDeriving , DeriveGeneric , DeriveDataTypeable , OverloadedStrings #-} module Veva.Types.Status ( Status(..) , Id(..) , Author(..) , Content(..) ) where import Data.JSON.Schema import Data.UUID.Aeson () import Hasql.Postgres (Postgres) import Hasql.Backend (CxValue) import Data.Typeable (Typeable) import Data.Functor ((<$>)) import GHC.Generics (Generic) import Rest.ShowUrl (ShowUrl) import Data.Aeson hiding (Value(..)) import Rest.Info (Info(..)) import Data.Time (UTCTime) import Data.Text (Text) import Data.UUID (UUID) import qualified Veva.Types.User as User newtype Id = Id { unId :: UUID } deriving ( Eq , Show , FromJSON , ToJSON , Generic , CxValue Postgres , ShowUrl , Typeable ) instance Info Id where describe _ = "id" instance JSONSchema Id where schema _ = Value LengthBound { lowerLength = Just 36 , upperLength = Just 36 } instance Read Id where readsPrec d r = map f (readsPrec d r) where f (i, s) = (Id i, s) newtype Author = Author { authorId :: User.Id } deriving (Eq, Show, Generic, CxValue Postgres, Typeable) instance FromJSON Author where parseJSON = withObject "Author" $ \o -> Author <$> o .: "id" instance ToJSON Author where toJSON (Author uid) = object ["id" .= toJSON uid] instance JSONSchema Author where schema _ = Object [Field "id" True (schema (Proxy :: Proxy User.Id))] newtype Content = Content { unContent :: Text } deriving (Eq, Show, FromJSON, ToJSON, Generic, CxValue Postgres, Typeable) instance JSONSchema Content where schema _ = Value LengthBound { lowerLength = Nothing , upperLength = Just 144 } data Status = Status { id :: Id , author :: Author , content :: Content , created_at :: UTCTime , updated_at :: UTCTime } deriving (Generic, Typeable) instance FromJSON Status instance ToJSON Status instance JSONSchema Status where schema = gSchema
L8D/veva
lib/Veva/Types/Status.hs
mit
2,201
0
13
657
657
373
284
65
0
module FieldMarshal.Cpp where import Data.List data Name = Name [String] String deriving Eq instance Show Name where show (Name namespaces name) = concat $ intersperse "::" $ namespaces ++ [name] data Pointer = Pointer Name | NestedPointer Pointer | PointerToConst Const deriving Eq instance Show Pointer where show (Pointer name) = show name ++ " *" show (NestedPointer pointer) = show pointer ++ " *" show (PointerToConst const) = show const ++ " *" data Const = Const Name | ConstPointer Pointer deriving Eq instance Show Const where show (Const name) = "const " ++ show name show (ConstPointer pointer) = show pointer ++ " const" data Reference = Reference Name | ReferenceToPointer Pointer | ReferenceToConst Const deriving Eq instance Show Reference where show (Reference name) = show name ++ " &" show (ReferenceToPointer pointer) = show pointer ++ " &" show (ReferenceToConst const) = show const ++ " &" data Template = Template Name Type [Type] deriving Eq showTypes :: [Type] -> String showTypes types = concat $ intersperse ", " $ map show $ types instance Show Template where show (Template name typ types) = show name ++ "<" ++ showTypes (typ:types) ++ ">" data Type = NameType Name | PointerType Pointer | ConstType Const | ReferenceType Reference | TemplateType Template deriving Eq instance Show Type where show (NameType name) = show name show (PointerType pointer) = show pointer show (ConstType const) = show const show (ReferenceType reference) = show reference show (TemplateType template) = show template data MaybeVoidType = NotVoid Type | Void deriving Eq instance Show MaybeVoidType where show (NotVoid typ) = show typ show Void = "void" data Variable = Variable Type String deriving Eq instance Show Variable where show (Variable typ name) = show typ ++ " " ++ name data Function = Function Name [Variable] MaybeVoidType | TemplateFunction Name Type [Type] [Variable] MaybeVoidType deriving Eq showParameters :: [Variable] -> String showParameters parameters = concat $ intersperse ", " $ map show parameters instance Show Function where show (Function name parameters return) = show return ++ " " ++ show name ++ "(" ++ showParameters parameters ++ ")" show (TemplateFunction name firstType types parameters return) = show return ++ " " ++ show name ++ "<" ++ showTypes (firstType:types) ++ ">(" ++ showParameters parameters ++ ")" newtype FunctionPointer = FunctionPointer Function deriving Eq instance Show FunctionPointer where show (FunctionPointer (Function name parameters return)) = show return ++ " (* " ++ show name ++ ")(" ++ showParameters parameters ++ ")"
scott-fleischman/field-marshal
FieldMarshal.Cpp.hs
mit
2,700
0
13
520
923
469
454
67
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Language.Dash.IR.Data ( Constant (..) , ConstTable , SymbolNameList , Reg , mkReg , regToInt , SymId , mkSymId , symIdToInt , FuncAddr , mkFuncAddr , funcAddrToInt , ConstAddr , mkConstAddr , constAddrToInt , HeapAddr , mkHeapAddr , heapAddrToInt , Name ) where import Control.Exception import Language.Dash.Limits -- Intermediate representation for data static runtime data data Constant = CPlainSymbol SymId | CCompoundSymbol SymId [Constant] | COpaqueSymbol SymId SymId [Constant] -- own sym id, owner, fields | CString String | CNumber Int | CMatchData [Constant] | CMatchVar Int -- Can only be used inside CMatchData | CFunction FuncAddr | CCompoundSymbolRef ConstAddr deriving (Show, Eq) type ConstTable = [Constant] -- TODO move these out of here type SymbolNameList = [String] type Name = String newtype Reg = MkReg Int deriving (Show, Eq, Ord, Num) mkReg :: Int -> Reg mkReg i = assert (i >= 0 && i < maxRegisters) $ MkReg i regToInt :: Reg -> Int regToInt (MkReg i) = i newtype SymId = MkSymId Int deriving (Show, Eq, Ord) mkSymId :: Int -> SymId mkSymId i = assert (i >= 0 && i < maxSymbols) $ MkSymId i symIdToInt :: SymId -> Int symIdToInt (MkSymId i) = i newtype FuncAddr = MkFuncAddr Int deriving (Show, Eq, Ord) mkFuncAddr :: Int -> FuncAddr mkFuncAddr i = assert (i >= 0) $ MkFuncAddr i funcAddrToInt :: FuncAddr -> Int funcAddrToInt (MkFuncAddr i) = i -- TODO is ConstAddr before or after encoding the data? not clear. We should have separate types! newtype ConstAddr = MkConstAddr Int deriving (Eq, Show, Ord) mkConstAddr :: Int -> ConstAddr mkConstAddr i = assert (i >= 0) $ MkConstAddr i constAddrToInt :: ConstAddr -> Int constAddrToInt (MkConstAddr i) = i newtype HeapAddr = MkHeapAddr Int deriving (Eq, Show, Ord) mkHeapAddr :: Int -> HeapAddr mkHeapAddr i = assert (i >= 0) $ MkHeapAddr i heapAddrToInt :: HeapAddr -> Int heapAddrToInt (MkHeapAddr i) = i
arne-schroppe/dash
src/Language/Dash/IR/Data.hs
mit
2,036
0
10
427
607
341
266
78
1
module Y2020.M08.D28.Exercise where {-- Clean words. Today let's make those words clean. What words, you ask? Welp, one answer is: "alles o' dems wordz!" so, ... yeah: that. Yesterday, we found we have some weird words in a document we were scanning, and, also, we found the weird characters in those weird words. So. Let's remove the weird characters FROM the document, THEN rescan the document. Voila, and I hope, we will have a scanned document of clean words. If only it were that simple (play weird, moody, and forboding music here). --} import Control.Monad ((>=>)) import Data.List (sortOn) import Data.Map (Map) import qualified Data.Map as Map import Data.Ord import Data.Set (Set) import Y2020.M08.D25.Solution (gutenbergIndex, workingDir, gutenbergTop100Index) import Y2020.M08.D26.Exercise (importBook, Text) -- a helpful function to import a document to analyze: study :: FilePath -> IO Text study = gutenbergIndex >=> importBook . head . Map.toList encleanifyDoc :: Set Char -> Text -> Text encleanifyDoc weirdChars doc = undefined {-- `encleanify` takes a set of weird characters and removes those weird characters from a document. N.B.: not all weird characters are weird characters. What? From yesterday, we saw that the weird characters for a specific doc were: {"!\"#$%'()*,-./0123456789:;?@[]\182\187\191"} But we know that '-' is a word-connector, ... for example: "word-connector" is a word that has '-' as one of its characters. [... ya see wha' I dun did wid dat? lol ...] Are there any other characters that you know and love and want to deweirdify? Also, the word "don't" but not the words "'A" and "Proposal,'" in the phrase: "'A Modest Proposal,'" ... so ... simple? easy? straightforward? Hmmmm. >>> let bookus = study (workingDir ++ gutenbergTop100Index) >>> length <$> bookus 182057 >>> let weirdos = Set.fromList "!\"#$%'()*,-./0123456789:;?@[]\182\187\191" >>> let subweirds = deweirdify weirdos (Set.fromList "-'") >>> let cleenBook = encleanifyDoc subweirds <$> bookus >>> length <$> cleenBook 174776 --} deweirdify :: Set Char -> Set Char -> Set Char deweirdify weirdos nonweirdos = undefined {-- After you magically encleanify the document, let's encleanify EACH WORD! *EEK*! >>> let weirdos = Set.fromList "!\"#$%'()*,-./0123456789:;?@[]\182\187\191" >>> deweirdify weirdos (Set.fromList "-'") fromList "!\"#$%()*,./0123456789:;?@[]\182\187\191" --} encleanifyWord :: Set Char -> String -> String -- I ... think (?) if we remove weird characters at the bookends of the word, -- it's encleanified? Let's give that a try encleanifyWord weirdos word = undefined {-- >>> encleanifyWord weirdos "'asffag;;;." "asffag" >>> encleanifyWord weirdos "don't" "don't" After you've encleanified the document and the words of the document, you can now create a word-count (there's that pesky '-', again, and "there's" has that pesky inlined '\'' in it, too! ... IT'S TURTLES ALL THE WAY DOWN, I TELL YA!). We'll look at the problem of 'stop-words' (often called "STOPWORDS" (caps intentional)), ... but not today. --} cleanDoc :: Set Char -> Text -> [String] cleanDoc weirds book = undefined {-- >>> let bookwords = cleanDoc weirdos <$> bookus >>> length <$> bookwords 31530 --} wordFreq :: [String] -> Map String Int wordFreq encleanifiedDoc = undefined -- I mean: you can wordFreq a weirded-out doc, but why? -- Also ... it ... 'MIGHT'(?) be nice to have all the words be of uniform case? -- ... but then ... proper nouns? Or is that an issue for Named Entity -- recognizers to deal with? {-- >>> let wordus = wordFreq <$> bookwords >>> take 5 . sortOn (Down . snd) . Map.toList <$> wordus [("the",1742),("and",1118),("of",778),("a",761),("to",738)] --} {-- BONUS ------------------------------------------------------- Thought-experiment: So, I'm thinking about weirdos being (Char -> Bool) as opposed to Set Char. There are trade-offs to either approach. What are they? Redeclare the above functions to use weirdo as one type or the other. What impact does that have on your approaches and implementations to the problem solution? --}
geophf/1HaskellADay
exercises/HAD/Y2020/M08/D28/Exercise.hs
mit
4,111
0
7
671
279
162
117
-1
-1
-------------------------------------------------------------------------- -- Copyright (c) 2007-2010, ETH Zurich. -- All rights reserved. -- -- This file is distributed under the terms in the attached LICENSE file. -- If you do not find this file, copies can be found by writing to: -- ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -- -- Architectural definitions for Barrelfish on x86_64. -- -------------------------------------------------------------------------- module X86_64 where import HakeTypes import Path import qualified Config import qualified ArchDefaults ------------------------------------------------------------------------- -- -- Architecture specific definitions for x86_64 -- ------------------------------------------------------------------------- arch = "x86_64" archFamily = "x86_64" compiler = "gcc" cxxcompiler = "g++" ourCommonFlags = [ Str "-m64", Str "-mno-red-zone", Str "-fPIE", Str "-fno-stack-protector", Str "-Wno-unused-but-set-variable", Str "-Wno-packed-bitfield-compat" ] cFlags = ArchDefaults.commonCFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cxxFlags = ArchDefaults.commonCxxFlags ++ ArchDefaults.commonFlags ++ ourCommonFlags cDefines = ArchDefaults.cDefines options ourLdFlags = [ Str "-Wl,-z,max-page-size=0x1000", Str "-Wl,--build-id=none", Str "-m64" ] ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags options = (ArchDefaults.options arch archFamily) { optFlags = cFlags, optCxxFlags = cxxFlags, optDefines = cDefines, optLdFlags = ldFlags, optLdCxxFlags = ldCxxFlags, optInterconnectDrivers = ["lmp", "ump", "multihop"], optFlounderBackends = ["lmp", "ump", "multihop"] } -- -- The kernel is "different" -- kernelCFlags = [ Str s | s <- [ "-fno-builtin", "-nostdinc", "-std=c99", "-m64", "-mno-red-zone", "-fPIE", "-fno-stack-protector", "-U__linux__", "-Wall", "-Wshadow", "-Wstrict-prototypes", "-Wold-style-definition", "-Wmissing-prototypes", "-Wmissing-declarations", "-Wmissing-field-initializers", "-Wredundant-decls", "-Wno-packed-bitfield-compat", "-Wno-unused-but-set-variable", "-Werror", "-imacros deputy/nodeputy.h", "-mno-mmx", "-mno-sse", "-mno-sse2", "-mno-sse3", "-mno-sse4.1", "-mno-sse4.2", -- "-Wno-unused-but-set-variable", "-mno-sse4", "-mno-sse4a", "-mno-3dnow" ]] kernelLdFlags = [ Str s | s <- [ "-Wl,-N", "-pie", "-fno-builtin", "-nostdlib", "-Wl,--fatal-warnings", "-m64" ] ] ------------------------------------------------------------------------ -- -- Now, commands to actually do something -- ------------------------------------------------------------------------ -- -- Compilers -- cCompiler = ArchDefaults.cCompiler arch compiler cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler makeDepend = ArchDefaults.makeDepend arch compiler makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler cToAssembler = ArchDefaults.cToAssembler arch compiler assembler = ArchDefaults.assembler arch compiler archive = ArchDefaults.archive arch linker = ArchDefaults.linker arch compiler cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler -- -- Link the kernel (CPU Driver) -- linkKernel :: Options -> [String] -> [String] -> String -> HRule linkKernel opts objs libs kbin = let linkscript = "/kernel/linker.lds" in Rules [ Rule ([ Str compiler, Str Config.cOptFlags, NStr "-T", In BuildTree arch "/kernel/linker.lds", Str "-o", Out arch kbin ] ++ (optLdFlags opts) ++ [ In BuildTree arch o | o <- objs ] ++ [ In BuildTree arch l | l <- libs ] ++ [ NL, NStr "/bin/echo -e '\\0002' | dd of=", Out arch kbin, Str "bs=1 seek=16 count=1 conv=notrunc status=noxfer" ] ), Rule [ Str "cpp", NStr "-I", NoDep SrcTree "src" "/kernel/include/", Str "-D__ASSEMBLER__", Str "-P", In SrcTree "src" "/kernel/arch/x86_64/linker.lds.in", Out arch linkscript ] ]
modeswitch/barrelfish
hake/X86_64.hs
mit
5,581
4
17
2,191
782
445
337
99
1
module HaskSplit.Algorithm ( encode , decode ) where import System.Random import FiniteField.PGF256 import FiniteField.GF256 import HaskSplit.Util import Prelude hiding ((/)) encode :: [GF256Elm] -> Int -> StdGen -> GF256Elm -> [GF256Elm] encode xs degree g d = let poly = d:(generateCoeffs degree g) -- the randomly generated polynomial in map (calc poly) xs decode :: [GF256Elm] -> [GF256Elm] -> GF256Elm decode xs ys = let len = length xs termF = (\i -> getTerm xs ys i) in sum $ map termF [0..(len-1)] -- get the ith term of lagrange's interpolation polynomial getTerm :: [GF256Elm] -> [GF256Elm] -> Int -> GF256Elm getTerm xs ys i = let topX = nfoldr1 (*) xs i botX = product $ nmap ((-) (xs !! i)) xs i res = (ys !! i) * (topX / botX) in res generateCoeffs :: Int -> StdGen -> [GF256Elm] generateCoeffs 0 _ = [] generateCoeffs degree g = let (r, nextG) = toGF256Elm $ randomR (1, 255) g in generateCoeffs' (degree - 1) [r] nextG where generateCoeffs' :: Int -> [GF256Elm] -> StdGen -> [GF256Elm] generateCoeffs' 0 coeffs _ = coeffs generateCoeffs' deg coeffs g = let (r, nextG) = toGF256Elm $ randomR (1, 255) g in generateCoeffs' (deg - 1) (r:coeffs) nextG toGF256Elm :: (Integer, StdGen) -> (GF256Elm, StdGen) toGF256Elm (a, g) = (fromInteger a, g)
jtcwang/HaskSplit
src/lib/HaskSplit/Algorithm.hs
mit
1,545
0
14
508
550
298
252
35
2
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE BangPatterns #-} module Control.Workflow.Language.TH (build) where import Control.Arrow.Free (mapA, effect) import Control.Arrow (arr, (>>>)) import qualified Data.Text as T import Language.Haskell.TH import Instances.TH.Lift () import qualified Data.HashMap.Strict as M import qualified Data.Graph.Inductive as G import Control.Monad.State.Lazy (execState) import Data.Hashable (hash) import Data.Maybe (fromJust) import Control.Workflow.Language import Control.Workflow.Types import Control.Workflow.Interpreter.FunctionTable (mkFunTable) import Control.Workflow.Language.TH.Internal -- | Generate template haskell codes to build the workflow. build :: String -- ^ The name of the compiled workflow. -> TypeQ -- ^ The workflow signature. -> Builder () -- ^ Worflow builder. -> Q [Dec] build name sig builder = compile name sig wf where wf = addSource $ execState builder $ Workflow M.empty M.empty {-# INLINE build #-} -- Generate codes from a DAG. This function will create functions defined in -- the builder. These pieces will be assembled to form a function that will -- execute each individual function in a correct order. compile :: String -- ^ The name of the compiled workflow -> TypeQ -- ^ The function signature -> Workflow -> Q [Dec] compile name sig wf = do d1 <- defFlow wfName d2 <- mkFunTable (name ++ "__Table") (name ++ "__Flow") -- the function signature wf_signature <- (mkName name) `sigD` sig d3 <- [d| $(varP $ mkName name) = SciFlow $(varE wfName) $(varE tableName) $ G.mkGraph nodes edges |] return $ d1 ++ d2 ++ (wf_signature:d3) where nodes = let mkNodeLabel k (UNode _) = NodeLabel k "" False True mkNodeLabel k Node{..} = NodeLabel k _node_doc _node_parallel False in flip map (M.toList $ _nodes wf) $ \(k, nd) -> (hash k, mkNodeLabel k nd) edges = flip concatMap (M.toList $ _parents wf) $ \(x, ps) -> flip map ps $ \p -> (hash p, hash x, ()) tableName = mkName $ name ++ "__Table" wfName = mkName $ name ++ "__Flow" defFlow nm = do main <- compileWorkflow wf return [ValD (VarP nm) (NormalB main) []] {-# INLINE compile #-} mkJob :: T.Text -> Node -> ExpQ mkJob nid Node{..} | _node_parallel = [| step $ Job { _job_name = nid , _job_descr = _node_doc , _job_resource = _node_job_resource , _job_parallel = True , _job_action = mapA $ effect $ Action $_node_function } |] | otherwise = [| step $ Job { _job_name = nid , _job_descr = _node_doc , _job_resource = _node_job_resource , _job_parallel = False , _job_action = effect $ Action $_node_function } |] mkJob nid (UNode fun) = [| ustep nid $fun |] {-# INLINE mkJob #-} addSource :: Workflow -> Workflow addSource wf = execState builder wf where builder = do uNode name [| \() -> return () |] mapM_ (\x -> [name] ~> x) sources sources = filter (\x -> not $ x `M.member` _parents wf) $ M.keys $ _nodes wf name = "SciFlow_Source_Node_2xdj23" {-# INLINE addSource #-} adjustIdx :: [Int] -- ^ positions removed -> [Int] -- ^ Old position in the list -> Maybe [Int] -- ^ new position in the list adjustIdx pos old = case filter (>=0) (map f old) of [] -> Nothing x -> Just x where f x = go 0 pos where go !acc (p:ps) | x == p = -1 | p < x = go (acc+1) ps | otherwise = go acc ps go !acc _ = x - acc {-# INLINE adjustIdx #-} compileWorkflow :: Workflow -> ExpQ compileWorkflow wf = let (functions, _, _) = foldl processNodeGroup ([], M.empty, 0) $ groupSortNodes wf sink = [| arr $ const () |] in linkFunctions $ reverse $ sink : functions where nodeToParents :: M.HashMap T.Text ([T.Text], Int) nodeToParents = M.fromList $ flip map nodes $ \(_, (x, _)) -> let i = M.lookupDefault undefined x nodeToId degree = case G.outdeg gr i of 0 -> 1 d -> d in (x, (M.lookupDefault [] x $ _parents wf, degree)) processNodeGroup (acc, nodeToPos, nVar) nodes = case (map (\x -> M.lookupDefault (error "Impossible") (fst x) nodeToParents) nodes) of -- source node [([], n)] -> let oIdx = [0 .. n - 1] (nid, f) = head nodes nodeToPos' = M.insert nid oIdx nodeToPos fun = [| $f >>> $(replicateOutput 1 n) |] in (fun:acc, nodeToPos', n) parents -> let inputPos = let computeIdx count (x:xs) = let (x', count') = go ([], count) x in x' : computeIdx count' xs where go (acc, m) (y:ys) = case M.lookup y m of Nothing -> go (acc ++ [(y, 0)], M.insert y 1 m) ys Just c -> go (acc ++ [(y, c)], M.insert y (c+1) m) ys go acc _ = acc computeIdx _ _ = [] lookupP (p, i) = M.lookupDefault errMsg p nodeToPos !! i where errMsg = error $ unlines $ ("Node not found: " <> show p) : show (map fst nodes) : map show (M.toList nodeToPos) --map show (M.toList nodeToParents) in map (map lookupP) $ computeIdx M.empty $ map fst parents nInput = map length inputPos nOutput = map snd parents nodeToPos' = let outputPos = let i = scanl1 (+) nOutput in zipWith (\a b -> [a .. b-1]) (0:i) i m = fmap (map (+(sum nOutput))) $ M.mapMaybe (adjustIdx $ concat inputPos) nodeToPos in foldl (\x (k, v) -> M.insert k v x) m $ zip (map fst nodes) outputPos fun = let combinedF = combineArrows $ flip map (zip3 nodes nInput nOutput) $ \((_, f), ni, no) -> (ni, [| $f >>> $(replicateOutput 1 no) |], no) in selectInput nVar (sum nOutput) (concat inputPos) combinedF nVar' = nVar - (sum nInput) + (sum nOutput) in (fun:acc, nodeToPos', nVar') gr = let edges = flip concatMap (M.toList $ _parents wf) $ \(x, ps) -> let x' = M.lookupDefault (error $ show x) x nodeToId in flip map ps $ \p -> (M.lookupDefault (error $ show p) p nodeToId, x', ()) in G.mkGraph nodes edges :: G.Gr (T.Text, Node) () nodes = zip [0..] $ M.toList $ _nodes wf nodeToId = M.fromList $ map (\(i, (x, _)) -> (x, i)) nodes {-# INLINE compileWorkflow #-} groupSortNodes :: Workflow -> [[(T.Text, ExpQ)]] groupSortNodes wf = go [] $ G.topsort' gr where go acc [] = [acc] go [] (x:xs) = go [x] xs go acc (x:xs) | any (x `isChildOf`) acc = acc : go [x] xs | otherwise = go (acc <> [x]) xs isChildOf x y = gr `G.hasEdge` (hash $ fst y, hash $ fst x) gr = let edges = flip concatMap (M.toList $ _parents wf) $ \(x, ps) -> flip map ps $ \p -> (hash p, hash x, ()) in G.mkGraph nodes edges :: G.Gr (T.Text, ExpQ) () nodes = map (\(k, x) -> (hash k, (k, mkJob k x))) $ M.toList $ _nodes wf {-# INLINE groupSortNodes #-}
kaizhang/SciFlow
SciFlow/src/Control/Workflow/Language/TH.hs
mit
7,915
0
27
2,788
2,570
1,372
1,198
153
6
sumsqreven = compose [sum, map (^ 2), filter even] compose :: [a -> a] -> (a -> a) compose = foldr (.) id
AlexMckey/FP101x-ItFP_Haskell
Sources/sumsqreven.hs
cc0-1.0
106
0
8
23
63
35
28
3
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} ----------------------------------------------------------------------------- -- -- Module : IDE.Pane.Modules -- Copyright : (c) Juergen Nicklisch-Franken, Hamish Mackenzie -- License : GNU-GPL -- -- Maintainer : Juergen Nicklisch-Franken <[email protected]> -- Stability : provisional -- Portability : portable -- -- | The pane of ide where modules are presented in tree form with their -- packages and exports -- ------------------------------------------------------------------------------- module IDE.Pane.Modules ( IDEModules(..) , ModulesState(..) , ExpanderState(..) , showModules , selectIdentifier , reloadKeepSelection , replaySelHistory , replayScopeHistory , addModule ) where import Graphics.UI.Gtk hiding (get) import Graphics.UI.Gtk.Gdk.Events import Data.Maybe import qualified Data.Map as Map import Data.Map (Map) import qualified Data.Set as Set import Data.Set (Set) import Data.Tree import Data.List import Distribution.Package import Distribution.Version import Data.Char (toLower) import Prelude hiding (catch) import Data.IORef import IDE.Core.State import IDE.Pane.Info import IDE.Pane.SourceBuffer import Distribution.ModuleName import Distribution.Text (simpleParse,display) import Data.Typeable (Typeable(..)) import Control.Exception (SomeException(..),catch) import Control.Applicative ((<$>)) import IDE.Package (packageConfig,addModuleToPackageDescr,delModuleFromPackageDescr,getEmptyModuleTemplate,getPackageDescriptionAndPath, ModuleLocation(..)) import Distribution.PackageDescription (PackageDescription, BuildInfo, hsSourceDirs, hasLibs, executables, testSuites, exeName, testName, benchmarks, benchmarkName, libBuildInfo, library, buildInfo, testBuildInfo, benchmarkBuildInfo) import System.FilePath (takeBaseName, (</>),dropFileName) import System.Directory (doesFileExist,createDirectoryIfMissing, removeFile) import Graphics.UI.Editor.MakeEditor (buildEditor,FieldDescription(..),mkField) import Graphics.UI.Editor.Parameters (paraMinSize, paraMultiSel, Parameter(..), emptyParams, (<<<-), paraName) import Graphics.UI.Editor.Simple (textEditor, boolEditor, staticListEditor) import Graphics.UI.Editor.Composite (maybeEditor) import IDE.Utils.GUIUtils (stockIdFromType, __) import IDE.Metainfo.Provider (getSystemInfo, getWorkspaceInfo, getPackageInfo) import System.Log.Logger (debugM) import Default (Default(..)) import IDE.Workspaces (packageTry) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad (when, void) import Control.Monad.Trans.Class (MonadTrans(..)) import Control.Monad.Trans.Reader (ask) import IDE.Utils.GUIUtils (treeViewContextMenu) import System.Glib.Properties (newAttrFromMaybeStringProperty) import Data.Text (Text) import qualified Data.Text as T (unpack, isInfixOf, toLower, pack) import Data.Monoid ((<>)) import qualified Text.Printf as S (printf) import Text.Printf (PrintfType) import qualified Data.Text.IO as T (writeFile) printf :: PrintfType r => Text -> r printf = S.printf . T.unpack -- | A modules pane description -- type ModuleRecord = (Text, Maybe (ModuleDescr,PackageDescr)) data IDEModules = IDEModules { outer :: VBox , paned :: HPaned , treeView :: TreeView , treeStore :: TreeStore ModuleRecord , descrView :: TreeView , descrStore :: TreeStore Descr , packageScopeB :: RadioButton , workspaceScopeB :: RadioButton , systemScopeB :: RadioButton , dependsB :: CheckButton , blacklistB :: CheckButton , oldSelection :: IORef SelectionState , expanderState :: IORef ExpanderState } deriving Typeable data ModulesState = ModulesState Int (Scope,Bool) (Maybe ModuleName, Maybe Text) ExpanderState deriving(Eq,Ord,Read,Show,Typeable) data ExpanderState = ExpanderState { packageExp :: ExpanderFacet , packageExpNoBlack :: ExpanderFacet , packageDExp :: ExpanderFacet , packageDExpNoBlack :: ExpanderFacet , workspaceExp :: ExpanderFacet , workspaceExpNoBlack :: ExpanderFacet , workspaceDExp :: ExpanderFacet , workspaceDExpNoBlack :: ExpanderFacet , systemExp :: ExpanderFacet , systemExpNoBlack :: ExpanderFacet } deriving (Eq,Ord,Show,Read) type ExpanderFacet = ([TreePath], [TreePath]) data SelectionState = SelectionState { moduleS' :: Maybe ModuleName , facetS' :: Maybe Text , scope' :: Scope , blacklist' :: Bool} deriving (Eq,Ord,Show) instance Pane IDEModules IDEM where primPaneName _ = (__ "Modules") getAddedIndex _ = 0 getTopWidget = castToWidget . outer paneId b = "*Modules" --liftIO $ widgetGrabFocus (descrView p) getModules :: Maybe PanePath -> IDEM IDEModules getModules Nothing = forceGetPane (Right "*Modules") getModules (Just pp) = forceGetPane (Left pp) showModules :: IDEAction showModules = do pane <- getModules Nothing displayPane pane False instance RecoverablePane IDEModules ModulesState IDEM where saveState p = do m <- getModules Nothing sc <- getScope mbModules <- getPane recordExpanderState expander <- liftIO $ readIORef (expanderState p) case mbModules of Nothing -> return Nothing Just p -> liftIO $ do i <- panedGetPosition (paned p) mbTreeSelection <- getSelectionTree (treeView m) (treeStore m) mbFacetSelection <- getSelectionDescr (descrView m) (descrStore m) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbFacetSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) return (Just (ModulesState i sc mbs expander)) recoverState pp (ModulesState i sc@(scope,useBlacklist) se exp) = do nb <- getNotebook pp p <- buildPane pp nb builder mod <- getModules Nothing liftIO $ writeIORef (expanderState mod) exp liftIO $ writeIORef (oldSelection mod) (SelectionState (fst se) (snd se) scope useBlacklist) liftIO $ panedSetPosition (paned mod) i return p builder pp nb windows = do packageInfo' <- getPackageInfo reifyIDE $ \ ideR -> do let forest = case packageInfo' of Nothing -> [] Just (GenScopeC fst,GenScopeC snd) -> subForest (buildModulesTree (fst,snd)) treeStore <- treeStoreNew forest treeView <- treeViewNew treeViewSetModel treeView treeStore --treeViewSetRulesHint treeView True renderer0 <- cellRendererPixbufNew set renderer0 [ newAttrFromMaybeStringProperty "stock-id" := (Nothing :: Maybe Text) ] renderer <- cellRendererTextNew col <- treeViewColumnNew treeViewColumnSetTitle col (__ "Module") treeViewColumnSetSizing col TreeViewColumnAutosize treeViewColumnSetResizable col True treeViewColumnSetReorderable col True treeViewAppendColumn treeView col cellLayoutPackStart col renderer0 False cellLayoutPackStart col renderer True cellLayoutSetAttributes col renderer treeStore $ \row -> [ cellText := fst row] cellLayoutSetAttributes col renderer0 treeStore $ \row -> [ newAttrFromMaybeStringProperty "stock-id" := case snd row of Nothing -> Nothing Just pair -> if isJust (mdMbSourcePath (fst pair)) then Just ("ide_source" :: Text) else Nothing] renderer2 <- cellRendererTextNew col2 <- treeViewColumnNew treeViewColumnSetTitle col2 (__ "Package") treeViewColumnSetSizing col2 TreeViewColumnAutosize treeViewColumnSetResizable col2 True treeViewColumnSetReorderable col2 True treeViewAppendColumn treeView col2 cellLayoutPackStart col2 renderer2 True cellLayoutSetAttributes col2 renderer2 treeStore $ \row -> [ cellText := case snd row of Nothing -> "" Just pair -> (T.pack . display . pdPackage . snd) pair] treeViewSetHeadersVisible treeView True treeViewSetEnableSearch treeView True treeViewSetSearchEqualFunc treeView (Just (treeViewSearch treeView treeStore)) -- Facet view descrView <- treeViewNew descrStore <- treeStoreNew [] treeViewSetModel descrView descrStore renderer30 <- cellRendererPixbufNew renderer31 <- cellRendererPixbufNew renderer3 <- cellRendererTextNew col <- treeViewColumnNew treeViewColumnSetTitle col (__ "Interface") --treeViewColumnSetSizing col TreeViewColumnAutosize treeViewAppendColumn descrView col cellLayoutPackStart col renderer30 False cellLayoutPackStart col renderer31 False cellLayoutPackStart col renderer3 True cellLayoutSetAttributes col renderer3 descrStore $ \row -> [ cellText := descrTreeText row] cellLayoutSetAttributes col renderer30 descrStore $ \row -> [ cellPixbufStockId := stockIdFromType (descrIdType row)] cellLayoutSetAttributes col renderer31 descrStore $ \row -> [ cellPixbufStockId := if isReexported row then "ide_reexported" else if isJust (dscMbLocation row) then if dscExported row then ("ide_source" :: Text) else "ide_source_local" else "ide_empty"] treeViewSetHeadersVisible descrView True treeViewSetEnableSearch descrView True treeViewSetSearchEqualFunc descrView (Just (descrViewSearch descrView descrStore)) pane' <- hPanedNew sw <- scrolledWindowNew Nothing Nothing scrolledWindowSetShadowType sw ShadowIn containerAdd sw treeView scrolledWindowSetPolicy sw PolicyAutomatic PolicyAutomatic sw2 <- scrolledWindowNew Nothing Nothing scrolledWindowSetShadowType sw2 ShadowIn containerAdd sw2 descrView scrolledWindowSetPolicy sw2 PolicyAutomatic PolicyAutomatic panedAdd1 pane' sw panedAdd2 pane' sw2 (Rectangle _ _ x y) <- liftIO $ widgetGetAllocation nb panedSetPosition pane' (max 200 (x `quot` 2)) box <- hButtonBoxNew boxSetSpacing box 2 buttonBoxSetLayout box ButtonboxSpread rb1 <- radioButtonNewWithLabel (__ "Package") rb2 <- radioButtonNewWithLabelFromWidget rb1 (__ "Workspace") rb3 <- radioButtonNewWithLabelFromWidget rb1 (__ "System") toggleButtonSetActive rb3 True cb2 <- checkButtonNewWithLabel (__ "Imports") cb <- checkButtonNewWithLabel (__ "Blacklist") boxPackStart box rb1 PackGrow 0 boxPackStart box rb2 PackGrow 0 boxPackStart box rb3 PackGrow 0 boxPackEnd box cb PackNatural 0 boxPackEnd box cb2 PackNatural 0 boxOuter <- vBoxNew False 0 boxPackStart boxOuter box PackNatural 2 boxPackStart boxOuter pane' PackGrow 0 oldState <- liftIO $ newIORef $ SelectionState Nothing Nothing SystemScope False expanderState <- liftIO $ newIORef emptyExpansion scopeRef <- newIORef (SystemScope,True) let modules = IDEModules boxOuter pane' treeView treeStore descrView descrStore rb1 rb2 rb3 cb2 cb oldState expanderState cid1 <- after treeView focusInEvent $ do liftIO $ reflectIDE (makeActive modules) ideR return True cid2 <- after descrView focusInEvent $ do liftIO $ reflectIDE (makeActive modules) ideR return True (cid3, cid4) <- treeViewContextMenu treeView $ modulesContextMenu ideR treeStore treeView cid5 <- treeView `on` rowActivated $ modulesSelect ideR treeStore treeView (cid6, cid7) <- treeViewContextMenu descrView $ descrViewContextMenu ideR descrStore descrView cid8 <- descrView `on` rowActivated $ descrViewSelect ideR descrStore on rb1 toggled (reflectIDE scopeSelection ideR) on rb2 toggled (reflectIDE scopeSelection ideR) on rb3 toggled (reflectIDE scopeSelection ideR) on cb toggled (reflectIDE scopeSelection ideR) on cb2 toggled (reflectIDE scopeSelection ideR) sel <- treeViewGetSelection treeView on sel treeSelectionSelectionChanged $ do fillFacets treeView treeStore descrView descrStore reflectIDE recordSelHistory ideR return () sel2 <- treeViewGetSelection descrView on sel2 treeSelectionSelectionChanged $ do fillInfo descrView descrStore ideR reflectIDE recordSelHistory ideR return () return (Just modules,map ConnectC [cid1, cid2, cid3, cid4, cid5, cid6, cid7, cid8]) selectIdentifier :: Descr -> Bool -> IDEAction selectIdentifier idDescr openSource= do liftIO $ debugM "leksah" "selectIdentifier" systemScope <- getSystemInfo workspaceScope <- getWorkspaceInfo packageScope <- getPackageInfo currentScope <- getScope case dsMbModu idDescr of Nothing -> return () Just pm -> case scopeForDescr pm packageScope workspaceScope systemScope of Nothing -> return () Just sc -> do when (fst currentScope < sc) (setScope (sc,snd currentScope)) selectIdentifier' (modu pm) (dscName idDescr) when openSource (goToDefinition idDescr) scopeForDescr :: PackModule -> Maybe (GenScope,GenScope) -> Maybe (GenScope,GenScope) -> Maybe GenScope -> Maybe Scope scopeForDescr pm packageScope workspaceScope systemScope = case ps of (True, r) -> Just (PackageScope r) _ -> case ws of (True, r) -> Just (WorkspaceScope r) _ -> case systemScope of Nothing -> Nothing Just (GenScopeC(PackScope ssc _)) -> if Map.member pid ssc then Just SystemScope else Nothing where pid = pack pm ps = case packageScope of Nothing -> (False,False) Just (GenScopeC (PackScope psc1 _), GenScopeC (PackScope psc2 _)) -> if Map.member pid psc1 then (True,False) else if Map.member pid psc2 then (True,True) else (False, False) ws = case workspaceScope of Nothing -> (False,False) Just (GenScopeC (PackScope wsc1 _), GenScopeC (PackScope wsc2 _)) -> if Map.member pid wsc1 then (True,False) else if Map.member pid wsc2 then (True,True) else (False, False) selectIdentifier' :: ModuleName -> Text -> IDEAction selectIdentifier' moduleName symbol = let nameArray = map T.pack $ components moduleName in do liftIO $ debugM "leksah" "selectIdentifier'" mods <- getModules Nothing mbTree <- liftIO $ treeStoreGetTreeSave (treeStore mods) [] case treePathFromNameArray mbTree nameArray [] of Just treePath -> liftIO $ do treeViewExpandToPath (treeView mods) treePath sel <- treeViewGetSelection (treeView mods) treeSelectionSelectPath sel treePath col <- treeViewGetColumn (treeView mods) 0 treeViewScrollToCell (treeView mods) (Just treePath) col (Just (0.3,0.3)) mbFacetTree <- treeStoreGetTreeSave (descrStore mods) [] selF <- treeViewGetSelection (descrView mods) case findPathFor symbol mbFacetTree of Nothing -> sysMessage Normal (__ "no path found") Just path -> do treeViewExpandToPath (descrView mods) path treeSelectionSelectPath selF path col <- treeViewGetColumn (descrView mods) 0 treeViewScrollToCell (descrView mods) (Just path) col (Just (0.3,0.3)) bringPaneToFront mods Nothing -> return () findPathFor :: Text -> Maybe (Tree Descr) -> Maybe TreePath findPathFor symbol (Just (Node _ forest)) = foldr ( \i mbTreePath -> findPathFor' [i] (forest !! i) mbTreePath) Nothing [0 .. ((length forest) - 1)] where findPathFor' :: TreePath -> Tree Descr -> Maybe TreePath -> Maybe TreePath findPathFor' _ node (Just p) = Just p findPathFor' path (Node wrap sub) Nothing = if dscName wrap == symbol then Just (reverse path) else foldr ( \i mbTreePath -> findPathFor' (i:path) (sub !! i) mbTreePath) Nothing [0 .. ((length sub) - 1)] findPathFor symbol Nothing = Nothing treePathFromNameArray :: Maybe ModTree -> [Text] -> [Int] -> Maybe [Int] treePathFromNameArray (Just tree) [] accu = Just (reverse accu) treePathFromNameArray (Just tree) (h:t) accu = let names = map (\t -> fst $ rootLabel t) (subForest tree) mbIdx = elemIndex h names in case mbIdx of Nothing -> Nothing Just i -> treePathFromNameArray (Just (subForest tree !! i)) t (i:accu) treePathFromNameArray Nothing _ _ = Nothing treeViewSearch :: TreeView -> TreeStore ModuleRecord -> Text -> TreeIter -> IO Bool treeViewSearch treeView treeStore string iter = do liftIO $ debugM "leksah" "treeViewSearch" path <- treeModelGetPath treeStore iter val <- treeStoreGetValue treeStore path mbTree <- treeStoreGetTreeSave treeStore path exp <- treeViewRowExpanded treeView path when (isJust mbTree && (not (null (subForest (fromJust mbTree)))) && not exp) $ let found = searchInModSubnodes (fromJust mbTree) string in when found $ do treeViewExpandRow treeView path False return () let str2 = case snd val of Just (mod,_) -> showPackModule (mdModuleId mod) Nothing -> "" let res = T.isInfixOf (T.toLower string) (T.toLower str2) return res searchInModSubnodes :: ModTree -> Text -> Bool searchInModSubnodes tree str = not $ null $ filter (\ (_,mbPair) -> case mbPair of Nothing -> False Just (mod,_) -> let cstr = T.pack $ show (Present (mdModuleId mod)) in T.isInfixOf (T.toLower str) (T.toLower cstr)) $ concatMap flatten (subForest tree) descrViewSearch :: TreeView -> TreeStore Descr -> Text -> TreeIter -> IO Bool descrViewSearch descrView descrStore string iter = do liftIO $ debugM "leksah" "descrViewSearch" path <- treeModelGetPath descrStore iter val <- treeStoreGetValue descrStore path tree <- treeStoreGetTree descrStore path exp <- treeViewRowExpanded descrView path when (not (null (subForest tree)) && not exp) $ let found = searchInFacetSubnodes tree string in when found $ do treeViewExpandRow descrView path False return () return (T.isInfixOf (T.toLower string) (T.toLower (descrTreeText val))) searchInFacetSubnodes :: DescrTree -> Text -> Bool searchInFacetSubnodes tree str = not $ null $ filter (\ val -> T.isInfixOf (T.toLower str) (T.toLower (descrTreeText val))) $ concatMap flatten (subForest tree) fillFacets :: TreeView -> TreeStore ModuleRecord -> TreeView -> TreeStore Descr -> IO () fillFacets treeView treeStore descrView descrStore = do liftIO $ debugM "leksah" "fillFacets" sel <- getSelectionTree treeView treeStore case sel of Just (_,Just (mod,package)) -> let forest = buildFacetForrest mod in do emptyModel <- treeStoreNew [] treeViewSetModel descrView emptyModel treeStoreClear descrStore mapM_ (\(e,i) -> treeStoreInsertTree descrStore [] i e) $ zip forest [0 .. length forest] treeViewSetModel descrView descrStore treeViewSetEnableSearch descrView True treeViewSetSearchEqualFunc descrView (Just (descrViewSearch descrView descrStore)) otheriwse -> treeStoreClear descrStore getSelectionTree :: TreeView -> TreeStore ModuleRecord -> IO (Maybe ModuleRecord) getSelectionTree treeView treeStore = do liftIO $ debugM "leksah" "getSelectionTree" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of [] -> return Nothing a:r -> do val <- treeStoreGetValue treeStore a return (Just val) getSelectionDescr :: TreeView -> TreeStore Descr -> IO (Maybe Descr) getSelectionDescr treeView treeStore = do liftIO $ debugM "leksah" "getSelectionDescr" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of a:r -> do val <- treeStoreGetValue treeStore a return (Just val) _ -> return Nothing fillInfo :: TreeView -> TreeStore Descr -> IDERef -> IO () fillInfo treeView lst ideR = do liftIO $ debugM "leksah" "fillInfo" treeSelection <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows treeSelection case paths of [] -> return () [a] -> do descr <- treeStoreGetValue lst a reflectIDE (setInfo descr) ideR return () _ -> return () findDescription :: SymbolTable alpha => PackModule -> alpha -> Text -> Maybe (Text,Descr) findDescription md st s = case filter (\id -> case dsMbModu id of Nothing -> False Just pm -> md == pm) (symLookup s st) of [] -> Nothing l -> Just (s,head l) getEmptyDefaultScope :: Map Text [Descr] getEmptyDefaultScope = Map.empty fillModulesList :: (Scope,Bool) -> IDEAction fillModulesList (scope,useBlacklist) = do liftIO $ debugM "leksah" "fillModulesList" mods <- getModules Nothing prefs <- readIDE prefs case scope of SystemScope -> do accessibleInfo' <- getSystemInfo case accessibleInfo' of Nothing -> liftIO $ do treeStoreClear (treeStore mods) --treeStoreInsertTree (treeStore mods) [] 0 (Node ("",[]) []) Just (GenScopeC ai@(PackScope pm ps)) -> let p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else ai (Node _ li) = buildModulesTree (PackScope Map.empty getEmptyDefaultScope,p2) in insertIt li mods WorkspaceScope withImports -> do workspaceInfo' <- getWorkspaceInfo packageInfo' <- getPackageInfo case workspaceInfo' of Nothing -> insertIt [] mods Just (GenScopeC l,GenScopeC p) -> let (l',p'@(PackScope pm ps)) = if withImports then (l, p) else (l, PackScope Map.empty symEmpty) p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else p' (Node _ li) = buildModulesTree (l', p2) in insertIt li mods PackageScope withImports -> do packageInfo' <- getPackageInfo case packageInfo' of Nothing -> insertIt [] mods Just (GenScopeC l,GenScopeC p) -> let (l',p'@(PackScope pm ps)) = if withImports then (l,p) else (l, PackScope Map.empty symEmpty) p2 = if useBlacklist then PackScope (Map.filter (filterBlacklist (packageBlacklist prefs)) pm) ps else p' (Node _ li) = buildModulesTree (l', p2) in insertIt li mods where insertIt li mods = liftIO $ do emptyModel <- treeStoreNew [] treeViewSetModel (treeView mods) emptyModel treeStoreClear (treeStore mods) mapM_ (\(e,i) -> treeStoreInsertTree (treeStore mods) [] i e) $ zip li [0 .. length li] treeViewSetModel (treeView mods) (treeStore mods) treeViewSetEnableSearch (treeView mods) True treeViewSetSearchEqualFunc (treeView mods) (Just (treeViewSearch (treeView mods) (treeStore mods))) filterBlacklist :: [Dependency] -> PackageDescr -> Bool filterBlacklist dependencies packageDescr = let packageId = pdPackage packageDescr name = pkgName packageId version = pkgVersion packageId in isNothing $ find (\ (Dependency str vr) -> str == name && withinRange version vr) dependencies type DescrForest = Forest Descr type DescrTree = Tree Descr descrTreeText :: Descr -> Text descrTreeText (Real (RealDescr id _ _ _ _ (InstanceDescr binds) _)) = id <> " " <> printBinds binds where printBinds [] = "" printBinds (a:[]) = a printBinds (a:b) = a <> " " <> printBinds b descrTreeText d = dscName d descrIdType :: Descr -> DescrType descrIdType = descrType . dscTypeHint buildFacetForrest :: ModuleDescr -> DescrForest buildFacetForrest modDescr = let (instances,other) = partition (\id -> case dscTypeHint id of InstanceDescr _ -> True _ -> False) $ take 2000 $ mdIdDescriptions modDescr -- TODO: Patch for toxioc TypeLevel package with 28000 aliases forestWithoutInstances = map buildFacet other (forest2,orphaned) = foldl' addInstances (forestWithoutInstances,[]) instances orphanedNodes = map (\ inst -> Node inst []) orphaned in forest2 ++ reverse orphanedNodes where -- expand nodes in a module desciption for the description tree buildFacet :: Descr -> DescrTree buildFacet descr = case dscTypeHint descr of DataDescr constructors fields -> Node descr ((map (\(SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real $ RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp})) []) constructors) ++ (map (\(SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real $ RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp})) []) fields)) NewtypeDescr (SimpleDescr fn ty loc comm exp) mbField -> Node descr (Node (makeReexported descr (Real $ RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = ConstructorDescr descr, dscExported' = exp})) [] : case mbField of Just (SimpleDescr fn ty loc comm exp) -> [Node (makeReexported descr (Real $ RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = FieldDescr descr, dscExported' = exp})) []] Nothing -> []) ClassDescr _ methods -> Node descr (map (\(SimpleDescr fn ty loc comm exp) -> Node (makeReexported descr (Real $ RealDescr{dscName' = fn, dscMbTypeStr' = ty, dscMbModu' = dsMbModu descr, dscMbLocation' = loc, dscMbComment' = comm, dscTypeHint' = MethodDescr descr, dscExported' = exp})) []) methods) _ -> Node descr [] where makeReexported :: Descr -> Descr -> Descr makeReexported (Reexported d1) d2 = Reexported $ ReexportedDescr{dsrMbModu = dsrMbModu d1, dsrDescr = d2} makeReexported _ d2 = d2 addInstances :: (DescrForest,[Descr]) -> Descr -> (DescrForest,[Descr]) addInstances (forest,orphaned) instDescr = case foldr (matches instDescr) ([],False) forest of (f,True) -> (f,orphaned) (f,False) -> (forest, instDescr:orphaned) matches :: Descr -> DescrTree -> (DescrForest,Bool) -> (DescrForest,Bool) matches (Real (instDescr@RealDescr{dscTypeHint' = InstanceDescr binds})) (Node dd@(Real (RealDescr id _ _ _ _ (DataDescr _ _) _)) sub) (forest,False) | not (null binds) && id == head binds = ((Node dd (sub ++ [Node newInstDescr []])):forest,True) where newInstDescr = if isNothing (dscMbLocation' instDescr) then Real $ instDescr{dscMbLocation' = dscMbLocation dd} else Real $ instDescr matches (Real (instDescr@RealDescr{dscTypeHint' = InstanceDescr binds})) (Node dd@(Real (RealDescr id _ _ _ _ (NewtypeDescr _ _) _)) sub) (forest,False) | not (null binds) && id == head binds = ((Node dd (sub ++ [Node newInstDescr []])):forest,True) where newInstDescr = if isNothing (dscMbLocation' instDescr) then Real $ instDescr{dscMbLocation' = dscMbLocation dd} else Real $ instDescr matches _ node (forest,b) = (node:forest,b) defaultRoot :: Tree ModuleRecord defaultRoot = Node ("",Just (getDefault,getDefault)) [] type ModTree = Tree ModuleRecord -- -- | Make a Tree with a module desription, package description pairs tree to display. -- Their are nodes with a label but without a module (like e.g. Data). -- buildModulesTree :: (SymbolTable alpha, SymbolTable beta) => (PackScope alpha,PackScope beta ) -> ModTree buildModulesTree (PackScope localMap _,PackScope otherMap _) = let modDescrPackDescr = concatMap (\p -> map (\m -> (m,p)) (pdModules p)) (Map.elems localMap ++ Map.elems otherMap) resultTree = foldl' insertPairsInTree defaultRoot modDescrPackDescr in sortTree resultTree insertPairsInTree :: ModTree -> (ModuleDescr,PackageDescr) -> ModTree insertPairsInTree tree pair = let nameArray = map T.pack . components . modu . mdModuleId $ fst pair (startArray,last) = splitAt (length nameArray - 1) nameArray pairedWith = (map (\n -> (n,Nothing)) startArray) ++ [(head last,Just pair)] in insertNodesInTree pairedWith tree insertNodesInTree :: [ModuleRecord] -> ModTree -> ModTree insertNodesInTree [p1@(str1,Just pair)] (Node p2@(str2,mbPair) forest2) = case partition (\ (Node (s,_) _) -> s == str1) forest2 of ([found],rest) -> case found of Node p3@(_,Nothing) forest3 -> Node p2 (Node p1 forest3 : rest) Node p3@(_,Just pair3) forest3 -> Node p2 (Node p1 [] : Node p3 forest3 : rest) ([],rest) -> Node p2 (Node p1 [] : forest2) (found,rest) -> case head found of Node p3@(_,Nothing) forest3 -> Node p2 (Node p1 forest3 : tail found ++ rest) Node p3@(_,Just pair3) forest3 -> Node p2 (Node p1 [] : Node p3 forest3 : tail found ++ rest) insertNodesInTree li@(hd@(str1,Nothing):tl) (Node p@(str2,mbPair) forest) = case partition (\ (Node (s,_) _) -> s == str1) forest of ([found],rest) -> Node p (insertNodesInTree tl found : rest) ([],rest) -> Node p (makeNodes li : forest) (found,rest) -> Node p (insertNodesInTree tl (head found) : tail found ++ rest) insertNodesInTree [] n = n insertNodesInTree _ _ = error (T.unpack $ __ "Modules>>insertNodesInTree: Should not happen2") makeNodes :: [(Text,Maybe (ModuleDescr,PackageDescr))] -> ModTree makeNodes [(str,mbPair)] = Node (str,mbPair) [] makeNodes ((str,mbPair):tl) = Node (str,mbPair) [makeNodes tl] makeNodes _ = throwIDE (__ "Impossible in makeNodes") instance Ord a => Ord (Tree a) where compare (Node l1 _) (Node l2 _) = compare l1 l2 sortTree :: Ord a => Tree a -> Tree a sortTree (Node l forest) = Node l (sort (map sortTree forest)) getSelectedModuleFile :: Maybe ModuleRecord -> Maybe FilePath getSelectedModuleFile sel = case sel of Just (_,Just (m,p)) -> case (mdMbSourcePath m, pdMbSourcePath p) of (Just fp, Just pp) -> Just $ dropFileName pp </> fp (Just fp, Nothing) -> Just fp _ -> Nothing otherwise -> Nothing modulesContextMenu :: IDERef -> TreeStore ModuleRecord -> TreeView -> Menu -> IO () modulesContextMenu ideR store treeView theMenu = do liftIO $ debugM "leksah" "modulesContextMenu" item1 <- menuItemNewWithLabel (__ "Edit source") item1 `on` menuItemActivate $ do mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> void $ reflectIDE (selectSourceBuf fp) ideR sep1 <- separatorMenuItemNew item2 <- menuItemNewWithLabel (__ "Expand here") item2 `on` menuItemActivate $ expandHere treeView item3 <- menuItemNewWithLabel (__ "Collapse here") item3 `on` menuItemActivate $ collapseHere treeView item4 <- menuItemNewWithLabel (__ "Expand all") item4 `on` menuItemActivate $ treeViewExpandAll treeView item5 <- menuItemNewWithLabel (__ "Collapse all") item5 `on` menuItemActivate $ treeViewCollapseAll treeView sep2 <- separatorMenuItemNew item6 <- menuItemNewWithLabel (__ "Add module") item6 `on` menuItemActivate $ reflectIDE (packageTry $ addModule' treeView store) ideR item7 <- menuItemNewWithLabel (__ "Delete module") item7 `on` menuItemActivate $ do mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> do resp <- reflectIDE (respDelModDialog)ideR if (resp == False) then return () else do exists <- doesFileExist fp if exists then do reflectIDE (liftIO $ removeFile fp) ideR reflectIDE (packageTry $ delModule treeView store)ideR else do reflectIDE (packageTry $ delModule treeView store)ideR reflectIDE (packageTry packageConfig) ideR return () sel <- getSelectionTree treeView store case sel of Just (s, Nothing) -> do mapM_ (menuShellAppend theMenu) [castToMenuItem item1, castToMenuItem sep1, castToMenuItem item2, castToMenuItem item3, castToMenuItem item4, castToMenuItem item5, castToMenuItem sep2, castToMenuItem item6] Just (_,Just (m,_)) -> do mapM_ (menuShellAppend theMenu) [castToMenuItem item1, castToMenuItem sep1, castToMenuItem item2, castToMenuItem item3, castToMenuItem item4, castToMenuItem item5, castToMenuItem sep2, castToMenuItem item6, castToMenuItem item7] otherwise -> return () modulesSelect :: IDERef -> TreeStore ModuleRecord -> TreeView -> TreePath -> TreeViewColumn -> IO () modulesSelect ideR store treeView path _ = do liftIO $ debugM "leksah" "modulesSelect" treeViewExpandRow treeView path False mbFile <- getSelectedModuleFile <$> getSelectionTree treeView store case mbFile of Nothing -> return () Just fp -> liftIO $ reflectIDE (selectSourceBuf fp) ideR >> return () descrViewContextMenu :: IDERef -> TreeStore Descr -> TreeView -> Menu -> IO () descrViewContextMenu ideR store descrView theMenu = do liftIO $ debugM "leksah" "descrViewContextMenu" item1 <- menuItemNewWithLabel (__ "Go to definition") item1 `on` menuItemActivate $ do sel <- getSelectionDescr descrView store case sel of Just descr -> reflectIDE (goToDefinition descr) ideR otherwise -> sysMessage Normal (__ "Modules>> descrViewPopup: no selection") item2 <- menuItemNewWithLabel (__ "Insert in buffer") item2 `on` menuItemActivate $ do sel <- getSelectionDescr descrView store case sel of Just descr -> reflectIDE (insertInBuffer descr) ideR otherwise -> sysMessage Normal (__ "Modules>> descrViewPopup: no selection") mapM_ (menuShellAppend theMenu) [item1, item2] descrViewSelect :: IDERef -> TreeStore Descr -> TreePath -> TreeViewColumn -> IO () descrViewSelect ideR store path _ = do liftIO $ debugM "leksah" "descrViewSelect" descr <- treeStoreGetValue store path reflectIDE (goToDefinition descr) ideR setScope :: (Scope,Bool) -> IDEAction setScope (sc,bl) = do liftIO $ debugM "leksah" "setScope" mods <- getModules Nothing case sc of (PackageScope False) -> liftIO $ do toggleButtonSetActive (packageScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) False (PackageScope True) -> liftIO $ do toggleButtonSetActive (packageScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) True (WorkspaceScope False) -> liftIO $ do toggleButtonSetActive (workspaceScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) False (WorkspaceScope True) -> liftIO $ do toggleButtonSetActive (workspaceScopeB mods) True widgetSetSensitive (dependsB mods) True toggleButtonSetActive (dependsB mods) True SystemScope -> liftIO $ do toggleButtonSetActive (systemScopeB mods) True widgetSetSensitive (dependsB mods) False liftIO $ toggleButtonSetActive (blacklistB mods) bl selectScope (sc,bl) getScope :: IDEM (Scope,Bool) getScope = do liftIO $ debugM "leksah" "getScope" mods <- getModules Nothing rb1s <- liftIO $ toggleButtonGetActive (packageScopeB mods) rb2s <- liftIO $ toggleButtonGetActive (workspaceScopeB mods) rb3s <- liftIO $ toggleButtonGetActive (systemScopeB mods) cb1s <- liftIO $ toggleButtonGetActive (dependsB mods) cbs <- liftIO $ toggleButtonGetActive (blacklistB mods) let scope = if rb1s then PackageScope cb1s else if rb2s then WorkspaceScope cb1s else SystemScope return (scope,cbs) scopeSelection :: IDEAction scopeSelection = do liftIO $ debugM "leksah" "scopeSelection" (sc,bl) <- getScope setScope (sc,bl) selectScope (sc,bl) selectScope :: (Scope,Bool) -> IDEAction selectScope (sc,bl) = do liftIO $ debugM "leksah" "selectScope" recordExpanderState mods <- getModules Nothing mbTreeSelection <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) mbDescrSelection <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) ts <- liftIO $ treeViewGetSelection (treeView mods) withoutRecordingDo $ do liftIO $ treeSelectionUnselectAll ts fillModulesList (sc,bl) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbDescrSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) selectNames mbs recordScopeHistory applyExpanderState liftIO $ bringPaneToFront mods selectNames :: (Maybe ModuleName, Maybe Text) -> IDEAction selectNames (mbModuleName, mbIdName) = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing case mbModuleName of Nothing -> liftIO $ do sel <- treeViewGetSelection (treeView mods) treeSelectionUnselectAll sel selF <- treeViewGetSelection (descrView mods) treeSelectionUnselectAll selF Just moduleName -> let nameArray = map T.pack $ components moduleName in do mbTree <- liftIO $ treeStoreGetTreeSave (treeStore mods) [] case treePathFromNameArray mbTree nameArray [] of Nothing -> return () Just treePath -> liftIO $ do treeViewExpandToPath (treeView mods) treePath sel <- treeViewGetSelection (treeView mods) treeSelectionSelectPath sel treePath col <- treeViewGetColumn (treeView mods) 0 treeViewScrollToCell (treeView mods) (Just treePath) col (Just (0.3,0.3)) case mbIdName of Nothing -> do selF <- treeViewGetSelection (descrView mods) treeSelectionUnselectAll selF Just symbol -> do mbDescrTree <- treeStoreGetTreeSave (descrStore mods) [] selF <- treeViewGetSelection (descrView mods) case findPathFor symbol mbDescrTree of Nothing -> sysMessage Normal (__ "no path found") Just path -> do treeSelectionSelectPath selF path col <- treeViewGetColumn (descrView mods) 0 treeViewScrollToCell (descrView mods) (Just path) col (Just (0.3,0.3)) reloadKeepSelection :: Bool -> IDEAction reloadKeepSelection isInitial = do liftIO . debugM "leksah" $ (T.unpack $ __ ">>>Info Changed!!! ") ++ show isInitial mbMod <- getPane case mbMod of Nothing -> return () Just mods -> do state <- readIDE currentState if not $ isStartingOrClosing state then do mbTreeSelection <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) mbDescrSelection <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) sc <- getScope recordExpanderState fillModulesList sc liftIO $ treeStoreClear (descrStore mods) let mbs = (case mbTreeSelection of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing, case mbDescrSelection of Nothing -> Nothing Just fw -> Just (dscName fw)) applyExpanderState selectNames mbs else if isInitial == True then do SelectionState moduleS' facetS' sc bl <- liftIO $ readIORef (oldSelection mods) setScope (sc,bl) fillModulesList (sc, bl) selectNames (moduleS', facetS') applyExpanderState else return () treeStoreGetTreeSave :: TreeStore a -> TreePath -> IO (Maybe (Tree a)) treeStoreGetTreeSave treeStore treePath = catch (do liftIO $ debugM "leksah" "treeStoreGetTreeSave" res <- treeStoreGetTree treeStore treePath return (Just res)) (\ (_ :: SomeException) -> return Nothing) expandHere :: TreeView -> IO () expandHere treeView = do liftIO $ debugM "leksah" "expandHere" sel <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows sel case paths of [] -> return () (hd:_) -> treeViewExpandRow treeView hd True >> return () collapseHere :: TreeView -> IO () collapseHere treeView = do liftIO $ debugM "leksah" "collapseHere" sel <- treeViewGetSelection treeView paths <- treeSelectionGetSelectedRows sel case paths of [] -> return () (hd:_) -> treeViewCollapseRow treeView hd >> return () delModule :: TreeView -> TreeStore ModuleRecord -> PackageAction delModule treeview store = do liftIO $ debugM "leksah" "delModule" window <- liftIDE $ getMainWindow sel <- liftIO $ treeViewGetSelection treeview paths <- liftIO $ treeSelectionGetSelectedRows sel categories <- case paths of [] -> return [] (treePath:_) -> liftIO $ mapM (treeStoreGetValue store) $ map (\n -> take n treePath) [1 .. length treePath] liftIDE $ ideMessage Normal (T.pack $ printf (__ "categories: %s") (show categories)) let modPacDescr = snd(last categories) case modPacDescr of Nothing -> liftIDE $ ideMessage Normal (__ "This should never be shown!") Just(md,_) -> do let modName = modu.mdModuleId $ md liftIDE $ ideMessage Normal ("modName: " <> T.pack (show modName)) delModuleFromPackageDescr modName respDelModDialog :: IDEM (Bool) respDelModDialog = do liftIO $ debugM "leksah" "respDelModDialog" window <- getMainWindow resp <- liftIO $ do dia <- messageDialogNew (Just window) [] MessageQuestion ButtonsCancel (__ "Are you sure?") dialogAddButton dia (__ "_Delete Module") (ResponseUser 1) dialogSetDefaultResponse dia ResponseCancel set dia [ windowWindowPosition := WinPosCenterOnParent ] resp <- dialogRun dia widgetDestroy dia return resp return $ resp == ResponseUser 1 addModule' :: TreeView -> TreeStore ModuleRecord -> PackageAction addModule' treeView store = do liftIO $ debugM "leksah" "addModule'" sel <- liftIO $ treeViewGetSelection treeView paths <- liftIO $ treeSelectionGetSelectedRows sel categories <- case paths of [] -> return [] (treePath:_) -> liftIO $ mapM (treeStoreGetValue store) $ map (\n -> take n treePath) [1 .. length treePath] addModule categories -- Includes non buildable allBuildInfo' :: PackageDescription -> [BuildInfo] allBuildInfo' pkg_descr = [ libBuildInfo lib | Just lib <- [library pkg_descr] ] ++ [ buildInfo exe | exe <- executables pkg_descr ] ++ [ testBuildInfo tst | tst <- testSuites pkg_descr ] ++ [ benchmarkBuildInfo tst | tst <- benchmarks pkg_descr ] addModule :: [ModuleRecord] -> PackageAction addModule categories = do liftIO $ debugM "leksah" "selectIdentifier" mbPD <- liftIDE $ getPackageDescriptionAndPath case mbPD of Nothing -> liftIDE $ ideMessage Normal (__ "No package description") Just (pd,cabalPath) -> let srcPaths = nub $ concatMap hsSourceDirs $ allBuildInfo' pd rootPath = dropFileName cabalPath modPath = foldr (\a b -> a <> "." <> b) "" (map fst categories) in do window' <- liftIDE getMainWindow mbResp <- liftIO $ addModuleDialog window' modPath srcPaths (hasLibs pd) $ map (T.pack . exeName) (executables pd) ++ map (T.pack . testName) (testSuites pd) ++ map (T.pack . benchmarkName) (benchmarks pd) case mbResp of Nothing -> return () Just addMod@(AddModule modPath srcPath libExposed exesAndTests) -> case simpleParse $ T.unpack modPath of Nothing -> liftIDE $ ideMessage Normal (T.pack $ printf (__ "Not a valid module name : %s") (T.unpack modPath)) Just moduleName -> do let target = srcPath </> toFilePath moduleName ++ ".hs" liftIO $ createDirectoryIfMissing True (dropFileName target) alreadyExists <- liftIO $ doesFileExist target if alreadyExists then do liftIDE $ ideMessage Normal (T.pack $ printf (__ "File already exists! Importing existing file %s.hs") (takeBaseName target)) addModuleToPackageDescr moduleName $ addModuleLocations addMod packageConfig else do template <- liftIO $ getEmptyModuleTemplate pd modPath liftIO $ T.writeFile target template addModuleToPackageDescr moduleName $ addModuleLocations addMod packageConfig liftIDE $ fileOpenThis target -- Yet another stupid little dialog data AddModule = AddModule { moduleName :: Text, sourceRoot :: FilePath, libExposed :: Maybe Bool, exesAndTests :: Set Text} addModuleLocations :: AddModule -> [ModuleLocation] addModuleLocations addMod = lib (libExposed addMod) ++ map ExeOrTestMod (Set.toList $ exesAndTests addMod) where lib (Just True) = [LibExposedMod] lib (Just False) = [LibOtherMod] lib Nothing = [] addModuleDialog :: Window -> Text -> [FilePath] -> Bool -> [Text] -> IO (Maybe AddModule) addModuleDialog parent modString sourceRoots hasLib exesTests = do liftIO $ debugM "leksah" "addModuleDialog" dia <- dialogNew set dia [ windowTransientFor := parent , windowTitle := (__ "Construct new module") ] #ifdef MIN_VERSION_gtk3 upper <- dialogGetContentArea dia #else upper <- dialogGetUpper dia #endif lower <- dialogGetActionArea dia (widget,inj,ext,_) <- buildEditor (moduleFields sourceRoots hasLib exesTests) (AddModule modString (head sourceRoots) (Just False) Set.empty) bb <- hButtonBoxNew boxSetSpacing bb 6 buttonBoxSetLayout bb ButtonboxSpread closeB <- buttonNewFromStock "gtk-cancel" save <- buttonNewFromStock "gtk-ok" boxPackEnd bb closeB PackNatural 0 boxPackEnd bb save PackNatural 0 on save buttonActivated (dialogResponse dia ResponseOk) on closeB buttonActivated (dialogResponse dia ResponseCancel) boxPackStart (castToBox upper) widget PackGrow 0 boxPackStart (castToBox lower) bb PackNatural 5 set save [widgetCanDefault := True] widgetGrabDefault save widgetShowAll dia resp <- dialogRun dia value <- ext (AddModule modString (head sourceRoots) (Just False) Set.empty) widgetDestroy dia --find case resp of ResponseOk -> return value _ -> return Nothing moduleFields :: [FilePath] -> Bool -> [Text] -> FieldDescription AddModule moduleFields list hasLibs exesTests = VFD emptyParams $ [ mkField (paraName <<<- ParaName ((__ "New module ")) $ emptyParams) moduleName (\ a b -> b{moduleName = a}) (textEditor (const True) True), mkField (paraName <<<- ParaName ((__ "Root of the source path")) $ paraMultiSel <<<- ParaMultiSel False $ paraMinSize <<<- ParaMinSize (-1, 120) $ emptyParams) (\a -> T.pack $ sourceRoot a) (\ a b -> b{sourceRoot = T.unpack a}) (staticListEditor (map T.pack list) id)] ++ (if hasLibs then [ mkField (paraName <<<- ParaName ((__ "Is this an exposed library module")) $ emptyParams) libExposed (\ a b -> b{libExposed = a}) (maybeEditor (boolEditor, emptyParams) True (__ "Expose module"))] else []) ++ map (\ name -> mkField (paraName <<<- ParaName ((__ "Include in ") <> name) $ emptyParams) (Set.member name . exesAndTests) (\ a b -> b{exesAndTests = (if a then Set.insert else Set.delete) name (exesAndTests b)}) boolEditor) exesTests -- * Expander State emptyExpansion = ExpanderState ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) ([],[]) recordExpanderState :: IDEAction recordExpanderState = do liftIO $ debugM "leksah" "recordExpanderState" m <- getModules Nothing liftIO $ do oldSel <- readIORef (oldSelection m) let (sc,bl) = (scope' oldSel, blacklist' oldSel) paths1 <- getExpandedRows (treeView m) (treeStore m) paths2 <- getExpandedRows (descrView m) (descrStore m) modifyIORef (expanderState m) (\ es -> case (sc,bl) of ((PackageScope False),True) -> es{packageExp = (paths1,paths2)} ((PackageScope False),False) -> es{packageExpNoBlack = (paths1,paths2)} (PackageScope True,True) -> es{packageDExp = (paths1,paths2)} (PackageScope True,False) -> es{packageDExpNoBlack = (paths1,paths2)} ((WorkspaceScope False),True) -> es{workspaceExp = (paths1,paths2)} ((WorkspaceScope False),False) -> es{workspaceExpNoBlack = (paths1,paths2)} (WorkspaceScope True,True) -> es{workspaceDExp = (paths1,paths2)} (WorkspaceScope True,False) -> es{workspaceDExpNoBlack = (paths1,paths2)} (SystemScope,True) -> es{systemExp = (paths1,paths2)} (SystemScope,False) -> es{systemExpNoBlack = (paths1,paths2)}) st <- readIORef (expanderState m) return () getExpandedRows :: TreeView -> TreeStore alpha -> IO [TreePath] getExpandedRows view store = do liftIO $ debugM "leksah" "getExpandedRows" mbIter <- treeModelGetIterFirst store case mbIter of Nothing -> return [] Just iter -> expandedFor iter [] where expandedFor :: TreeIter -> [TreePath] -> IO [TreePath] expandedFor iter accu = do path <- treeModelGetPath store iter expanded <- treeViewRowExpanded view path res <- if expanded then do mbIter <- treeModelIterChildren store iter case mbIter of Nothing -> return (path : accu) Just iter -> expandedFor iter (path : accu) else return accu next <- treeModelIterNext store iter case next of Nothing -> return res Just iter -> expandedFor iter res applyExpanderState :: IDEAction applyExpanderState = do liftIO $ debugM "leksah" "applyExpanderState" m <- getModules Nothing (sc,bl) <- getScope liftIO $ do es <- readIORef (expanderState m) let (paths1,paths2) = case (sc,bl) of ((PackageScope False),True) -> packageExp es ((PackageScope False),False) -> packageExpNoBlack es (PackageScope True,True) -> packageDExp es (PackageScope True,False) -> packageDExpNoBlack es ((WorkspaceScope False),True) -> workspaceExp es ((WorkspaceScope False),False) -> workspaceExpNoBlack es (WorkspaceScope True,True) -> workspaceDExp es (WorkspaceScope True,False) -> workspaceDExpNoBlack es (SystemScope,True) -> systemExp es (SystemScope,False) -> systemExpNoBlack es mapM_ (\p -> treeViewExpandToPath (treeView m) p) paths1 mapM_ (\p -> treeViewExpandToPath (descrView m) p) paths2 -- * GUI History recordSelHistory :: IDEAction recordSelHistory = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing ideR <- ask selTree <- liftIO $ getSelectionTree (treeView mods) (treeStore mods) selDescr <- liftIO $ getSelectionDescr (descrView mods) (descrStore mods) let selMod = case selTree of Just (_,Just (md,_)) -> Just (modu $ mdModuleId md) otherwise -> Nothing let selFacet = case selDescr of Nothing -> Nothing Just descr -> Just (dscName descr) oldSel <- liftIO $ readIORef (oldSelection mods) triggerEventIDE (RecordHistory ((ModuleSelected selMod selFacet), (ModuleSelected (moduleS' oldSel) (facetS' oldSel)))) liftIO $ writeIORef (oldSelection mods) (oldSel{moduleS'= selMod, facetS' = selFacet}) return () replaySelHistory :: Maybe ModuleName -> Maybe Text -> IDEAction replaySelHistory mbModName mbFacetName = do liftIO $ debugM "leksah" "replaySelHistory" mods <- getModules Nothing selectNames (mbModName, mbFacetName) oldSel <- liftIO $ readIORef (oldSelection mods) liftIO $ writeIORef (oldSelection mods) (oldSel{moduleS'= mbModName, facetS' = mbFacetName}) recordScopeHistory :: IDEAction recordScopeHistory = do liftIO $ debugM "leksah" "recordScopeHistory" (sc,bl) <- getScope ideR <- ask mods <- getModules Nothing oldSel <- liftIO $ readIORef (oldSelection mods) triggerEventIDE (RecordHistory ((ScopeSelected sc bl), (ScopeSelected (scope' oldSel) (blacklist' oldSel)))) liftIO $ writeIORef (oldSelection mods) (oldSel{scope'= sc, blacklist' = bl}) return () replayScopeHistory :: Scope -> Bool -> IDEAction replayScopeHistory sc bl = do liftIO $ debugM "leksah" "selectIdentifier" mods <- getModules Nothing liftIO $ do toggleButtonSetActive (blacklistB mods) bl toggleButtonSetActive (packageScopeB mods) (sc == (PackageScope False)) toggleButtonSetActive (workspaceScopeB mods) (sc == PackageScope True) toggleButtonSetActive (systemScopeB mods) (sc == SystemScope) setScope (sc,bl) oldSel <- liftIO $ readIORef (oldSelection mods) liftIO $ writeIORef (oldSelection mods) (oldSel{scope'= sc, blacklist' = bl})
573/leksah
src/IDE/Pane/Modules.hs
gpl-2.0
64,688
0
33
23,344
17,329
8,586
8,743
1,227
12
module Computability.FiniteStateAutomata.Macro where import Types import Macro.MetaMacro import Macro.Tuple -- * Automata -- ** NFSA -- | NFSA definition nfsa :: Note -- ^ Set of states -> Note -- ^ Alphabet -> Note -- ^ Transition function -> Note -- ^ Set of accepting states -> Note -- ^ Set of initial states -> Note nfsa = quintuple -- | Concrete NFSA nfsa_ :: Note nfsa_ = "hi" -- | Concrete set of NFSA states nfas_ :: Note nfas_ = "Q" -- | Concrete NFSA transition function nfatf_ :: Note nfatf_ = delta -- | Starting state nfass_ :: Note nfass_ = "q" !: "s" -- | Appecting states nfaas_ :: Note nfaas_ = "F" -- ** DFSA
NorfairKing/the-notes
src/Computability/FiniteStateAutomata/Macro.hs
gpl-2.0
695
0
9
186
118
75
43
21
1